text:
Q: activateController is called twice when the page loads I am using HotTowel.Angular, and noticed that all of my controllers load twice.

Here is the dashbhoard.js
(function () {
    'use strict';
    var controllerId = 'dashboard';
    angular.module('app').controller(controllerId, ['common', 'datacontext', 'localStorageService', 'authenticator', dashboard]);

    function dashboard(common, datacontext, localStorageService, authenticator) {
        var getLogFn = common.logger.getLogFn;
        var log = getLogFn(controllerId);

        var vm = this;
        vm.title = 'Dashboard';
        vm.assignedToDoItems = [];
        vm.toogleAssignedToDoItem = toogleAssignedToDoItem;

        activate();

        function activate() {
            var promises = [getActions()];
            common.activateController(promises, controllerId)
                .then(function () { log('Activated Dashboard View'); });
        }

        function getActions() {
            return datacontext.assignedtodoitem.getAssignedToMe(authenticator.authData).then(function (data) {
                vm.assignedToDoItems = data;
                return vm.assignedToDoItems;
            });
        }

        function toogleAssignedToDoItem(todoItem) {
            todoItem.isCompleted = !todoItem.isCompleted;
            datacontext.save(todoItem);
        }
    }
})();

Here is the app.js
(function () {
    'use strict';

    var app = angular.module('app', [
        // Angular modules
        'ngAnimate',        // animations
        'ngRoute',          // routing
        'ngSanitize',       // sanitizes html bindings (ex: sidebar.js)

        // Custom modules
        'common',           // common functions, logger, spinner
        'common.bootstrap', // bootstrap dialog wrapper functions

        // 3rd Party Modules
        'ui.bootstrap',      // ui-bootstrap (ex: carousel, pagination, dialog)

        'ngzWip',

        //Breeze
        'breeze.angular',
        'LocalStorageModule',

        'xeditable',
        'angularMoment',
        'mgo-angular-wizard'
    ]);

    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('authInterceptor');
    }]);

    // Handle routing errors and success events
    app.run(['$route', '$rootScope', '$q', 'breeze', 'datacontext', 'routemediator', 'editableOptions',
        function ($route, $rootScope, $q, breeze, datacontext, routemediator, editableOptions) {
        // Include $route to kick start the router.
        routemediator.setRoutingHandlers();
        editableOptions.theme = 'bs3';
        var ajaxAdapter = breeze.config.getAdapterInstance("ajax");
        breeze.ajaxpost(ajaxAdapter);
        }]);
})();

These are all the script files loaded:

I am using the following versions:

*

*AngularJS v1.2.22

*Breeze.Angular.js v.0.9.0

----EDIT----
config.route.js
(function () {
    'use strict';

    var app = angular.module('app');

    // Collect the routes
    app.constant('routes', getRoutes());

    // Configure the routes and route resolvers
    app.config(['$routeProvider', 'routes', routeConfigurator]);
    function routeConfigurator($routeProvider, routes) {

        routes.forEach(function (r) {
            //$routeProvider.when(r.url, r.config);
            setRoute(r.url, r.config);
        });
        $routeProvider.otherwise({ redirectTo: '/' });

        function setRoute(url, definition) {
            definition.resolve = angular.extend(definition.resolve || {}, {
                prime: prime,
                checkSecurity: checkSecurity
            });
            $routeProvider.when(url, definition);
        }
    }

    prime.$inject = ['datacontext'];
    function prime(dc) {
        return dc.prime();
    }

    checkSecurity.$inject = ['$route', 'authenticator', 'common'];
    function checkSecurity($route, authenticator, common) {
        var deferred = common.$q.defer();
        authenticator.fillData().then(function () {
            var settings = $route.current.settings;
            var loginRequired = settings.loginRequired || false;
            var roles = settings.roles || [];
            if (loginRequired) {
                if (!authenticator.authData.isAuth) {
                    common.$location.path('/login');
                } else {
                    if (roles.length > 0) {
                        if (!common.checkRole(authenticator.authData.roles, roles)) {
                            common.$location.path('/notauthorized').replace();
                        }
                    }
                }
            }
            deferred.resolve(true); //We want to return just true even if we have to re-route.
            //If we returned an reject, the the global handler will re-route us to home
        }, function (error) {
            deferred.reject

(error);
        });
    return deferred.promise;
}

// Define the routes
function getRoutes() {
    return [
        {
            url: '/',
            config: {
                templateUrl: 'app/dashboard/dashboard.html',
                title: 'Dashboard',
                settings: {
                    nav: 1,
                    loginRequired: true,
                    roles: [],
                    content: ' Dashboard'
                }
            }
        }, {

            url: '/goals',
            config: {
                title: 'Goals',
                templateUrl: 'app/goals/goals.html',
                settings: {
                    nav: 2,
                    loginRequired: true,
                    roles: [],
                    content: ' Goals'
                }
            }
        }, {

            url: '/goal/:id',
            config: {
                title: 'Goals',
                templateUrl: 'app/goal/goal.html',
                settings: {
                    loginRequired: true,
                    roles: []
                }
            }
        }, {

            url: '/goals/search/:search',
            config: {
                title: 'goals-search',
                templateUrl: 'app/goals/goals.html',
                settings: {
                    loginRequired: true,
                    roles: []
                }
            }
        }, {

            url: '/evaluations',
            config: {
                title: 'Evaluations',
                templateUrl: 'app/evaluations/evaluations.html',
                settings: {
                    nav: 3,
                    loginRequired: true,
                    roles: [],
                    content: ' Evaluations'
                }
            }
        }, {
            url: '/profile',
            config: {
                title: 'profiles',
                templateUrl: 'app/profile/profile.html',
                settings: {
                    loginRequired: true,
                    roles: []
                }
            }
        }, {
            url: '/settings',
            config: {
                title: 'settings',
                templateUrl: 'app/settings/settings.html',
                settings: {
                    loginRequired: true,
                    roles: []
                }
            }
        }, {
            url: '/login',
            config: {
                title: 'login',
                templateUrl: 'app/login/login.html',
                settings: {
                }
            }
        }, {
            url: '/signup',
            config: {
                title: 'Sign Up',
                templateUrl: 'app/signup/signup.html',
                settings: {
                }
            }
        }, {
            url: '/deactivated',
            config: {
                title: 'Oh Man!!',
                templateUrl: 'app/deactivated/deactivated.html',
                settings: {
                }
            }
        },{
            url: '/notauthorized',
            config: {
                title: 'not authorized',
                templateUrl: 'app/home/notauthorized.html',
                settings: {
                }
            }
        }
    ];
}

})();

A: Do you have a controller defined in the html too? if you have it in the route and the html, then it will be invoked twice


text:
Q: Toast Message pops up when holding Action Bar Button I have an app and when I press and hold on of the buttons I have put on the action bar this weird blank message pops up and looks like this.
When I tap and hold the profile button that weird empty box pops up and then disappears like a toast?

But no where in my activity do I set anything to pop up...?
Thanks for the help.

A: This is an automatic "tool-tip"-style hint for the user, put on all your action items. Set the title attribute in your menu resource (e.g., android:title for the native action bar) to fill in the string resource to appear there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i mock/fake a method in a service that was inherited from another service and gives back an Observable? I want to write a unit test for a method in a service. However the method is written in another service and it is used here. I would like to mock/fake said method.
This is the service:
export class UserService extends ProxyService<UserInterface> {
  constructor() {
    super(new User());
  }
  getOneByEmail(email: string): Observable<any> {
    return this.getUri('user/by-email/').pipe(map((result: any) => result));
  }
  getCurrentUser(): UserInterface {
    return new User().init(localStorage.getItem('user'));
  }
}

This is the part in the proxy service:
getUri(uri: string): Observable<any> {
    return this.remoteStorageService.getUri(uri).pipe(map((result: any) => result));
  }

This is my .spec file for the unit tests:
describe('UserService', () => {
  const data = {
    email: 'test@gmail.com',
  };
  const fakeUser = new User().init(data);
  beforeAll(() => {
    TestBed.initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting()
    );
  });
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        // angular testing module that provides mocking for http connections
        HttpClientTestingModule,
      ],
      // add declaration of services or components and use inject to get to them in tests
      providers: [
        Injector,
        {
          provide: UserService,
          useValue: new User()
        },
      ],
    });
  }));
  beforeEach(() => {
    AppModule.InjectorInstance = TestBed;
    TestBed.inject(UserService);
  });
  it('should be created', () => {
    const service: UserService = TestBed.inject(UserService);
    expect(service).toBeTruthy();
  });
  it('getCurrentUser should return a user', () => {
    const service: UserService = new UserService();
    const user = new User().init();
    expect(service.getCurrentUser()).toEqual(user);
  });
  it('getOneByEmail should return the user who has the specified email', fakeAsync(inject([
    HttpTestingController,
    UserService,
  ], (
    httpMock: HttpTestingController,
    done
  ) => {
    const service = new UserService();
    service.getOneByEmail(data.email).subscribe((res) => {
      expect(res.data.length).toBe(1);
      expect(res.data[0]).toBeInstanceOf(User);
      done();
    });
    const req = httpMock.expectOne('http://projekt.test/by-email/');
    expect(req.request.method).toEqual('GET');
  }
  )));
});

The first 2 tests are working fine.
In the subscribe method none of the expects are recognized.


text:
Q: Intel gallileo or arduino yun? What are the main differences between the arduino Yun and Gallileo Intel?
Which one do you recommend me to buy?
I want to use it for IoT projects, I want to be able to connect it to the SAP and Intel Platform as a service.

A: There is very good discussion on the Arduino forum, wherein both have been compared to each other. Check this link.
For the second part of your question, could you elaborate more on exactly what is your usecase and exactly how do you want to connect to SAP?
Also by SAP, I guess, you meant the SAP ERP 6.0?


