text:
Q: When would be occasions to use a lower clock given that high speed would always be preferable? I am using STM32F0 MCU and STM32 CubeMX configurator. I encountered the clock configuration below

When would be occasions to use a lower clock speed? Wouldn't faster always be preferable?

A: Lower clock frequency means lower consumption. As soon as you don't have infinite power, i.e. a wall outlet, every mA will count toward your battery life, and of course all this power will be turned into waste heat that you might have to deal with.
Processing events as fast as possible, then putting the controller to sleep/standby would be another possibility to achieve lower average consumption, but it could also introduce some unpleasant spikes and emissions that are simply not there when running at a slower speed. Waking up from sleep, and waiting for the clocks to stabilize takes some time too.
Some peripherals might perform better at lower speeds, e.g. if your flash needs wait states above 32 MHz, then running code at 48 MHz might actually be slower than at 32 MHz.

A: The microcontroller draws more power when running at higher clock speeds. In battery-powered devices, running at a lower speed may improve battery life.
Additionally, many peripherals derive their clocks from core clocks; the requirements of those peripherals and the devices they're connected to may place requirements on core clock speeds. (To give a specific example: The USB peripherals on certain STM32 microcontrollers require that a 48 MHz clock be available. If the core clock is not a multiple of 48 MHz, this isn't possible.)


text:
Q: Dynamic numberpicker android does not work I'm looking for instantiate dynamically a numberpicker. I want to place a value (kitQty - YourQty) in numberpicker order.
The next code is now working but only for the last one Id=9.
Because this only working with the last record?
Try setTag and setId and I can not change the numberpicker that desire. Anyone know what may be wrong in my code?
Thank you very much!
 public class MyKits extends Fragment {

private Button performAudit;
private Button submitOrder;
NumberPicker yourQty;
NumberPicker kitQty;
NumberPicker order;
Conexion basedatos;

@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
 savedInstanceState) {

View v = inflater.inflate(R.layout.fragment_mykits, container, false);
Context context=v.getContext();

basedatos=new Conexion(v.getContext());

TextView tvModel = (TextView) v.findViewById(R.id.tvModel);
TableLayout table= (TableLayout) v.findViewById(R.id.Tabla);
tvModel.setText(getArguments().getString("model"));

for(int i=0;i<10;i++)
{
    TableRow tR = new TableRow(v.getContext());
    LinearLayout l1= new LinearLayout(v.getContext());
    LinearLayout l2= new LinearLayout(v.getContext());
    LinearLayout l3= new LinearLayout(v.getContext());
    LinearLayout l4= new LinearLayout(v.getContext());
    Button item = new Button(v.getContext());

    kitQty = new NumberPicker(getActivity().getApplicationContext());
    yourQty= new NumberPicker(getActivity().getApplicationContext());
    order= new NumberPicker(getActivity().getApplicationContext());

    item.setText("Prueba Imparjdsbfjbdsjfgbijsdfgijnsfdignsidfgh");

    l1.addView(kitQty);
    l2.addView(item);
    l3.addView(yourQty);
    l4.addView(order);

    ///Tamaño Texto
    item.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    kitQty.setMaxValue(100);
    kitQty.setValue(50);
    kitQty.setMinValue(0);
    kitQty.setEnabled(false);
    order.setMinValue(0);
    order.setMaxValue(kitQty.getMaxValue());
    yourQty.setMaxValue(kitQty.getMaxValue());
    yourQty.setMinValue(0);
    yourQty.setTag(i);
    yourQty.setId(i);
    order.setTag(i);
    order.setId(i);
    kitQty.setTag(i);
    kitQty.setId(i);

   yourQty.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            Log.e("oldValue: " + oldVal + "   ID:     " + picker.getId(), "   newVal: " + newVal + "   ID: " + picker.getTag());

            kitQty.setId(picker.getId());
            yourQty.setId(picker.getId());
            order.setId(picker.getId());
            order.setValue(kitQty.getValue() - yourQty.getValue());

        }
    });

    order.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            Log.e("oldValue: " + oldVal + "   ID:     " + picker.getId(), "   newVal: " + newVal + "   ID: " + picker.getTag());

        kitQty.setTag(picker.getTag());
        yourQty.setTag(picker.getTag());
        order.setTag(picker.getTag());
        order.setValue(kitQty.getValue() - yourQty.getValue());

           // calcularQty(picker);
        }
    });

    tR.addView(l1);
    tR.addView(l2);
    tR.addView(l3);
    tR.addView(l4);
    table.addView(tR);

}

return v;}
public static MyKits newInstance(String model) {

MyKits f = new MyKits();
Bundle b = new Bundle();
b.putString("model", model);

f.setArguments(b);

 return f;} }

A: Well, there are a few things wrong in your code...
But let's just focus on the main question in saying first that you should not assign id by yourself. I'd rather either inflate each of them with a granular xml layout file, or if you insist on creating your widgets using "new", then leave the id alone and Android should assign them properly.
But really the main reason why your code don't work is that you assign widget ids in a "for" loop with your counter variable (i) and you are using the same value as an id for order widget, yourQty widget and kitQty widget. You need to understand that each widget id must be unique in the same view hierarchy. First start by fixing this issue. But I won't tell you how: you should be able to fix this by yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS How to reload then redirect to another view? I'm trying to make some button disappear when I logout, but if I don't put reload command It won't reload and button wouldn't disappear. After I put reload command view doesn't change because the process end at reload line.
Here my code :
$scope.logout = function(){
    deleteCookie("Username","/");
    location.reload();
    $location.path('/view1');

}

Please help !
UPATE: app.js
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.viewLogin',
  'myApp.SaveCafeDetail',
  'myApp.viewUserprofile',
  'myApp.viewManageuser',
  'myApp.viewEditcafe',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

A: You can use absolute url or just add target="_self" on your <a> tag, if you use it in your HTML.

A: I suggest this approach..
     $scope.logout = function(){
     deleteCookie("Username","/");

        if (-----)  {   //deletecokkie value is null
       window.location = "http://.../..."  //full URL of the designation;
          }

    }

A: To reload to another view, simply use:
$state.go("your_view_name");

Hope this helps!


text:
Q: Toggle, change html and reset form I'm relatively new to JQuery, but I'm pretty sure this is possible...
Add Item

<form id="theForm" class="hidden">
(form inputs)
Cancel
<input type="submit">

Add an Item

If you click formLink1 or formLink3 above:

*

*the form should display

*formLink1 should have the text change to "Cancel" and the link should be set to do a "cancel" action

