text:
Q: Create new numpy array-scalar of flexible dtype I have a working solution to my problem, but when trying different things I was astounded there wasn't a better solution that I could find. It all boils down to creating a single flexible dtype value for comparing and inserting into an array.
I have an RGB 24-bit image (so 8-bits for each R, G, and B) image array. It turns out for some actions it is best to use it as a 3D array with HxWx3 other times it is best to use it as a structured array with the dtype([('R',uint8),('G',uint8),('B',uint8)]). One example is when trying to relabel the image colors so that every unique color is given a different value. I do this with the following code:
# Given im as an array of HxWx3, dtype=uint8
from numpy import dtype, uint8, unique, insert, searchsorted
rgb_dtype = dtype([('R',uint8),('G',uint8),('B',uint8)]))
im = im.view(dtype=rgb_dtype).squeeze() # need squeeze to remove the third dim
values = unique(im)
if tuple(values[0]) != (0, 0, 0):
    values = insert(values, 0, 0) # value 0 needs to always be (0, 0, 0)
labels = searchsorted(values, im)

This works beautifully, however I am tried to make the if statement look nicer and just couldn't find a way. So lets look at the comparison first:
>>> values[0]
(0, 0, 0)
>>> values[0] == 0
False
>>> values[0] == (0, 0, 0)
False
>>> values[0] == array([0, 0, 0])
False
>>> values[0] == array([uint8(0), uint8(0), uint8(0)]).view(dtype=rgb_dtype)[0]
True
>>> values[0] == zeros((), dtype=rgb_dtype)
True

But what if you wanted something besides (0, 0, 0) or (1, 1, 1) and something that was not ridiculous looking? It seems like there should be an easier way to construct this, like rgb_dtype.create((0,0,0)).
Next with the insert statement, you need to insert 0 for (0, 0, 0). For other values this really does not work, for example inserting (1, 2, 3) actually inserts (1, 1, 1), (2, 2, 2), (3, 3, 3).
So in the end, is there a nicer way? Thanks!

A: I could make insert() work for your case doing (note that instead of 0 it is used [0]):
values = insert(values, [0], (1,2,3))

giving (for example):
array([(0, 1, 3), (0, 0, 0), (0, 0, 4), ..., (255, 255, 251), (255, 255, 253), (255, 255, 255)],
       dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1')])

Regarding another way to do your if, you can do this:
str(values[0]) == str((0,0,0))

or, perhaps more robust:
eval(str(values[0])) == eval(str(0,0,0))


text:
Q: Expected an indented block, python Hello can someone fix it I tried to find solution online but nothing work.
Python Version: 3.7.9
if engine == "example1":
        search = example1(engine)
        request = partial(search.search_for, string)
        all = p.map(request, pages)

elif engine == "example2":
        filepath = "list.txt"
        with open(filepath) as fp:
            line = fp.readline()
            count = 1
            while line:
                search = example2(engine)
                request = partial(search.search_for, line.strip())
                all = p.map(request, pages)
                line = fp.readline()
                count += 1
            input(" press close to exit ")

A: It appears that the biggest issue is with lines immediately following your with statement.  Those should be indented to be part of the context manager scope.
elif engine == "example2":
    filepath = "list.txt"
    with open(filepath) as fp:
        line = fp.readline() # <--- note indent
        count = 1            # <--- note indent
        while line:
            search = example2(engine)
            request = partial(search.search_for, line.strip())
            all = p.map(request, pages)
            line = fp.readline()
            count += 1

A: Here you have 2 intent mistakes.copy this code and try it
if engine == "example1":
     search = example1(engine)
     request = partial(search.search_for, string)
     all = p.map(request, pages)

1. In elif there is one space before the line
elif engine == "example2":
    filepath = "list.txt"

2.After the next line With open you need to leave 4 spaces
    with open(filepath) as fp:
        line = fp.readline()
    count = 1
    while line:
        search = example2(engine)
        request = partial(search.search_for, line.strip())
        all = p.map(request, pages)
        line = fp.readline()
        count += 1
    input(" press close to exit ")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update Eloquent model without touching timestamp (Laravel 3)? I need to update an Eloquent model in Laravel 3 without touching the automatic timestamp. Code is super simple:
$thread->views = $thread->views + 1;
$thread-> save();

However that also updates the timestamp. I've seen this: Update without touching timestamps (Laravel) but it does not seem to work in L3, or maybe I've done something wrong. In the Thread model there is:
public static $timestamps = true;

Which updates the updated_at timestamp field in the database. I need to update the thread model somehow without touching the timestamp. Anyone know how? The documentation http://three.laravel.com/docs/database/eloquent does not have anything about this issue...

A: Not sure if this works for L3, but in L4 I think you can do:
$thread->timestamps = false;
$thread->save();

A: Answered my own question with a workaround. Just do:
$thread->views = $thread->views + 1;
DB::table('threads')->where('id', '=', $thread->id)->update(array('views' => $thread->views));


text:
Q: Uncaught ReferenceError: Component not defined in Meteor I'm trying to display my Deal component but I keep getting this error below.
I'm using Meteor with ReactJS.

Uncaught ReferenceError: Deal is not defined
      at meteorInstall.imports.routes.routes.js

Here is my routes.js file
<Route path="/deals" component={Deal} secure="auth" />

My Deal.js component file, that the route should be linking too.
import React from 'react';
import { Link } from 'react-router';
import PrivateHeaderNav from './PrivateHeaderNav.js'

export default class Deal extends React.Component {
  render() {
    return (
      <div className="content">
        <PrivateHeaderNav/>
        Deal
      </div>
    );
  }

}
Am I missing something in the imports or in my Deal component?
Thanks

A: Your routes.js file is lacking the import of Deal component.
make sure you have this line in route.js:
import Deal from './path/to/Deal.js';


text:
Q: How to send Parameter to an action, using formatter: 'showlink' in jqGrid 4.6.0 in MVC I have a column named " CONTRACT_REQ_SUBJECT " in my jqGrid .  and i want to make it a link that redirects to another action with sending parameter to that action. and I want to get this parameter from a different column of this  jqgrid . and of course i want the text to be the value of  CONTRACT_REQ_SUBJECT  that i get from database.
here is my Code :
{  name:'CONTRACT_REQ_SUBJECT',index:'CONTRACT_REQ_SUBJECT',edittype:'select'  , formatter: 'showlink'  , formatoptions: { baseLinkUrl: '/Home/Steps_Details/' , idName: 'CONTRACT_REQ_SUBJECT' }   },

Everything is ok , I just can't send the parameter  to the action.
Maybe it will work with  "  addParam:  "  , but i don't know how to use it.
Thanks in Advance...
UPDATE THE QUESTION :
@Oleg Thanks for your solutions in comments, but I couldn't solve this problem. so i decided  to do it in another way like below codes:
 {  name:'CONTRACT_REQ_SUBJECT',index:'CONTRACT_REQ_SUBJECT',edittype:'select'  , formatter: 'showlink'  , formatoptions: { baseLinkUrl: '/Home/Steps_Details/' , idName: 'CONTRACT_REQ_SUBJECT'  , addParam : "Contract_Req_Id= 123" }   },

And now the problem is that instead of 123(in my above code) I want to send the value of " CONTRACT_REQ_ID " of the current row to my controller  and don't know how to do this.
Is there  a way to save the " CONTRACT_REQ_ID " into a variable and then sending the variable as parameter to my action ?
Maybe something like this :
var myGrid = $('#list'),
selRowId = myGrid.jqGrid ('getGridParam', 'selrow'),
celValue = myGrid.jqGrid ('getCell', selRowId, 'CONTRACT_REQ_ID');

But i don't know where to place it in my code.
My code is :
 <script type="text/javascript">
$(document).ready(function () {
    $('#list').jqGrid({
        caption: "گزارش پیگیری قراردادها",
        url: '@Url.Action("Get_Contracts_Steps","Home")',
        datatype: 'json',
        jsonReader: {
            root: "Rows",
            page: "Page",
            total: "Total",
            records: "Records",
            repeatitems: true,
            userdata: "UserData",
            id: "Vahed_Descript",
            cell: "RowCells"
           // ,  data: { REQ_UNIQE: "REQ_UNIQE" },
        },
        mtype: 'GET',

        //columns names
        colNames: [' عنوان واحد ',
                            ' کد دبیرخانه ',
                            ' شماره درخواست ',
                            ' شرح درخواست ',
                            ' مبلغ برآوردی ',
                            ' تاریخ ثبت درخواست',
                            ' تاریخ تایید مدیر اجرایی ',
                            ' تاریخ تایید قائم مقام / معاونت ',
                            ' تاریخ ارسال درخواست به تدارکات ',
                            ' تاریخ اخذ استعلام ',
                            ' تاریخ ارسال پاکات قیمت',
                            ' تاریخ تایید بودجه- درخواست ',
                            ' تاریخ بازگشایی پاکات',
                            'تاریخ تایید صورت جلسه استعلام ',
                            ' تاریخ نامه احراز صلاحیت ',
                            ' تاریخ اخذ مدارک  ',
                            'تاریخ تهیه پیش نویس قرارداد ',
                            'تاریخ ارسال پیش نویس به دفتر  IT',
                            'تاریخ تایید پیش نویس توسط معاون',
                            'تاریخ تایید پیش نویس توسط مدیر',
                            ' تاریخ ثبت پیش نویس در سامانه کتاب ما ',
                            ' تاریخ تایید بودجه-پیش نویس ',
                            'تاریخ ارسال به ممیزی ',
                            'تاریخ تایید ممیزی',
                            'تاریخ تهیه نسخ قرارداد',
                            'تاریخ امضای شرکت',
                            'تاریخ امضاو ابلاغ قرارداد',
                            'شماره قرارداد ',
                            '',
                            ' نمایش جزییات '
        ],
        //columns model

        colModel: [
            { name: 'DESCRIPT', index: 'DESCRIPT', align: 'right'  },
            { name: 'DABIR_VAHED_CODE', index: 'DABIR_VAHED_CODE', align: 'right' },
            { name: 'CONTRACT_REQ_ID', index: 'CONTRACT_REQ_ID', align: 'right' },

            { name: 'CONTRACT_REQ_SUBJECT', index: 'CONTRACT_REQ_SUBJECT', edittype: 'select'
                , formatter: 'showlink'
                , formatoptions: {
                    baseLinkUrl: '/Home/Steps_Details/', addParam: '&CONTRACT_REQ_ID=123' , idName: 'CONTRACT_REQ_SUBJECT'
                  }
            },
            { name: 'AMNT_TOT_ESTIMATE', index: 'AMNT_TOT_ESTIMATE', align: 'center',  formatter: 'currency',
                formatoptions:
                {  decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 0  }
            },
            { name: 'Req_Creation_Date', index: 'Req_Creation_Date', align: 'center'   },
            { name: 'Req_Exec_Confirm', index: 'Req_Exec_Confirm', align: 'center'  },
            { name: 'Req_Moavenat_Cnfrm', index: 'Req_Moavenat_Cnfrm', align: 'center'  },
            { name: 'SendToTadarokat', index: 'SendToTadarokat', align: 'center' },
            { name: 'GotEstelam', index: 'GotEstelam', align: 'center' },
            { name: 'SendPricePockets', index: 'SendPricePockets', align: 'center' },
            { name: 'Req_Budg_Cnfrm', index: 'Req_Budg_Cnfrm', align: 'center' },
            { name: 'OpenPockets', index: 'OpenPockets', align: 'center' },
            { name: 'ConfirmedEstelamSuratJalase', index: 'ConfirmedEstelamSuratJalase', align: 'center' },
            { name: 'EhrazSalahiatConfirmed', index: 'EhrazSalahiatConfirmed', align: 'center' },
            { name: 'GotDocs', index: 'GotDocs', align: 'center' },
            { name: 'Pre_Contract_Prepared', index: 'Pre_Contract_Prepared', align: 'center' },
            { name: 'sendprecontrtoIT', index: 'sendprecontrtoIT', align: 'center' },
            { name: 'PreContrConfirmed_Moaven', index: 'PreContrConfirmed_Moaven', align: 'center' },
            { name: 'PreContrConfirmed_Modir', index: 'PreContrConfirmed_Modir', align: 'center' },
            { name: 'SavePreCntrInKetabMa', index: 'SavePreCntrInKetabMa', align: 'center' },
            { name: 'Pre_BudgtCnfrm', index: 'Pre_BudgtCnfrm', align: 'center' },
            { name: 'SendToMomayeziDate', index: 'SendToMomayeziDate', align: 'center' },
            { name: 'Pre_MomayzCnfrm', index: 'Pre_MomayzCnfrm', align: 'center' },
            { name: 'ContrVersionsPreparedDate', index: 'ContrVersionsPreparedDate', align: 'center' },
            { name: 'CompanySignedVersionsDate', index: 'CompanySignedVersionsDate', align: 'center' },
            { name: 'ContrSignedDate', index: 'ContrSignedDate', align: 'center' },
            { name: 'CONTR_NO', index: 'CONTR_NO', align: 'center' },
            { name: 'REQ_UNIQE', index: 'REQ_UNIQE', width: 1, align: 'left', hidden: true },

            { name: 'Link', formatter: function (cellvalue, options, rowObject) {
                var x = '@Html.ActionLink("جزییات", "Steps_Details", "Home", new { REQ_UNIQE = "id" }, new { @style = "color:Blue;font-weight:bold;" })';
                return x.replace("id", rowObject[28]);
            }, align: 'center', width: 150,editurl: ' / Home / Steps_Details / '
            },

       ],

    pager: $('#pager'),
    rowNum: 300,
    rowList: [10, 20, 40, 60, 80, 100, 150, 200, 300, 400, 500, 600, 800, 1000, 1200],
    sortname: 'CONTRACT_REQ_SUBJECT',
    sortorder: 'asc',
    viewrecords: true,
    altRows: true,
    shrinkToFit: false ,
    width: 'auto',
    height: '300px',
    hidegrid: false,
    direction: "rtl",
    gridview: true,
    rownumbers: true,
    footerrow: true,
    userDataOnFooter: true,
    scrollerbar: true,
    loadComplete: function() {
        $("tr.jqgrow:odd").css("background", "#E0E0E0");
    },
    loadError: function(xhr, st, err) {
        jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
    }
    , loadonce: true

})

      .jqGrid('navGrid', "#pager",
         {
             edit: false, add: false, del: false, search: true,   refresh: true
         })

      .jqGrid('navButtonAdd', '#pager', {
          caption: "", buttonicon: "ui-icon-print", title: "خروجي پي دي اف",
          onClickButton: function () {

              $("#list").jqGrid('excelExport', { url: '@Url.Action("Get_Contracts_Steps", "Home")' });
          }
      })

    function toolbarSearching() {
        $("#list").jqGrid('filterToolbar', {
            autosearch: true,
            stringResult: false,
            searchOnEnter: true,
            defaultSearch: "cn",
        });
    };

    $("#list").jqGrid('filterToolbar', {
        autosearch: true,
        stringResult: false,
        searchOnEnter: true,
        defaultSearch: "cn",
    });

    var maxNameLength = 10;
    $("input[id=gs_name]").blur(function () {
        var $th = $(this).closest(".ui-search-toolbar>th"),
            colIndex = $th[0].cellIndex,
            $colHeader = $th.parent().siblings(".ui-jqgrid-labels").children("th").eq(colIndex),
            colHeaderText = $colHeader.children("div").text();
        if (this.value.length > maxNameLength) {
            alert(colHeaderText + ' is longer than ' + maxNameLength + ' characters.');
        }
    });
    $('#gs_invdate').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true
    });

})