text:
Q: Set custom scaling on Retina MacBook Pro (13inch) I want my scaling to look like 2560x1600. Currently, according to Display preferences, it looks like 1680x1050, and that is the smallest option.
I want everything to be WAY WAY smaller. My eyes are super good and I bought a MacBook with a retina display for a reason - so I could fit more stuff on the screen.
Notice how in the attached screenshot underneath the picture of the MacBook, it says "Looks like 1680x1050". That is no good. I need to fit a lot of stuff on my screen at once.
An example is when I open up League of Legends in Retina resolution, the cursor becomes extremely tiny for 3 seconds. That is how I want my whole Mac to look like.
Is there any way to set the scaling to 100%, like you can in Windows?

A: I have a 15" MacBook Pro with Retina Display and by itself, the highest resolution I can set in System Preferences > Hardware > Display > Display > (o) Scaled, is 1920x1200. To get an even higher resolution, e.g 2880x1800 I use a third-party utility named Display Menu. It's available in the App Store for free.


text:
Q: Transpose elements in a column into multiple columns by group in R Given the data
test_id <- c(1, 1, 1, 2, 2, 2)
test_values <- c(1, 2, 3, 4, 5, 6)
test_df <- data.frame(test_id, test_values)
test_df

  test_id       test_values
        1           1
        1           2
        1           3
        2           4
        2           5
        2           6

I would like to transpose the value column into a row
test_df$x1 <- c(1, 1, 1, 4, 4, 4)
test_df$x2 <- c(2, 2, 2, 5, 5, 5)
test_df$x3 <- c(3, 3, 3, 6, 6, 6)
test_df

 test_id        test_values   x1           x2           x3
        1           1          1            2            3
        1           2          1            2            3
        1           3          1            2            3
        2           4          4            5            6
        2           5          4            5            6
        2           6          4            5            6

I originally had in mind something like
test_df <- test_df %>%
  group_by(test_id) %>%
  mutate(X = t(test_values))%>%
  ungroup()

but this does not allow splitting the column into multiple entries - x1,x2,x3. Any suggestion about how to tackle the issue would be much appreciated!

A: You could do it with pivots and joins:
test_id <- c(1, 1, 1, 2, 2, 2)
test_values <- c(1, 2, 3, 4, 5, 6)
test_df <- data.frame(test_id, test_values)

test_df %>%
  group_by(test_id) %>%
  mutate(var = seq_along(test_values)) %>%
  pivot_wider(values_from="test_values", names_from="var", names_prefix="x") %>%
  left_join(test_df %>% dplyr::select(test_id, test_values), .)
# Joining, by = "test_id"
#   test_id test_values x1 x2 x3
# 1       1           1  1  2  3
# 2       1           2  1  2  3
# 3       1           3  1  2  3
# 4       2           4  4  5  6
# 5       2           5  4  5  6
# 6       2           6  4  5  6

Or, if you only wanted one row per test_id you could just remove the last line:
test_df %>%
  group_by(test_id) %>%
  mutate(var = seq_along(test_values)) %>%
  pivot_wider(values_from="test_values", names_from="var", names_prefix="x")
# # A tibble: 2 x 4
# # Groups:   test_id [2]
#   test_id    x1    x2    x3
#      <dbl> <dbl> <dbl> <dbl>
# 1       1     1     2     3
# 2       2     4     5     6

A: Here is a data.table option
setDT(test_df)[,c(.(test_values = test_values),data.frame(outer(rep(1,.N),test_values))),test_id]

where outer is applied to make the transpose, such that
   test_id test_values X1 X2 X3
1:       1           1  1  2  3
2:       1           2  1  2  3
3:       1           3  1  2  3
4:       2           4  4  5  6
5:       2           5  4  5  6
6:       2           6  4  5  6

A: Using unnest_wider from tidyr
library(dplyr)
library(tidyr)
test_df %>%
    group_by(test_id) %>%
    transmute(col1 = list(test_values)) %>%
    unnest_wider(c(col1)) %>%
    rename_at(vars(starts_with("...")),
       ~ str_replace(., fixed("..."), "x")) %>%
    ungroup

-output
# A tibble: 6 x 4
#  test_id    x1    x2    x3
#    <dbl> <dbl> <dbl> <dbl>
#1       1     1     2     3
#2       1     1     2     3
#3       1     1     2     3
#4       2     4     5     6
#5       2     4     5     6
#6       2     4     5     6

Or using base R
test_df[paste0('x', 1:3)] <-  do.call(rbind, with(test_df,
          split(test_values, test_id)))[test_df$test_id,]


text:
Q: Different CSS for different screen size? I was searching arround here and I found that I can use one of the following:
Adapt.js or Media Queries
I was wondering what is better to use? I Basically need to resize some specified divs with different width for different screens. (800x600 and 640x480)
If none of mentioned is good, any other solution ? Thank you :)

A: <link rel="stylesheet" media="all" href="css/common.css">
<!--Responsive style sheets -->
<link rel="stylesheet" media="all and (min-width: 600px) and (max-width: 800px)" href="css/name1.css">
<link rel="stylesheet" media="all and (min-width: 480px) and (max-width: 640px)" href="css/name2.css">

A: you might be able to use something like this in CSS
@media only screen and (min-device-width: 768px) {
   ... put your css here
}

The above is probably for mobile devices only

A: If you are planning to support multiple screens I would recommend using 960 Grid http://960.gs/.

A: Media Queries are the best solution for you
have a detailed info about these here


text:
Q: If a car is travelling faster than the speed of light, do the headlights still work? If a car is travelling faster than the speed of light, do the headlights still work?
If you can help because i really need to know i am going on a trip with my car tomorrow!

A: Google tachyons. That's about the best you can do.
With our current understanding, any particle that has mass must travel slower than the speed of light. Any massless particles must travel at the speed of light.
Additionally the speed of light is constant relative to the observer. If your car were traveling at 99% of the speed of light, the light leaving your car would be escaping your headlights at the speed of light relative to you. (A stationary observer would also see the light escaping at the speed of light, but only 1% the speed of light faster than you, hence the need for Lorentz transformations).
As for faster than light travel, there is no evidence that it occurs with any particles in the detectable universe. With that in mind, good luck with your road trip tomorrow.


text:
Q: Sinon not stubbing property value of object I am using sinon v4.1.2. According to the documentation (http://sinonjs.org/releases/v4.1.2/sandbox/), I should be able to set a property using the following:
sandbox.stub(myObject, 'hello').value('Sinon');

However, I am getting the error:

Property 'value' does not exist on type 'SinonStub'

What is the real way to do this? I looked through all the available functions, and tried returnValue, but that isn't a valid function either.
The following was working on an older version of sinon:
sandbox.stub(myObject, 'hello', 'Sinon');

A: This works for me with Sinon.JS v4.1.2:
myObject = {hello: 'hello'}
sandbox = sinon.createSandbox()
sandbox.stub(myObject, 'hello').value('Sinon')
myObject.hello // "Sinon"
sandbox.restore()
myObject.hello // "hello"

A: In my expirience, it's not necessary to create a sandbox everytime. You can use stubs without it to reduce complexity in your code.
Just define a stub like this:
const stubHello = sinon.stub(myObject, 'helloFunction');

And then you will have all stub powers!


text:
Q: What is the formula for multiplication of two finite power series? What is formula for multiplication of two finite power series?
$$\sum_{i=0}^m {m \choose i}x^i   \sum_{j=0}^n {n \choose j}x^j$$

A: Using well known Binomial Theorem, $(a+b)^n=\sum_{k=0}^n {n \choose k}a^{n-k}b^k$ for natural $n,$
$$\left(\sum_{k=0}^m {m \choose k}x^k  \right) \left(\sum_{k=0}^n {n \choose k}x^k\right)=(1+x)^m(1+x)^n=(1+x)^{m+n}=\sum_{r=0}^{m+n} {{m+n} \choose r}x^r$$

A: The finite series are just polynomials, so you multiply them as such. More generally, the Cauchy product of two formal power series is obtained by multiplying them as if they were polynomials. Thus, the coefficient of $x^n$ in
$$\left(\sum_{k\ge 0}a_kx^k\right)\left(\sum_{k\ge 0}b_kx^k\right)$$
is $$\sum_{k=0}^na_kb_{n-k}\;.$$
In your problem, if
$$\left(\sum_{k=0}^m\binom{m}kx^k\right)\left(\sum_{k=0}^n\binom{n}kx^k\right)=\sum_{k=0}^{m+n}c_kx^k\;,$$
then $$c_k=\sum_{i=0}^k\binom{m}i\binom{n}{k-i}=\binom{m+n}k\;.$$
Added: That last step uses Vandermonde's identity, which is easily proved either from the binomial theorem, as in lab bhattacharjee's answer, or by a purely combinatorial argument.


text:
Q: jquery - How to properly copy data from div to new window dynamically I have a problem. Im trying to create a very simple print preview that when the user clicks the Print Preview button it will open a new window and copies the data I wanted. There are some elements like the checkbox that I don't want to include but Im able to do it successfully. My problem is when the new window is loaded the original div is also altered. Like the checkboxes are removed in the original div and the Print button also appears.
I want my original div which is divData to remain the same. I don't have problem with the new window.
Btw my jquery codes are below:
        $("#btnPrintPreview").click (function () {
            var printContents = new $("#divData");
            var myWindow = window.open("", "popup","width=1000,height=600,scrollbars=yes,resizable=yes," +
                "toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0");
            var doc = myWindow.document;
            doc.open();
            $(printContents).find(".tCheckboxes").remove();
            var button = "<input type='button' id='btnPrint' value='Print' style='float: right;' onclick='window.print();'/>";
            $(printContents).append($(button));
            doc.write($(printContents).html());
            doc.close();
        });

To see my demo here is the link http://jsfiddle.net/dU7et/.
PS: Please check the main div after clicking the Print Preview.
Please help me....

A: For this to do what you are wanting change the following line to:
// Before:
var printContents = new $("#divData");
// After:
var printContents = $("#divData").clone();

See http://api.jquery.com/clone/ for further reference.


text:
Q: How i can use this command of Imagemagick in a batch file process? im trying to add a caption below each image using the following Imagemagick command:
convert 3_1.jpg   -background Khaki  label:"@3_1.txt" -gravity Center -append 3_1_text.png

This works fine and got this:
figure with label below
Basically i use an image file named e.g. xxx.jpg and add the caption from a text file with the same name (xxx.txt).
What i want to do now is the same process but for a bunch of jpg files in a folder, using a batch process. I have the following folder:
folder with JPGs and text files
So i want to make a batch file that process each image with his respective txt file, and ideally save all the outputs in a specific directory.
Thank you in advance, and best regards,
Jorge

A: i modified the code of the third answer and it did the job:
@ECHO OFF FOR %%G IN (*.jpg) DO convert %%G   -background Khaki  label:"@%%~nG.txt" -gravity Center -append "%%~nG_text.png"

it works like charm!


text:
Q: Problem with Java Timestamp with SQL Date type In my db table I have a column c_dob of Type date
For my controller Request class, I use the above field like this :
import java.sql.Timestamp;
public class UpdateUserProfileRequest {

    private Timestamp dob;
    public Timestamp getDob() {
        return dob;
    }
    public void setDob(Timestamp dob) {
        this.dob = dob;
    }
}

Problems :

*

*What happens is when I have the value 1979-06-30 passed as a
request json value, in the controller class, the request class logs
the value as 1979-06-30 02:00:00.0 (hour part is added and given a value on its own)

*Second, for setting the dob the following code I am using :
Map<String, Object> outMap = proc.execute(inParams);
profile.setDob((Date) outMap.get("out_dob") != null
                         ? new Timestamp(((Date) outMap.get("out_dob")).getTime()) : null);

And what happens here is that 1979-06-30 02:00:00.0 is changed to 1979-06-30 01:00:00.0 which causes logical problem.
So, is there any reason or any solution for this behavior?
Edit  : Database is MySql

A: You are using the wrong data types. The MySQL type DATE represents a date-only value, without time-of-day and without time zone. In contrast, the java.sql.Timestamp class represents a moment, a specific point on the timeline, a date with time-of-day as seen in UTC. Square peg, round hole.
Use only java.time classes. Never use the terrible legacy date-time classes such as Timestamp.
For MySQL DATE use java.time.LocalDate with a JDBC driver that complies with JDBC 4.2 or later.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;

A: Make use of java.time.LocalDateTime which is timezone aware and should help you a lot...
java.sql.Timestamp is a terrible and some leftover of the dark ages :)