Clicking on either formLink2, or formLink1 when the form is open (and it shows "cancel" would:

*

*reset the form fields to blank
(they're all text)

*hide the form

*toggle formLink1 back to it's original text.

I've been trying a combination of .toggle() to flip it, and then .html() to write the changed text but no luck.
Can't find a search that matches close enough to what I'm doing that makes sense.

A: http://jsfiddle.net/ftDL8/ - DEMO
// switch your anchors to use classes. A href isn't a good idea, and a class
// allows us to select the multiple elements easier
$('.addItem').click(function(e){
    // if it's not already visible, show the form
    $('#theForm:not(:visible)').show();

    // prevent the anchor from firing
    e.preventDefault();
});

// again, anchor with the class
$('.cancelItem').click(function(e){
    // locate the form
    var $form = $('#theForm');

    // fire the native reset (bring all elements back to default values
    $form[0].reset();

    // now hide it
    $form.hide();

    // prevent the anchor from firing
    e.preventDefault();
});

// start off with the form hidden (using code)
$('#theForm').hide();

The HTML:
Add an Item

<form id="theForm">
    <input type="text" value="Original Content" />

    <input type="text" value="Default Value" />

    Cancel
</form>

Add an Item

A: First, change the <a name= bit to <a id=. The name attribute is a deprecated attribute originally used to do anchor links. It was replaced by the id attribute.
Then:
$('#formLink1').click(function(){
    $a = $(this);
    if ($a.text() == 'Add Item') {
        $('#theForm').show();
        $a.text('Cancel');
    } else {
        $('#theForm').hide();
        $a.text('Add Item');
    }
    return false;
});


text:
Q: Syncing Windows 2012 time to Windows 7 I have one Windows 2012 server and one Windows 7 computer, none of them are running Active Directory.
I want the Windows 2012 server to sync its clock with the Windows 7 computer (the Windows 7 computer has correct clock, the Windows 2012 computer has wrong clock).

A: Some bad advice is given in the Superuser answer linked in the comments. There is absolutely no reason to setup a domain to only get time sync working. It would be pointless to setup a virtual environment to run a NTP server.
Windows Time Service is automatically working in domain mode and in those cases you should be very carefully when playing around as it has special algorithms to choose the best time source.
When not in a domain the Windows Time Service is using NTP to set time against time.windows.com.
You can change that with the command:
w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:MANUAL

Change pool.ntp.org to your local IP address of your  NTP server.
The Windows Time Service can furthermore act as a NTP server. This is done by a setting in the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer

Change Enabled from 0 to 1 and restart the service (or server).
Be sure to open for incoming UDP on port 123 on your NTP server (and other firewalls inbetween).
Windows Time Service have an accuracy of 1 - 2 seconds. If you need to be more precise than this then you should use a third party service.


text:
Q: How to check if every properties in an object are null I have an object, sometimes it is empty like so {} other times it will have properties that are set to null.
{
  property1: null,
  property2: null
}

How can I determine if ALL the properties within this object is null?
If they are all null then return false.
At the moment I'm using lodash to check for the first case where the object is simply {} empty. But I also need to cover the second case.
if (isEmpty(this.report.device)) {
  return false;
}
return true;

A: Approach using .some() instead of .every():
function isEmpty (obj) {
    return !Object.values(obj).some(element => element !== null);
}

This function (named isEmpty to match the name given in the question) shall return false if any obj property is not null and true otherwise.

A: You can use the Object.keys() method this will return all keys in that Object as an Array. This makes it possible to do Object.keys(this.report.device).filter(key => !this.report.device[key] === null), which will return you the amount of not null keys, if this is 0 then you have your answer.
In essence relying on null properties is not such a good approach it's better to make those properties undefined or just to return a flat Object from your API.
Hope this helped.

A: You can use Object.values to convert the object into array and use every to check each element. Use ! to negate the value.

let report = {
  property1: null,
  property2: null,
}

let result = !Object.values(report).every(o => o === null);

console.log(result);

An example some elements are not null

let report = {
  property1: null,
  property2: 1,
}

let result = !Object.values(report).every(o => o === null);

console.log(result);

Doc: Object.values(), every()

A: This is very simple and can be done with a one liner !
function IsAllPropertiesNull(obj) {
 return Object.values(obj).every(v=>v == null);
}

a = {'a': null, 'b':null};
var isAllNull = IsAllPropertiesNull(a)
// isAllNull = true

explanation -
get all values of object - iterate them and check for null
Good luck!

A: Use Object.entries and Array.every

let obj = {
   property1: null,
   property2: null,
};

function isEmpty(o) {
  return Object.entries(o).every(([k,v]) => v === null);
}

if(isEmpty(obj)) {
   console.log("Object is empty");
}

A: In order to check if object has null value for all the keys. One cleaner approach could be.
const set = new Set(Object.values(obj));
const hasOnlyNullValues = set.size === 1 && set.has(null);

A: For Es2015
if (Object.keys(obj).map(e => obj[e]).every(a => a.length === 0)) {
  console.log('all are empty');
}


text:
Q: calling function that is in the parent page from inside an iframe I have deployed an app that is using iframes.
In one of the pages I have called parent.functionname()
The problem is, this application is shown in an iframe in a different domain.
So this line parent.functionname() is trying to call the main iframe's function which is not possible due to cross domain security policy.
How can i have this parent.functionname() call the function that is in the main home page of my application?
I need not access function in the parent iframe that is in the other domain, but I need to specify that the function is in immediate iframe and not the iframe containing that


text:
Q: Cmake/Ctest test failure when initializing googletest I am trying to integrate Ctest and googletest in my project. I included googletest in my project as described in https://crascit.com/2015/07/25/cmake-gtest/.
I created a new test folder with a CoreTest.cpp and a CMakeLists.txt. The CMakeLists contains:
ADD_EXECUTABLE(CoreTest CoreTest.cpp)
TARGET_LINK_LIBRARIES(CoreTest corelib gtest gmock)
ADD_TEST(NAME CoreTest COMMAND CoreTest)

CoreTest.cpp contains:
int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    //return RUN_ALL_TESTS();
    return 0;
}

This fails:
1>------ Rebuild All started: Project: RUN_TESTS, Configuration: Debug x64 ------
1>  Test project
1>      Start 1: CoreTest
1>  1/1 Test #1: CoreTest .....................***Failed    1.52 sec
1>
1>  0% tests passed, 1 tests failed out of 1

However if I comment the InitGoogleTest line then the test succeeds.
Any idea on what could be the problem here ?
Many thanks !
Thanks axalis! I tried to run from the command line and realized that the googletest dlls were not in my path, which was the problem.
I added multiple tests but I can only see the ctest output in MSVC:
1>------ Rebuild All started: Project: RUN_TESTS, Configuration: Debug x64 ------
1>  Test project
1>      Start 1: CoreTest
1>  1/1 Test #1: CoreTest .....................   Passed    0.03 sec
1>
1>  100% tests passed, 0 tests failed out of 1

Is there a way to see the googletest output like what I get from the console ?:
>CoreTest.exe
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from MathTest
[ RUN      ] MathTest.TwoPlusTwoEqualsFour
[       OK ] MathTest.TwoPlusTwoEqualsFour (0 ms)
[ RUN      ] MathTest.TwoPlusFourEqualsSix
[       OK ] MathTest.TwoPlusFourEqualsSix (0 ms)
[----------] 2 tests from MathTest (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (4 ms total)
[  PASSED  ] 2 tests.

A: The GoogleTest module provides two functions which can be used to show the result of each individual test defined within your test executable. gtest_add_tests() is the traditional method which scans your source file(s) at configure time, while gtest_discover_tests() (available from CMake 3.10) delays working out the set of tests until either build time or when CTest is run (see below) and is more robust (e.g. it has no problem with things like type- or value-parameterised tests).
By default, gtest_discover_tests() will query the test executable at build time using a POST_BUILD step on the target. With CMake 3.18 or later, you can ask it to query the test executable at test time instead. The DISCOVERY_MODE option controls when the query is performed. POST_BUILD corresponds to the default behavior, while PRE_TEST delays the query to test time. Rather than setting this option on every test, you can change the default behavior globally with the CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE variable, which accepts the same values as the DISCOVERY_MODE option. If you are cross-compiling, then PRE_TEST mode should be used, since you know the test executable must be runnable at test time (i.e. an emulator would have to be set already), but the same is not true at build time.
If using CMake 3.8 or earlier, the gtest_add_tests() function is provided by FindGTest rather than GoogleTest. If you need compatibility with older CMake versions, use FindGTest because it pulls in the GoogleTest module anyway. If you can require CMake 3.9 or later, use GoogleTest directly because you don't actually want to try to find gtest since you are incorporating it directly into your build. With 3.10 or later, your test can be defined like this:
include(GoogleTest)
gtest_discover_tests(CoreTest)


text:
Q: Performing selector on Main thread from the current thread inside performAndWait block of a NSManagedObjectContext I have an NSManagedObjectContext which is initialised from newBackgroundContext of the persistentContainer as following:
managedContext = coreDataStack.persistentContainer.newBackgroundContext()

This is how persistentContainer looks like:
lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "myXCDataModelName")
    container.loadPersistentStores(completionHandler: { [weak self] (_, error) in
        if let self = self,
            let error = error as NSError? {
            print("error!")
        }
    })
    return container
}()

I'm using newBackgroundContext to make sure any CRUD operation with CoreData can be done safely, regardless what thread attempts to make changes on the managedContext, instead of making sure or forcing each operation is done on main thread.
I have a saveContext method where I try to perform save operation on managedContext inside performAndWait block as following:
managedContext.performAndWait {
    do {
        guard UIApplication.shared.isProtectedDataAvailable,
            managedContext.hasChanges else {
            return
        }
        try managedContext.save()
    } catch {
        print("error!")
    }
}

It looks like performAndWait is most of the time runs on main thread but when it is run on another thread, the thread checker generates a warning for following check UIApplication.shared.isProtectedDataAvailable since it should be done on main thread.
I decided to run a selector on main thread for this check so I declared a isProtectedDataAvailable Bool by defaulting it to false at class level and then update its value when this selector runs.
@objc private func checker() {
     isProtectedDataAvailable = UIApplication.shared.isProtectedDataAvailable
}

Now I refactored the performAndWait block as following to run the check on main thread if it is called from another thread.
managedContext.performAndWait {
    do {
        if Thread.isMainThread {
            checker()
        } else {
            print("RUNNING ON ANOTHER THREAD")
            Thread.current.perform(#selector(checker),
                                   on: Thread.main,
                                   with: nil,
                                   waitUntilDone: true,
                                   modes: nil)
        }

        guard isProtectedDataAvailable,
            managedContext.hasChanges else {
            return
        }
        try managedContext.save()
    } catch {
        print("error!")
    }
}

It seems to be working fine when I run it on simulator or real device, I generate different core data related operations which would trigger saving context both on main and background threads.
But what happens is, if I put some breakpoints inside performAndWait block and stop execution to examine how the code block is working, it sometimes results in application freeze when I continue execution, like a deadlock occurs. I wonder if it is somehow related to stopping execution with breakpoints or something is wrong with my implementation even though it is working fine without breakpoints, no app freeze or anything.
I'm worried because before going with this solution, I tried synchronizing on main thread by the inspiration from this answer to just switch to main thread to make this check, as following (which resulted in app freeze and I assume a deadlock) inside performAndWait block:
var isProtectedDataAvailable = false

if Thread.isMainThread {
    isProtectedDataAvailable = UIApplication.shared.isProtectedDataAvailable
} else {
    DispatchQueue.main.sync {
        isProtectedDataAvailable = UIApplication.shared.isProtectedDataAvailable
    }
}

I had to use sync instead of async, because I had to retrieve updated value of isProtectedDataAvailable before proceeding execution.
Any ideas on this?

A: I assume your question is about the right approach so that the code is working fine and it allows to set any breakpoints without running into deadlocks. :)
Why not try it this way (from what you stated i cannot see reasons against it):

*

*First evaluating UIApplication.shared.isProtectedDataAvailable on the main thread. (I guess that there are more complex conditions that must hold not only UIApplication.shared.isProtectedDataAvailable = true, but to keep it simple ...)

*If UIApplication.shared.isProtectedDataAvailable (and otherConditions) evaluates as true continue with data processing and saving on background thread. As managedContext was created as a newBackgroundContext it can be used there.

Instructions on main thread
    if UIApplication.shared.isProtectedDataAvailable && otherConditions {
        DispatchQueue.global(qos: .userInitiated).async {
            dataProcessing()
        }
    }

Instructions on background thread
    static func dataProcessing() {
       // get the managedContext
       let context = AppDelegate.appDelegate.managedContext
       context.performAndWait {
          if context.hasChanges {
             do {
                try context.save()
             } catch {
                print("error!")
             }
          }
       }
    }

A: For some reason, moving the following check and synchronising with main queue outside of the performAndWait solves all the problems.
No deadlock or app freeze occurs either with break points or without, regardless which thread triggers the method which contains performAndWait
So the method body looks like following now:
var isProtectedDataAvailable = false
if Thread.isMainThread {
    isProtectedDataAvailable = UIApplication.shared.isProtectedDataAvailable
} else {
    DispatchQueue.main.sync {
        isProtectedDataAvailable = UIApplication.shared.isProtectedDataAvailable
    }
}

managedContext.performAndWait {
    do {
        guard isProtectedDataAvailable,
        managedContext.hasChanges else {
            return
        }
        try managedContext.save()
    } catch {
        print("error")
    }
}