A: Here is how I did :
    { name: 'CONTRACT_REQ_SUBJECT', index: 'CONTRACT_REQ_SUBJECT', edittype: 'select'
           , formatter: 'showlink'  , formatoptions: {
                    baseLinkUrl: '/Home/Steps_Details/', addParam: '&REQ_UNIQE=' ,
                      idName: 'CONTRACT_REQ_SUBJECT'
                  }


text:
Q: "Undefined" button when I try to save a table in phpMyAdmin I am new with phpMyAdmin but I want to learn so I make a table with diferent values (float, varchar, decimal, int, boolean). I also have an ID field as a primary key with A_I and cotejamiento (utf8 spanish ci) but when I try to save it appears a red "Undefined" button. What am I doing wrong.
Thank you all.


text:
Q: Failing to run tests using Karma I am setting up Karma to simplify unit tests in a legacy project. The problem is, I am getting an error You need to include some adapter that implements __karma__.start method!. As I have found, this is a very non-specific error, so I am at a loss of how to debug it further. I have reduced my setup to the bare minimum, but the error still persists.
Here is the karma config file:
module.exports = function (config) {
  config.set({
    browsers: [ 'PhantomJS' ], //run in Phantom
    autoWatch: false,
    singleRun: true, //just run once by default
    frameworks: [ 'mocha', 'chai', 'sinon', 'chai-sinon' ], // test frameworks
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    files: [
      './js/test/tests.webpack.js' //just load this file
    ],
    preprocessors: {
      './js/test/tests.webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader
    },
    reporters: [ 'mocha' ], //report results in this format
    webpack: { // webpack settings
      devtool: 'inline-source-map',
      module: {
        loaders: [
          { test: /\.js$/, loader: 'babel-loader' }
        ]
      }
    },
    webpackServer: {
      noInfo: true
    },
    plugins: [
        'karma-mocha',
        'karma-webpack',
        'karma-sourcemap-loader',
        'karma-mocha-reporter',
        'karma-phantomjs-launcher',
        'karma-chai',
        'karma-sinon',
        'karma-chai-sinon'
    ]
  });
};

Here are the packages I have installed (from package.json):
"babel-core": "^6.9.1",
"babel-loader": "^6.2.4",
"babel-plugin-module-alias": "^1.5.0",
"babel-preset-es2015": "^6.9.0",
"chai": "^3.5.0",
"karma": "^1.0.0",
"karma-chai": "^0.1.0",
"karma-chai-sinon": "^0.1.5",
"karma-chrome-launcher": "^1.0.1",
"karma-mocha": "^1.0.1",
"karma-mocha-reporter": "^2.0.4",
"karma-phantomjs-launcher": "^1.0.1",
"karma-sinon": "^1.0.5",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^1.7.0",
"mocha": "^2.5.3",
"phantomjs": "^2.1.7",
"phantomjs-polyfill": "0.0.2",
"sinon": "^1.17.4",
"sinon-chai": "^2.8.0",
"webpack": "^1.13.1"

Here is .babelrc:
{
  "presets": ["es2015"]
}

And here is the test file that I am referencing in karma.conf.js (tests.webpack.js). My initial idea was to require all spec files in it, but now I have changed it to run at least a single test. Still no luck:
import chai from 'chai';
var expect = chai.expect;

console.log('I was found');
it('works', function () {
    expect(true).to.equal(true);
})

Could you please advise how to debug this problem further?
UPDATE: Here's a gist with a minimal reproducible case. I must be doing something wrong there, because I am still receiving the error You need to include some adapter that implements __karma__.start method!, but I can't figure out what my mistake is.

A: Try removing the reference to chai-sinon in karma config. When I get rid of it, the test runs. I can't exactly explain why, but perhaps there is version incompatibility going on.


text:
Q: Remove items in a for loop without side effects? Can I remove items that I am looping through in an Objective-C for loop without side effects?
For example, is this ok?
for (id item in items) {
   if ( [item customCheck] ) {
      [items removeObject:item];   // Is this ok here?
}

A: Nope:

Enumeration is "safe"—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.

Options for changing an array that you want to enumerate through are given in Using Enumerators: either copy the array and enumerate through, or build up an index set that you use after the loop.

A: No, you'll get an error if you mutate the array while in a fast enumeration for loop.  Make a copy of the array, iterate over it, and remove from your original.
NSArray *itemsCopy = [items copy];

for (id item in itemsCopy) {
   if ( [item customCheck] )
      [items removeObject:item];   // Is this ok here
}

[itemsCopy release];

A: you can remove like this:
    //Create array
    NSMutableArray* myArray = [[NSMutableArray alloc] init];

    //Add some elements
    for (int i = 0; i < 10; i++) {
        [myArray addObject:[NSString stringWithFormat:@"i = %i", i]];
    }

    //Remove some elements =}
    for (int i = (int)myArray.count - 1; i >= 0 ; i--) {
        if(YES){
            [myArray removeObjectAtIndex:i];
        }
    }


text:
Q: Pcsx2 unable to play with controller I want to play Gears of War 2 with an Xbox 360 controller in pcsx2. I am running Windows 10 with no problems with FPS or anything except the controller. Even after enabling lilypad and configuring it I'm unable to use it.
What could cause this? How can I fix it?

A: Try using the XPad plugin instead of LilyPad if you're using an X360 Controller.


text:
Q: Intellij IDEA 2017.1.5 connection times out during plugin installation I have a problem with my IDE. It does not want to neither update or install any plugins (but it allows me to register my licence and browse through every plugin). It gives me a notification:

Connection failed (Read timed out). Please check network connection and try again

I looked into a log file and here what's there is:
> 2017-07-12 19:32:41,687 [ 653407]   INFO -
> .script.IdeScriptEngineManager - javax.script.ScriptEngineManager
> initialized in 2327 ms  2017-07-12 19:33:50,610 [ 722330]   WARN -
> Settings.impl.PluginDownloader - Cannot download
> 'https://plugins.jetbrains.com/pluginManager/?action=download&id=Lombook+Plugin&build=IU-171.4694.70&uuid=52f34c2e-c3bf-400b-a1c7-d11cc4fdb02b':
> Read timed out  java.io.IOException: Cannot download
> 'https://plugins.jetbrains.com/pluginManager/?action=download&id=Lombook+Plugin&build=IU-171.4694.70&uuid=52f34c2e-c3bf-400b-a1c7-d11cc4fdb02b':
> Read timed out    at
> com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:363)
>   at
> com.intellij.openapi.updateSettings.impl.PluginDownloader$1.process(PluginDownloader.java:245)
>   at
> com.intellij.openapi.updateSettings.impl.PluginDownloader$1.process(PluginDownloader.java:242)
>   at
> com.intellij.util.io.HttpRequests.lambda$doProcess$0(HttpRequests.java:420)
>   at
> com.intellij.util.net.ssl.CertificateManager.runWithUntrustedCertificateStrategy(CertificateManager.java:349)
>   at com.intellij.util.io.HttpRequests.doProcess(HttpRequests.java:420)
>   at com.intellij.util.io.HttpRequests.process(HttpRequests.java:395)
>   at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:61)
>   at
> com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:263)
>   at
> com.intellij.openapi.updateSettings.impl.PluginDownloader.a(PluginDownloader.java:242)
>   at
> com.intellij.openapi.updateSettings.impl.PluginDownloader.prepareToInstall(PluginDownloader.java:142)
>   at
> com.intellij.ide.plugins.PluginInstaller.a(PluginInstaller.java:239)
>   at
> com.intellij.ide.plugins.PluginInstaller.a(PluginInstaller.java:131)
>   at
> com.intellij.ide.plugins.PluginInstaller.prepareToInstall(PluginInstaller.java:70)
>   at
> com.intellij.ide.plugins.PluginManagerMain$5.run(PluginManagerMain.java:431)
>   at
> com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:726)
>   at
> com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:176)
>   at
> com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:556)
>   at
> com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:501)
>   at
> com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:66)
>   at
> com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:163)
>   at
> com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:137)
>   at
> com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:334)
>   at
> java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
>   at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
>   at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
>   at java.lang.Thread.run(Thread.java:745) Caused by:
> java.net.SocketTimeoutException: Read timed out   at
> java.net.SocketInputStream.socketRead0(Native Method)     at
> java.net.SocketInputStream.socketRead(SocketInputStream.java:116)     at
> java.net.SocketInputStream.read(SocketInputStream.java:170)   at
> java.net.SocketInputStream.read(SocketInputStream.java:141)   at
> sun.security.ssl.InputRecord.readFully(InputRecord.java:465)  at
> sun.security.ssl.InputRecord.read(InputRecord.java:503)   at
> sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)     at
> sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930)
>   at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)    at
> java.io.BufferedInputStream.fill(BufferedInputStream.java:246)    at
> java.io.BufferedInputStream.read1(BufferedInputStream.java:286)   at
> java.io.BufferedInputStream.read(BufferedInputStream.java:345)    at
> sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)  at
> sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)    at
> sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1536)
>   at
> sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
>   at
> java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
>   at
> sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
>   at
> com.intellij.util.io.HttpRequests.openConnection(HttpRequests.java:511)
>   at com.intellij.util.io.HttpRequests.access$300(HttpRequests.java:61)
>   at
> com.intellij.util.io.HttpRequests$RequestImpl.getConnection(HttpRequests.java:289)
>   at
> com.intellij.util.io.HttpRequests$RequestImpl.getInputStream(HttpRequests.java:298)
>   at
> com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:359)
>   ... 27 more