text:
Q: How can I ensure that services occur in the same route using constraints? I'm trying to use Jsprit constraints to ensure that a solution route has a specific set of services.. Given the services [S1, S2, S3, ..., S10], I want to ensure that services [S2, S4, S6] occur in the same route..
For this, I am using HardRouteConstraint..
@Override
public boolean fulfilled(JobInsertionContext context) {

    // jobIds = [S2, S4, S6]

    Job thisJob = context.getJob();
    if (jobIds.contains(thisJob.getId())) {
        for (String jobId : jobIds) {
            VehicleRoute route = stateManager.getProblemState(stateManager.createStateId(jobId), VehicleRoute.class);
            // if the jobs are assigned to a different route, reject this route
            if (route != null && route != context.getRoute()) return false;
        }
    }
    return true;
}

This works partially fine.. If S2, S4 and S6 are part of the solution, they appear in a single route, and are not split between different routes..
The problem is that if I have a limited vehicle capacity (say, 3), Jsprit can possibly return a solution like:
Routes: [
    [S1, S2, S3]
    [S5, S7, S8]
    [S9, S10]
]
Unassigned Jobs: [S4, S6]

This is understandable, but not what I want.. I want that if a route includes S2, it should also include S4 and S6, in any order..
How can I ensure that a valid solution does not contain such routes: [X, S2, Y] or [S2, X, S4]..
Thanks,
Asim


text:
Q: Tensorflow and Numpy missing I am using Ubuntu 14.04. I am trying to use the tensorflow module, but although I have it installed, and installed it the same way I would install any other pkg or module, it is not recognized by python as being installed. Even though pip says it is installed... I am not sure what the hell is going on.
See for yourselves:
$ sudo pip install tensorflow
The directory '/home/tex/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/tex/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: tensorflow in /home/tex/.local/lib/python2.7/site-packages
Requirement already satisfied: six>=1.10.0 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: markdown>=2.6.8 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: bleach==1.5.0 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: backports.weakref==1.0rc1 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: html5lib==0.9999999 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: werkzeug>=0.11.10 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: mock>=2.0.0 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: numpy>=1.11.0 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: wheel in /usr/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: protobuf>=3.2.0 in /home/tex/.local/lib/python2.7/site-packages (from tensorflow)
Requirement already satisfied: funcsigs>=1; python_version < "3.3" in /home/tex/.local/lib/python2.7/site-packages (from mock>=2.0.0->tensorflow)
Requirement already satisfied: pbr>=0.11 in /home/tex/.local/lib/python2.7/site-packages (from mock>=2.0.0->tensorflow)
Requirement already satisfied: setuptools in /home/tex/.local/lib/python2.7/site-packages (from protobuf>=3.2.0->tensorflow)

But when I try to import it from python, this is what I get:
$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named tensorflow

Why is this happening? I am also having a much weirder error. I am using flask on a virtualenv. When I start my virtualenv, it does not recognize that numpy is installed, even though it is, and it is recognized outside the virtualenv. Let me show you:
(venv)tex@ubuntu:~/scratch/ilya/mock$ sudo pip install numpy
The directory '/home/tex/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/tex/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: numpy in /home/tex/.local/lib/python2.7/site-packages
(venv)tex@ubuntu:~/scratch/ilya/mock$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named numpy

However, when I exit the virtualenv...
tex@ubuntu:~/scratch/ilya/mock$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>>

⊙_ʘ
Edit: not a possible duplicate because the link posted doesn't address the same issues... so... basically, a completely different question.

A: Just because you source your virtualenv, this doesn't mean the 'pip' command will reference the pip library of the virtualenv. The 'pip' command is more than likely still linked to your default python interpreter.
You can try the following to get it working:
Start by uninstalling both modules:
[root@server] sudo pip uninstall tensorflow
[root@server] sudo pip uninstall numpy

Then source your virtualenv:
[root@server] source ~/venv/activate

Then install the modules using pip whilst explicitly calling the python command:
(venv)[root@server] python -m pip install tensorflow
(venv)[root@server] python -m pip install numpy

Then see if they are available:
(venv)[root@server] python
>> import numpy


text:
Q: Saving the Popup data using jQuery I am having a drop down with "Create New" option. If user clicks "Create New" option then popup window will display with save button. In that popup window, user will enter data and after user will save this data on server.
This is jQuery function for save the data in a popup.

And passing that script like this,
<button runat="server" id="Savefile" class="btn btn-primary" onclick="savefile()">Save </button>

This is the code for jQuery popup:

When user clicks "Save" button then data has to store in that given path. but it is not performing any action. And it is closing automatically when I click "Save" button. Can you please help me to solve this problem.
Any wrong in this code?

A: Try it:

A: You need to pass that data in the ajax function in an order to save it.
  $(document).ready(function () {
                $('#Savefile').click(function () {
                    $.ajax({
                        url: 'D:\C#.Net\Scramble.txt',
                        datatype: "json",
                        data : Your Data to be passed,
                        method: 'post',
                        success: function () {
                            var scrtabledata = $('#modaltable');//Table ID
                            scrtabledata.empty();

                            $(data).each(function () {
                                scrtabledata.append('
' + scrtabledata.comment + '	' + scrtabledata.DropDownList2 + '	' + scrtabledata.DropDownList1 + '
');
                            });

                        }

                     });
                });
            });
        };

here in the data attribute you need to pass your data in json format as key value pair.
var myData={"id":"1","Name":"Test"}

In this way you can form your own JSON and pass it to your ajax function.
You  have to consider like
if
<input type="text" id="userId"/>
<input type="text" id="userData"/>

var userID=$('#userId').val();
var userData=$('#userData').val();
  $(document).ready(function () {
                $('#Savefile').click(function () {
                    $.ajax({
                        url: 'D:\C#.Net\Scramble.txt',
                        datatype: "json",
                        data : {
                                 id:userID,
                                 info:userData
                                 },
                        method: 'post',
                        success: function () {
                            var scrtabledata = $('#modaltable');//Table ID
                            scrtabledata.empty();

                            $(data).each(function () {
                                scrtabledata.append('
' + scrtabledata.comment + '	' + scrtabledata.DropDownList2 + '	' + scrtabledata.DropDownList1 + '
');
                            });

                        }

                     });
                });
            });
        };

Updated


text:
Q: How to Read all anchor tags from Raw html using htmlagilitypack Here is my html string
string htmlData="<!DOCTYPE html><div><a target=\"_blank\" href=\"http://blender.palmbeachschools.org/GetFile.aspx?f=e9bf5637-c5bd-d4ba-3a1e-cf35ecfcad13\" style=\"font-family: Arial, Helvetica, sans-serif; font-size: large;\">Breakdown of Standards by Unit </a><span style=\"font-size: large; font-family: Arial, Helvetica, sans-serif;\"><br></span><br><br><br></div>"

I have to read all the anchor tags from this html. the challenge here is all the anchor tags are not parsed.
I tried using
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmltemp);
var pre = doc.DocumentNode.Descendants("a").FirstOrDefault();

It returned me null.

A:        string htmlData = "First

Second

Third

";
        HtmlDocument doc = new HtmlDocument();

        doc.LoadHtml(htmlData);
        var anchorTags = doc.DocumentNode.Descendants("a");

You can use this code.


text:
Q: Query Facebook Graph using FQL by fetching a url I'm currently trying to us FQL to find the networks of registered users.
According to the documentation, the url fetched should be something along the lines of:
https://api.facebook.com/method/fql.query?query=SELECT affiliations FROM standard_user_info WHERE uid=me()&access_token=tokengoeshere&application_secret=appsecretgoeshere
However, when querying I get Error code 15: The method you are calling must be called with an app secret signed session.
Does anyone know how to fix this?
Thanks.