text:
Q: Passing slice to function used for go routine I have the following function which takes as parameters two slices of two dimensional arrays of ints (where coreCount is amount of cores available)
func calculate(slice_1 [][array_size][array_size]int, slice_2 []  [array_size[array_size]int, coreCount int) {
//for each (coreCount*k + i, i = 0, ... , coreCount) matrix from slice_1 take matrix from slice_2 and check some criteria while not changing matrix under check
}

Slices are quite big in size (thousands of two dimensional arrays) so it's good idea to do the checking in parallel. So I simply create (in case of 4 cores compurer)
go calculate(slice_1 , slice_2, 4)
go calculate(slice_1 , slice_2, 4)
go calculate(slice_1 , slice_2, 4)
go calculate(slice_1 , slice_2, 4)

But it still calculates not in parallel. What's wrong?

A: There's no need for func in a go statement (just write go funcName(arg1, arg2)).
Also, we'll need the whole program (or at least a simplified, working version) to be able to help you. Have you set GOMAXPROCS?

A: To do some checking in parallel, your goroutines would need to look at different parts of the input data and from your very brief code sketch, at best you'd run the same calculation four times. That is, of course, assuming that you actually spawn four goroutines with the same arguments and nothing to distinguish them from each other.


text:
Q: How to mock async action call from react component with jest and RTL I have a component that when you click a button, it will call an async redux action that makes POST call to api,, and it will resolve if call was successful and reject if not.
import { reduxAction } from 'store/actions';

function TestBtn(props) {
    const { href, action } = props;

    const onClick= () =>
        action ({
            method: 'post',
            path: href
        })
            .then(() => {
                //do something
            })
            .catch(() => {
                //do something
            });

    return (
            <Button
                variant={'outlined'}
                onClick={onClick}
                label='Click'
            />
    );
}

const mapDispatchToProps = dispatch => ({
    action : payload => dispatch(reduxAction(payload))
});

export default connect(null, mapDispatchToProps)(TestBtn);

I would like to test this functional component with Jest and react-testing-library, but I do not know how properly mock this action, so it does not make a real call.
I tried something like this
import React from 'react';

import { render, screen, fireEvent } from 'test-utils';
import '@testing-library/jest-dom';
import TestBtn from 'components';
import * as actions from 'store/actions';

const mockGetData = jest
    .spyOn(actions , 'reduxAction')
    .mockImplementation(() => Promise.resolve());

const href = '/test';

test('acts properly, when click on a button', () => {
    render(<TestBtnhref={href} />);

    fireEvent.click(screen.getByText(/send_to_cc/));
});

But it doesn't work, I receive
TypeError: Cannot read property 'then' of undefined

A: Your mock implementation returns a Promise.resolve() that is going to be resolved to an undefined value. This is the reason you were getting the error. You must give a value as an argument to resolve by the promise.
You could also use .mockResolvedValue() for this. This API is used when you want to return a promise value of an async function to resolve.
import React from 'react';

import { render, screen, fireEvent } from 'test-utils';
import '@testing-library/jest-dom';
import TestBtn from 'components';
import * as actions from 'store/actions';

const mockGetData = jest
    .spyOn(actions , 'reduxAction')
    .mockResolvedValue({ fakeObjectKey1: "anything"}); // here is the change

const href = '/test';

test('acts properly, when click on a button', () => {
    render(<TestBtnhref={href} />);

    fireEvent.click(screen.getByText(/send_to_cc/));
});


text:
Q: What does __dyld_dyld_fatal_error_disassembly mean? I have an Iphone app that was nearing its development completion and literally between "build and run"s this error appeared. I commented out all of the code that might be offending the simulator but nothing could make the error resolve. I put a couple of NSLogs in the app delegate to see how far the application was getting before it crashes and nothing appeared from the console.  It appears the app is loading its splash screen and then dying. I'm an intermediate Iphone developer but I can not decipher that error message. Did my simulator get corrupted or something similar? I didn't add any new libraries or any thing drastic to the code in between builds. I also tried cleaning the build file, and deleting the app on the simulator and force a re-install.
Any help would be great. Thanks so much.

A: This happened to me and this is how I got it working (XCode 4):
In the Product menu, select Manage Schemes. Select the scheme you're using and click edit. Click the Run build type in the column on the left and the Diagnostics tab at the top.
I unchecked all of the checkboxes and the error you're describing went away. I didn't spend the time to discover which specific checkbox or combination was the culprit.
I was only getting the error when I tried to run on a device.

A: Have you tried doing a clean before you build again? There might be some leftover files doing some nasty things to your build.
Past that, have you tried using breakpoints and the debugger to step through your program and see exactly what threads/operations are causing the problem?
Finally, are you testing on the device, too? The simulator is not an accurate representation of running the application on the actual hardware.

A: Guard Malloc has to be disabled in the Product Menu, Edit Scheme..., Run section, Memory Management.


text:
Q: APUE ld: archive has no table of contents file '../lib/libapue.a' for architecture x86_64 I starts to learn APUE and compile the source code
1, downloads the source code from Source Code
2, extract it to
$ pwd
/Users/me/Desktop/PubRepo/C/APUE/apue.3e

3, read readmd
$ cat readme
Read the file called DISCLAIMER.

On Freebsd, type "gmake".
On other platforms, type "make" (as long as this is gnu make).

For FAQs, updated source code, and the lost chapter, see http://www.apuebook.com.
Please direct questions, suggestions, and bug reports to sar@apuebook.com.

Steve Rago
January 2013

I checked make version
$ make --version
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i386-apple-darwin11.3.0

4, make but report error:
gcc -ansi -I../include -Wall -DMACOS -D_DARWIN_C_SOURCE   -c -o sleep.o sleep.c
making intro
gcc -ansi -I../include -Wall -DMACOS -D_DARWIN_C_SOURCE  getcputc.c -o getcputc  -L../lib -lapue
ld: archive has no table of contents file '../lib/libapue.a' for architecture x86_64
clang: error: unable to execute command: Segmentation fault: 11
clang: error: linker command failed due to signal (use -v to see invocation)
make[1]: *** [getcputc] Error 254
make: *** [all] Error 1

I searched and found answer to add cp ./lib/error.c /usr/local/include/

    $ cp ./lib/error.c /usr/local/include/
make clean and make
making intro
gcc -ansi -I../include -Wall -DMACOS -D_DARWIN_C_SOURCE  getcputc.c -o getcputc  -L../lib -lapue
ld: archive has no table of contents file '../lib/libapue.a' for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [getcputc] Error 1
make: *** [all] Error 1

The error still there.
How could I apply apue.h?


text:
Q: Dropping external table in spark is dropping the location or data too import org.apache.hadoop.fs.{Path,FileSystem}
import org.apache.hadoop.conf.Configuration
import org.apache.spark.sql.{SaveMode, SparkSession}
import org.apache.spark.sql.functions.{current_date, from_unixtime, unix_timestamp}
import spark.implicits._
    spark.sql("drop table if exists Staging.test_partiton_drop")
    val df = Seq(("Aravind", "DIP"), ("Karthik", "DTP")).toDF("name", "dept")
      .withColumn("hdp_load_dt", current_date()).withColumn("hdp_load_hr", from_unixtime(unix_timestamp(), "HH"))
    var partitionBySeq = Seq("hdp_load_dt", "hdp_load_hr")
    df
      .write.partitionBy(partitionBySeq:_*)
      .format("parquet")
      .mode(SaveMode.Append)
      .option("path", "/krnoir/streaming_test")
      .option("compression", "snappy")
      .saveAsTable("Staging.test_partiton_drop")

    val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
    val finalPath = new Path("/krnoir/streaming_test/_REPLICATION.DONE")
    fs.create(finalPath,false)

When I ran the above code, /krnoir/streaming_test/ is getting overwritten in each run while I am expecting new files to be added and not overwritten.


text:
Q: random css position jquery using math.random, I can position the div to the left, randomly. But i need set the "left" and "right" positions randomly.

jQuery('#popup-container').css({'left' : (Math.floor(Math.random() * 15) + 3) + '%'})

Example, in attribute ".css({left", have an randon with "left or right". An array with these positions. how do I do that?

A: Simply make an array and push 'left' and 'right' into it.
var positions = [];
positions.push('left');
positions.push('right');

Now, use Math.random for selecting the index for positions array.
 jQuery('#popup-container').css(positions[Math.floor(Math.floor(Math.random()%2))], (Math.floor(Math.random() * 15) + 3) + '%')

Hope this helps.
Regards


text:
Q: Positioning a jQuery UI dialog offset from the Center I'd like to position my jQuery UI dialogs a bit better.  The default "center" position puts them directly in the middle of the page, but it certainly looks better to have them offset about 70% up the page as they are in Facebook.  I'm looking at the .position function but am a bit unclear what the simplest solution is.

A: The easiest way would be to use the position()
$("#dialog").dialog("widget").position({
       my: 'left',
       at: 'right',
       of: target
});

Or, if you already have calculated the dimensions
var x = 50; //calculate the 70%, with your own logic
var y = 100;
$("#dialog").dialog('option', 'position', [x,y]);

Or you can specify the height during initialisation of the widget
$("#dialgo").dialog({
     autoOpen: false,
     width: 400 ,
     position: [300,200]
});

A: For jquery-ui 1.9+:
$("#dialog").dialog({ position: { my: "center", at: "top+30%", of: window } });

For jquery-ui 1.8:
$("#dialog").dialog({ position: { my: "center", at: "top", of: window, offset: "0 30%" } });

It's something like that but play around with offset values.


text:
Q: Append/Remove Text with Jquery UI Slider I want to append and remove random text to a div with the Jquery UI Slider. It should add text by moving the slider handle in one direction, while removing text in the other direction. I read the API, but I couldn't find information about directional events.
var rhetoric = ["lorem", "ipsum", "consectetur", "adipiscing"];
$(document).ready(function() {
  $('#slider-vertical').slider({
    orientation: "vertical",
    min: 0,
    max: rhetoric.length - 1,
    step: 1,
    value: 3,
    slide: function(event, ui) {
      $("#ipsum-text").append(rhetoric[ui.value] + " ");
    }
  });
  $("#ipsum-text").val($("#slider-vertical").slider("value", 0));
});

jsFiddle Example

A: I got it! I combined a solution from another thread. Basically, you need to use the change in value to trigger the text add or remove. The full code is below:

var rhetoric = ["lorem", "ipsum", "consectetur", "adipiscing"];
var last = 0;

$(document).ready(function() {
  $('#slider-vertical').slider({
    orientation: "vertical",
    range: "min",
    min: 0,
    max: rhetoric.length,
    step: 1,
    value: rhetoric.length + 1,
    slide: function(event, ui) {
      if (ui.value < last) $("#ipsum-text").append('' + rhetoric[ui.value] + ' ');
      if (ui.value > last) $(".ipsum-item:last-child").remove();
      last = ui.value;
    }
  });
  $("#ipsum-text").val($("#slider-vertical").slider("value"));
});


text:
Q: swfdotnet library reference issue in vs2010 I am creating an windows forms app using vs2010, framework 4.0, C#. I am adding reference of swfdotnet library's three dll files, include them in the code, intellisense is also the showing its classes, methods and properties.
But when i run the program it gives following warning and program doesnt work.

The referenced assembly "SwfDotNet.IO" could not be resolved because
  it has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently
  targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please
  remove references to assemblies not in the targeted framework or
  consider retargeting your project.

Should i need to add some other files. HelP!

A: You get this message because System.Web assembly is not part of the Client Profile.
You should switch your project target framework to ".NET Framework 4.0" instead of ".NET Framework 4.0 Client Profile".
Another (but not recommended) way is manual deploying of System.Web.dll with your project


text:
Q: Spring MVC change  options dynamically with other  I am working on a Spring MVC platform, and I have encountered a problem.
I wish to allow users to send invites to Conventions and Events that they have added on the platform. I have a model for both of those, and they work fine, but when sending an invite to someone, I just can't seem to find a way to dynamically update a <form:select> option list.
When a person invites another person to a convention, they have a two dropdown lists. The first one is the convention dropdown list and it contains all the convention the person has added. Each Convention has a list of Events, and the second dropdown list should show all events for the selected convention.
So for each option on the first dropdown list, there should be multiple options on the second dropdown list.
I'll post the models here, if they mean something to you, and cut the code that isn't relevant for this question.
Event:
 public class Event {

        @Id
        @GeneratedValue
        private int eventId;
        private int conventionId;
        private String conventionName;

        private String eventName;
        private String eventDescription;
        private String websiteLink, facebookLink, twitterLink, instagramLink, youtubeLink;
        private String eventType;
        private String eventDateFrom;
        private String eventDateTo;
        private String hostedBy;
        private String eventAddress;
        private String eventPr;
  //getters and setters

Convention:
@Entity
public class Convention {

    @Id
    @GeneratedValue
    private int conventionId;

    private String conventionName;
    private String conventionDescription;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Event> conventionEvents;
    private String websiteLink, facebookLink, twitterLink, instagramLink, youtubeLink;
    private String conventionType;
    private String conPr;
    private String hostedBy;
    private boolean isAccepted;
//getters and setters

Invite:
@Entity
public class Invite {
    @Id
    @GeneratedValue
    private int inviteId;

    private String senderName;
    private int senderId;
    @NotEmpty(message = "Convention name must not be empty!")
    private String conName;
    private String eventName;
    @NotEmpty(message = "Message must not be empty!")
    private String message;
    private String tripType;
    private String dateFrom;
    private String dateTo;
    private boolean isRead;
    private String sendingTo;

sendInvite.jsp [EDIT - CHANGED THE CODE]
      <%@ include file="/WEB-INF/views/template/header.jsp" %>
    <form:form action="${pageContext.request.contextPath}/sendInvite/{${sendingTo}}" method="post" commandName="invite">
        <form:hidden path="senderName" value="${pageContext.request.userPrincipal.name}"/>
        <form:hidden path="sendingTo" value="${sendingTo}"/>

            Convention:

        <form:select path="conName" name="conName">

            <c:forEach items="${conventionList}" var="convention">
                <form:option value="${convention.conventionName}">${convention.conventionName}</form:option>
            </c:forEach>
        </form:select>

        <form:select path="eventName">
            <c:forEach items="${eventList}" var="event">
                <c:if test="${event.conventionName == convention.conventionName}">
                    <form:option value="${event.eventName}">${event.eventName}</form:option>
                </c:if>
            </c:forEach>
        </form:select>

//HERE I JUST NEED TO FIND A WAY TO GET " <c:if test="${event.conventionName == convention.conventionName}">" WORKING SINCE I CAN'T GET THE ACTUAL VALUE OF THE CONVENTION NAME.//

            Message body
            <form:textarea path="message" id="message" class="form-Control"/>

            Trip type

            <form:select path="tripType" name="tripType">
                <form:option value="Paid">Paid</form:option>
                <form:option value="Unpaid">Unpaid</form:option>
                <form:option value="To be agreed">To be agreed</form:option>

            </form:select>

        <input type="submit" value="Send invitation" class="btn btn-default">
    </form:form>

Thank you in advance.
[EDIT - Adding InviteController]
@Controller
public class InviteController {

    @Autowired
    InviteService inviteService;

    @Autowired
    ProfileService profileService;

    @Autowired
    ConventionService conventionService;

    @Autowired
    EventService eventService;

    @RequestMapping("/sendInvite/{sendingTo}")
    public String sendInvite(@PathVariable("sendingTo") String sendingTo, Model model, Principal principal) {
        Invite invite = new Invite();
        List<Convention> conventionList = conventionService.getConventionsByUsername(principal.getName());
        List<Event> eventList = eventService.getEventListForOwner(principal.getName());
        model.addAttribute("eventList", eventList);
        model.addAttribute("conventionList", conventionList);
        model.addAttribute("invite", invite);

        return "sendInvite";
    }

    @RequestMapping(value = "/sendInvite/{sendingTo}", method = RequestMethod.POST)
    public String sendInvitePost(@ModelAttribute("invite") Invite invite, @PathVariable("sendingTo") String sendingTo, Model model) {
        model.addAttribute("sendingTo", sendingTo);
        inviteService.addInvite(invite);
        return "sendInviteSuccess";
    }

}

The method names of the services are self explanatory, I simply get a list with some sort of criteria, be it a username or convention.

A: In your entity you has declared a List of event, then you can access your events like this convetionList.eventName

    Event:
    <form:select path="conName" name="conName" items="${conventionList.eventName}"/>

[EDIT]
Try modifying the response from your controller:
@RequestMapping("/sendInvite/{sendingTo}")
public String sendInvite(@PathVariable("sendingTo") String sendingTo, Model model, Principal principal) {

    List<Convention> conventionList = conventionService.getConventionsByUsername(principal.getName());
    List<Event> eventList = eventService.getEventListForOwner(principal.getName());

    for(Covention convention : conventionList){

        for(Event event : eventList){

            if(convention.getConventionId() == event.getConventionId())
            {
                convention.conventionEvents.add(event);

            }
        }

    }
    //Now you have all of your events associated to your conventions
    model.addAttribute("conventionList", conventionList);
    model.addAttribute("invite", new Invite());

    return "sendInvite";
}

Now you should be able to use ${conventionList.conventionName} to get all conventions in your dropdown view and ${conventionList.conventionsEvents.eventName} and this object should be dinamically displayed by convention
Let me know if you need more help.
Regards,


text:
Q: Automatic MD5 column in Entity Framework We are starting a new project here and as a premise, every row in every table must have a md5 column calculated with the other columns contents, to check if it was modified outside the application (using manual updates or inserts).
There are already any solution for that?

A: You can use Triggers package by Nick Strupat. This gives you a possibility to react on every row's inserting/updating. In triggers implementation you can calculate MD5 for the actual data.


text:
Q: Count number of permutations of a string with two distinct digits How can i calculate how many numbers are there between 000000 and 999999 that contain only two distinct digits?
For example 000001 can be counted as one. The same goes for 002200, 112211, 100000. However 112233 contains three distinct digits so it can't be counted.
Thanks

A: Let's simplify the problem.
Suppose we need find all the permutations of numbers with just 0,1. So the possible combinations can be like 000011,000001,001110 etc. Since there needs to be 2 distinct digits There can be following combinations:
[Zeroes, Ones]: {1,5},{2,4},{3,3},{4,2},{5,1}
That means 1 zeroes 5 ones will have: 000001, 000010, 000100, 001000, 010000, 100000
So if there are Z zeroes then there will be 6CZ combinations with Z zeroes and 6 - Z ones.
Since Z can have a value from 1-5, we can say that there are  5∑Z=16CZ possible numbers with 0,1 combination with at-least 1 zero & 1 one.
Now coming back to original problem Since there are 10 digits and we need two distinct digits so 10C2 i.e. 45 Combination will be there ex: {0,1}, {0,2} ..... {1,2} ....
So the answer is 10C2 *  5∑Z=16CZ

A: As you haven't specified any specific programming language, I did use of javascript with proper comments. Hope it helps you.
 var counter = 0; // this counts if it contains exactly two different digits only
 for(var i=10000; i<10005 ; i++) { // change the loop values as you need
     var x = i.toString(); // converting number to string which makes easy to split
     var chars = x.split(''); // split characters and keep in an array
     var uniqueChars = Array.from(new Set(chars)); // get distinct characters from array
     if(uniqueChars.length == 2){ // check if it contains exactly two elements
         counter++;
     }
 }
 console.log(counter);


text:
Q: client app specifications making backend calls (HTTP REST) We have a scenario, where when the end user login into our mobile apps (these apps can be any 3rd party); we expect the app to make a call to backend services (built using HTTP REST) every 30 seconds.
But because of the various releases and bugs got introduced on mobile apps; some times we see the spike more than expected.
My question is are there any open specifications available for clients (in this case mobile apps) to send some additional information on why they are making more no.of calls than expected ?


text:
Q: Prestashop mail confirmation layout I'm developing a Prestashop 1.7 e-commerce and I'm stuck with a layout problem about the order confirmation that the customer receives. The mail itself works, but it's showed badly when viewed with a smartphone and this because is made using tables with pre-assigned column sizes that I cannot change

Is there a way to change this layout easily through the Back Office or should I dig into the code?

A: Translation tool in the backend
Log into your PrestaShop admin panel.
Navigate to Localization -> Translations, find Modify translations section.
Select the E-mail template translations from the Type of translation dropdown menu, Core (no theme selected) and the required language:

Click Modify button.
Open Core e-mails and by using search tool (CTRL + F) find order_conf.
You can change the body of the message in WYSIWYG editor, that appears after clicking on
Edit HTML version. And also you can view/edit the .txt version:

Edit account email in the same way :

After all changes click Save or Save and stay button.


text:
Q: Link Excel workbooks so that I can use them on another computer (Excel 2011 for Mac) We have an Excel spreadsheet that uses data from another workbook.
We use Dropbox to share the files.
When I open the spreadsheet on another Mac or PC the links need relinking.
Is there a way to make the links reference just the immediate folder?
Here's the problem explained further.

Workbook contains a link to: ~my-mac/dropbox/work/source.xlsx
It doesn't work when opened on: ~ãnother-mac/dropbox/work/source.xlsx
I want Excel 2011 for Mac just to look for ~/dropbox/work/source.xlsx

I've read several help pages on Absoulte links and relative links and UNC links.
It seems it is possible to link workbooks using the short link, however, I am unable to make it work.
Is it a Mac thing? Is it a me thing?
Any potshots from hotshots most welcome!
J

A: This VBA code will update the links to the immediate folder, provided your file only links to one other book:
Sub DropBox()

    Dim vOldLink As Variant, sOldLink As String
    vOldLink = ActiveWorkbook.LinkSources(xlExcelLinks)
    sOldLink = vOldLink(1)

    Dim vFilename As Variant, sFilename As String
    vFilename = Split(sOldLink, "\")
    sFilename = vFilename(UBound(vFilename))

    Dim sPath
    sPath = ThisWorkbook.Path & "\"

    ActiveWorkbook.ChangeLink Name:=sOldLink, NewName:=sPath & sFilename, Type:=xlLinkTypeExcelLinks

End Sub

I am not sure about Mac though...


text:
Q: SELECT query in chunks using PostgreSQL I have a table with well over a million entries. I'm putting all this data into perl and storing it into a variable ($query = "SELECT * FROM table1". The problem now is that I'm using a lot of resources (mostly memory). Given my novice state with perl and postgres, How would I transform that query into chunks or parts?
For example,
$query = "SELECT * FROM table1 LIMIT 100000";

Would put 100K results into $query. table1 is 10M records in size. How would I transform it so that only 100K results are stored into $query at a time until the query is finished?

A: First of all do you really need all 10M records? don't think so and thus retrieve only the records for your work to be done. Second, do you really need all columns data? may not be and in such case select only the columns needed saying select col1, col2, col3 ... from table instead of doing a select *.... Cause, there is no point in getting all data and filling your server's memory.
In worst case, if what you have said is what you actually in need then you have no other way than retrieving all records. You can probably implement paging to get data in batches rather than getting all of them at once.

A: Pagination?
Maybe this might be of use:
https://www.postgresql.org/docs/8.3/static/queries-limit.html
Sorry if I have misunderstood.

A: Trick :
you can use modulus for chunk data
e.g :
you want chunk data from 1000 record, chunk data 4 pieces using seq id
you just modulus seq id data 4,
SELECT *
  FROM input_data_control b
 WHERE  b.bill_schedule_month = '201910'
        AND mod(input_data_control_id, 4) = [1...4]


text:
Q: Delete the previous and next element from an array while using array.map() in javascript How can I delete the previous and next element from an array while using array.map();
In the code below, when I get to 'crossover' I want to delete both 'SUV' and 'sedan'.
The following code deletes 'sedan' and 'truck' instead of 'sedan' and 'SUV' ;
let arr = ['excavator','SUV','crossover','sedan','truck'] ;
arr = arr.map((ele,ind,ar) => {
  if (ele === 'crossover'){
    ar.splice(ind+1,1);
    ar.splice(ind-1,1);
  }
  return ele + ": Sold.";
});
return arr; //it produces ['excavator: Sold.','SUV: Sold.','crossover: Sold.',,]

A: You can first remove the elements and then map the array, here is an example:

let arr = ['excavator','SUV','crossover','sedan','truck'];
arr.splice(arr.indexOf('crossover') - 1, 3, 'crossover');
arr = arr.map((ele) => {
  return ele + ": Sold.";
});
console.log(arr);

The .splice(..) call replaces SUV, crossover and sedan with crossover

A: You should not remove elements on a .map interation since the array size will change as well as the array indexes.
You should try something like this:

let arr = ['excavator','SUV','crossover','sedan','truck'] ;
arr = arr.filter(element => element != "crossover");
arr = arr.map(ele => `${ele} :Sold.`);
console.log(arr);

Or, from an old school perspective:

let arr = ['excavator','SUV','crossover','sedan','truck'];
let newArr=[]
for (var i=0; i<arr.length; i++)
  if(arr[i] !== 'crossover')
     newArr.push(`${arr[i]} :Sold.`)

console.log(newArr);

A: itus has the correct anwer, IMO but for the sake of fun this is an alternative way:
let arr = ['excavator','SUV','crossover','sedan','truck'] ;

let suvIndex = null;
const result = arr.map((item, index) => {
  if (item === "SUV") {
    suvIndex = index;
  }

  if(suvIndex && index <= suvIndex + 2) {
    return null;
  }

  return item;
}).filter(chunk => chunk)

console.log(result);

https://jsfiddle.net/vbz14fw6/


text:
Q: count_if implementation - C++ I am trying myself to create the generic function count_if()
(so I don't have to depend on the inclusion of <algorithm> by the STL).
This is my code:
template <class InputIterator, class Pred>
int count_if (InputIterator first, InputIterator last, Pred pred) {
  int count = 0;
  while(first != last ) {
    if(pred(*first)) ++count;
    ++first;
  }
  return count;
}

I am trying to use this function as the predicate:
bool size_more_than_10(std::string val) {
  return val.size() > 10;
}

Problem: my predicate works with std::string, but when I dereference the iterator I get a char type, and a compilation error:
error: could not convert '__it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<char*, std::__cxx11::basic_string<char> >()' from 'char' to 'std::__cxx11::basic_string<char>'
  { return bool(_M_pred(*__it)); }

This is my main (where I call count_if()):
int main() {
    std::string s;
    std::getline(std::cin,s);
    std::cout<<"count: "<<count_if(s.begin(),s.end(),size_more_than_10);
    return 0;
}

How can I overcome this problem?

A: You are using this algorithm incorrectly.
Your usage causes iteration over characters and predicate accepts string.
Here is working example:
#include <iostream>
#include <iterator>

template <class InputIterator, class Pred>
int count_if (InputIterator first, InputIterator last, Pred pred) {
  int count = 0;
  while(first != last ) {
    if(pred(*first)) ++count;
    ++first;
  }
  return count;
}

bool size_more_than_10(std::string val) {
  return val.size() > 10;
}

int main()
{
    std::cout << count_if(std::istream_iterator<std::string>(std::cin), {}, size_more_than_10) << '\n';
    return 0;
}


text:
Q: Using stuff from other files in Cocos2d? I am making a game (obviously) and I noticed that my HelloWorldLayer.m file is getting EXTREMELY cramped. I KNOW that there is a way to run methods from other .m files, I just don't know how. For example, I want to have a Character.h and Character.m file. Can I make it so in the HelloWorldLayer init layer, it just uses everything from the Character files instead of having to declare everything in the HelloWorldLayer? I hope my question makes sense, and any help is appreciated. Thanks!
Here is Character.m:
@implementation Character

@synthesize health,velocity;

-(void)dealloc {
    [super dealloc];
}

-(id)initWithTexture:(CCTexture2D *)texture rect:(CGRect)rect
{
    if((self = [super initWithTexture:texture rect:rect]))
    {
        [self scheduleUpdate];
    }
    return self;
}

-(void)update:(ccTime)dt {
    [self setPosition:ccp(self.position.x,self.position.y)];

    self = [CCSprite spriteWithFile:@"nukeboyGreen.gif"];
}

@end

And here's HelloWorldLayer.m (I skimped it down and took out the parts that aren't necessary):
self = [super init];
    if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {

        CGSize winSize = [[CCDirector sharedDirector] winSize];

        character = [Character spriteWithFile:@"nukeboyGreeen.gif"];
        character.position = ccp(winSize.width/2,winSize.height/2);
        character.scale = 0.15;
        [self addChild:character];

Note that I have a Character declared in HelloWorldLayer.h

A: This is where object oriented programming comes to the rescue. OOP encourages you to encapsulate variables and functions that is pertinent to an object in that object itself. In your case, you should put the methods that are specific to Character in the Character class, and only get your HelloWorld to trigger those methods.
Examples:
@interface Character : CCSprite {
   ...
}

- (void)didCollideWith:(Object *)object;

- (void)moveTo:(CGPoint)nextPoint;

- (void)shootArrow:(ckDirection)direction;

- (BOOL)isAlive;

- (int)numberOfLivesRemaining;

...

@end

Then in HelloWorldLayer:
[character moveTo:ccp(100, 200)];
[character shootArrow:kDirectionUp];

if (![character isAlive]) {
   [self showGameOver];
}

Not only that your HelloWorldLayer is less cluttered, you can easily understand what your code does by simply looking at the reasonably named methods.
EDIT:
To answer your question as in the comment about how to designate the sprite image in Character class:
@implementation Character

- (id)init {
   self = [super initWithFile:@"sprite_character.png"];
   if (self) {
       // further customization
   }
   return self;
}

@end

EDIT (after code was added to the question):
First let me point out a few mistake (sorry for the lack of softer word):

*

*You rarely need your sprite to call the [self scheduleUpdate] or [self schedule:SEL]. Normally people implement the update (or tick) method at the CCLayer or CCScene level, where the purpose is to check all the actors (sprites, menus, nested layers etc) for collision/interaction and update their attributes. If you just want to animate movement of a sprite to a specific position, just call runAction method from CCLayer (in the init, update, ccTouchBegan or somewhere). You can read cocos2d-iphone tutorial on Actions by clicking here. So, move the update method and the scheduleUpdate call into your HelloWorldLayer, and then you no longer need to override initWithTexture.

*I'm seeing you instantiating a CCSprite in the update method. My above point on the inappropriateness of update method in CCSprite notwithstanding, there is something more important you need to understand when you implement a method: that is you need to decide how and how often your method is going to be used/called. Since the update method is going to be called once per frame (that is 60 times per second), it is simply wrong to unconditionally instantiate an object in that method. You are making the iPhone to allocate (and deallocate) the object with no apparent reason, wasting the processor time/power the device has. You might want to ask where should you instantiate the CCSprite. The answer is in the init method because that method is only called once per object instance. Again, all you need to know is whether a method is going to be called once or multiple times, and decide whether a piece of code should be in there or somewhere else.

*In your code for HelloWorldLayer, did you realize that you are calling the super init* methods twice. You don't need to call [super init] since [super initWithColor:ccc4( ... )] is going to call specific init method internally. Although it is not entirely wrong to do so, you are going to break the 'assumption' that init is going to be called once per instance, so you might end up breaking some object integrity unintentionally (and believe me it's going to be hard to debug later)

*And finally, care to enlighten me what's the real purpose of the line [self setPosition:ccp(self.position.x,self.position.y)];. You basically set the position of the self object to its current position, so that's like saying "hey you, move your position to your current position" and he'll be like "huh?" :P


text:
Q: How to read a csv column as list and not as a string in python? I have a CSV file in which one column is a list of tuples. But when I am reading it in python the list of tuples is read as a string object.

A: Read csv using pandas, using following function
pandas.read_csv()
It will read list as string. To convert it into list use following function
import ast

ast.literal_eval()


text:
Q: Spring JDBC template connection management I am using Spring Framework to manage the transaction and connection, but my question is that whether there is a way to verify the DB connection is closed successfully or not after every DB communication ?

A: One way is to enable jdbc driver logs. Normally connection pools also do provide ways to detect connection leaks. For tomcat jdbc connection pool does it by providing few properties.
Connection Leaks

removeAbandoned = true – Flag to remove abandoned connections if they
exceed the removeAbandonedTimeout. A connection is considered
abandoned and eligible for removal if it has been in use longer than
the removeAbandonedTimeout. This way db connections can be recovered
from applications that fail to close a connection.
removeAbandonedTimeout = 54 – timeout in seconds before an
abandoned(in use) connection can be removed. The value should be set
to the longest running query your applications might have.
validationQuery= "SELECT 1" – MySql SQL query used to validate
connections from the pool before returning them to the caller

Apart from this you could rely on spring doing its job :)


text:
Q: How to display the IP address of the default Interface with Internet connection? I need to create a script that outputs the internal IP address, that is configured as the default Interface.

A: Here's another slightly terser method using procfs (assumes you're using Linux):
default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route)
ip addr show dev "$default_iface" | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }'

This returns both the IPv4 and (if available) the IPv6 address of the interface. You can change the test if you only want one or the other (look for inet for IPv4, and inet6 for IPv6).

$ default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route)
$ ip addr show dev "$default_iface" | awk '$1 ~ /^inet/ { sub("/.*", "", $2); print $2 }'
10.0.2.15
fe80::a00:27ff:fe45:b085