Does anyone encounter similar problem and know how to solve it?

A: Posting CrazyCoder's comment as answer, because it also worked for me.

Workaround is to uncheck Use secure connection option in Appearance & Behavior → System Settings → Updates section in Settings window:

A: Ran into the same problem in IntelliJ 2020.3. Turned out IntelliJ's default proxy setting is "No proxy". I set it to auto-detect and the problem was solved. If you're behind a firewall (e.g. corporate environment), check this.

A: Settings--Apperance & Behavior--System Settings--Updates--Use secure connection(make it unchecked)
enter image description here

A: Check if you use VPN. This can cause trouble with the connection.
Switching VPN off could help.


text:
Q: EclipseLink error when persisting an entity ( id null ) Stacktrace 1: Error coming from method "submitTicket" line 74 which is: em.persist(bean);
at com.sun.proxy.$Proxy237.creer(Unknown Source)
    at projet.helpdesk.dao.__EJB31_Generated__TicketDao__Intf____Bean__.creer(Unknown Source)
    at projet.helpdesk.form.CreationTicketForm.soumettreTicket(CreationTicketForm.java:74)

Stacktrace 2:
    Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: ORA-01502: index 'BDD2.TICKETS_PK' or partition of such index is in unusable state

Error Code: 1502
Call: INSERT INTO Tickets (ID_TICKET, DATE_ENVOI, DATE_FERMETURE, DESCRIPTION, ETAT, ID_EMPLOYE, ID_TECHNICIEN, PRIORITE, SUJET) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    bind => [9 parameters bound]
Query: InsertObjectQuery(projet.helpdesk.beans.Ticket@1d796c68)
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)

Mentionining that the ORA-1502 ERROR started showing after i restarted my PC and before that it was the ORA-0001 ERROR which describes the duplicated values problem.
When i'm inserting the bean through em.persist(bean); the Primary key aka id_ticket is set to null and it is a Trigger used in Oracle that increments the value.

A: The Java Persistence Query Language seems to generate 0 for Primary keys that don't have values when inserted instead of sending them as null objects, so i just Changed the Trigger in ORACLE that generates the primary key, as follows:
create or replace trigger "BI_TICKETS"
  before insert on "TICKETS"
  for each row
begin
  if :NEW."ID_TICKET" is null or :NEW."ID_TICKET"=0 then
    select "TICKETS_SEQ".nextval into :NEW."ID_TICKET" from dual;
  end if;
end;

Added the :NEW."ID_TICKET"= 0 to the condition, and it's done.


text:
Q: Is it possible to force uninstall my app? I have business apps, both iOS and Android, and my business is discontinuing.
Ideally, I would like to have my apps removed from the app store and uninstalled all devices they're installed. Is that possible?

A: You can delist your application in both stores so new users can not find / install the application, but I'm unaware of any way in which you force uninstall the application from existing devices.   If you are discontinuing a service that has been paid for, for subscriptions you'll need to sort out pro-rota refunds for all affected customers too (if you're planning on discontinuing the service).  You can withdraw the paid option in the store, so no one else can sign up, and existing users won't renew at the end of their subscription period.


text:
Q: "tangent" (the trig ratio) vs "tangent" (the geometric concept) Do the terms "tangent" (the trigonometric ratio), which is defined as "opposite-side / adjacent-side", and "tangent" (of the curve), which is a line that touches a curve at a point, have the SAME meaning? If yes, how? Also: Is this same for "secant" and "cosecant"?

A: No, they are not the same.
The tangent function $\tan$ is a function defined on numbers: you put in one number (namely an angle) and obtain another number (namely the quotient between opposite and adjacent leg in a right triangle with the given angle). The property of a line to be tangent to a given curve is something different. As is the operation of finding the tangent to a curve at a given point on the curve. The input here is a curve and one point on it, the output is a line. Since a line is not a number (at least in general), the two things are different.
That doesn't mean the two are not related. The post What reasoning is behind the names of the trigonometric functions "sine", "secant" and "tangent"? pointed out by Michael Seifert contains a picture which demonstrates how various trigonometric functions can be seen as lengths related to a right triangle of unit length hypothenuse. There the value of the trigonometric tangent function is indeed the length of a certain segment along the tangent of the unit circle around one corner. But being related is not being the same.


text:
Q: Running Rails Server on Cloud9 results in 'Server timed out or sent incomplete response' I've been following the railstutorial.org and have everything has been running fine, but now when I run rails server -b $IP -p $PORT, the rails server seems to take forever to respond, causing the cloud9 proxy to time out and send this message:
Something went wrong !
Server timed out or sent incomplete response
Click here to try again, or Go back to dashboard.
If that still doesn't work, please Issue a bug report.
Any idea how I can work around this/resolve it to get a working production preview?

A: I just noticed that you wrote:
rails server -b -$IP ...

There shouldn't be a - before $IP. Can you see if that resolves the issue?


text:
Q: How to solve this partial fraction decomposition equation? $$\frac{1}{(x-a)(x-b)(x-c)} =
 \frac{A}{(x-a)}
+\frac{B}{(x-b)}
+\frac{C}{(x-c)}$$
a,b and c are constants.
I have tried three times by hand but I can't get the right result.
The result is
$$\frac{1}{(x-a)(x-b)(x-c)} =
 \frac{1}{(a-b)(a-c)(x-a)}
+\frac{1}{(b-a)(b-c)(x-b)}
+\frac{1}{(c-a)(c-b)(x-c)}$$
Is there any easy and clear solution to this?

A: Hint
Starting with $$\frac{1}{(x-a)(x-b)(x-c)} =
 \frac{A}{(x-a)}
+\frac{B}{(x-b)}
+\frac{C}{(x-c)}$$ multiply by ${(x-a)(x-b)(x-c)}$ to get
$$1=A(x-b)(x-c)+B(x-a)(x-c)+C(x-a)(x-b)$$ Now, make
$$x=a\implies 1=A(a-b)(a-c)\implies A= ???$$
$$x=b\implies 1=B(b-a)(b-c)\implies B= ???$$
$$x=c\implies 1=C(c-a)(c-b)\implies C= ???$$

A: $$\frac{1}{(x-a)(x-b)(x-c)} =
 \frac{A}{(x-a)}
+\frac{B}{(x-b)}
+\frac{C}{(x-c)}$$
Rearrange to give,
$$A = \frac{1}{(x-b)(x-c)} - \frac{B(x-a)}{(x-b)}
-\frac{C(x-a)}{(x-c)}
$$
Put $x = a$ to get
$$A = \frac{1}{(a-b)(a-c)}
$$
Similiarly,
$$B = \frac{1}{(b-a)(b-c)}
$$
And
$$C = \frac{1}{(c-a)(c-b)}
$$

A: $$A(x-b)(x-c)+B(x-a)(x-c)+C(x-a)(x-b)=1$$
$$A(x^2-(b+c)x+bc)+B(x^2-(a+c)x-ac)+C(x^2-(a+b)x-ab)=1$$
Equate coefficients.
Coefficient of $x^2$ is 0
$$(A+B+C)x^2=0x^2$$
Thus $A+B+C=0$
You can form similar equations and then solve them by equating the coefficients of $x$ and $1$

A: The easy way is to follow the hint by @JackD'Aurizio,  but let me spell it out in a little more detail.  Start with
$$\frac{1}{(x-a)(x-b)(x-c)} =
 \frac{A}{x-a}
+\frac{B}{x-b}
+\frac{C}{x-c}$$
Multiply by $(x-a)$:
$$\frac{1}{(x-b)(x-c)} = A + (x-a) \left( \frac{B}{x-b} + \frac{C}{x-c} \right)$$
Now set $x=a$, with the result
$$\frac{1}{(a-b)(a-c)} = A$$ because all the stuff with a factor of $(x-a)$ vanishes.
$B$ and $C$ are obtained similarly.  Voila!


text:
Q: Exchanging the pixel_array for a DICOM RT Dose file - values change - pydicom I have a DICOM RT Dose file that I want to change the original pixel_array with a new one. The problem is that when I give a certain pixel its new value, somewhere in the process it changes randomly. The block of code for the exchange is given below. I do the exchange one pixel at a time only to check where the problem is, so I know it can be done much faster:
print pixel_arrayFLK[86][85][78]
print dosem.pixel_array[86][85][78]
for a in range(zBinsTPS):
    for b in range(yBinsTPS):
        for c in range(xBinsTPS):
            dosem.pixel_array[a][b][c] = pixel_arrayFLK[a][b][c]
            if a == 86 and b == 85 and c == 78:
                print dosem.pixel_array[a][b][c]
                print pixel_arrayFLK[a][b][c]

The original pixel_array is the dosem.pixel_array and new one is the pixel_arrayFLK. As an example of what happens:
pixel_arrayFLK[86][85][78] has the value 65813. The original dosem.pixel_array[86][85][78] has the value 62947. After the exchange pixel_arrayFLK[86][85][78] still has the value 65813 whereas dosem.pixel_array[86][85][78] suddenly now has the value 277.
Print functions yield:
65813
62947
277
65813

However, if I divide all the values of pixel_arrayFLK by 2, the exchange works fine. I really do not understand what's happening. Does it maybe has something to do with the data type in the DICOM file? Some more information contained in the DICOM:
(0028, 0002) Samples per Pixel                   US: 1
(0028, 0004) Photometric Interpretation          CS: 'MONOCHROME2'
(0028, 0100) Bits Allocated                      US: 16
(0028, 0101) Bits Stored                         US: 16
(0028, 0102) High Bit                            US: 15
(0028, 0103) Pixel Representation                US: 0
(7fe0, 0010) Pixel Data                          OW or OB: Array of 6750000 bytes

I have another DICOM file where the Bits Allocated = 32, Bits Stored = 32 and High Bit = 31. The pixel_array exchange in this file works seemingly fine.

A: Figured it out. As the bits are 16, the maximum value is 65536, where 65813 overrides this value by 277, and therefore start at 0.


text:
Q: CSS table-cell weird gap issue I have a problem with my css. There is a mysterious margin above name in second table-cell div. Please see more at: http://jsfiddle.net/xnms15uf/

Peter

CSS
#comment {
    width: 550px;
    height: 50px;
    display: table;
}