A: I execute this query by passing my app's access_token (not an access token that associates me with a certain user) and without the app_secret. I get an empty set in response but no error.
Also (just making sure) you will obviously need to URL-escape the query.

A: This usually works
var facebookURL = 'https://api.facebook.com/method/fql.query?query='

var query = 'SELECT bla FROM bla'

var accessToken = 'your access token'

var appToken = '&access_token='+accessToken+'&callback=?'

var url = facebookURL + query + appToken;

A: Query the user table instead.


text:
Q: Fixed position div causes page to be truncated in less common mobile browsers I know there are many similar issues, but this is different to anything I have encountered before, so I thought I would describe the bug here, and offer a solution - and ask if anyone else has a better solution or can shed light on the cause of this weird issue.
The Bug:
In a page that has a div in position:fixed style, in some less common mobile browsers, e.g. Star Safari, DU Browser, Tint Browser - the page loads as expected, and the div is fixed as expected, however if the page height is greater than about 1500px, then the bottom of the page will be truncated - complete white curtain. You can still scroll to the bottom, but it's just white, zero content.
 This bug does NOT happen in more common browsers like chrome, firefox, opera, safari etc..
Here's a screen shot from my phone (HTC M8 - Tint Browser) - also reproduced this bug on Samsung S5.

There are many reasons that you might want a fixed div, in my case it was for a menu button that can follow the viewport, so the visitor doesn't have to scroll back to the top to get the menu.
I have posted a semi-solution bellow, but I will not mark it correct for a week, so hopefully someone else can offer a better solution.
Tim

A: The reason I call this a "semi-solution" for two reasons:
1) This will not keep the div perfectly fixed, but it will elegantly move the div after a scroll event.
2) While this doesn't cause the page to truncate permanently, it does flash the 'curtain' during the opacity transitions. Weird, right?
EDIT: I should mention that this solution looks great in the common browsers (chrom, safari etc...), the flashing curtain will only apply to browsers that would otherwise be truncated with the fixed position div, so although it isn't pretty in some less common browsers, it's still better than the alternative, and is a minor compromise in style for more the common browsers.
This is the code for the menu button example, adapt for your own needs.
HTML Example

CSS
#menuButton {
    position: absolute;
    top:25px;
    left: 25px;
    opacity: 1;
    z-index: 1001;
    transition: opacity .4s ease-in-out;
    -moz-transition: opacity .4s ease-in-out;
    -webkit-transition: opacity .4s ease-in-out;
}

.image {
    width:50px;
    height:50px;
    background-color:red;
}

JavaScript
function menuButton() {
    setTimeout(function () {
        var button = document.getElementById("menuButton").style;
        var pos = document.documentElement.scrollTop || document.body.scrollTop;
        var newPos = pos + 25 + 'px'; // Offset is the start value of the div top position.
        button.opacity = 0;
        setTimeout(function () {
            button.top = newPos;
                    setTimeout(function () {
                        button.opacity = 1;
                    }, 500);
        }, 500);
    }, 800);
}

And here is a jsfiddle


text:
Q: access file path outside application directory in javascript I need to access file (videos) stored somewhere in a server that is accessible via intranet.
I am having trouble fetching and loading the file path.
The file is situated in the same server that is hosting the application though.
Here's what I tried:
<video id="video_player_frame" class="video-js vjs-default-skin" controls preload="none" width="595" data-setup="{}">
  <source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">

Javascript is disabled.

</video>

The one with the public address is working fine (obviously).
But the file path \\192.168.11.32\www\GBD... is not working.
How can I access that file and render it?


text:
Q: How to call a common function effectively whether synchronous or asynchronous function is executed using Promises? I need to call a common function whether synchronous function is invoked or asynchronous function is invoked.
This is how I first wrote but this is not correct as foo will be called before asynchronous function is completed.
function main(element) {
  if (element.id === 'sync') {
    syncFunction();
  } else {
    asyncFunction();
  }
  foo();
}

So, I came up with this but here I feel like I am repeating the call to foo too many times. Is there a better way?
function main(element) {
  if (element.id === 'sync') {
    syncFunction();
    foo();
  } else {
    asyncFunction().then(() => {
      foo();
    });
  }
}

I could use async/await and refactor this even better but where this code eventually will run doesn't support it. Is there a way to better write this using promises?

A: If you put the result of the call into a Promise.resolve(), you can chain .then onto it unconditionally.
function main(element) {
    Promise.resolve((element.id === 'sync' ? syncFunction : asyncFunction)())
        .then(foo);
}


text:
Q: How to set total count of kendo pager manually I've used JayData to load data from OData enabled asp.net web api within following query:
.withInlineCount().filter('it.IsArchived != true').orderBy('it.dVehicle_01').take(6)
As a result, I have an array of entities, that have a property named totalCount which is correct.
Then I'd like to set this results and it's total count for kendo pager datasource.
I could set data, but for totalCount I've tested a lot of options, but I couldn't figure it out.
My data grid should work with both offline and online databases so using kendo ui remote data source is not a suitable option for me.

A: you can set it in the schema configuration,
        schema: {
            total: function (data) {
               return data.totalCount ;
            }
         }

A: you mean that it worked with the old version and stopped working with the recent version ?
with the old version it just worked out of the box: http://jaydata.org/examples/KendoUI/Grid_ReadOnly
if you have to setup paging manually then see this example: http://jaydata.org/examples/KendoUI/ListView

A: I've tested a lot of options before, but within recent kendoUI api changes, we should get an instance of kendo.data.dataSource class instead of using old syntax to provide dataSource to pager.


text:
Q: URLs with no prefixes I wonder if it is possible to access all pages and its detail pages without any extra prefix.
Example:
'''
/vegetables
/carrot -->  (detail page for vegetables)
/fruits
/apple  -->  (detail page for fruits)
'''

Sample URL patterns and I add the views on request.
#urls.py
urlpatterns = [
    path('', views.index, name='index'),
    path('fruits/', views.all_fruits, name='fruits'),
    path('vegetables/', views.all_vegetables, name='vegetables'),
    path('<slug:slug>/', views.fruit_detail, name='fruit'),
    path('<slug:slug>/', views.vegatable_detail, name='vegetable'),
    ]

#views.py
    from .models import Fruit, Vegetable
    def index(request):
        return render (request, 'index.html')

    def all_fruits(request):
        fruits=Fruit.objects.all()
        return render(request, 'fruits.html', {'fruits':fruits})

    def all_vegetables(request):
        vegetables=Vegetable.objects.all()
        return render(request, 'vegetables.html', {'vegetables':vegetables})

    def fruit_detail (request, slug):
        fruit = get_object_or_404(Fruit, slug=slug)
        return render(request, 'fruit_detail.html', {'fruit':fruit})

    def vegetable_detail (request, slug):
        vegetable = get_object_or_404(Vegetable, slug=slug)
        return render(request, 'vegetable_detail.html', {'vegetable':vegetable})

Predictably;  when trying to access the vegetable detail page, gives an error because of using fruit's views.
Thanks in advance for your help and feedback.

A: The thing you are trying to achieve is possible by writting special redirecting view when you look for particular slug firstly in Fruit objects and then in Vegetable objects and add found instance to template context but it is highly inefficient and "dirty". Using standard urls (as you do now) the Django router will not know which slug you are refering to when someone enters for example yoursite.com/xyzabc Django doesnt know if it should look for instance by slug in fruit table or vegetable table. You should continue creating your problem as you do now but I propose you using (in my opinion) more mature solution using Django's generic views. Of course you can use them without deep understanding of Class Based Views but I strongly recommend you using them.
intro
As you probably notices you used the "same" copy/paste code for all your function based views. It's okay nothing wrong with that on a small project but you should always want to make your code flexible, scalable and more importantly easy to refactor/reformat
ListView
is useful when most of your view focuses on rendering a list of objects like your all_fruits and all_vegetables
DetailView
is useful when you want to display template with your particular instance's info. That's exactly what you do in your fruit_detail and vegetable_detail
Your code but written in CBV
views.py
    from .models import Fruit, Vegetable
    from django.views.generic.base import TemplateView
    from django.views.generic.detail import DetailView
    from django.views.generic.list import ListView

    class IndexView(TemplateView):
        template_name = 'index.html'

    # former all_fruits view
    class FruitListView(ListView):
        model = Fruit
        template_name = 'fruits.html'

    class VegetableListView(ListView):
        model = Vegetable
        template_name = 'vegetables.html'

    # former fruit_detail view
    class FruitDetailView(DetailView):
        model = Fruit
        template_name = 'fruit_detail.html'

    class VegetableDetailView(DetailView):
        model = Vegetable
        template_name = 'vegetable_detail.html'

if you look closely into generic views you'd notice you can even skip the template_name part if you build your project tree accordingly to Django's docs

urls.py
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('fruits/', views.FruitListView.as_view(), name='fruits'),
    path('vegetables/', views.VegetableListView.as_view(), name='vegetables'),
    path('fruits/<slug:slug>/', views.FruitDetailView.as_view(), name='fruit'),
    path('vegetables/<slug:slug>/', views.VegetableDetailView.as_view(), name='vegetable'),
    ]

The above anwser shows how it should be done following best Django practices but as we know sometimes clients have special needs for example because of CEO reasons so in order to fully anwser the question here is how to access detail page of multiple models using one route (url).

views.py
# instead of using two views VegetableDetailView and FruitDetalView
# we will use one common view to filter out the needed instance
# Rest of the code stays as in upper answer

...

class FruitOrVegetableDetailView(View):
    def get(self, request, slug, *args, **kwargs)
        try:
            return render(request, 'fruit_detail.html',
                    {'fruit': Fruit.objects.get(slug=slug)})
        except Fruit.DoesNotExist:
            veg = get_object_or_404(Vegetable, slug=slug)
            return render(request, 'vegetable_detail.html',
                    {'vegetable': veg})

of course we need to change routing