$ ip addr show dev "$default_iface" | awk '$1 == "inet" { sub("/.*", "", $2); print $2 }'
10.0.2.15

$ ip addr show dev "$default_iface" | awk '$1 == "inet6" { sub("/.*", "", $2); print $2 }'
fe80::a00:27ff:fe45:b085

A: Lots of good answers here, but wanted to throw in my usual approach:
The simplest solution is to get the route for a public internet address:
$ ip route get 1.1.1.1 | grep -oP 'src \K\S+'
192.168.0.20

Another solution is to get the default gateway, and then get the IP addr used to communicate with that gateway:
$ ip route get $(ip route show 0.0.0.0/0 | grep -oP 'via \K\S+') | grep -oP 'src \K\S+'
192.168.0.20

A: Here's what I wrote:

*

*Get the default interface from the "route" command.

It will print out which interface is the "default". For my host, I need to get the last column of the default line.
[root@pppdc9prd3ga mdesales]# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.4.0     *               255.255.252.0   U     0      0        0 bridge0
10.132.60.0     *               255.255.252.0   U     0      0        0 eth4
link-local      *               255.255.0.0     U     1002   0        0 eth4
link-local      *               255.255.0.0     U     1003   0        0 bridge0
default         10.132.60.1     0.0.0.0         UG    0      0        0 eth4