#left_side {
    width: 40px;
    background: #00ff00;
    display: table-cell;
}

#right_side {
    background: #ff0000;
    display: table-cell;
}

UPDATE:
this is what I want to achieve

(vectors from Illustrator)

A: #right_side {
background: #ff0000;
display: table-cell;
vertical-align:top;}

If I am understanding correctly, this is all you have to do to get the text 'Peter' to not have that spacing at the top.


text:
Q: Display Image On Text Link Hover CSS Only I have a text link. When the user hovers over the text link, I want an image to be displayed elsewhere on the page. I want to do this using css. I thought it could be done simply with a single line of code in the link like an onmouseover but it seems that requires other code elsewhere on the page.
I tried using the a:hover with the picture I want to show as a background-image but I don't think it can be manipulated to display in full instead of being clipped down to the size of the text link.
I see hundreds of results when I try to search for this but none of them are what I want. The closest thing I found was this.
http://www.dynamicdrive.com/style/csslibrary/item/css-image-gallery/
But that's working with hovering over thumbnail images. I just want the user to hover over a single text link to have an image show on the page somewhere else. I found that gallery from this thread: Pop up image css link on hover
I don't want to deal with whatever that jquery is or too much scripts because I'm more familiar with css. Does anyone know of a simple way to do this or is there still no way, not even with all the changes made for css3?
Thanks!

A: It can be done using CSS alone. It works perfect on my machine in Firefox, Chrome and Opera browser under Ubuntu 12.04.
CSS :
.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none; z-index:99; }
.hover_img a:hover span { display:block; }

HTML :

     Show Image

A: CSS isn't going to be able to call other elements like that, you'll need to use JavaScript to reach beyond a child or sibling selector.
You could try something like this:
Some Link

then...
a>div { display: none; }
a:hover>div { display: block; }

A: add
.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

A: From w3 schools:

Hover over me

Sounds like about what you want

A: I did something like that:
HTML:

text text text

CSS:
.child {
    visibility: hidden;
}

.parent:hover .child {
    visibility: visible;
}

A: It is not possible to do this with just CSS alone, you will need to use Javascript.

Text


text:
Q: Fatal error: Call to a member function data_seek() on boolean on line 4 I am having a problem with my code.
We all know mysql_result is deprecated. So what I've done is created a similar function to replace mysql_result with mysqli_result. My code is shown below.
function mysqli_result($result, $row, $field = 0) {
    $result->data_seek($row);
    $data = $result->fetch_array();

    return $data[$field];
}

Use this code if you need to for your own projects, it works perfect on almost all my pages. On-topic, on some of my pages which uses mysqli_connect, I'm getting an error.

Fatal error: Call to a member function data_seek() on boolean in ...
  on line 4

Then we have line 4, which is
    $result->data_seek($row);

I'm asking you nicely, how can I adjust my code so it does not give this error anymore? Or maybe dump the code so it doesn't appear anymore.
I've also tried looking up the error on Google, it didn't gave me any answers really.

EDIT: Give us source code where you are calling the function.
if(mysqli_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(id) FROM downloads"),0) == 0) {
    echo 'No downloads were added.';
}


text:
Q: Selecting all list items with a certain class in jQuery How do I pick all the <li> items on my DOM having the class .tab, using jQuery? $('.tab')returns all the DOM elements having .tab, but I want only the <li> elements to be selected.

A: Use:
$('li.tab');

That is the element selector plus class selector.
Notice that you can't have spaces. As li .tab would mean "all elements with the class tab that are children of a <li>".

A: Combine element selector with class selector
$("li.tab")

A: Use the following syntax  -
$("li.tab")

A: just add li. This is correct syntex
$("li.tab")

Demo output will be at console


text:
Q: Why does a rigid body rotates about it's centre of mass? When an impulsive force is acted upon a rigid body, (and the force doesn't pass through the centre of mass) why does the body rotates specifically about an axis passing through centre of mass ?

A: An impulsive force directed along a line crossing the center of mass doesn't produce a torque relative to this center. It causes only a linear momentum change, i.e., a translational movement and no rotation of the body. Any other impulsive force  on the body produces a torque relative to the center of mass causing an angular acceleration of the body around the center of mass (and a linear acceleration). This results in a constant angular momentum, i.e., a constant rotation of the body around an axis through the center of mass after the impulsive force has ended. A free floating rotating body always rotates around an axis going through its center of mass.


text:
Q: Is the timelike free boson CFT a valid CFT as per Segal's functorial CFT prescription? Is the timelike free boson CFT a valid CFT as per Segal's functorial CFT prescription?
I am aware that the Euclidean free boson theory is a well-defined CFT, but I was wondering whether one might run into problems when trying to place the timelike free boson CFT into Segal's FQFT framework since the spectrum of the timelike free boson theory is unbounded from below.


text:
Q: Intellij 2016.1.4 and React render() method I have a render method inside React component:
import * as React from "react";
import MediaService from "./service/MediaService";
import ComponentLifecycle = require("@types/react");
import DOMHelper from "../helpers/DOMHelper";

export default class PictureTaker extends React.Component implements ComponentLifecycle {
    // Not important

    render () {
        return (
          <article>
              <video id="ra-video">
                  Video not supported
              </video>
          </article>
        );
    }
}

It marks id as attribute id is not allowed here, but OK - I got it. I want to refactor code to extract <video> to another component:
import * as React from "react";

export default class VideoPlayer extends React.Component {
    constructor () {
        super();
    }

    render () {
        return (
            <video id="ra-video">
                Video not supported
            </video>
        );
    }
}

But it brokes with message: unresolved type video. Here is how it looks like:

Code for VideoPlayer is pasted from PictureTaker, and it suprised me. I have React:

And React DOM:

inside Settings / Languages and frameworks / Javascript / Libraries. Do you see any mistakes made by me? Thank you in advance for every answer.

A: Geez, I found a solution... I used .ts extension instead of .tsx.
 It was VideoPlayer.ts, and should be VideoPlayer.tsx, my bad.

A: What is video? You will have to import video.js along with React.js to use


text:
Q: What constructions of "elementary" mathematics are actually functors? I'm not looking for the usual simple examples of functors like the fundamental group or forgetful functors, what I'm looking for is some interesting examples of constructions from "elementary" mathematics that are secretly functorial. Like the derivative: it's actually a functor, with the chain rule expressing the composition rule of functors, but that's never discussed in basic Calculus courses.

A: The function that sends a set $X$ to its powerset $\mathcal{P}(X)$ is a functor; and interestingly, it is a functor in more than one way!
Probably the most natural way to make it into a functor is to define, given a function $f:X\to Y$,
$$\mathcal{P}(f):\mathcal{P}(X)\to \mathcal{P}(Y):A\mapsto f(A)=\{f(a)\mid a\in A\};$$
in other words, we send $f$ to the function "direct image by $f$". This is a functor, because (pretty much by definition) $g(f(A))=(g\circ f)(A)$ for all $f:X\to Y$, $g:Y\to Z$ and $A\subset X$.
But there is also the function "inverse image by $f$", defined as
$$\mathcal{P}'(f):\mathcal{P}(Y)\to \mathcal{P}(X):B\mapsto f^{-1}(B)=\{a\in X\mid f(a)\in B\}.$$
Note that here I've switched $X$ and $Y$; so it's not a functor on the category of sets, but from the opposite category of sets to the category of sets, or if you prefer a contravariant functor on the category of sets. Here the functoriality amounts to the fact that $f^{-1}(g^{-1}(C))=(g\circ f)^{-1}(C)$ for all $f:X\to Y$, $g:Y\to Z$ and $C\subset Z$.