urls.py
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('fruits/', views.FruitListView.as_view(), name='fruits'),
    path('vegetables/', views.VegetableListView.as_view(), name='vegetables'),
    path('<slug:slug>/', views.FruitOrVegetableDetailView.as_view(), name='fruit_or_vegetable_detail'),
    ]


text:
Q: GitLab: include branches from a similar project to local repo i am pretty new to GitLab and have a question concerning branches and updating the local repo.
Around two weeks ago i cloned a project and did a bit of work on it (mainly added one branch). Other people also have local repositories of that same project (hope that makes sense). Now I would like to clone only a single branch of one of those local repos made by other people and include it into my local repo.... How do i do this? Ofc I can clone the branch into a different directory, but my goal is only having one directory with only one name in which that branch is contained, so that I can switch between the branches I had from the beginning and the new branch I cloned.
Basically, in order to be more clear: There is a project called a_proj. Me and another person have cloned a_proj and therefore have local repos on which we do work. The other person added a branch called a_branch which I don't have. I want to include a_branch into my version of a_proj.
Additionally i have a different question concerning updating a branch. What if some person does some work on their local version of a branch I also have on my Local and I want to include their changes, or even change my branch to their version. How could I do that?
Thank you a lot for any helpful answers on this topic. If there is constructive critic about this post or the way I think about GitLab I am happy to hear it, as already mentioned, this is a pretty new topic to me and I want to learn wherever i can!

A: Okay, i figured it out. Was pretty easy actually once one knows what to do. For information, i am using GitKraken so it might be different for different environments but essentially the idea is to add the other person's project as remote, (where ones own project should also be a remote named origin). Then one can add any branch of those remotes to the Local project, simply by checking out the wanted branch. It then gets added to the Local repository on which work can be done.
I guess that isn't anything new to anybody who uses GitLab but i'll just leave it here in case some noob (Like me) also has this question.


text:
Q: Python, can I iterate through a list within an if statement? I am trying to edit a str (myString) based on user input str (userInput). There are already a known set of subStrings that myString may or may not contain and are put into a list of str (namingConventionList) that, if any are used in myString should be replaced with userInput. If none of the set of naming conventions are used, I want the userInputadded to myString in a couple of different ways depending on if and where an underscore ("_") is.
Is there a way to iterate through namingConventionList in an if statement?
        if myString.count(conv for conv in namingConventionList):
            myString= myString.replace(conv, userInput))
        elif userInput.startswith('_'):
            myString= '%s%s' % (name, userInput)
        elif userInputConvention.endswith('_'):
            myString= '%s%s' % (userInput, name)
        else:
            myString= '%s_%s' % (name, userInput)

A: This is how I might approach your problem:
for conv in namingConventionList:
    if conv in myString:
        myString = myString.replace(conv, userInput)
        break
else:
    if userInput.startswith('_'):
        myString= '%s%s' % (name, userInput)
    elif userInputConvention.endswith('_'):
        myString= '%s%s' % (userInput, name)
    else:
        myString= '%s_%s' % (name, userInput)

A: success = False
for conv in namingConventionList:
    if conv in myString:
        myString = myString.replace(conv, userInput)
        success = True

if not success:
    if userInput.startswith('_'):
        myString= '%s%s' % (name, userInput)
    elif userInputConvention.endswith('_'):
        myString= '%s%s' % (userInput, name)
    else:
        myString= '%s_%s' % (name, userInput)


text:
Q: c# method first run is slower than after first run I made this code
using UnityEngine;

public class InstanceTest : MonoBehaviour {
public int cnt; public bool startTest1 = false; public bool startTest2 = false;

 void Update()
 {
     if (startTest1)
         Test1(cnt);
     if (startTest2)
         Test2(cnt);
 }
 void Test1(int cnt)
 {
     float a;
     for (int i = 0; i < cnt; i++)
         a = 1f + 1f;
 }
 static void Test2(int cnt)
 {
     float a;
     for (int i = 0; i < cnt; i++)
         a = 1f + 1f;
 }
}

On Profiler
enter image description here
why CPU Time on Update() hiccup when call Test1() and Test2() at first time?

A: There's probably some JIT (Just In Time) compilation happening during the first call of the functions.
The second and subsequent times the functions are called, there's an optimized version of them waiting.


text:
Q: Problems connecting via serial to usb port to PCengines APU board using HL-340 To connect to my APU board via serial line, I bought a QinHeng Electronics HL-340. My operating system is Debian Linux 9.4
What ever I try, I only see junk displayed on screen or the cursor jumping around. PCEngines documentation tells me that their APU boards use 115200 8N1 for their serial console.
https://www.pcengines.ch/ht_com.htm
So I am using that in minicom. Hardware flow control and software flow control are both off.
CTRL-A Z for help | 115200 8N1 | NOR | Minicom 2.7 | VT102 | Offline | ttyUSB0

dmesg
[ 9947.078152] usb 2-1.1: ch341-uart converter now attached to ttyUSB0

lsusb
Bus 002 Device 007: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

I also checked the gender changer cable, and it has pins 2 and 3 swapped.
I also tried it with
cu -l /dev/ttyUSB0 -s 115200

with the same result.
As well as other common baud rates (9600, 19200, 38400, 57600, 115200).
I also tried to modprobe ch341 to load the correct kernel driver but that also did not work.
Removing the module lists
modprobe -vr ch341
rmmod ch41
rmmod usbserial

modprobe -v
insmod /lib/modules/4.9.0-6-amd64/kernel/drivers/serial/usbserial.ko
insmod /lib/modules/4.9.0-6-amd64/kernel/drivers/serial/ch341.ko

What else can I try?


text:
Q: Android: How to load the main activity while on the splash screen I got a splash screen activity and a main activity with webview. It takes 4 to 5 seconds after loading of the main activity which is after the Splash screen, I wanted solution for start loading the main activity parallelly while in the splash screen
Thank you in advance

A: Within splash activity you should create background service to finish time consuming jobs,
then transfer obtained data to main activity using bundle.Thus your main activity will load faster.
There are many ways to complete background tasks,please ref this doc.

A: Have loader on your MainActivity, once everything is loaded, just set loader's visibility to GONE.
No need to use SplashScreen in this case


text:
Q: Python: Speed up re.sub to redact files (multi-processing doesn't help) I need to redact certain words from several thousand files. There's a separate reference file of about 50,000 words that need to be redacted from the files.
With the code I've written, the process is going to take weeks, and I need to make it faster.
import glob, re, sys
from multiprocessing.dummy import Pool as ThreadPool

def redact_file(file):
    with open(file, 'r') as myfile:
        data=myfile.read()

        for word in words_to_redact:
            search_term = r"(?:\b)"+word+r"(?:\b)"
            data = re.sub(search_term, '#', data, flags=re.IGNORECASE)  #this seems to be the slow bit?

    with open(file+'_REDACTED', 'w') as file:
        file.write(data)

if __name__ == "__main__":
    words_to_redact = []
    with open ("words_to_redact.txt") as myfile:    #about 50,000 rows in this reference file
        words_to_redact=myfile.read().splitlines()

    input_files = glob.glob("input_*.txt")

    pool = ThreadPool(multiprocessing.cpu_count())
    pool.map(redact_file, input_files)

Using multi-processing doesn't seem to help.
I think the performance issue comes from calling re.sub 50,000 times for each file.  Because this creates a new copy of the "data" string every iteration, I think the process becomes limited by memory/cache speed.
I think I have to use re.sub because using regEx is the only way to match words.
Is there a way to do re.sub without a copy each time, or some other way to make this faster?

A: *

*use re.compile() to compile your pattern once, and not every time you perform the search

*put all your words into a large pattern.
Then your code might look like this:
import re

words_to_redact = [ 'aa', 'bb', 'cc', etc...] # load 'em from file

patt = re.compile( r"(?:\b)(" + '|'.join( words_to_redact ) + r")(?:\b)" )

patt.sub( .. )  # you know what to do, need to call this only once (no loop)


text:
Q: open external links in new tab, embeded in fancybox popup I am trying to manipulate the following code to open a link in a new tab. Which is embeded in fancybox 1.3.4 popup.  The issue is adding target="_blank" and onclick function gets ignored and causes the link to open in the parent page. I have also tried using javascript void (0) target"_blank" and have managed to leave the page in a new tab however the new page is blank when it appears.
this is the line of the code I am trying to manipulate to leave fancybox and open in a new tab:
$link = ($attachment_meta)? "$image" : $image;

ex: $link = ($attachment_meta)? "$image" : $image; <-- adding target_blank in code
does not work!--

This is a snippet of the code:
if( 'custom' == $attr['link']){
      $image = wp_get_attachment_image($id, $size, false);
      $attachment_meta = get_post_meta($id, '_rt-image-link', true);
 $link = ($attachment_meta)? "$image" : $image;
} else {
      $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
  }

      $output .= "<{$itemtag} class='gallery-item'>";
     $output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
     if ( $captiontag && trim($attachment->post_excerpt) ) {
     $output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
     }
     $output .= "</{$itemtag}>";
     if ( $columns > 0 && ++$i % $columns == 0 )
     $output .= '
';

}


text:
Q: Is it possible to show Evolution Calendar Events in applet or indicator using MATE Panel? As long time Ubuntu user I remembered how this was realized in Ubuntu 12.04 LTS.
It had indicator-datetime and showed calendar events from GNOME Evolution (connected to some CalDav server or used local calendar). The needed applet should look like

(from this Q&A)
How to get this functionality in the modern MATE desktop?

A: It is possible in Ubuntu MATE 18.04 LTS and newer versions.
We need to install indicator-datetime and GNOME Evolution with
sudo apt-get install indicator-datetime --no-install-recommends
sudo apt-get install evolution

Then set up calendar account in Evolution (E-Mail, Contacts and Calendar here) and ensure that the calendar is visible.
Note: if we are running Ubuntu MATE 18.10 or 19.04, then we need to install GNOME Calendar with
sudo apt-get install gnome-calendar --no-install-recommends before proceeding.
Start the indicator manually for the first time with:
systemctl start indicator-datetime.service --user