*Use "ifconfig" to retrieve the IP address of that interface.

Just getting the addr: value.
[root@pppdc9prd3ga mdesales]# ifconfig eth4
eth4      Link encap:Ethernet  HWaddr 00:50:56:01:42:91
          inet addr:10.132.63.191  Bcast:10.132.63.255  Mask:255.255.252.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1346288 errors:0 dropped:0 overruns:0 frame:0
          TX packets:438844 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:276243478 (263.4 MiB)  TX bytes:116188062 (110.8 MiB)

So here's the script I came up with.
/app/myPublicIp.sh
defaultInterface=$(route | grep default | awk '{print $(NF)}')
ifconfig $defaultInterface | grep 'inet addr:' | cut -d: -f2 |  awk '{ print $1}'

Here's it executing:
/app/ipFor.sh
10.132.63.191

A: My favorite one is following.
Get the default interface:
$ ip r | grep -oP 'default .* \K.+'
eth0

Get the ip of an interface:
$ ip a show eth0 | grep -oP 'inet \K[\d\.]+'
10.33.44.135

Combined:
$ ip a show $(ip r | grep -oP 'default .* \K.+') | grep -oP 'inet \K[\d\.]+'
10.33.44.135

A: One other approach is:
ip a|awk /$(ip r|awk '/default/ { print $5 }')/|awk '/inet/ { print $2 }'| cut -f1 -d"/"