A: In almost any course a (U.S.) undergraduate math major would take, the construction $F(X)=A \times X$ for fixed $A$ defines a functor from any reasonable category to itself (obvious action on maps).  This works for sets, (abelian) groups, topological spaces, vector spaces, rings, etc.  (Of course it works in any category with products, but I'm trying to keep it "elementary.")

A: Any homomorphism $f:G_1\rightarrow G_2$ between two groups, both considered as one object categories, is a functor from $G_1$ to $G_2$.
This is true for ring homomorphisms as well.

A: One of my favourite examples of these is group actions.
A (monoid or) group $G$ can be considered as a category with a single object $\star$, whose morphisms $\star \to \star$ are the elements of $G$, and whose identity and composition are given by the unit element $e$ and the group operation, respectively.
A left action of $G$ on a set $X$ is precisely a functor $\alpha : G \to \mathbf{Set}$, where $G$ is considered as a category in the above sense.

*

*The set $X$ is the value of $\alpha(\star)$;

*For each $g \in G$, we obtain a function $\alpha_g = \alpha(g) : X \to X$;

*Functoriality expresses the fact that $\alpha_e = \mathrm{id}_X$ and $\alpha_{gh} = \alpha_g \circ \alpha_h$.

Likewise a right action on a set is precisely a functor $\alpha : G^{\mathrm{op}} \to \mathbf{Set}$.

A: As noted, differentiation is a functor in the category of (real, finite-dimensional) smooth manifolds. In particular, it maps every manifold $X$ to its tangent bundle $TX$, which is locally isomorphic to $X \times \mathbb{R}^{n}$ for appropriate $n$. In some sense, one might consider differentiation ''locally'' an example functor of the form $F(X) = A \times X$ described by @Randall (well, technically $X \mapsto X \times A$).
However, the functor maps smooth functions in a non-trivial way. For manifolds $X, Y$ and smooth $f: X \to Y$, the derivative $D(f): TX \to TY$ is the map
 $$ D(f): (x,v) \mapsto (f(x), df_{x}(v)) $$
where $df_{x}$ is the ordinary total derivative of $f$ at $x$.


text:
Q: How does the Linux kernel enter supervisor mode in x86? I tried to probe the event when the mode switch happens (user->kernel mode), as a result, I need to find which function will be triggered when the transition happens.
It seems that SBI is the placed doing transition for RISC-V. I'm wondering where is the code to handle this for x86?

A: It's not that simple. In x86, there are 4 different privilege levels: 0 (operating system kernel), 1, 2, and 3 (applications). Privilege levels 1 and 2 aren't used in Linux: the kernel runs at privilege level 0 while user space code runs at privilege level 3. The current privilege level (CPL) is stored in bits 0 and 1 of the CS (code segment) register.
There are multiple ways in which the transition from user to kernel can happen:

*

*Through hardware interrupts: page faults, general protection faults, devices, hardware timer, and so on.

*Through software interrupts: the int instruction raises a software interrupt. The most common in Linux is int 0x80, which is configured to be used for system calls from user space to kernel space.

*Through specialized instructions like sysenter and syscall.

In any case, there is no actual code that does the transition: it is done by the processor itself, which switches from one privilege level to the other, and sets up segment selectors, instruction pointer, stack pointer and more according to the information that was set up by the kernel right after booting.
In the case of interrupts, the entries of the Interrupt Descriptor Table (IDT) are used. See this useful documentation page about interrupts in Linux which explains more about the IDT. If you want to get into the details, check out Chapter 5 of the Intel 64 and IA-32 architectures software developer's manual, Volume 3.
In short, each IDT entry specifies a descriptor privilege level (DPL) and a new code segment and offset. In case of software interrupts, some privilege level checks are made by the processor (one of which is CPL <= DPL) to determine whether the code that issued the interrupt has the privilege to do so. Then, the interrupt handler is executed, which implicitly sets the new CS register with the privilege level bits set to 0. This is how the canonical int 0x80 syscall for x86 32bit is made.
In case of specialized instructions like sysenter and syscall, the details differ, but the concept is similar: the CPU checks privileges and then retrieves the information from dedicated Model Specific Registers (MSR) that were previously set up by the kernel after boot.
For system calls the result is always the same: user code switches to privilege level 0 and starts executing kernel code, ending up right at the beginning of one of the different syscall entry points defined by the kernel.
Possible syscall entry points are:

*

*entry_INT80_32 for 32-bit int 0x80

*entry_INT80_compat for 32-bit int 0x80 on a 64-bit kernel

*entry_SYSENTER_32 for 32-bit sysenter

*entry_SYSENTER_compat for 32-bit sysenter on a 64-bit kernel

*entry_SYSCALL_64 for 64-bit syscall

*entry_SYSCALL_compat for 32-bit syscall on 64-bit kernel (special entry point which is not used by user code, in theory syscall is also a valid 32-bit instruction on AMD CPUs, but Linux only uses it for 64-bit because of its weird semantics)


text:
Q: finding the explict homotopy Assume that the homotopy F:$\phi_0$ $\simeq$ $\phi_1$ ,where $\phi_i$ :$X \to Y$ and let $\Gamma$ denote the path $F(x_0, .)$ in Y, where choosing $x_0$ $\in$ X, from $\phi_0(x_0)$ to $\phi_1(x_1)$  then we can find the isomorphism $i$ such that the diagram commute.
\begin{equation}
\require{AMScd}
\begin{CD}
\pi_1(X,x_0) @>{(\phi_1)_*}>> \pi_1(Y,\phi_1(x_0))\\
@V{h}VV @V{i}VV \\
\pi_1(X,x_0) @>{(\phi_0)_*}>> \pi_1(Y,\phi_0(x_0))
\end{CD}
\end{equation}
where $h$ be identity map, since I don't know how to draw that picture.
every thing go well until I need to find the homotopy J:$\phi_0 $ $\circ$ $b$ $\simeq$ ($\Gamma$ $*$($\phi_1$ $\circ$ $b$)) $*$ $\Gamma ^{-1}$  where [b] $\in$ $\pi_1(X,x_0)$
Can some one help me with this "explicit" formula for this homotopy? Or can someone tell me how to find this homoptopy systematic.
If you can help me with a "systematic" method, I will be very appreciate, since I always have a trouble finding the explicit formula for the homotopy for some hard problem.
Thanks in advanced.


text:
Q: C++ template class change static member's value I have the following classes -
class Matrix<T> that stands for a matrix of objects of type T, and it's super class baseMAtrix that holds a static boolean variable parallel_ common to all types of Matrix<T>.
I want to access parallel_ but it seems my code does not link -
class baseMatrix {
protected:
    static bool parallel_;
};

template<class T>
class Matrix : baseMatrix{

public:
    static void setParallel (bool parallel){
        if(parallel != baseMAtrix::parallel_){
            cout << "message" << endl;
        }
        baseMAtrix::parallel_ = parallel;
    }
};

I get the this message -
`CMakeFiles/ex3.dir/Tester.cpp.o:Tester.cpp:(.rdata$.refptr._ZN10baseMatrix9_parallelE[.refptr._ZN10baseMatrix9_parallelE]+0x0): undefined reference to `baseMatrix::_parallel'
collect2: error: ld returned 1 exit status`

the Tester.cpp file is where I call setParallel -
Matrix<int>::setParallel(true);
is this the proper way to call setParallel?
is this the proper way to access baseMatrix::_parallel?

A: If you want to stay just-header-friendly, you could change base class to template:
template<class T>
class baseMatrix
{
protected:
    static bool _parallel;
};

template<class T>
bool baseMatrix<T>::_parallel;

template<class T>
class Matrix : baseMatrix<void>
...

This way there is no need for baseMatrix::_parallel in cpp file.


text:
Q: Solving an equation for B I am having an issue solving this. I wrote this equation to find the with of a bar for a bar chart that is comparative.
\begin{equation}
D-P*(N+1) = ((N-1)*M)*B*0.75+N*B
\end{equation}

A: No guarantee that the result will be an integer, but just distribute the $B$ out of the terms on the right and divide.
$\begin{equation}
D-P*(N+1) = ((N-1)*M)*B*0.75+N*B
\end{equation}$
$\begin{equation}
D-P*(N+1) =( ((N-1)*M)*0.75+N)*B
\end{equation}$
$\begin{equation}
(D-P*(N+1))/( ((N-1)*M)*0.75+N)=B
\end{equation}$


text:
Q: Android: View in lower resolution screen (ldpi) truncated I'm implementing my view and have been testing with xdpi hdpi and tvdpi mdpi, and they all look fine.
However, a quick test in a ldpi device, it seems like parts of my views are being truncated. Why is that? My contents are truncated both horizontally (right part truncated), and vertically (the content seems to go off the bottom of the screen without any scroll bar available for me to scroll).
My View uses fragments via the support library. The fragment which has its bottom truncated is as follow:

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/event_title"
        android:id="@+id/textView1"
        android:layout_gravity="left|center_vertical"
        android:textSize="18sp"
        android:textColor="#20b2aa"/>

<EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/event_title"
        android:id="@+id/new_event_title"
        android:textColor="#000000"
        android:textSize="26sp"
        android:shadowColor="#20b2aa"
        android:singleLine="true"
        android:background="@drawable/edit_text_custom"
        android:textCursorDrawable="@null"/>

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/suggested_times"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textColor="#20b2aa"
        android:textSize="18sp"
        android:id="@+id/textView3"
        android:layout_gravity="left|center_vertical"
        android:layout_marginTop="20dp"/>

<RelativeLayout
        android:id="@+id/date_selection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="30sp"
        android:layout_gravity="center|left">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/suggestion"
            android:id="@+id/textView"
            android:textSize="16sp"
            android:layout_gravity="right|center_vertical"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"/>

    <ImageButton
            android:layout_width="64dp"
            android:layout_height="66dp"
            android:id="@+id/add_suggested_time_btn"
            android:layout_alignParentRight="true"
            android:background="@drawable/social_person"
           android:src="@drawable/social_person"
            android:contentDescription="Suggest a time"/>

</RelativeLayout>

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/invitees"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textColor="#20b2aa"
        android:textSize="18sp"
        android:layout_marginTop="20dp"/>
<RelativeLayout
        android:id="@+id/invitee_selection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">

    <ImageButton
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:id="@+id/add_invitee_btn"
            android:layout_alignParentRight="true"
            android:layout_alignBottom="@+id/textView"
            android:background="@drawable/social_add_person"
            android:contentDescription="Suggest a time"/>
</RelativeLayout>

<!-------------- CONTENT FROM HERE ON ARE OFF THE SCREEN ------------------------>
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/description"
        android:id="@+id/textView2"
        android:layout_gravity="left|center_vertical"
        android:textSize="18sp"
        android:layout_marginTop="20dp"
        android:textColor="#20b2aa"/>

<EditText
        android:textColor="#000000"
        android:textSize="26sp"
        android:background="@drawable/edit_text_custom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/description"
        android:id="@+id/description"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:textCursorDrawable="@null"
        />

The above fragment is added into this following container inside fragment_container:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
        android:background="@drawable/background_image">

<FrameLayout
        android:id="@+id/fragment_container"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_weight="1" />
</LinearLayout>


text:
Q: find, printf and odd behaviour with ssh So, this works:
find /dir/ -type f -printf "%p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n" > /dir/output.txt

But this doesn't:
ssh -o StrictHostKeyChecking=no "servername" find /dir/ -type f -printf "%p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n" > /dir/output.txt

When run through the ssh command, I get the following errors:
bash: %TY-%Tm-%Td: command not found
bash: %TH:%TM: command not found
bash: %s: command not found
bash: %u: command not found
bash: %Un: command not found

Is there something specific with reformatting this command that I'm missing?

A:
Is there something specific with reformatting this command that I'm missing?

Yes.  You lose one level of quoting when you execute a command via ssh.  So this:
find /dir/ -type f -printf "%p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n"

Becomes:
find /dir/ -type f -printf %p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n

Which is a bunch of shell commands tied together with pipes (|).  You can fix this by putting the whole thing in single quotes:
ssh -o StrictHostKeyChecking=no "servername" 'find /dir/ -type f -printf "%p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n"' > /dir/output.txt

Or by passing in your script as stdin to bash instead:
ssh -o StrictHostKeyChecking=no "servername" bash <<EOF > /dir/output.txt
find /dir/ -type f -printf "%p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n"
EOF

A: Answer on a postcard is...prefix and suffix the original command with a single quote, like this:
ssh -o StrictHostKeyChecking=no "servername" 'find /dir/ -type f -printf "%p|%TY-%Tm-%Td|%TH:%TM|%s|%u|%U\n" > /dir/output.txt'


text:
Q: Bitwise operator on a large unsigned integers (>1024bit) in SQL query I am writing a query that looks something like this:
SELECT *
  FROM lists
  WHERE ((1 << lists.index_number) & :fingerprint_value) = (1 << lists.index_number)
  AND lists.list_id = :listid;

However, bitwise operators work up to 64bit unsigned integers, but I have to work with 1024bit unsigned integers. Maybe even larger values in the future. So does anyone have any idea how I could approach the same thing but with bigger unsigned integers/binary values?

A: Turns out I cannot read,
Starting from Mysql 8 bitwise operators can be used and the query in the question should work fine.


text:
Q: Finding current directory during Visual Studio debugging session? How can I find the current directory for a .NET application
running under the Visual Studio debugger?
Update 1. To be clear: I don't want to change the code
or get information in the program itself - I just want to
get information about the application currently being
debugged.
While debugging a .NET Windows Forms application (mixed VB.NET and
C#) I was not sure from which location a XML file was being
read from. I expected the current directory to be the
application's directory. However, using Process Explorer,
properties for the process result in:

D:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\

(right click on process/Properties/tab Image/Current Directory).
Hovering the cursor over the process in the main view of Process Explorer
revealed a different result (see below for a screenshot):

D:\dproj\DTASCall\DTASuperCharge\bin\

What is correct?
Starting the application standalone displays the expected
current directory,

D:\dproj\DTASCall\DTASuperCharge\bin\

in the Process Explorer process properties window.

Annotated screen-shot of Process Explorer:
Alt text http://www.pil.sdu.dk/1/until2039-12-31/PEdiscrepancy_2009-09-02.png

A: Within your code, call the function
System.IO.Directory.GetCurrentDirectory()

By default, unless you've changed the Debug properties of your project, the current directory will start as the bin\Debug directory of your project (where the .exe runs from).

A: In Visual Studio, under the project's settings in the debug tab, you can set the "Working Directory" if you want.
To determine the current working directory in code or in the immediate window in a breakpoint, try
System.IO.Directory.GetCurrentDirectory()

A: The best way is to run the application in WinDbg (the Windows debugger), then attach to the process and run the !handle command. Each open file will have an associated handle. By dumping all the handles for the corresponding process, you will see the corresponding file path.
Here is an example:
!handle 0 f process-id

Replace the process-id with the value of your process id. In place of the process id you can also use the process address. If this does not show the file object, then file handle has already been closed. In this case you need to trace the handles. This can be done with the !htrace command.


text:
Q: Should i use Coherence standalone server ? for a java webservice to use cache data ? I am new to oracle coherence
Basically we  have some data and we wanted some java/bpel webservice to get those data from coherence cache instead of database. [we are planning to load all those data to cache server]
So we have below questions before we start this solution.
Webservice we are planning to start is going to be just java would be fine.
And all operations are reading only.
Question
1. IS it Coherence needs to be stand alone server ? (down load from oracle and install it separately and run the default cacheserver) ?
2.If so we are planning to do the pre loading of data from database to cache server by using code ? i hope thas possible ? Any pointers would be helpful ?
3.How does the webservice connect with Coherence server if webservice running in different nmachine vs coherence server running ?
(OR)
Is it mandatory that webservice and coherence should run in the same machine ?

*If webservice can run in different machine how does the webservice code connects to coherence server (any code sample , url would be helpful) ?

*Also what is that coherence comes with weblogic ? Is it not fit for our applications design i assume ?!!!! then what type of solution we go for weblogic with coherence ?
FYI : Our goal is simple we want to store the data in cache server and have our new webservice to retrieve the data from Cache servere instead of database(because v are planning to avoid database trip )

A: Well, you questions are very open and probably have more than 1 correct answer. I'll try to answer all of them.
First, please take into consideration, that Coherence is not a free tool and you have to pay for a license.
Now, to the answers:

*

*Basically, coherence has 2 parts: proxy and server. The first is the responsible to routing your requests and the second for hosting the data. You can run both together in the same service but this has pros&cons. One Con is that your services will be very loaded and the memory will be shared between two kind of processes. A pro is that is very simple to run.

*You can preload all the data from the DB. For that you have to open the Coherence and write your own code. For that, you need to define you own cachestore (look for that keyword in coherence docs) and override the loadAll method.

*As far I remember Coherence comes together with Weblogic. That says the license for the one is the license for the second and they come in the same product. I'm not familiar with weblogic, but I suppose is a service of the package. In any case, for connecting to coherence you can refer to Configuring and Managing Coherence Clusters

*The coherence services can run in different machines, in different network and even in different places of the world if you want. Each, proxy or server, consumer and DB, could be in a different network. Everything can be configured. You have to say you weblogic server where the coherence proxy will be, you'll set in the coherence proxy/server the addresses of them and you'll configure your coherence server for finding out his database by configuration. Is a bit complicated to explain everything here.

*I think I answered before.
Just take into consideration coherence is a very powerful tool but very complicated to operate and to troubleshoot. Consider the pros/cons of accessing directly your DB and think about if you really need it.
If you have specific questions, please don't hesitate. Is a bit complicated to explain everything here since you're trying to set up one of the complicated system I ever seen. But is excellent and I really recommend it.

EDIT:
Basically Coherence is composed by 2 main parts: proxy and server. The names are a bit confusing since both are servers, but the proxy serves to the clients trying to perform cache operations (CRUD) while the "servers" serve to the proxies. Proxy is the responsible for receiving all the requests, processing them and routing them, according to their keys, to the respective server who holds the data or who would be the responsible for holding it if the operation requires a loading act. So the answer to your questions is: YES, you need at least one proxy active in your cluster, otherwise you'll be unable to operate correctly. It can run on one of your machines on into a third one. Is recommended to hold more than 1 proxy for HA purposes and proxies can act as servers as well (by setting the localstorage flag to true). I know, is a bit complicated and I recommend to follow oracle docs.

A: Essentially, there are 2 types of Coherence installation.
1) Stand-alone installation (without a WebLogic Server in the mix)
2) Managed installation (with Weblogic Server in the mix)
Here are a few characteristics for each of the above
Stand-alone installation (without a WebLogic Server in the mix)

*

*Download the Coherence installation package and install (without any dependency on existing WebLogic or FMW installations)

*Setup and Configure the Coherence Servers from the command-line

*Administer and Maintain the Coherence Servers from the command-line

Managed installation (with Weblogic Server in the mix)

*

*Utilize the existing installation of Coherence that was installed when WebLogic or FMW was installed

*Setup and Configure the Managed Conherence Servers to work with WebLogic server

*Administer and Maintain the Managed Coherence Servers via the WebLogic console

Note the key difference in terminology, Coherence Servers (no WL dependency) vs. Managed Coherence Servers (with WL dependency)


text:
Q: Using media queries, following standards with SASS and BEM? I am following the BEM practice and want to add specific break points, it appears 2 formats work for me. Does anyone know the advantage of either ?
Here is the first, I embed the media directly into the element (BEM)
.my-component {
  &__section-field {
    display: flex;
    flex-wrap: wrap;
  }

  &__section-sep {
    width: 100%;
    @media(min-width: 900px) {
        width: 50%;
    }
  }
}

Here is the second, where I embed the media query outside of the section and redefine the section again.
.my-component {
  &__section-field {
    display: flex;
    flex-wrap: wrap;
  }

  &__section-sep {
    width: 100%;
  }
  @media(min-width: 900px) {
    &__section-sep {
      width: 50%;
    }
  }
}

As you can see the, I am basically changing the width of an item between either 50% or 100% depending if it's mobile only resolution. I am using flexbox with flex-wrap and it wraps depending on there is space left on the line.
They both seem to work the same as far as I can say. Would anyone confirm if there is a difference and which one would be more scalable and maintainable?
Maybe there is something that I haven't thought of, I did think about storing my media queries in a separate file but I was trying to keep everything together and follow the bem methodology.

A: I prefer the 2nd variant for the following reason: when you have many media queries, indeed, the 1st variant requires less copy/paste.
But though, the code becomes much less readable if you have many elements or modifiers in the block, i.e. selectors. It's common to face a situation when it's needed to change style for several elements/modifiers at exact screen. And when that case appears - as for me - it's easier to navigate between media queries, find the needed media and change code there - so you work at one place in the file, whereas in the 1st variant you would need to jump between selectors. In my opinion when it comes to work with media queries - it's faster to navigate between them, then to navigate between selectors.
imagine the following code with media query inside every selector :
.section_name_educational {
    display: flex;
    flex-direction: row;
    padding: 0px;

    .fp-tableCell {
        display: flex;
        flex-direction: row;
    }

    .section {

        &__inner {
            display: flex;
            flex-direction: row-reverse;
            height: 100vh;
            height: calc(100vh - 80px);
            box-sizing: border-box;
            width: 50%;
            padding-left: 40px;
            margin-top: auto;
            padding-bottom: 40px;
        }

        &__header {
            position: relative;
            width: 100%;
            top: 62px;
            left: 40px;
        }

        &__text-holder {
            width: 100%;
        }

        &__title {
            font-size: 48px;
        }

        &__subtitle {
            width: 150%;
            margin: 20px 0px;
        }

        &__description {
            color: #669900;
            font-size: 18px;
        }

        &__primary {
            height: 100%;
            display: flex;
            box-sizing: border-box;
            flex-direction: column;
            justify-content: space-between;
            width: 100%;
        }

        &__additional {
            display: none;
        }

        &__kettles {
            display: flex;
        }

        &__kettle {
            height: auto;
            margin-right: 20px;

            &_order {
                &_1 {
                    width: 183px;
                    min-width: 183px;
                    max-width: 183px;
                }

                &_2 {
                    width: 108px;
                    min-width: 108px;
                    max-width: 108px;
                }

                &_3 {
                    width: 127px;
                    min-width: 127px;
                    max-width: 127px;
                }
            }
        }

        &__background-holder {
            overflow: hidden;
            max-height: 100vh;
        }

        &__background {
            position: relative;
            width: auto;
            height: 100vh;
        }
    }
}

@media all and (max-height: 600px) {
.section_name_educational {
    .section {
        &__kettle {
            &_order {
                &_2 {
                    width: 68px;
                    max-width: 68px;
                    min-width: 68px;
                    height: 120px;
                    margin-left: 30px;
                }

                &_3 {
                    width: 78px;
                    max-width: 78px;
                    min-width: 78px;
                    height: 120px;
                }
            }
        }
    }
}
}

@media all and (max-height: 760px) {
.section_name_educational {
    .section {
        &__header {
            top: 40px;
        }

        &__subtitle {
            width: 100% !important;
        }

        &__additional {
            display: none !important;
        }
    }
}
}

@media (--large) {
.section_name_educational {
    .section {
        &__subtitle {
            width: 120%;
        }
    }
}
}

@media (--xlarge) {
.section_name_educational {
    padding-top: 120px;

    .section {

        &__inner {
            height: calc(100vh - 60px);
            margin-top: 0;
        }

        &__header {
            transition-delay: 1s;
            opacity: 0;
            right: -100px;
            bottom: -40px;
            transform: translateY(20px);
        }

        &__subtitle {
            width: 120%;
        }

        &__primary {
            width: calc(100% - 160px);
        }

        &__additional {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        &__bubbles {
            display: block;
            position: relative;
            top: 40px;
            width: 160px;
            min-width: 160px;
            max-width: 160px;
            height: auto;
            transform: translateY(20px);
            opacity: 0;
            transition-delay: 1s;
        }

        &__kettle {
            opacity: 0;
            transform: translateY(20px);
            transition-delay: 1s;
        }
    }

    &.active {
        .section {
            &__header {
                    transition: opacity 1s ease-out 0.8s,
                            transform 0.8s ease-out 0.8s;
                opacity: 1;
                transform: translateY(0px);
            }

            &__kettle {
                opacity: 1;
                transform: translateY(0px);
                transition: opacity 0.6s ease-out,
                            transform 0.6s ease-out;
                &_order {
                    &_1 {
                        transition-delay: 1.6s;
                        display: block;
                    }

                    &_2 {
                        transition-delay: 1.9s;
                    }

                    &_3 {
                        transition-delay: 2.1s;
                    }
                }
            }

            &__bubbles {
                transition: opacity 0.8s ease-out 2.5s,
                            transform 0.8s ease-out 2.3s;
                transform: translateY(0px);
                opacity: 1;
            }
        }
    }
}
}

@media all and (min-width: 1400px) {
.section_name_educational {
    .section {
        &__header {
            left: 60px;
        }

        &__subtitle {
            width: 110%;
        }
    }
}
}

@media (--xxlarge) {
.section_name_educational {
    .section {

        &__primary {
            width: calc(100% - 148px);
        }

        &__subtitle {
            width: 80%;
            margin: 40px 0px;
        }

        &__description-inner {
            width: 60%;
        }

        &__bubbles {
            width: 148px;
            min-width: 148px;
            max-width: 148px;
            top: 40px;
        }
    }
}
}

@media (--monster) {
.section_name_educational {
    .section {
        &__primary {
            width: calc(100% - 227px);
        }

        &__header {
            left: 200px;
            top: 150px;
        }

        &__title {
            font-size: 58px;
        }

        &__subtitle {
            font-size: 24px;
            width: 80%;
        }

        &__description {
            font-size: 24px;
        }

        &__bubbles {
            width: 227px;
            min-width: 227px;
            max-width: 227px;
            left: 0px;
        }
    }
}
}

As for me - it would be difficult to read it if I had done it with the 1st variant.


text:
Q: Typescript interface fails to work The following code fails with an error:

readCandidates is not a function:

Here is the code
export class Candidates {
    private _dataService : ModelContracts.IDataService;

    constructor(private tag: ModelContracts.ITag, private dataService: ModelContracts.IDataService) {
        this._value = tag;
        this._dataService = dataService;
    }

    private _value : ModelContracts.ITag;
    public get value() : ModelContracts.ITag {
        return this._value;
    }
    public set value(v : ModelContracts.ITag) {
        this._value = v;
    }

    candidates = [];

    activate() {
       this._dataService.readCandidates().then(candidates => this.candidates = candidates);
    }
}

export interface IDataService {
    readCandidates(): Promise<ModelContracts.ICandidate[]>
}

export class DataService {
    //some implementation
}

I'm using Aurelia bet 1.1.0 and Typescript.
The dataService dependency gets injected but the function call fails.

A: If the context of the call is not the class (for example, because you are calling activate as a callback or from an event) you'll need to make sure you sort out your scope.
For example:
activate = () => {
   this._dataService.readCandidates().then(candidates => this.candidates = candidates);
}

Although there are some better ways to do this if you want to have a consitent approach to handling the responsibility of scope in TypeScript. The recommendation is to handle scope off-class, as the class shouldn't know how it is going to be called.

A: it's impossible to use interfaces with DI in aurelia.


text:
Q: React+Redux. Не получается получить данные при помощи fetch Начал осваивать Redux и applyMiddleware. Попробовал написать свою простенькую программу. И получил ошибку, в логах пишет, что данные json до моего компонента-контейнера не доходят, т.е. undefined. Возможно я упустил что-то элементарное.
index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';

import reducer from './reducers/index';
import App from "./components/App";

const store = createStore(
 reducer,
 applyMiddleware(thunk)
 )

console.log(store.getState()) // тут выводит только пустой объект

store.subscribe(() => {
  console.log('store updated', store.getState());  // обновлений стора нет, в консоль ничего не выводит
 });

ReactDOM.render(
 <Provider store={store}>
    <App />
 </Provider>,
 document.getElementById('root')
 )

action:

export const REQUEST_DATA = 'REQUEST_DATA';
export const RECEIVE_DATA = 'RECEIVE_DATA';

export const requestData = () => ({
type: REQUEST_DATA,
});

export const receivedData = json => ({
type: RECEIVE_DATA,
json: json,
});

export function fetchPosts() {
 return function (dispatch) {
   dispatch(requestData());
   return fetch(`http://www.json-generator.com/api/json/get/ceRHciXcVu?indent=2`)
   .then(
      response => response.json(),
      error => console.log('An error occurred.', error),
  )
   .then((json) => {
      dispatch(receivedData(json));
   },
  );
 };
}