Then we will see the second clock (provided by indicator-datetime) with calendar in the MATE Panel:

To make it start on every boot we need to add this line to the Startup Applications (mate-session-properties) or set it with programmatical way:
mkdir -p ~/.config/autostart/
cat << EOF > ~/.config/autostart/indicator-datetime.desktop
[Desktop Entry]
Type=Application
Exec=systemctl start indicator-datetime.service --user
Hidden=false
X-MATE-Autostart-enabled=true
Name[en_US]=indicator-datetime
Name=indicator-datetime

EOF

All we need is to rearrange MATE Panel to have single clock and other indicators in place.
Really we need to remove right Clock applet.
The result will look like:

and clock will have the needed calendar.

For Ubuntu MATE 16.04 LTS see other answer with hacky method.


text:
Q: Amazon AWS and Tomcat war file deployment if i have already developed servlet for the Tomcat server, can I use it as is and deploy using the AWS Elastic Beanstalk? Has anybody experience with that?
Thanks,
STeN


text:
Q: Solving differential equation involving Heaviside's unit step function using Laplace Transform $\ddot y(t)+2\dot y(t)+2y(t)=5H(t-2\pi)sint$
Also, $y(0)=1$ and $\dot y(0)=0$
I took the usual approach of solving an initial value problem but things get a bit tricky after the first few steps due to involvement of Heaviside's function.
Any help is appreciated.

A: Try using
$$\mathcal{L}\{H(t-a)g(t)\}=\mathcal{L}\{g(t+a)\}e^{-as}$$

A: Hint:)
\begin{eqnarray*}
&& {\cal L}(y^{\prime\prime})+2{\cal L}(y^{\prime})+2{\cal L}(y)={\cal L}(5H(t-2\pi)\sin t) \\
&& s^2{\cal L}(y)-sy(0)-y^\prime(0)+2\Big(s{\cal L}(y)-y(0)\Big)+2{\cal L}(y)=5\dfrac{e^{-2\pi s}}{s^2+1} \\
&& {\cal L}(y)\Big(s^2+2s+2\Big)=5\dfrac{e^{-2\pi s}}{s^2+1}+s+2 \\
&& {\cal L}(y)=5\dfrac{e^{-2\pi s}}{(s^2+1)(s^2+2s+2)}+\frac{s+2}{s^2+2s+2}
\end{eqnarray*}
Now using partial-fraction decomposition continue!


text:
Q: UDP socket C#.NET I'm using udp socket in .NET;in particular I made a program that,by udp socket,sends image,from picture box,to other program.
This is the code:
this is the listener part where the socket receives image from port 8000
private void Listening()
        {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Loopback, 8000);

            Socket newsock = new Socket(AddressFamily.InterNetwork,
                            SocketType.Dgram, ProtocolType.Udp);

            newsock.Bind(ipep);

            int recv;
            IPEndPoint sender1 = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 6000);

            EndPoint Remote = (EndPoint)sender1;
            byte[] data = new byte[11230];

            recv = newsock.ReceiveFrom(data,ref Remote);

            MemoryStream x = new MemoryStream(data);

            Image y = Image.FromStream(x);

            pictureBox2.Image = y;

         }

this is the sending part where socket sends image
[code]
private void Sending()
        {
            IPAddress host = IPAddress.Parse("127.0.0.1");
            IPEndPoint hostep = new IPEndPoint(host, 8000);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,    ProtocolType.Udp);

            sock.Connect(hostep);

            MemoryStream ms = new MemoryStream();

            pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            sock.Send(ms.ToArray());

          }

Both parts are in the same PC.
My problem is when it's called "Send" function in the "Sending" part it generates exception whit this message:
"The size of the message sent on a datagram socket is larger than the internal message buffer or some other network limit, or the size of the receive buffer of the datagram are lower than those of the datagram itself"
Thanks for your time

A: I would advise you against your current approach. What you are attempting to achieve is not so simple to accomplish in a robust manner. I would advise you to check out the excellent zeromq library that nicely encapsulates raw socket api's and that provides a number of specific patterns to send and receive data.
For the problem that you are describing, the "publish / subscribe" pattern supported by zeromq might be a very good fit.
Zeromq is a crossplatform c library, but good CLR/.NET wrappers are available for it. I would urge you to read this article for example as an introduction: http://www.codeproject.com/Articles/488207/ZeroMQ-via-Csharp-Introduction

A: The error message is pretty straitforward: you are exceeding the limit of message size. In UDP, you send datagrams, not a stream of bytes. In IPv4, you cannot send a UDP datagram larger than 65507 bytes (i.e., 64KiB including IPv4 and UDP headers).
UDP suits well for passing short messages, but for transferring large amounts of data TCP is more preferable.


text:
Q: Getting AttributeError when exporting Heatmap using qgis2web? I want to make a heatmap layer on my webgis.

using these options

but when i'm trying to export it using qgis2web i always get this error.
2019-06-21T10:15:53     WARNING    Traceback (most recent call last):
              File "C:/Users/Rizki Permana/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\qgis2web\maindialog.py", line 323, in previewMap
              preview_file = self.createPreview()
              File "C:/Users/Rizki Permana/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\qgis2web\maindialog.py", line 286, in createPreview
              dest_folder=utils.tempFolder()).index_file
              File "C:/Users/Rizki Permana/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\qgis2web\leafletWriter.py", line 100, in write
              folder=dest_folder)
              File "C:/Users/Rizki Permana/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\qgis2web\leafletWriter.py", line 268, in writeLeaflet
              useVT, useShapes, useOSMB)
              File "C:/Users/Rizki Permana/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\qgis2web\leafletLayerScripts.py", line 88, in writeVectorLayer
              new_obj = heatmapLayer(layer, safeLayerName, renderer)
              File "C:/Users/Rizki Permana/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\qgis2web\leafletLayerScripts.py", line 430, in heatmapLayer
              hmWeightId = layer.fieldNameIndex(hmWeight)
             AttributeError: 'QgsVectorLayer' object has no attribute 'fieldNameIndex'

How do I solve it?

A: There was a bug in qgis2web which caused that error when "weight points by" was set. I've now fixed that in the master branch on the QGIS to web repo at https://github.com/tomchadwin/qgis2web (fix is here: https://github.com/tomchadwin/qgis2web/commit/2efe919378a2fb3077f697d977c4bdf23f0230bf). You can wait for the next release, or install directly from that master branch (instructions are on the repo).


text:
Q: How to get the sum of the product of selected column in a data frame? This is probably very simple but I couldn't think of a solution.
I have the following data frame, and I want to multiply column y with column z and sum the answer.
> df <- data.frame(x = c(1,2,3), y = c(2,4,6), z = c(2,3,4))
> df
  x y z
1 1 2 2
2 2 4 3
3 3 6 4

The value found should be equal to 40.

A: with would be an option here if we don't want to repeat df$ or df[[ to extract the column
with(df, sum( y * z))
#[1] 40

Or %*%
c(df$y %*% df$z)

A: Additionally, you could use data table. The second row after the comma indicates columns (j). You don't need the spaces, they're just there to show how it works.
library(data.table)

a <- data.table(x = c(1,2,3), y = c(2,4,6), z = c(2,3,4))
#dt i    j      by
a[   , sum(y*z),  ]


text:
Q: How to use an exitcode of an executable in an installcondition of a package in WIX I am creating a bundle with several packages. One of these packages needs to be installed if the exit code of an executable has a certain value.
Is it possible to set the install condition of a package based on the exit code of an executable?

A: Burn only runs packages after it's already planned what to do with all of them. So no, you can't run an ExePackage and use its exit code to change the plan for another package. If you write a custom bootstrapper application, you could run an .exe, capture its exit code, and use it in the plan.

A: You may be able to use Burn Bootstrapper - part of the WIX toolkit:
Wix Burn: How to stop Bootstrapper from installing itself


text:
Q: Android TeeChart Line Chart Touch Sensitivity I realized that the Line Chart Drag Point is not really sensitive and it is difficult to select a point to drag. Aside from that, occasionally might trigger the wrong point. I wanted to ask is there workaround can solve this issue? I checked the example code the DragPoint basically selects the entire Line but not the point (I guess?). Other than that, TeeChart is a great library for charts!  Any comments and answers will be highly appreciated.
        Line seriesLine;
        seriesLine = new Line(chart.getChart());
        seriesLine.fillSampleValues(5);
        SeriesPointer tmpPointer = seriesLine.getPointer();
        tmpPointer.setInflateMargins(true);
        tmpPointer.setVisible(true);
        tmpPointer.setVertSize(10);
        tmpPointer.setHorizSize(10);
        DragPoint toolDragPoint;
        toolDragPoint = new DragPoint(seriesLine);
        toolDragPoint.setStyle(DragPointStyle.BOTH);

A: You are right. It seems the pointer isn't clickable&draggable.
I've found the fix for the problem here also fixes this. So I've applied the same fix for the Java version.
This will be available with the next maintenance release.


text:
Q: Hierarchical data copy I have a master table like below in parent child relation having more than 2000 record
Table Name : MasterTable
Id     ReqId       Title                  ParentId
---------------------------------------------------
1      AC1.        Account Control.       null
2      Ac1-1.      account c.             1
3      Ac1-1-1.    account c.             2

Another table is Child table where I need to copy data in same hierarchy as below
TableName: ChildTable (sample data after copy)
Id     ReqId             Title                  ParentId    MasterTableId
--------------------------------------------------------------------
101    AC1.              Account Control.       null           1
102    Ac1-1.            account c.             101            2
103    Ac1-1-1.          account c.             102            3

what I have tried is first inserted the data using insert into... select statement then update the parent id using join with master table and self join but this query takes 2 -5 sec to update.
I have used following query to update the parent Id
insert into ChildTable(ReqId,Title,ParentId,MasterTableId)
select ReqId,Title,null,Id from MasterTable