the benefit of this is that uses only ip a and ip r that is available by default at all linux systems

A: If what you want is the IP address assigned to the default interface (which is what I understood from the comments under the question), using the Swiss army knife of network setup (ip) should be enough:
$ ip route | grep '^default'
default via 10.176.143.1 dev eth1  metric 203
$ ip addr show eth1
4: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether c0:de:f1:72:30:48 brd ff:ff:ff:ff:ff:ff
    inet 10.176.143.71/24 brd 10.176.143.255 scope global eth1
       valid_lft forever preferred_lft forever

This shortens to
$ ip addr show \
    $( /sbin/ip route \
        | grep '^default'\
        | sed 's/^.*dev \([^ \t]*\) .*$/\1/' )

which is ugly, because it is parsing something that probably wasn't really meant to be parsed (output of ip route), but should work.

A: Simple Command with the default interface.
ip -o route get "8.8.8.8" 2>/dev/null | sed -e 's/^.* src \([^ ]*\) .*$/\1/'

or
ip route | grep src | awk -F 'src' '{print $NF; exit}' | awk '{print $1}'

or
ip route | sed -n 's/.* src \(.*\) metric .*/\1/p' | uniq

Tested on All Unix OS

A: This worked for me on Centos 7. Find default interface using ip
ifconfig $(ip route | awk '/default/ { print $5 }') | grep "inet " | awk '{print $2}'

A: Any Linux OS-es using /proc (but without using iproute tools):
cat /proc/net/fib_trie|grep -A50 '\|-- 0\.0\.0\.0$'|grep -B50 -wm1 'LOCAL'|tail -n2|grep -oP '\|-- \K\S+'


text:
Q: Need Help with Custom Controller & VF Page Can anyone provide insight into what I need to do to prevent my page from displaying Territories that return zero results?
They are currently showing because I made a list and my VF page loops through all "Close Date (Forecasted)" fields  in the list using apex:repeat. Then an inner apex:repeat loops through all territories in the territory list.
The problem is that there are not always opportunities that are in both lists.
******** CONTROLLER *******

public class ForecastController {

    public List<Opportunity> opportunities {get;set;}
    public String[] closeDates {get;set;}
    public String[] terrs {get;set;}

    public void load(){

        Opportunities = [SELECT Id, Name, Account.Name, Account.Territory_Manager__c, StageName, CloseDate, Forecastable__c,
                         Forecasted_Close_Date_30_60_90__c, Close_Month_Forecasted__c, Account.Terr_From_Zip__c,
                         (Select Id, Account_Name__c, ADRBD_Forecast_Close_Date__c, Close_Date__c, Close_Month_Forecasted__c, Install_Date_Instruments_only__c, Opportunity__c,
                          Opportunity_Name__c, Opp_Safe_ID__c, Quantity__c, Stage__c, Territory__c, Territory_Manager__c, Total_FS_Modules__c, Total_Instr_Revenue__c, Total_Price__c, CreatedDate FROM Opportunity_Snapshots__r)
                         FROM Opportunity
                         WHERE (NOT Name LIKE 'Test')
                         AND (Account.BillingCountryCode = 'US' OR Account.BillingCountryCode = 'CA')
                         AND Forecastable__c = true
                         AND Forecasted_Close_Date_30_60_90__c <> null
                         ORDER BY Account.Name
                        ];

        // Creating Set to store unique values
        Set<String> monthSet = new Set<String>();
        Set<String> terrSet = new Set<String>();
        for (Opportunity o : opportunities){
            monthSet.add(o.Close_Month_Forecasted__c);
            terrSet.add(o.Account.Terr_From_Zip__c);
        }

        // Converting to List in order to sorth the results alphabetically
        List<String> monthList = new List<String>(monthSet);
        List<String> terrList = new List<String>(terrSet);
        monthList.sort();
        terrList.sort();

        closeDates = new String[monthList.size()];
        Integer i = 0;
        for(String month : monthList){
            closeDates[i] = month;
            i++;

        }

        terrs = new String[terrList.size()];
        Integer i2 = 0;
        for(String terr : terrList){
            terrs[i2] = terr;
            i2++;

        }

    }

}

**** VF PAGE ****
<apex:page controller="ForecastController" action="{!load}" sidebar="false"  tabStyle="Opportunity" docType="html-5.0">

    <apex:sectionHeader title="Opportunities" subtitle="Forecast Review"/>
    <apex:repeat value="{!closeDates}" var="c" >

        <apex:pageBlock title="Close Date (Forecasted) {!c}" >

            <apex:repeat value="{!terrs}" var="t" >
                <apex:pageBlock title="Territory {!t}" >

                            Account Name

                            Territory

                            Territory Manager

                            Stage

                            Prev Stage

                            Opportunity Name

                        <apex:repeat var="opps" value="{!opportunities}">

                            <apex:variable var="v" value="" rendered="{!IF(c=opps.Close_Month_Forecasted__c && t=opps.Account.Terr_From_Zip__c,true,false)}">

                                     {!opps.Account.Name}

                                    {!opps.Account.Terr_From_Zip__c}

                                     {!opps.Account.Territory_Manager__c}

                                    {!opps.StageName}

                                        <apex:outputText rendered="{!IF(opps.Opportunity_Snapshots__r.size > 0,true,false)}">
                                            {!opps.Opportunity_Snapshots__r[0].Stage__c}
                                        </apex:outputText>

                                    {!opps.Name}

                            </apex:variable>

                        </apex:repeat>

                </apex:pageBlock>
            </apex:repeat>
        </apex:pageBlock>

    </apex:repeat>

</apex:page>

A: You need to structure your data into maps, so that you have more control on the Apex side; this will also greatly improve performance. Here's a modified version of the controller logic:
public class ForecastController {
    public Map<String, Map<String, List<Opportunity>>> values { get; set; }
    public class ForecastWrapper {
        public String closeMonth { get; set; }
        public String[] territories { get; set; }
    }
    public List<ForecastWrapper> forecasts { get; set; }

    public void load(){
        // Load all the data into a map
        values = new Map<String, Map<String, List<Opportunity>>>();
        for(Opportunity record:
                        [SELECT Id, Name, Account.Name, Account.Territory_Manager__c, StageName, CloseDate, Forecastable__c,
                        Forecasted_Close_Date_30_60_90__c, Close_Month_Forecasted__c, Account.Terr_From_Zip__c,
                        (Select Id, Account_Name__c, ADRBD_Forecast_Close_Date__c, Close_Date__c, Close_Month_Forecasted__c, Install_Date_Instruments_only__c, Opportunity__c,
                        Opportunity_Name__c, Opp_Safe_ID__c, Quantity__c, Stage__c, Territory__c, Territory_Manager__c, Total_FS_Modules__c, Total_Instr_Revenue__c, Total_Price__c, CreatedDate FROM Opportunity_Snapshots__r)
                        FROM Opportunity
                        WHERE (NOT Name LIKE 'Test')
                        AND (Account.BillingCountryCode = 'US' OR Account.BillingCountryCode = 'CA')
                        AND Forecastable__c = true
                        AND Forecasted_Close_Date_30_60_90__c <> null
                        ORDER BY Account.Name
                        ]) {
            Map<String, List<Opportunity>> dateRange = values.get(record.Close_Month_Forecasted__c);
            if(dateRange == null) {
                values.put(record.Close_Month_Forecasted__c, dateRange = new Map<String, List<Opportunity>>());
            }
            List<Opportunity> territoryList = dateRange.get(record.Account.Terr_From_Zip__c);
            if(territoryList == null) {
                dateRange.put(record.Account.Terr_From_Zip__c, territoryList = new List<Opportunity>());
            }
            territoryList.add(record);
        }
        // Load the "keys" into our specified order
        forecasts = new ForecastWrapper[0];
        String[] months = new List<String>(values.keySet());
        months.sort();
        for(String month: months) {
            Map<String, List<Opportunity>> territoryList = values.get(month);
            String[] territories = new List<String>(territoryList.keySet());
            territories.sort();
            ForecastWrapper wrap = new ForecastWrapper();
            wrap.month = month;
            wrap.territories = territories;
            forecasts.add(wrap);
        }
    }
}

And then, the Visualforce page would use that wrapper instead:
<apex:page controller="ForecastController" action="{!load}" sidebar="false"  tabStyle="Opportunity" docType="html-5.0">

    <apex:sectionHeader title="Opportunities" subtitle="Forecast Review"/>
    <apex:repeat value="{!forecasts}" var="c" >

        <apex:pageBlock title="Close Date (Forecasted) {!c.month}" >

            <apex:repeat value="{!c.territories}" var="t" >
                <apex:pageBlock title="Territory {!t}" >

                            Account Name

                            Territory

                            Territory Manager

                            Stage

                            Prev Stage

                            Opportunity Name

                        <apex:repeat var="opps" value="{!values[c][t]}">

                                     {!opps.Account.Name}

                                    {!opps.Account.Terr_From_Zip__c}

                                     {!opps.Account.Territory_Manager__c}

                                    {!opps.StageName}

                                        <apex:outputText rendered="{!opps.Opportunity_Snapshots__r.size > 0}">
                                            {!opps.Opportunity_Snapshots__r[0].Stage__c}
                                        </apex:outputText>

                                    {!opps.Name}

                            </apex:variable>

                        </apex:repeat>

                </apex:pageBlock>
            </apex:repeat>
        </apex:pageBlock>

    </apex:repeat>