reducer:

import { REQUEST_DATA, RECEIVE_DATA } from '../actions/index';

const reducer = (state = {}, action) => {
  switch (action.type) {
    case REQUEST_DATA:
       return { ...state, loading: true };
    case RECEIVE_DATA:
       return { ...state, json: action.json };
    default:
       return state;
  }
};
export default reducer;

container:

import React from 'react';
import { connect } from 'react-redux'

let App = ({filteredArr}) => {
  console.log({filteredArr}); // получаю undefined

  return(

test

  )
};

const mapStateToProps = (state) => ({
    filteredArr: state.json
  })

  App = connect(
    mapStateToProps,
    null
  )(App)

export default App;


text:
Q: Android SQLite - changing journal_mode I am trying to alter the journal_mode for my database, through code. I tried SQLiteDatabase.execSQL("PRAGMA journal_mode=OFF") but it fails because, the expression "PRAGMA journal_mode=OFF" returns a result (I verified this from the terminal), and so Android thinks this is a query and complains that I should be using execQuery instead. But what I am trying to execute isn't a query.
I also tried compiling the pragma expression to a SQLiteStatement and invoked the execute method, but same result.
Can someone suggest any alternatives to make this work through code?
Thanks,
Ranjit

A: Perhaps you are suffering from this problem that the execSQL docs talk about:

When using enableWriteAheadLogging(), journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using enableWriteAheadLogging()

Check that you are not using write ahead logging and then it might work.
Update: As Ranjit said in the comments, this should work:
Cursor c1 = db.rawQuery("PRAGMA journal_mode=OFF", null);
c1.close();

A: It can be done with the next command:
db.execSQL("PRAGMA journal_mode=OFF;");

(No need to create a Cursor as it is suggested in one of the comments to Robert's answer)


text:
Q: Html Agility Pack, couldn't SelectNodes Here's the HTML file, it's truncated due to the content size and contained with an "img" tag at the end.
<?xml version="1.0" encoding="UTF-8"?>

    <meta charset="utf-8"></meta>
    <title>The Waste Land</title>
    <link rel="stylesheet" type="text/css" href="wasteland.css" class="day" title="day"/>
    <link rel="alternate stylesheet" type="text/css" href="wasteland-night.css" class="night" title="night"/>

The Waste Land

T.S. Eliot

For Ezra Pound: il migliorfabbro

I. THE BURIAL OF THE DEAD

Looking into the heart of light, the silence.

                    Od' und leer das Meer.*

                The lady of situations.

Here is the man with three staves, and here the Wheel,

And here is the one-eyed merchant, and this card,

Here's my code
HtmlNodeCollection imgNodes= HTMLDoc.DocumentNode.SelectNodes("//img");

or
 List<HtmlNode> imgNodes = HTMLDoc.DocumentNode.Descendants().Where(n => n.Name =="img").ToList();

Neither can retrieve any tags. What can i do?


text:
Q: Any possible way to programmatically save to another folder other than the designated downloads folder? I'm developing a ASP.NET Web application in which a table is converted to an excel spreadsheet. I would like to give the option to the user to save somewhere else than the downloads section. I realize that is a good likelihood that this is prohibited, but maybe there is some sort of class/mechanism facilitated by ASP.net framework.
Here is my current code:
protected void saveDataButton_Click(Object sender, EventArgs e)
    {
        SaveFileDialog browser = new SaveFileDialog();
        string fileName;

        if (browser.ShowDialog() == DialogResult.OK)
        {
            fileName = browser.FileName;
        }
        else
            return;

       DataTable table = (DataTable)Session["tableData"];

       HttpContext context = HttpContext.Current;
       context.Response.Clear();

       context.Response.ContentType = "text/csv";
       context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");

       foreach (DataColumn column in table.Columns)
       {
            context.Response.Write(column.ColumnName + ";");
       }
       context.Response.Write(Environment.NewLine);
       foreach (DataRow row in table.Rows)
       {
            for (int i = 0; i < row.ItemArray.Length; i++)
            {
                context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");
            }
            context.Response.Write(Environment.NewLine);
       }

       context.Response.End();
    }

I know the way I'm using fileName is wrong in this context, as fileName is actually storing file path + file name in my code. Any way to specify a file path?
The only other solution I can think of is if I created the some sort of file on the page and had them right click + save as. Is this a bad alternative? Are there others?

A: No.  The web application doesn't know anything about the local file system.  (Indeed, aside from the content-disposition header, the HTTP protocol doesn't even really know what a "file" is.)
What you're doing (aside from having the full path in the content-disposition header) is correct.  The standard way to send a file to a web client is to set that header and write the file content to the output.  What happens on the client-side is entirely up to the web browser.  If the user's web browser is set to automatically save downloads to a specific folder without prompting then you can't change that from the server.

A: no, where the file is saved on the user's computer is dictated by the web browser, it has nothing to do with the web server.  think about it, you don't know what operating system a site visitor is running, let alone some arbitrary path you specify on the server.


text:
Q: symfony2 link a file to server I have PDF files hosted on the server. Could I open those files by pressing a button with Symfony2? The path to those files will be housed in an entity in the database. Pressing the button by AJAX gets the path in the controller.

A: Not sure it that's what you're looking for but AJAX cannot handle file download by itself. The closest match would be to send AJAX request that would build file path which would then be returned to view.
Let's assume you're using JSON as a manner of trasporing data back to view..
Then, you either redirect using:
window.location.href = response.path;

where response is JSON object returned from controller
or set src attribute of some, previously created, iframe tag:
$('#myDocumentIframe').attr('src', response.path);

Is this what you trying to achieve?


text:
Q: repartitionAndSortWithinPartitions & remove duplicates which a single shuffle I have a use-case wherein I need to use custom partitioner & eventually sort the partitions.
    implicit val ordering: Ordering[Array[Byte]] = new LexicographicalOrdering

    val partitionedDf = spark.createDataFrame(
        dataset
          .select(RecordProvider.getKeyUDF(sparkArguments.getDatasetArguments)(col(hashKeyName), col(rangeKeyName)).as("key"),
              RecordProvider.getValueUDF(avroSchema)(to_json(struct(dataset.columns.map(col): _*))).as("value")).
        rdd
          .map(record => (record.getAs[Array[Byte]](0),record.getAs[Array[Byte]](1)))
          .repartitionAndSortWithinPartitions(new XXHashRangeBasedPartitioner(sparkArguments.getPartitionConfigurationArguments.getNumberOfPartitions))
          .map(pair => Row(pair._1, pair._2))
      , DefaultSource.SUPPORTED_SCHEMA)