After insertion I am updating the parent id of Child table
UPDATE TSR1
set ParentId = TSR2.Id
from ChildTable TSR1
JOIN MasterTable SR ON TSR1.MasterTableId = SR.Id
JOIN ChildTable TSR2 ON TSR2.MasterTableId = SR.ParentId
WHERE SR.ParentId IS NOT NULL

Can anyone suggest an efficient query for above copying of data?


text:
Q: Show data from nested NSMutableArrays and NSDictionarys I have an array filled with dictionaries in a plist:

The dictionary itself contains an array, keyed by Taskitler. I want to show the items in that array in a table view. What should I write to see them? How can I define my data paths?
This code doesnt work:
cell.textLabel.text = [[mainList objectAtIndex:indexPath.row] objectForKey:@"Urun"];

A: You traverse items in an NSArray using objectAtIndex, and you traverse or seek objects in an NSDictionary using objectForKey:
NSArray *root = // ... root object
NSDictionary *dict = [root objectAtIndex:0]
NSArray *task = [dict objectForKey:@"Tasksitler"];
NSDictionary *taskdict = [task objectAtIndex:0];
NSString *urun = [taskdict objectForKey:@"Urun"];

A: The easiest way to do it is this. The code below takes advantage of the subscripting syntax in Objective-C.
NSArray *root = // root object
NSString *urun = root[0][@"Tasksitler"][0][@"Urun"];

Explanation:
myArray[index] is equivalent to [myArray objectAtIndex:index].
myDictionary[@"key"] is equivalent to [myDictionary objectForKey:@"key"].
You can see which is shorter and easier to understand.


text:
Q: How can I have a Discord bot await my message? I'm making a simple discord bot, this is my first time doing so. I want the Discord bot to await my message before continuing but I can't seem to get this to work.
How can I have the Discord bot wait before continuing on? Also, I know my "throw new Error"'s might not be super correct; I wasn't sure of another way to stop the run.
Any help is greatly appreciated! Thank you so much!
Code:
const Discord = require('discord.js');

module.exports = class NewgameCommand extends BaseCommand {
  constructor() {
    super('newgame', 'managment', []);
  }

  async run(client, message, args) {
    if (!message.member.roles.cache.some((r) => r.name === "staff")) {
      return message.channel.send("Only staff members can set up games!");
    }
    const gameEmbed = new Discord.MessageEmbed()
      .setTitle('New MvM Mondays Game!')
      .setDescription('Add description here.')
      .setColor("#FF0000")
      .setTimestamp();
    const twoCitiesMissionsDisplayed = "\`\`\`\n1 - Empire Escalation\n2 - Metro Malice\n3 - Hamlet Hostility\n4 - Bavarian Botbash\`\`\`";
    const twoCitiesMissionsArray = ['Empire Escalation', 'Metro Malice', 'Hamlet Hostility', 'Bavarian Botbash'];
    const numOfMissions = [1, 2, 3, 4];
    message.channel.send("What Two Cities mission?");
    message.channel.send(twoCitiesMissionsDisplayed);
    message.channel.awaitMessages(m => m.author.id == message.author.id,
      {max: 1, time: 30000}).then(collected => {
        const chosenMission = collected.first().content;
        if (!numOfMissions.includes(chosenMission)) {
          message.channel.send("You chose an invalid number!");
          throw new Error("Chose invalid mission number");
        }
      }).catch(() => {
        message.channel.send('No answer after 30 seconds, operation canceled.');
        throw new Error("Took too long to respond.");
      });
    message.channel.send("Default classes? (yes/no)");
    message.channel.awaitMessages(m => m.author.id == message.author.id,
      {max: 1, time: 30000}).then(collected => {
        const classesAnswer = collected.first().content;
        if (!numOfMissions.includes(collected.first().content)) {
          message.channel.send("All you had to do was say \"yes\" or \"no\"...");
          throw new Error("Didn't say \"yes\" or \"no\"");
        }
      }).catch(() => {
        message.channel.send('No answer after 30 seconds, operation canceled.');
        throw new Error("Took too long to respond.");
      });
  }
}

What I see in Discord:

A: We can detect timeouts using the catch block of the awaitMessages promise. Then, we can make it emit an error after timeout. Here is an example.
function filter(m){
    if(m.author.id != message.author.id) return false;
    if (!numOfMissions.includes(chosenMission)) {
        m.channel.send('You chose an invalid number!');
        return false;
    }
    return true;
}
message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] })
    .then(collected => {
        const chosenMission = collected.first().content;
        message.channel.send(`You chose the ${chosenMission} mission`);
    })
    .catch(() => {
        message.channel.send('No answer after 30 seconds, operation canceled.');
    });

As you can see, I included the valid-number-check in the filter. This can allow the message collector not to end even if an invalid number is entered.
Also, I included errors: ['time'] in the options of the awaitMessages() function. This tells the function to throw an error when the time is up (30 seconds in this case), and the error will cause the code to fall in the catch block of the promise.


text:
Q: Categorical and Numerical Features - Correlation I am working with a dataset that has both numerical and categorical features. I have seen this post which discusses the problem in R, and was wondering if someone could recommend the same in Scikitlearn
I am trying to find the best way to examine the correlation among all of the features in my dataset. Currently, I am only able to see the numeric features, for example, using the seaborn library,
 c = data.corr()
 sns.heatmap(c, annot=True, cmap='Greens')

Thank you in advance

A: You can try pandas.factorize to get the numerical representation of the categorical variables. Then you can use data.corr() to get the correlation among all the features(numerical and categorical).
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html
You might want to read this post "The search for categorical correlation by Shaked Zychlinski" on towardsdatascience blog, https://towardsdatascience.com/the-search-for-categorical-correlation-a1cf7f1888c9
I hope this helps.


text:
Q: Use sequentially promise to run some ajax requests in Javascript and jQuery I have steps array like:
var stepsToDo = [step1, step2, step3,...]

every step does ajax call:
function step1() { return $.ajax({ ... }); }
function step2() { return $.ajax({ ... }); }

The sample ajax call for step 1 (step 2 and others are similar):
return $.ajax({
            url: "test.php",
            type: "POST",
            dataType: "json",
            data: {"step-1": ""},
            beforeSend: function () {
                writeResult("Processing-> test 1");
            },
            success: function (result) {
                if (result) {
                    if (result instanceof Array) {
                        writeResult("Found: " + result.length + " items");
                        arr = result;
                    } else {
                        writeResult(result);
                        arr = [];
                    }
                }
            }
        });

function writeResult(str)  { console.log(str); }

I want to execute sequentially (defined in stepsToDo).
I tried like:
stepsToDo.reduce(
    (promise, method) => {
        return promise.then(method);
    },
    Promise.resolve()
);

Nothing happens, no print in console happens.
Why ?

A: Drop the new Promise. Your steps are functions that return promises, not promise executors - they never would call a resolve callback passed into them.

A: For the reducer function you initially created...
stepsToDo.reduce((promise, method) => {
    return promise.then(_ => new Promise(method));
}, Promise.resolve());