</apex:page>

This is only a quick hack--you may need additional work. However, it is my hope that this demonstration will at least get you started on the right path.
Note that this also solves a major performance bottleneck. If you have 10 territories with 10 months and 100 opportunities, your code previously needed 10,000 loop iterations, while the new code requires only a few hundred. You should see greatly improved performance. Also, this new design won't crash when you have more than 1,000 opportunities to display (total), but can instead handle tens of thousands of opportunities.


text:
Q: count no of spans of specific class within a dynamically generated div Supposing I have a number of divs that are dynamically generated and contain text. Each of these divs have a unique id which is also dynamically generated, e.g.

 ... text ...

Now within those divs there are spans of a particular type that have been dynamically generated according to a regex, e.g. when the word "significant" is encountered it is tagged as
significant

This is being done via mark.js
What would be a suggestion for a javascript function to enable counting the spans within each div with the aim of placing the count value in an element associated with that div?

A: Using jQuery you can do:

$('div[id^="abstract_"]').each(function () {
  var $this = $(this),
      len = $this.find('span.emphasis').length;

  console.log($this.attr('id'), len);
});
div {margin: 0 0 15px 0;}
span.emphasis {color: red;}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente ipsam animi, alias harum aut est unde voluptates repudiandae vel molestias significant, officia! Illum dolore pariatur sequi magnam minus, aliquid voluptate officia, quaerat sint quam commodi.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente ipsam animi, alias harum aut est unde voluptates repudiandae vel molestias, officia! Illum dolore pariatur sequi magnam minus, aliquid voluptate officia, quaerat sint quam commodi.

A: If you want to do using plain Javascript.
function myFunction() {
    var i;
    var x = document.querySelector("[id^=abstract_]").querySelectorAll("span");
    for (i = 0; i < x.length.i++){
        x[i].id = i;
    }
}

This code will add id to each span as the index of the span inside the div with id=abstract_12345.

A: This should do the trick, if I understand your wish correctly.
$('id*="abstract_"').each(function() {
  var amount = $(this).find('span.emphasis').length;

  $(this).prepend(amount);
});


text:
Q: Add HTTP Header to all of Django Admin? I'm looking to add an HTTP header to all requests in the Django admin panel. I'm not sure if this could be done with custom views?
I'm using an http header to check later if a user has access to another portion of the website, and the library I'm using does admin scope via HTTP headers.
Thanks!

A: You can add it using a django middleware adding headers to the HttpResponse objects of admin views: https://docs.djangoproject.com/en/1.8/topics/http/middleware/


text:
Q: WebRTC remote stream size too big I'm trying to record the remote video stream in a WebRTC call. I think the main problem is that I can't use codecs to compress the recorded video.
I've tried this code
  let options = {mimeType: 'video/mp4;codecs=vp9'};
  if (!MediaRecorder.isTypeSupported(options.mimeType)) {
    console.error(`${options.mimeType} is not Supported`);
  options = {mimeType: 'video/mp4;codecs=vp8'};
  if (!MediaRecorder.isTypeSupported(options.mimeType)) {
  console.error(`${options.mimeType} is not Supported`);
  options = {mimeType: 'video/mp4'};
  if (!MediaRecorder.isTypeSupported(options.mimeType)) {
    console.error(`${options.mimeType} is not Supported`);
    options = {mimeType: ''};
  }
}
}

In the snippet above I'm trying .mp4 type but codecs are rejected. Same happens if I try other codecs like h.264 instead of vp9.
The only file type that is accepted is .webm with vp9 encoding but its size is too big.
Code is based on this source

A: Not all browsers support all the formats you're trying to use.  In any case, you're complaining that the output with VP9 is too big, and yet it's one of the most efficient codecs available.
Your actual problem is that the default bitrates are too high, and you're not setting them.  Try this instead:
const mediaRecorder = new MediaRecorder(stream, {
  audioBitsPerSecond: 128 * 1000, // 128 kbit/s
  videoBitsPerSecond: 2 * 1000 * 1000, // 2 Mbit/s
});

Adjust those values as necessary for your quality/file size tradeoff.

A: From my experience in this same scenario, we have two options

*

*Write the file type as .mp4 still the file internally is .webm.

*Use a third-party library for compressing or converting the file type in the browser or in Node Backend.
Ex: https://github.com/bgrins/videoconverter.js (not actively maintained)

Actually, it's not a good idea to load a heavy file in a browser. FFMPEGJS gzipped takes 6.7MB which is quite heavy.
I did write a screen recorder though https://s.ajx.io try it. I followed option 1 :P


text:
Q: Net use on scheduled bat I have this bat file scheduled in a windows server 2008 r2:
net use \\ip\share\employees\ /user:domain\user password
robocopy C:\Zucchetti\Timbrature\sicurezza\ \\ip\share\employees\ Timbrature_Giornaliere_5min.csv /R:0 /W:0 /v > C:\Zucchetti\Timbrature\sicurezza\logcopia.txt
del "Timbrature_Giornaliere_5min.csv"

If I run the bat manually the it runs fine.
If I run the bat scheduled with windows server 2008 task scheduler wether the user is logged on or not I get the following error in the log:
-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows
-------------------------------------------------------------------------------

  Started : Thu Mar 21 16:52:00 2019

2019/03/21 16:52:00 ERROR 1326 (0x0000052E) Getting File System Type of Destination \\ip\share\employees\
Logon failure: unknown user name or bad password.

   Source : C:\Zucchetti\Timbrature\sicurezza\
     Dest - \\ip\share\employees\

    Files : Timbrature_Giornaliere_5min.csv

  Options : /V /COPY:DAT /R:0 /W:0

------------------------------------------------------------------------------

2019/03/21 16:52:00 ERROR 1326 (0x0000052E) Accessing Destination Directory \\ip\share\employees\
Logon failure: unknown user name or bad password.

How could I make it work in a scheduled bat file?


text:
Q: JSONP call => ReferenceError : document is not defined For my internship I'm asked to develop a mobile application based on this website (www.claroline.net). The technology I have to use is Nativescript combined with Angular 2. I managed to implement the login function so users of the website can now sign in on the app.
Then I have to be able to get the notifications of the website on the app. At the beginning I just want to display the notifications in a JSON array. I already have the url to get the JSON array (the get request works on the browser) but when I do that from the mobile application, I get a 500 error.
I heard then about JSONP which might help me solve my problem. Apparently there is few things to do :
- import JSONP_PROVIDERS in the root component and bootstrap it
- import Jsonp in the component you want to do the Jsonp call
- add a callback parameter in the url
Am i missing anything ? Because even though I did all that, I get an error in the console :"ReferenceError : document is not defined" in some Javascript file which is weird because since I'm coding in Typescript, there are no variables called document.

A: Here is the way to use JSONP support in Angular2.
After having registered JSONP_PROVIDERS when calling the bootstrap function:
import {bootstrap} from 'angular2/platform/browser'
import {JSONP_PROVIDERS} from 'angular2/http'
import {AppComponent} from './app.component'

bootstrap(AppComponent, [ JSONP_PROVIDERS ]);

You can then execute your request using an instance of the Jsonp class you injected from constructor:
import {Component} from 'angular2/core';
import {Jsonp} from 'angular2/http';

@Component({
  selector: 'my-app',
  template: `
    <div>
      Result: {{result | json}}
    </div>
  `
})
export class AppComponent {
  constructor(jsonp:Jsonp) {
    var url = 'https://...&c=JSONP_CALLBACK';
    jsonp.request(url, { method: 'Get' })
     .subscribe((res) => {
       this.result = res.json()
     });
  }
}

In your case, the c parameter could have another name but you need to set the JSONP_CALLBACK value in it.
See this plunkr: http://plnkr.co/edit/dqreqBL6kyNkR8Z2wgGR?p=preview