As you might have already noticed, getKeyUDF & getValueUDF returns Array[Byte]. I have defined a custom Partitioner XXHashRangeBasedPartitioner and have a [Array[Byte]] to be used internally for sorting.
I need to drop duplicates from my dataset at some point of time. Considering repartitionAndSortWithinPartitions already causes a shuffle & sorts my partitions. Is there a way I can club a dropDuplicates with it or have a dropDuplicates which works efficiently on sorted partitions (just at partition level) without invoking another shuffle. So, basically achieve duplication removal, custom partition & sort with just one shuffle.
A reduceByKey on the rdd or a dropDuplicates on dataset both results into an addition shuffle. reduceByKey on rdd has another issue that it won't work with Array[Byte] and I will have to wrap it & provide hashCode & equals implementation.
So, what's best that can be done in this situation?

A: you could add an mapPartitions - step after repartitionAndSortWithinPartitions
def dedup(rows : Seq[(Array[Byte],Array[Byte])]) : Seq[(Array[Byte],Array[Byte])]= {
  // your deduplication logic
}

rdd
  .repartitionAndSortWithinPartitions(new XXHashRangeBasedPartitioner(sparkArguments.getPartitionConfigurationArguments.getNumberOfPartitions))
  .mapPartitions(rows => dedup(rows.toList).toIterator, preservesPartitioning = true)

This will not add a shuffle and partitioning will be preserved (but maybe not sorting)


text:
Q: mapping categorical variable in ggmap in r am having this data
Zip    incidentType        city state latitude longitude
1 00660           Flood Hormigueros    PR 18.13911 -67.12085
2 00660 Severe Storm(s) Hormigueros    PR 18.13911 -67.12085
3 00660 Severe Storm(s) Hormigueros    PR 18.13911 -67.12085
4 00660           Flood Hormigueros    PR 18.13911 -67.12085
5 00660           Flood Hormigueros    PR 18.13911 -67.12085
6 01255           Flood Sandisfield    MA 42.08897 -73.12444

and i want to great a heat map to plot incident variable which is a factor with various levels with the following code
library(ggmap)

map <- get_map(location = "United States",zoom = 4,maptype = "terrain",
               color = "color",source = "google")

ggmap(map,extent = "device") + geom_point(aes(x=latitude,y=longitude,
                         alpha=0.7,fill=incidentType,
                        col=incidentType),fun=sum,
                        data = dat1,na.rm = TRUE)

But the points are not plotted on the map.
please help.

A: There were multiple issues.

*

*zoom = 4 is too small. Please use zoom = 3.

*longitude should be mapped to x. latitude should be mapped to y.

*It is better to specify the ggplot call in the base_layer argument.

*Not sure what does fun = sum mean here.

*Not sure why alpha = 0.7 is the in aes argument.

Here is the fixed code.
dat <- read.table(text = "Zip    incidentType        city state latitude longitude
1 00660           Flood Hormigueros    PR 18.13911 -67.12085
2 00660 'Severe Storm(s)' Hormigueros    PR 18.13911 -67.12085
3 00660 'Severe Storm(s)' Hormigueros    PR 18.13911 -67.12085
4 00660           Flood Hormigueros    PR 18.13911 -67.12085
5 00660           Flood Hormigueros    PR 18.13911 -67.12085
6 01255           Flood Sandisfield    MA 42.08897 -73.12444",
                  header = TRUE, stringsAsFactors = FALSE)

library(ggmap)

map <- get_map(location = "United States",zoom = 3,maptype = "terrain",
               color = "color",source = "google")

ggmap(map,
      base_layer = ggplot(data = dat, aes(x = longitude, y = latitude))) +
  geom_point(aes(fill = incidentType, col = incidentType), alpha = 0.7, size = 2)

Here is the plot.


text:
Q: What is the minimum version of Xcode I can use for submission to app store (as of 2015 October) I have an app on the appstore currently that is built using Xcode 6.2 with a deployment target of iOS 8. The recent release Xcode 7, however only works on OSX 10.10
Can I submit updates to the app store(on 2015 October) by building on an earlier version of Xcode (6.2 in my case) because I am unable to update OSX to 10.10? Does Apple release documentation about this when it releases a new Xcode version? The only thing I found was this
https://developer.apple.com/library/ios/qa/qa1806/_index.html
which says that I should aim to build with the latest version of Xcode but does not mention if the app would be rejected/approved if built with a lower version.
Can anybody help me to get a confirmation regarding this.

A: You can go ahead with your update, Apple will not reject the App.
Make sure you keep Deployment Target as iOS 8 or less.
Risk is your App may get crashed on User devices with iOS 9 as its not been tested and compiled with iOS 9/Xcode 7.


text:
Q: Prepared Statements - Iterative query I have to upgrade the following code to use prepared statements:
OdbcCommand cmd = sql.CreateCommand();
cmd.CommandText = "SELECT [EMail] from myTable WHERE "+,
for (int i = 0; i < 50; i++)
{
   if (i > 0)
   {
      cmd.CommandText += " OR ";
   }
   cmd.CommandText += "UNIQUE_ID = " + lUniqueIDS[i];
}

Forbid my stupid code above, it's just an example... I'm trying to fetch all the Emails of users with IDs either x, y, z, etc...
The question is - how can I rewrite it using prepared statements?
A blind naive guess would be
for (int i = 0; i < 50; i++)
{
   if (i > 0)
   {
      cmd.CommandText += " OR ";
   }
   cmd.CommandText += "UNIQUE_ID = ?";
   cmd.Parameters.Add("@UNIQUE_ID", OdbcType.BigInt).Value = lUniqueIDS[i];
}

Should it work? Can I append the same parameter (unique_id) more than once?

A: It looks like you're using positional parameters (i.e. ? in the query, rather than @UNIQUE_ID) which means the names of the parameters shouldn't matter as far as the SQL is concerned. However, I wouldn't be entirely surprised to see the provider complain... and it may make diagnostics harder too. I suggest you use the index as a suffix:
cmd.Parameters.Add("@UNIQUE_ID" + i, ObdcType.BigInt).Value = lUniqueIDs[i];


text:
Q: Android programming : how to programmatically create various view types in a grid fashion I'm not sure how to ask this question exactly, but I'll give it a try.
Here's what I'm trying to do, in one Activity.
Build a Grid, that contains [x] rows of 3 columns each, with this content
[a TextView (containing a name)] [a Spinner (containing a list of states)] [an EditText]
How to start ? The Views I can create programmatically, that's not a problem, I even store them in 3 array lists for later easy reference, but I can't see how to do it right.
Should I create an xml layout with e.g. (and pseudocode)
LinearLayout (horizontal)
   TextView ...
   Spinner ...
   EditText ...
/LinearLayout

and try to inflate it in the loop I use to create each row, and setting the id of each view in a standard way (e.g. viewName[x] where x is the current "i" from my for, but is it of any use?), as we do for example for an ExpendableList Adapter's groups/childs ?
Or is there a way to actually use a GridView/GridLayout to do that (in this case, being in my Activity, how do I put each specific created View into the correct GridView/GridLayout) ?
Or still another way I don't suspect at all ?
Thanks in advance

A: if you want to add views programatically then, just create a layout.xml with 3 Linearlayouts(horizontal) in it. Also assign id to those LinearLayouts. Then in your java code, just find the views and call addView() on those LinearLayouts.
Example:
LinearLayout ll_1 = (LinearLayout)findViewById(R.id.linearlayout1);
LinearLayout ll_2 = (LinearLayout)findViewById(R.id.linearlayout2);
LinearLayout ll_3 = (LinearLayout)findViewById(R.id.linearlayout3);

...

ll_1.addView(new TextView(this));
ll_1.addView(new Spinner(this));
ll_1.addView(new EditText(this));
...

In detail, say for example, if i want to add spinner to LinearLayout, programatically then,
You need to get layout
LinearLayout linearLayout =  findViewById(R.id.layoutID);

Create spinner as below:
   Spinner spinner = new Spinner(this);

spinner .setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
                        android.R.layout.simple_spinner_dropdown_item, spinnerList);
                spinner.setAdapter(spinnerArrayAdapter);

Then add spinner to view
linearLayout.addView(spinner);


text:
Q: Help with tricky integral of rational function that deals with positive and negative cases? Evaluate the integral $$\int \frac{dx}{1+k+(1-k)x^2}$$ for all values of $k \in \mathbb{R}$.
Now when $-1 \le k \le 1$ this integral is trivial by using inverse tangent substitution.
But this doesn't work when $|k|>1$. So why can't you evaluate the integral using this method, and how do you evaluate it then? (especially when $k$ is negative)
Is it possible to work out the definite integral with respect to $x$ from $0$ to $1$?

A: For $k > 1$, we can rewrite the integral as
$$\frac{1}{k + 1} \int \frac{dx}{1 - \frac{k - 1}{k + 1} x^2} = \frac{1}{k + 1} \int \frac{dx}{1 - \left(\sqrt{\frac{k - 1}{k + 1}} x\right)^2},$$
which suggests the substitution $\sin \theta = \sqrt{\frac{k - 1}{k + 1}} x$ (or a suitable hyperbolic substitution, or partial fractions, though the last of these works out to be slightly messy).
The case $k < -1$ can be handled similarly.

A: The antiderivative is equal to $$\frac{1}{1-k}\sqrt{\frac{1-k}{1+k}}atan(\sqrt{\frac{1-k}{1+k}}x)$$ for k not equal to 1 or -1 and if $\frac{1-k}{1+k}$ >=0. The case k=1 is trivial. For k=-1 the antiderivative is $$\frac{-1}{2x}$$
If $\frac{1-k}{1+k}$ <0 the you can use simple fraction to integrate.


text:
Q: Strava authentication Api Login Issue I have implemented Strava authentication in my asp application. I am facing issue with call back url. If I am not login into strava account from browser and then try to connect user with strava from my application, Login prompt appears for strava account. After successfully login Starva dashboard screen opens up. It neither ask for authorization not goes back to my application.
However flow is working fine if i already have login to strava in my browser. Callack url is working perfect for this scenario.
Here is my call back URL :
https://www.strava.com/oauth/authorize?client_id=+ clientid + "&response_type=code&redirect_uri=www.zbc.com/Starva/CallBack.aspx?Source=1&scope=write";


text:
Q: Generic Rest API design for internal applications I am designing REST API for  internal applications.
I have many database CURD operations and don't want to define each endpoints for different tables. so I came up with the 2 generic endpoints,
/api/1.0/hub/generic/query.json
/api/1.0/hub/generic/NonQuery.json

So a POST request with JSON obj {'sql': 'insert ...', 'param': [...] } will serve all CURD operations. Is this design against best practices?
Thanks,