...your step functions should resolve or reject the promises created in your reducer - therefore should implement the promise executor signature, I.E:
type executor = (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void;

For example:
function step1(resolve, reject) {
    $
        .ajax({ /* ... */ })
        .done(resolve)
        .fail(reject);
}

EDIT
As @Bergi states in the comments, this is an anti-pattern. Instead you could move the Promise construction into your step functions. A basic example (the jQuery ajax API still has to be converted to promises)
function step1() {
    return new Promise((resolve, reject) => {
        $.ajax({ /* ... */ }).done(resolve).fail(reject);
    });
}

If all your steps return you promises your reducer can get much simpler:
stepsToDo.reduce((promise, method) => promise.then(method), Promise.resolve());

You could in this case even just return the result of $.ajax, since jQuery promises do implement a then method:
function step1() {
    return $.ajax({ /* ... */ });
}

If a native promise is required for error handling, i.e. Promise.catch, you can explicitly cast the jQuery promise to a native promise with Promise.resolve:
function step1() {
    return Promise.resolve($.ajax({ /* ... */ }));
}

A: I'm not sure what's wrong with the other answers but $.get (or ajax or post) will return a promise like.
So your step methods can look like this:
var stepOne = () => {
  return $.ajax({//just return the promise like
    url: "test.php",
    type: "POST",
    dataType: "json",
    data: {"step-1": ""}
  });
}

You can then reduce it to one promise that resolves with the results of the three steps:
[stepOne,stepTwo,stepThree].reduce(
  (p,fn)=>
    p.then(
      results=>fn().then(result=>results.concat([result]))
    ),
  $.Deferred().resolve([])
)
.then(
  results=>console.log("got results:",results),
  err=>console.warn("Something went wrong:",err)
);

You see I don't pass Promise.resolve as second argument to reduce but $.Deferred().resolve([]), this is jQuery promise like value. You can now support browsers that don't have native promises without the need to polyfill.
Although if you need to support those I'd recomment not using the arrow function syntax and use function(something){return something} instead of something=>something

A: There most be something missing from the original question or the implementation. If all the step functions return the$.ajax promise then the Array.reduce pattern should work.
Below is a working prove of concept using a step() function to simulate the asynchronous code execution and using the exact same Array.reduce pattern:

// Step generator
function step(number) {
  return function() {
    return $.Deferred(function(def) {
      setTimeout(function() {
        console.log('Running Step ', number);
        def.resolve();
      }, Math.floor(Math.random() * Math.floor(250)));
    }).promise();
  }
}

// List of steps
var stepsToDo = [step(1), step(2), step(3), step(4), step(5)];

// Consume steps one at a time
stepsToDo.reduce(
  (promise, method) => {
    return promise.then(method);
  },
  Promise.resolve()
).then(() => console.log('All Done!'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: Storing api keys I am using the Goodreads api to get book data for my react native app. I have to use a key for using the api. Is it OK for me to store the api key on the app itself or should I put the key on a server that redirects all the data to the app?

A:
Is it OK for me to store the api key on the app itself

No, because as I demonstrate in the article How to Extract an API Key from a Mobile App by Static binary analysis it can be extracted with the help of several open source tools, like by using the Mobile Security Framework, but you can also grab the API key with a MitM attack, as I show in the article Steal that API Key with a Man in the Middle Attack, that uses the open source tool MiTM Proxy.
If you leave a third party API key in the mobile app, then they are up for grabs from attackers, and when they start using it without your knowledge your bill in the third party provider may go through the roof before you acknowledge that something is wrong, and on that time the only solution is to revoke the API key, thus shutting down the use of the mobile app, and if you make a new release of your mobile app with a new API key it will be just a matter of hours until the attacker come back and steal the API key again.

or should I put the key on a server that redirects all the data to the app?

Yes, and this is a good approach, because now you have only one place to store and protect all third part API keys. This have the benefit to let you control and throttle the use of them as you see fit.
With this solution you still need an API key in your mobile app to allow access to your API server, but while you continue vulnerable for attackers to steal it, you are now in direct control of throttling the access to your API server and if you identify in each access the WHO and the WHAT is accessing the API server, then you have a more fine grade control, but attacker will continue to be able to slip between all our defenses, because is very hard to know WHAT is accessing the API server.
You may be thinking by now... do you mind to explain the WHO vs the WHAT?
The Difference Between WHO and WHAT is Accessing the API Server
To better understand the differences between the WHO and the WHAT are accessing an API server, let's use this picture:

The Intended Communication Channel represents the mobile app being used as you expected, by a legit user without any malicious intentions, using an untampered version of the mobile app, and communicating directly with the API server without being man in the middle attacked.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using a repackaged version of the mobile app, a hacker using the genuine version of the mobile app, while man in the middle attacking it, to understand how the communication between the mobile app and the API server is being done in order to be able to automate attacks against your API. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.

While user authentication may let the API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, the original version of the mobile app.
Now we need a way to identify WHAT is calling the API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of the mobile app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman?
For your surprise you may end up discovering that It can be one of the legit users using a repackaged version of the mobile app or an automated script that is trying to gamify and take advantage of the service provided by the application.
Well, to identify the WHAT, developers tend to resort to an API key that usually they hard-code in the code of their mobile app. Some developers go the extra mile and compute the key at run-time in the mobile app, thus it becomes a runtime secret as opposed to the former approach when a static secret is embedded in the code.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?, and that you can read in full here, that is the first article in a series of articles about API keys.
Your problem is not solved yet
Now that you know the difference between WHO and WHAT is accessing your API server you must have realized that your API server is still vulnerable to be abused by attackers.
You can resort now to employ several layers of defense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:

reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.

WAF - Web Application Firewall:

A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.

UBA - User Behavior Analytics:

User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.

All this solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.
Regarding APIs serving mobile apps a positive identification model can be used by using a Mobile App Attestation solution that guarantees to the API server that the requests can be trusted without the possibility of false positives.
Mobile App Attestation
Use a Mobile App Attestation solution to enable the API server to know is receiving only requests from a genuine mobile app.
The role of a Mobile App Attestation service is to guarantee at run-time that your mobile app was not tampered or is not running in a rooted device by running a SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
Now the App must sent with every API call the JWT token in the headers of the request. This will allow the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Once the secret used by the Mobile App Attestation service is not known by the mobile app, is not possible to reverse engineer it at run-time even when the App is tampered, running in a rooted device or communicating over a connection that is being the target of a Man in the Middle Attack.
The Mobile App Attestation service already exists as a SAAS solution at Approov(I work here) that provides SDKs for several platforms, including iOS, Android, React Native and others. The integration will also need a small check in the API server code to verify the JWT token issued by the cloud service. This check is necessary for the API server to be able to decide what requests to serve and what ones to deny.
Summary
Anything that runs on the client side and needs some secret to access an API can be abused in different ways and you must delegate the access to all third part APIs to a backend under your control, so that you reduce the attack surface, and at the same time protect their secrets from public pry eyes.
In the end, the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.

A: For react native use react-native-config library. While using this library you can secure your api keys as well as you can save more secret keys which use in the native code. Like we can save onesignal, codepush etc keys.
https://github.com/luggit/react-native-config

A: Store them in a .env file like this API_KEY=yourKey.
Install npm package react-native-dotenv.
Then import to to files as needed with react-native-dotenv package;
import { API_KEY } from 'react-native-dotenv'
The .env file should never be committed to Github.


text:
Q: Lua - Saving data to array in for loop in my lua program, I want to check the sides for a redstone input (using a for loop to check).
the last few lines are ment to print out ther result of the array, as a debug tool. the output is the side name followed by 0 (a true/false is expected). the data will be used later in the program.
thank you.
http://www.pastebin.com/0innMjcP
function array()
  a = {}
  for i=1, 6 do
    a[i] = {}

    for j=1, 2 do
      a[i][j] = 0
    end
  end
  a[1][1]= "front"
  a[2][1]= "back"
  a[3][1]= "left"
  a[4][1]= "right"
  a[5][1]= "top"
  a[6][1]= "bottom"
end

array()

for i=1, 6 do
  input=redstone.getInput(a[i][1])
  if input=="true" then
    a[2][2]="true"

  elseif input=="false" then
    a[3][2]="false"
  end
end
for i=1, 6 do
  print(a[i][1])
  print(a[i][2])
end

A: From the manual of redstone.getInput(), it returns a boolean, not a string, so this line
if input == "true" then

should be
if input == true then

The same for the elseif part.


text:
Q: Showing particular area from a texture by passing some points - OpenTK Using below shader code, I can show an image as it is. Now I want to show the portions of image in a way that :
I have three GLcontrols.
First glcontrol should show the first portion of one by third part of image in a curved shape as shown in image. So I have to pass three points L1,L2,L3 and should show those connected area on it.
And  the second glcontrol should show the last portion of one by third part of image in a curved shape. For that I have to pass the points R1,R2,R3.
And the third glcontrol should show the remain center portion of image.
 public void CreateShaders()
    {
        /***********Vert Shader********************/
        vertShader = GL.CreateShader(ShaderType.VertexShader);
        GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                                varying vec2 vTexCoord;
                                void main() {
                                vTexCoord = (a_position.xy+1)/2 ;
                                gl_Position = vec4(a_position, 1);
                                }");
        GL.CompileShader(vertShader);

        /***********Frag Shader ****************/
        fragShader = GL.CreateShader(ShaderType.FragmentShader);
        GL.ShaderSource(fragShader, @"precision highp float;
        uniform sampler2D sTexture;
        varying vec2 vTexCoord;
        uniform int sCurrentGLControl;
        uniform int L1;
        uniform int L2;
        uniform int L3;
        uniform int R1;
        uniform int R2;
        uniform int R3;
        void main ()
         {
        vec4 color;
        if(sCurrentGLControl==1) //first half
        {
         color = texture2D (sTexture, vec2(vTexCoord.x, vTexCoord.y));
        }
        else if(sCurrentGLControl==2) //third half
        {
         color = texture2D (sTexture, vec2(vTexCoord.x, vTexCoord.y));
        }
        else if(sCurrentGLControl==3) //second half
        {
          color = texture2D (sTexture, vec2(vTexCoord.x, vTexCoord.y));
        }
        gl_FragColor =color;

         }"); GL.CompileShader(fragShader);

A: Assuming the yellow dots are not relevant, and you are actually sampling from L1,L2,L3,R3,R2,R1 to create a double trapezoid shape, yes you will be able to map this to a curved surface or warped on a flat surface (going along the yellow dots would need more than 6 vertices). It's probably more difficult to write your shader to handle this, so instead pass in different uv coordinates to the shader from the rest of your program. So lift the GLControl related code out of shaders, and use it to determine draw calls with different buffered vertices (different vTexCoord).


text:
Q: How to skip appending some condition in map scala? I have a situation in which I need to create a map from a collection by applying some filter inside like given in the code below:
//Say I have a list
//I don't have to apply filter function ...

val myList = List(2,3,4,5)

val evenList = myList.map(x=>{
if ( x is even) x
else 0
}
//And the output is : List(2,0,4,0)
//The output actually needed was List(2,4) without applying filter on top like - ```myList.filter```
//I have objects instead of numbers of a case class so the output becomes :List(object1, None, object2, None)
But actual output needed was : List(object1,object2)

//The updated scenario
val basket = List(2,4,5,6)
case class Apple(name:Option[String],size:Option[Int])

val listApples: List[Apple] = basket.map(x=>{

  val r = new scala.util.Random
  val size = r.nextInt(10)

  if(x%2!=0){
    Apple(None,None)
  }
  else Apple(Some("my-apple"),Some(size))
})

Current Output :
Apple(Some(my-apple),Some(2))
Apple(Some(my-apple),Some(0))
Apple(None,None)
Apple(Some(my-apple),Some(4))

Expected was :
Apple(Some(my-apple),Some(2))
Apple(Some(my-apple),Some(0))
Apple(Some(my-apple),Some(4))

A: I believe collect best suits your case. It takes a partial function as an argument and only if that function matches then the element is transformed and added to result:
val myList = List(2,3,4,5)

case class Wrapper(i: Int)

val evenList = myList.collect{
  case x if x % 2 == 0 => Wrapper(x)
}

In this case only 2 and 4 will be wrapped inside Wrapper:
List(Wrapper(2), Wrapper(4))

A: I'm not sure if I understand you correctly, but why not just use a filter directly:
val myList = List(2,3,4,5)

myList.filter(_ % 2 == 0)

If you want to have the Filter as a function:
def even(n:Int) = n % 2 == 0

myList.filter(even)

After question update, here the difference between filter and collect:
Filter:
  myList
    .filter(even)
    .map(s => Apple(Some("my-apple"),Some(s)))

Collect:
myList
    .collect{ case s if(even(s)) => Apple(Some("my-apple"),Some(s))}

Both return List(Apple(Some(my-apple),Some(2)), Apple(Some(my-apple),Some(4)))
So the only difference is that you can do both steps at once with collect.
However for me to separate these 2 steps is mostly more readable.