text:
Q: Getting empty value from stored procedure (sybase) CREATE PROCEDURE [dbo].[proc1]
(
    @tbl1   varchar(30),
    @var2   varchar(7000)
)
AS
BEGIN
    DECLARE @sql VARCHAR(8000)

    BEGIN
        SET @sql = 'INSERT INTO ' + @tbl1 + '(column) VALUES (''' + @var2 + ''')'

        EXEC (@sql)

        RETURN CONVERT(int, NEXT_IDENTITY(@tbl1))
    END
END

C# Method:
//create connection
using (AseConnection cn = new AseConnection(connectionString)) {
    AseCommand cmd = new AseCommand();

    AseParameter[] paras = new AseParameter[]{
        new AseParameter("@tbl1", AseDbType.VarChar, 30),
        new AseParameter("@var1", AseDbType.VarChar, 7000),
        new AseParameter("@RetValue",AseDbType.Integer) };
    // Add all the parameters to command object
    foreach(AseParameter p in  paras) {
        cmd.Parameters.Add(p);
    }

    //finally, execute the command.
    return cmd.ExecuteNonQuery();
}

However, the third parameter is always empty. If I execute procedure directly in Sybase client, it gives me correct value.
Does anyone have good suggestion how to solve this issue?

A: Declare the third parameter as
AseParameter retParam = new AseParameter("@RetValue",AseDbType.Integer);
retParam.Direction = ParameterDirection.ReturnValue;

Also, select the identity with
RETURN @@identity


text:
Q: I'm playing around with different design patterns in Javascript. This factory has got me confused I'm playing around with different JS design patterns, and im trying to modify some samples I've seen out there.  I saw an example of a xhr factory, that had several nested try/catch statements that were nested within eachother.
try{
...
}catch(e){
    try{
    ...
    }catch(e){}
}

I figured I'd be able to do a self-invoking function.  However It seems to have eluded me as to how it should work.  Does anyone have any advice?
Example:
http://jsfiddle.net/jiggliemon/a7xWq/2/

[Update]:
http://jsfiddle.net/jiggliemon/b5LaZ/embedded/
Case Closed.

A: Changed try loop to:
for(var i = 0, l = instances.length; i < l; i ++) {
    try{
        var obj = instances[i].getInstance();
        return instances[i];
    }catch(e){ }
}

Full code

A: var XHR = (function(){
    var ins = [
        function(){return new XMLHttpRequest();},
        function(){return new ActiveXObject('Msxml2.XMLHTTP');},
        function(){return new ActiveXObject('Microsoft.XMLHTTP');}
    ],i,tmp;

    return (function tryIns(i){
        i = i || 0;
        while(i < ins.length){
            try{tmp = ins[i]();}
            catch(e){i++; tryIns(i);}
            finally{return ins[i];}
        }
        throw new Error("Your browser doesn\'t support Ajax requests");
    })();
})();


text:
Q: terminator requires java 6 or newer? I installed terminator (org.jessies.terminator.i386.deb) on ubuntu 12.04 but after executing it i got this error.
"Terminator requires Java 6 or newer.
http://java.sun.com/javase/downloads/ may link to a suitable JRE, if you can't use one provided by your OS vendor"
can anyone help me on this?
Farooq

A: If you are talking about the terminal emulator terminator, it does not need Java and it is installable from the main repositories. This is what you get when installing on a fresh 13.04 install:
terdon@oregano ~ $ sudo apt-get install terminator
Reading package lists... Done
Building dependency tree
Reading state information... Done

The following extra packages will be installed:
  libbonobo2-0 libbonobo2-common libbonoboui2-0 libbonoboui2-common
  libglade2-0 libgnome2-0 libgnome2-bin libgnome2-common libgnomecanvas2-0
  libgnomecanvas2-common libgnomeui-0 libgnomeui-common libgnomevfs2-0
  libgnomevfs2-common libidl-common libidl0 libkeybinder0 liborbit2
  libvte-common libvte9 python-gnome2 python-keybinder python-pyorbit
  python-vte
Suggested packages:
  libbonobo2-bin desktop-base libgnomevfs2-bin libgnomevfs2-extra gamin fam
  gnome-mime-data python-gnome2-doc python-pyorbit-dbg
The following NEW packages will be installed:
  libbonobo2-0 libbonobo2-common libbonoboui2-0 libbonoboui2-common
  libglade2-0 libgnome2-0 libgnome2-bin libgnome2-common libgnomecanvas2-0
  libgnomecanvas2-common libgnomeui-0 libgnomeui-common libgnomevfs2-0
  libgnomevfs2-common libidl-common libidl0 libkeybinder0 liborbit2
  libvte-common libvte9 python-gnome2 python-keybinder python-pyorbit
  python-vte terminator

As you can see in the output above, there is no java or JRE requirement and you can install terminator (which is a python program) directly from the Ubuntu repositories.

There are actually two terminal emulators with the same name. The one you tried to install does indeed need Java and if you are really sure you want that one, despite its being much heavier (java) and complicated to install, you can install a JRE with
sudo apt-get install openjdk-7-jre

I stress however, that installing jre to get a terminal emulator is ridiculous. As far as I can tell both terminator flavors have the same functionality but the one you want to install is simply much much much heavier on the system. Still, your choice.

A: I recommend the Oracle version over OpenJDK. Java 7 should work. Installation is described here:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer


text:
Q: APEI generic hardware error The following error message is shown while installing ubuntu 13.10
[hardware error]: Hardware error from APEI generic hardware error source 0
[hardware error]: APEI generic hardware error status
[hardware error]: severity: 1, fatal
[hardware error]: section: 0, severity: 1, fatal
[hardware error]: flags: 0X01
[hardware error]: primary
[hardware error]: fru_text: uncorrectedErr
[hardware error]: section_type: PCIe error
[hardware error]: command: 0x0010, status: 0x0147
[hardware error]: device_id: 0000:00:00.0
[hardware error]: slot: 0
[hardware error]: secondary_bus: 0x00
[hardware error]: vendo_id: 0x1077, device_id: 0x7322
[hardware error]: class_code: 00060c
kernel panic - not syncing: Fatal hardware error!
rebooting in 30 seconds


text:
Q: Opening GIMP with Ruby So I'm making a Ruby Shoes application and I want to be able to open a file with GIMP from it. So far I've tried running gimp from ruby and all it does is return the command line message:
gimp
/Applications/GIMP.app/Contents/MacOS
/Applications/GIMP.app/Contents/MacOS/:/Applications/GIMP.app/Contents/Resources/bin:/Users/a/.rvm/gems/ruby-2.0.0-p247/bin:/Users/a/.rvm/gems/ruby-2.0.0-p247@global/bin:/Users/a/.rvm/rubies/ruby-2.0.0-p247/bin:/Users/a/.rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/a/.rvm/bin:/Applications/GIMP.app/Contents/MacOS

Trying to open an application with open -a GIMP somefile.jpg from within ruby just gives me an error window saying GIMP cannot be opened because of a problem.
EDIT:
Okay, so I'm here with a friend of mine and we're working on it together and we found out something that makes me angry like the hulk. I made a small program that still has the same error.
Shoes.app width: 640, height: 756, title: 'Eine' do
  para `source ~/.bashrc; GIMP PRfyS.jpg`
end

What's stupid about it? I can go into my Terminal and type ruby -e " Shoes.app width: 640, height: 756, title: 'Eine' do para source ~/.bashrc; GIMP PRfyS.jpg end and it works. (backticks are removed for stackoverflow formatting)

A: I'm not sure I understand what exactly you want to do. if you just want to a button to launch GIMP then this is how I'd do it
Shoes.app do
    button "open gimp" do
        spawn 'gimp PRfyS.jpg'
    end
end


text:
Q: Dynamically generated partial applications of a function to be passed to a struct as function pointers So basically I am a complete beginner to a C++ but I have to face this complicated problem.
I basically have to design some strategy to a simple "dice poker game" similar to the one from Witcher. I came up with a strategy that relies on 4 parameters and I want to analyze which combination of parameters yields the best results by brute-forcely trying all of those combinations.
The strategy is represented by this struct:
typedef struct SOLUTION
{
    const char Name[32];
    const char ShortName[8];
    void(* Init)();
    int(* AI)(int, int, int, int);
}
SOLUTION;

Now, what I have is a "highly" parametric function:
static int AI_noRiskVar (int a, int b, int c, int d, int opponent_id, int bet, int state, int dice) {
    //do some stuff based on parameters a, b, c, d and the rest of parameters (which represent the game actual state)
}

Along with that, I have a simple API, that enables me to test any number of strategies against each other. All I have to do is to put them into an array of SOLUTION structs.
I came up with this plan, that tries to make use of std::bind function, which should be able to partially apply my AI_noRiskVar function to some parameters a, b, c, d:
SOLUTION Solution[83521]
int kauntr = 0;
for (int a = 3; a < 20; ++a) {
    for (int b = 3; b < 20; ++b) {
        for (int c = 3; c < 20; ++c) {
            for (int d = 3; d < 20; ++d) {
                // the identification of which struct contains which strategy is not important now
                Solution[kauntr] = (SOLUTION){"fixed length string of 31 chars", "7 chars", NULL, std::bind(&AI_noRiskVar, a, b, c, d)};
            }
        }
    }
}

I want to create an array of structs of which every one would have one combination of those a, b, c, d parameters partially fed into its AI function, i. e. have every possible configuration of the strategy tested via one of the generated structs.
Problem is, that the std::bind does not return a partially applied function of exactly type int* (int, int, int, int) but of type _Bind(int*(int, int, int, int))
Any suggestions on how to fix the type problem? Or am I missing something critical?
I had my hands on C, and almost all other major programming languages, but not C++ and I feel really lost even in the syntax arount types.
EDIT1:
I am not able to change the definition nor declaration of struct SOLUTION so i need to get exactly to the type described above. Is it even possible?
Also, if you are to present some C++ specific library functions or methods, could you please show how to use them in the context of my problem, it would help me understand the C++ way of coding.


text:
Q: C++ shared libraries I am trying to get my head around the way shared libraries work in the c++ unix environment. I understand we only need header files and no shared libraries specification when compiling code. But if I want to create an executable or shared library from my compiled files, do I need to specify shared library dependencies (those are dynamic)? And do the paths of shared libraries need to match the path at runtime loading?
I am using Linux 2.6.18-164.11.1.el5 #1 SMP x86_64 GNU/Linux
I am having a problem where my code is not able to pick up a library at runtime. I have tried setting LD_LIBRARY_PATH and PATH. But at runtime when I run the executable, I get the following error:
Error: librc.so: cannot open shared object file: No such file or directory
Sam

A: The headers are only for the compile phase. At link time, you usually have to specify which shared libs you are going to link to. You might see -L options to set locations to where shared libraries reside, and/or -l to specify which libraries to link. There is usually also a switch on the command line to alert the linker as to whether you are using thread-safe versions of the libs or the 'regular' ones, and another switch to specify dynamic linking.
At run time, whether you are starting the program that uses the libs, or running ldd to find out what it needs, the OS has a system for locating .so files, and this can vary from one unix version to another. The LD_LIBRARY_PATH variable specifies where to look for .so files, but may not be the full story, depending on the exact unix version in question. Also, you probably don't want to fiddle around with modifying LD_LIBRARY_PATH except from a throw-away shell, since it has system wide effects. A better option is to check it the 'missing' .so files are or are not on the existing path set by LD_LIBRARY_PATH, and if not, try putting copies of them somewhere on that path.

A: At run time, dynamic libraries are searched:

*

*in a path recorded in the executable (under linux with -rpath at link time, under Solaris with -R, using $ORIGIN in a directory name allows to specify a directory relative to the directory containing the executable)

*in the LD_LIBRARY_PATH (or equivalent, there are sometimes 64/32 bits variant).  If a path has been recorded in the executable, LD_LIBRARY_PATH may not searched (under Linux it is searched after the recorded path if the executable has been linked with the option --enable-new-dtags; I don't remember Solaris behavior for now)

*in a set of system dependant directories (Linux allows to specify them in /etc/ld.so.conf and has a cache, see ldconfig)


text:
Q: how to interpret as streaming feature from arff format? I am trying to build an algorithm for streaming feature selection.
currently I dont have streaming data , so I am using UCI dataset (arff format) as streaming data. Streaming data means each attribute comes one by one.
So, I want to use data as one attribute and class. The following code read data and store in instance object.
BufferedReader reader = new BufferedReader(new FileReader("D:\\Exp\\iris.arff"));
Instances data = new Instances(reader);
reader.close();
data.setClassIndex(data.numAttributes() - 1)

iris data has sepal length , sepal width, petal length, petal width attribute and class attribute.
I want to store sepal length and class attribute in another instance object.
HOw can I do this ?


text:
Q: PauseTransition Implementation event syntax I am struggling to get a pauseTransition that makes use of .setOnFinished().
I am new to dealing with javafx events and so suspect that my issue may lie here.
My original error, I proceeded to encounter many more whilst attempting to fix it, was as follows:
Code:

pt.setOnFinished(
  event -> {
  image=otherImage;
                }
                                  );

Resulting message:

illegal expression
illegal expression
illegal expression

If possible can the individual kind enough to give me an answer explain what the " event-> " does?


text: Q: Preview search not highlighting instances of the word I am using OSX Catalina. However, for quite some time, do not remember from which OSX, Preview stopped highlighting instances of a searched for word.  As suggested in the answer to the post Preview does not find words correctly, if I choose `Table of Contents' in View, the sections of pages where the searched for word appears are displayed in the sidebar but the word is not highlighted. Also, in the top right corner of the Preview window, below the search box, there are two arrows to go forward/backward through the search results. These arrows remain greyed out and do not work. These issues are rather irksome. Is there any way out?