text:
Q: Getting the error "There was an error in iCloud Preferences" I keep getting this error:

Not sure how to fix it. I tried moving the MobileMe.plist file from the preferences but still get this.
Ive saved the log file specifically for the iCloud error:

4/26/16 4:21:39.714 PM  com.apple.preferences.icloud.remoteservice[1315]    Failed to connect (_signInButton) outlet from (iCloudPref) to (NSButton): missing setter or instance variable
4/26/16 4:21:39.714 PM  com.apple.preferences.icloud.remoteservice[1315]    Failed to connect (_signInSpinner) outlet from (iCloudPref) to (NSProgressIndicator): missing setter or instance variable
4/26/16 4:21:39.715 PM  com.apple.preferences.icloud.remoteservice[1315]    Could not connect action, target class iCloudPref does not respond to -signinPressed:
4/26/16 4:21:39.800 PM  com.apple.preferences.icloud.remoteservice[1315]    Additional Logging , array retured in signedInAccounts is (
    " -- uid: 23E78709-2529-493E-A80A-17F8E3BABAB8; loginName: user@me.com; provider: com.apple.account.icloud; parent: (null)\n\taccount ID: user@me.com - com.apple.account.icloud - \n\tprovider attrs: {\n    IADSIDKey = 146390864;\n    \"com.apple.InternetAccounts.loginName\" = \"user@me.com\";\n    \"com.apple.InternetAccounts.provider\" = \"com.apple.account.icloud\";\n    fullName = \"Full Name\";\n}"
)
4/26/16 4:21:41.891 PM  com.apple.preferences.icloud.remoteservice[1315]    [AOSAccounts] :  [MMCopyMeCardImageFromiCloud]  : error from _AOSAccountRetrieveMeCardImage Error Domain=AOSErrorDomain Code=1000 "(null)" UserInfo={HttpStatusCode=404, DialogInfo={
    DialogType = Unknown;
}}
4/26/16 4:21:42.061 PM  com.apple.preferences.icloud.remoteservice[1315]    [AOSAccounts] :  [MMCopyMeCardImageFromiCloud]  : error from _AOSAccountRetrieveMeCardImage Error Domain=AOSErrorDomain Code=1000 "(null)" UserInfo={HttpStatusCode=404, DialogInfo={
    DialogType = Unknown;
}}
4/26/16 4:21:42.256 PM  com.apple.preferences.icloud.remoteservice[1315]    [AOSAccounts] :  [MMCopyMeCardImageFromiCloud]  : error from _AOSAccountRetrieveMeCardImage Error Domain=AOSErrorDomain Code=1000 "(null)" UserInfo={HttpStatusCode=404, DialogInfo={
    DialogType = Unknown;
}}
4/26/16 4:21:42.290 PM  com.apple.preferences.icloud.remoteservice[1315]    Failed to connect (_iconBadgeView) outlet from (IACastleServiceRow) to (NSImageView): missing setter or instance variable
4/26/16 4:21:42.350 PM  com.apple.preferences.icloud.remoteservice[1315]    [AOSAccounts] : [iCloudConfigurationDelegate] -[iCloudConfigurationDelegate completeSetupWithResponse:account:handler:] : Saving iCloud Account with username user@me.com 23E78709-2529-493E-A80A-17F8E3BABAB8
4/26/16 4:21:42.654 PM  com.apple.preferences.icloud.remoteservice[1315]    Migration of type ValidateCredentials already in progress
4/26/16 4:21:42.704 PM  com.apple.preferences.icloud.remoteservice[1315]    ValidateCredentials start
4/26/16 4:21:42.704 PM  com.apple.preferences.icloud.remoteservice[1315]      running ValidateCredentials step LogStatus
4/26/16 4:21:42.731 PM  com.apple.preferences.icloud.remoteservice[1315]    Master identity:  BAT: old-identity
4/26/16 4:21:42.753 PM  com.apple.preferences.icloud.remoteservice[1315]    KeychainGetICDPStatus: keychain: -25300
4/26/16 4:21:42.753 PM  com.apple.preferences.icloud.remoteservice[1315]    KeychainGetICDPStatus: status: off
4/26/16 4:21:42.753 PM  com.apple.preferences.icloud.remoteservice[1315]    Local iCDP status is 0
4/26/16 4:21:42.753 PM  com.apple.preferences.icloud.remoteservice[1315]      running ValidateCredentials step PreCheckKeychain
4/26/16 4:21:42.766 PM  com.apple.preferences.icloud.remoteservice[1315]     SecOSStatusWith error:[-25299] Error Domain=NSOSStatusErrorDomain Code=-25299 "duplicate item O,genp,0DC4BAEB,S,ak,appleaccount,0,desc,invi,acct,svce,gena,musr,20160426232142.764685Z,75C3AAAC" (errKCDuplicateItem / errSecDuplicateItem:  / The item already exists.) UserInfo={NSDescription=duplicate item O,genp,0DC4BAEB,S,ak,appleaccount,0,desc,invi,acct,svce,gena,musr,20160426232142.764685Z,75C3AAAC}
4/26/16 4:21:42.779 PM  com.apple.preferences.icloud.remoteservice[1315]      running ValidateCredentials step FixupKeychainItems
4/26/16 4:21:42.803 PM  com.apple.preferences.icloud.remoteservice[1315]     SecOSStatusWith error:[-25299] Error Domain=NSOSStatusErrorDomain Code=-25299 "duplicate item O,genp,0DC4BAEB,S,ak,appleaccount,0,desc,invi,acct,svce,gena,musr,20160426232142.802161Z,B5BBC74F" (errKCDuplicateItem / errSecDuplicateItem:  / The item already exists.) UserInfo={NSDescription=duplicate item O,genp,0DC4BAEB,S,ak,appleaccount,0,desc,invi,acct,svce,gena,musr,20160426232142.802161Z,B5BBC74F}
4/26/16 4:21:43.027 PM  com.apple.preferences.icloud.remoteservice[1315]      running ValidateCredentials step FetchMetaData
4/26/16 4:21:43.043 PM  com.apple.preferences.icloud.remoteservice[1315]     SecOSStatusWith error:[-25299] Error Domain=NSOSStatusErrorDomain Code=-25299 "duplicate item O,genp,0DC4BAEB,S,ak,appleaccount,0,desc,invi,acct,svce,gena,musr,20160426232143.04167Z,3AE70A56" (errKCDuplicateItem / errSecDuplicateItem:  / The item already exists.) UserInfo={NSDescription=duplicate item O,genp,0DC4BAEB,S,ak,appleaccount,0,desc,invi,acct,svce,gena,musr,20160426232143.04167Z,3AE70A56}
4/26/16 4:21:44.370 PM  com.apple.preferences.icloud.remoteservice[1315]    Could not find image named 'iCloudDrive'.
4/26/16 4:21:44.622 PM  com.apple.preferences.icloud.remoteservice[1315]    revealElementForKey iCloud
4/26/16 4:21:44.624 PM  com.apple.preferences.icloud.remoteservice[1315]    An uncaught exception was raised
4/26/16 4:21:44.624 PM  com.apple.preferences.icloud.remoteservice[1315]    *** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]
4/26/16 4:21:44.624 PM  com.apple.preferences.icloud.remoteservice[1315]    (
    0   CoreFoundation                      0x00007fff96abd4f2 __exceptionPreprocess + 178
    1   libobjc.A.dylib                     0x00007fff8a053f7e objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff969dd134 -[__NSArrayI objectAtIndex:] + 164
    3   iCloudPref                          0x00000001011b69a5 iCloudPref + 10661
    4   libdispatch.dylib                   0x00007fff8ca4f93d _dispatch_call_block_and_release + 12
    5   libdispatch.dylib                   0x00007fff8ca4440b _dispatch_client_callout + 8
    6   libdispatch.dylib                   0x00007fff8ca57c1c _dispatch_main_queue_callback_4CF + 1685
    7   CoreFoundation                      0x00007fff96a729e9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    8   CoreFoundation                      0x00007fff96a318dd __CFRunLoopRun + 1949
    9   CoreFoundation                      0x00007fff96a30ed8 CFRunLoopRunSpecific + 296
    10  HIToolbox                           0x00007fff932e4935 RunCurrentEventLoopInMode + 235
    11  HIToolbox                           0x00007fff932e476f ReceiveNextEventCommon + 432
    12  HIToolbox                           0x00007fff932e45af _BlockUntilNextEventMatchingListInModeWithFilter + 71
    13  AppKit                              0x00007fff8da68efa _DPSNextEvent + 1067
    14  AppKit                              0x00007fff8da6832a -[NSApplication _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 454
    15  ViewBridge                          0x00007fff8be2ab21 -[NSViewServiceApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 73
    16  AppKit                              0x00007fff8da5ce84 -[NSApplication run] + 682
    17  AppKit                              0x00007fff8da2646c NSApplicationMain + 1176
    18  libxpc.dylib                        0x00007fff9897245e _xpc_objc_main + 793
    19  libxpc.dylib                        0x00007fff98970e8a xpc_main + 494
    20  ViewBridge                          0x00007fff8be50683 xpc_connection_handler + 0
    21  ViewBridge                          0x00007fff8be2e9d9 NSViewServiceApplicationMain + 2818
    22  PreferencePanes                     0x00007fff854c95c1 PreferencePaneMain + 168
    23  com.apple.preferences.icloud.remoteservice 0x0000000100dccd24 main + 37
    24  libdyld.dylib                       0x00007fff8fc935ad start + 1
    25  ???                                 0x0000000000000001 0x0 + 1
)
4/26/16 4:21:44.634 PM  com.apple.xpc.launchd[1]    (com.apple.preferences.icloud.remoteservice[1315]) Service exited due to signal: Illegal instruction: 4
4/26/16 4:21:45.736 PM  ReportCrash[1345]   Saved crash report for com.apple.preferences.icloud.remoteservice[1315] version 316 (479) to /Users/doronkatz/Library/Logs/DiagnosticReports/com.apple.preferences.icloud.remoteservice_2016-04-26-162145_Dorons-MacBook-Pro.crash

A: Instead of launching iCloud in System Preferences (and getting that error), open Internet Accounts and log into your iCloud account to reset your credentials.  That fixed this error from iCloud preferences for me.

A: Omg i had the same problem.
Im a tech-blind wasted half of my life in this mess, so i must summarize all this for who needed...

*

*my Notes was not syncing, cannot sign out iCloud either (it seemed lag? i was unable to uncheck the Find my mac or Keychain)

*Then I used terminal to "defaults delete MobileMeAccounts" (100% regretful .-.)

*iCloud was forced signing out successfully, but cannot re-sign in any more. The caution "You can't sign in at this time. Try signing in again" appeared every time i entered id + password

*after some hopeless effort (like restart mac), the box "There was an error in iCloud preferences" appeared.

There were some suggestion on internet like updating macos.... but this one worked on me:
How to find that .plist file

*

*In the Finder, click on the Go menu and choose Go to Folder.

*Type ~/Library in the box.

*Select the Preferences folder and locate the file: com.apple.systempreferences.plist

*Drag the plist file to your desktop and close the folder.

*Try to access the iCloud preferences pane again.

!: pls dont delete plist file, simply drag it to your screen
!!: note down the location of plist file, idk but if sth wrong occur, at least you know exactly where to put it back, make a copy of it or whatever you want....


text:
Q:  path attribute must be a relative virtual path: Location starts with "." I need to set custom web.config settings for a location that starts with a ".":
<location path=".somepath">

Unfortunately, ASP.NET doesn't seem to like  paths that start with periods. I get the following error:

Configuration Error: <location> path attribute must be a relative virtual path.  It cannot start with any of ' ' '.' '/' or '\'.

Is there any workaround for this?

A: You can start the path with "~/" thus:
<location path="~/.somepath">

A: It turns out there's a pretty easy solution: put a web.config file in the actually directory that starts with a ".". So instead of using the root web.config with <location path=".somepath">, I simply created a web.config file in the ".somepath" directory and added the configuration there. If ".somepath" were a file, I'm not sure what I would've done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ngClass with three different states I have no idea if this is the dumbest way to do this, but you have to start at some point, and this seemed like one way to go.
Anyways, I have created a div box. This box appears when a button is clicked, i.e. this click adds a class to the box. When the box appears it has two buttons - both which does something to the box.
Each button has these two functions:
States: Array<boolean> = new Array;

toggleState(firstIndex: number, secondIndex: number): void {
    let totalIndex = this.getTotalIndex(firstIndex, secondIndex);

    this.States[totalIndex] = !this.States[totalIndex];
}

getState(firstIndex: number, secondIndex: number): boolean {
    let totalIndex = this.getTotalIndex (firstIndex, secondIndex);

    return this.States[totalIndex];
}

This is just a way for me to get the state for each individual item/ID, where this box can appear. But again, I then have two other buttons with similar functions (only the name differs).
The buttons are then activated by:
Button 1
Button 2
Button 3

Now, the trouble I am having (which I can't get to work, and it also looks terrible tbh) is with the div box HTML, which currently looks like:

             // here the box has appeared

Now, when I run this, I can't seem to get all the buttons working. It's only two out of three that actually works. There is always one, no matter how I arrange it, that doesn't work.
So basically, what am I doing wrong here ? :)

A: As you always used box-regular then you can push it to the class property right away.
<div class="box-regular" [ngClass]="[ { 'appear transparent' : getState1(firstIndex, secondIndex)}, { 'appear enlarge': getState3(firstIndex, secondIndex)} ]

The syntax for multiple values in ngclass is [ngClass]= [ {}, {}],
where object {} contains class value and condition like this { 'classValue': condition },
If you need more than one class then use ternary operator but int this way:
[ngClass]=[ condition ? true : false, condition2 ? true: false, etc]

A: If we reformulate the question from "how do do it with ngClass" into "how to do it in Angular", the answer would be - use [class.your-class]="condition" syntax.
The docs specifically highlight this as a preferred method, even mentioning that ngClass is gonna be deprecated in future.
Docs: https://angular.io/guide/attribute-binding#class-binding


text:
Q: Add new rows after a serial number in the first column from another table I need to add more rows to table_1 (first column sequence ) from another table_2 under the last first column [NO] from Table_1
for example
Table_1
 NO  F1  f2   code   f3   Name
 --  --  --    --   --    --
1     a   0    22    0    ID
2     b   0    19    0    ID
3     c   0    10    0    pass
4     d   0    05    0    pass

Table_2 that was imported from excel
NO    code     Name
--     --       --
5      11       ID
6      12       ID
7      06       pass
8      29       pass

My result
    NO   F1  f2   code  f3   Name
    --   --  --    --   --    --
    1     a   0    22    0    ID
    2     b   0    19    0    ID
    3     c   0    10    0    pass
    4     d   0    05    0    pass
    5     0   0    11    0    ID
    6     0   0    12    0    ID
    7     0   0    06    0    pass
    8     0   0    29    0    pass

A: Made edits based on updated results.
Let me specify what I think you are trying to do:

*

*Add all records from table 2 where No is greater than any record in table 1

This will insert and set f1 f2 & f3 to 0:
declare @maxNo int = (select max(NO) from t1)

insert into t1 (NO,code,Name,f1, f2,f3)
select NO,code,Name,'0',0,0 from t2
where NO > @maxNo

A: You can try this.
DECLARE @MaxID INT = (SELECT MAX([NO]) FROM Table_1)

INSERT INTO Table_1 ([NO], F1, f2, code, f3, Name)
SELECT ( @MaxID + (ROW_NUMBER() OVER(ORDER BY (SELECT NULL))) ) , 0 , 0, code, 0, Name FROM
Table_2


text:
Q: Getting dynamic output using JSONata while entering value and sample data in UI I try to pass the dynamic input value to JSONata but it is not taking it in line:15 I am using $add() in which I am assigning input value to it but it is not working.
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>JSONata test</title>

    <textarea id="json">{ "name": "Wilbur" }</textarea>
    <textarea id="query">name</textarea>
    <button onclick="greeting()">Click me</button>

I am creating $add() function inside JSONata method and return dynamic input value but it is not giving desired output.
As of now I am getting whatever I am passing inside field but what I need is when I pass key for Ex:"name" I should get that value using jsonata expression. I need output same as what JSONata method returns
Let me know If I need to provide any other information

A: The issue you're facing is because your $add() function is written to return the query itself, not the evaluated value of the query.
The parameters need to be passed in on the evaluation line and the body of your function needs to handle the evaluated result e.g.:
// Change: Note the passing of the textbox query as a param
var expression = jsonata(`$add(${query})`);
// Change: Using evaluated param as output
expression.registerFunction("add", (a) => `Hello ${a}!`);

You can see this described in the documentation's example of registerFunction:

var expression = jsonata("$add(61, 10005)");
expression.registerFunction("add", (a, b) => a + b, "<nn:n>");
expression.evaluate({}); // 10066

Working example: https://codepen.io/scarabaeus/pen/OJxJbXp?editors=1000


text:
Q: How to use if statement in xsl to check if a path is valid? What I am doing is reading in some xml and using xsl to output it in a table to make it more readable.
So some sample xml:
<example1>
  <sample name="aaa">
    <help1>Help</help1>
    <help2>Me</help2>
  </sample>
  <sample name="bbb">
    <noHelp1>No</noHelp1>
    <noHelp2>Help</noHelp2>
  </sample>
</example1>

So I have a for-each loop to go through each sample. so <xsl:for-each select="example1/sample"> and will use some value-of statements to print some of the values into a table.
Now what I wanted to do was use an if statement to say
if for-each sample, example1/sample/help1 = valid path, then do something

So I thought it would be something along the lines of...
...
<xsl:if test = "something">
  <xsl:for-each select="example1/sample">
    doWork
  </xsl:for-each>
</xsl:if>

The problem is I don't know how to test for this, ie. I don't know what the 'something' should be. I'm also not sure if I should use the if statement within the for-each statement instead.
Any help would be much appreciated.

A: <xsl:for-each select="example1/sample">
  <xsl:if test="help1">
    <!-- now we know that this example1/sample has a help1 child -->
  </xsl:if>
</xsl:for-each>


text:
Q: How to set up composer.json to navigate to another directory and run a script there while running "composer install" I'm building an admin dashboard using Laravel Nova. There, custom tools are being generated in nova-components directory. I have created a tool called "Team Dashboard" and in that team dashboard folder, there is a separate composer.json file & package.json file. To build assests, I have to run "npm run production".
What I want to is, run "npm run production" from Team Dashboard folder when I run "composer install" command from root folder. For that, I add the following lines to composer.json file in root. See "post-install-cmd".
"scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force",
            "npm install",
            "npm run production"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "cd nova-components/TeamDashboard npm run production",
            "npm install",
            "npm run production"
        ]
    },

When executing "cd nova-components/TeamDashboard npm run production" part, composer says The system cannot find the path specified..
How I can implement such a case in composer.json.

A: cd nova-components/TeamDashboard npm run production  tries to use cd  with all these arguments. It does not execute the parts after the path.
cd nova-components/TeamDashboard && npm run production could work, as it runs cd  first, and npm  afterwards


text:
Q: Java create custom exception class with specific status code In Spring Boot, I create custom exception class with specific status code, and I call it to throw exception with code: 100 and message: "No have content" at controller, but output still returns "status": 500 and "error": "Internal Server Error"
AppException.java
public class AppException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private final Integer code;

    public AppException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }
}

UserController.java
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping()
    public ApiResponseDto getAllUsers(Pageable pageable) {
        Page<User> users = userService.getAllUsers(pageable);

        if (users.getSize() < 0) {
            throw new AppException(100, "No have content");
        }

        return new ApiResponseDto(HttpStatus.OK.value(), users);
    }

Actual Output:
{
    "timestamp": 1550987372934,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.app.core.exception.AppException",
    "message": "No have content",
    "path": "/api/user"
}

My expectation:
{
    "timestamp": 1550987372934,
    "status": 100,
    "error": "No have content",
    "exception": "com.app.core.exception.AppException",
    "message": "No have content",
    "path": "/api/user"
}

A: In case you want to have global exception handling for your API, and prefer to have custom error responses, you can add @ControllerAdvice:
@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler({ ApiException.class })
    protected ResponseEntity<ApiErrorResponse> handleApiException(ApiException ex) {
        return new ResponseEntity<>(new ApiErrorResponse(ex.getStatus(), ex.getMessage(), Instant.now()), ex.getStatus());
    }
}

// you can put any information you want in ApiErrorResponse
public class ApiErrorResponse {

    private final HttpStatus status;
    private final String message;
    private final Instant timestamp;

    public ApiError(HttpStatus status, String message, Instant timestamp) {
        this.status= status;
        this.message = message;
        this.timestamp = timestamp;
    }

    public HttpStatus getStatus() {
        return this.status;
    }

    public String getMessage() {
        return this.message;
    }

    public Instant getTimestamp() {
        return this.timestamp;
    }
}

// your custom ApiException class
public class ApiException extends RuntimeException {

    private final HttpStatus status;

    public ApiException(HttpStatus status, String message) {
        super(message);
        this.status = status;
    }

    public HttpStatus getStatus() {
        return this.status;
    }
}

A: If you need a limited number of different error-messages or you want to reuse the same one several times, then that's all you need:
@ResponseStatus(value = HttpStatus.CONTINUE, reason = "No have content")
public class AppException extends RuntimeException {
    private static final long serialVersionUID = 1L;
}

No need of any extra classes and handlers. Your code will be clear and simple.
You can simply raise it like this:
throw new AppException();

A: There are multiple ways to achieve this:

*

*ExceptionHandler
You can add a @ExceptionHandler annotated method in your controller:
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public void handleException() {
//
}

*HandlerExceptionResolver
You can also implement a custom resolver to intercept all exceptions and handle them globally by overriding the doResolveException method
More detail on the above two approaches can be found here: https://www.baeldung.com/exception-handling-for-rest-with-spring


text:
Q: transfer a file bigger than 500mb i created a file with php that can stream a file in a server but the only problem i am having is the resume and i can download only with 1 parallel using IDM i have been searching for a week without finding any thing that helps this is my code
    <?php
$file = 'http://www.affymetrix.com/support/downloads/demo_data/Demo_Data_Barley_MAS5.zip';

function get_size($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    return intval($size);
}

$fp = @fopen($file, 'rb');

$size   = get_size($file); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte
header('Content-Type: application/octet-stream');
 header("Content-Disposition: attachment; filename=Demo_Data_Barley_MAS5.zip");
//header('Content-type: video/mp4');
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])) {

    $c_start = $start;
    $c_end   = $end;

    list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
    if (strpos($range, ',') !== false) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    if ($range == '-') {
        $c_start = $size - substr($range, 1);
    }else{
        $range  = explode('-', $range);
        $c_start = $range[0];
        $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
    }
    $c_end = ($c_end > $end) ? $end : $c_end;
    if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    $start  = $c_start;
    $end    = $c_end;
    $length = $end - $start + 1;
    fseek($fp, $start);
    header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);

$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {

    if ($p + $buffer > $end) {
        $buffer = $end - $p + 1;
    }
    set_time_limit(0);
    echo fread($fp, $buffer);
    flush();
}

fclose($fp);
exit();
?>

i am really thank full if some one can help me out here

A: Use following gist source code for this: https://gist.github.com/kijin/9735300
(im sorry for that linked gist source code annotated by Korean)
Translation of header:
supports:
 1. do not break filename when use UTF-8 filename.
 2. remove or replace if included unknown character by OS.
 3. Add Cache-Control, Expires header when you want to use cache.
 4. Fix the download error when use cache and IE <= 8.
 5. Support resume download (automatically detect Range header, auto generate Accept-Ranges header)
 6. Fix memory leak when download large file.
 7. Can limit download speed.

How to use: send_attachment('filename that provide to client', 'file path', [period of the caching], [speed limit]);

this example is download 'foo.jpg' from server to client named 'photo.jpg'
 send_attachment('photo.jpg', '/srv/www/files/uploads/foo.jpg')

Return: true when successfully sent else false.

Warning: 1. please execute 'exit' when end the transfer.
         2. don't ensure that php version is very low(< 5.1) or not UTF-8 environment.
         3. speed limitation is very dangerous when you using FastCGI/FPM. recommend to use web server's speed limitation.
         4. some android versions does not support UTF-8 encoding.

Note: I recommend to use X-Accel-Redirect(nginx) or X-Sendfile(apache) header when transfer a big file. If you transfer big file on the php interpreter, the php have many load and it works very inefficiently.
Add: here is the code that you want to do - https://gist.github.com/ssut/a3d97c7a35e5458687ed
(note: I'm very poor in english, some translation is imprecise)
I tested this code on nginx + php 5.5(fpm) environment and this is test code: send_attachment('ubuntu.iso', 'http://ftp.daum.net/ubuntu-releases/trusty/ubuntu-14.04-server-amd64.iso');
IDM screenshot:


text:
Q: Is query result null? This is for a data import script, I want to check if the Category Name with a Parent ID already exists; if it does then it does not need to be added to the database. My check however is not stopping duplicate entries.
$i = 1;
$check = FALSE;
echo'
';
do{
   //Turn import order into Colewood order.
   $tieroffset = $i - 1;

   $tier = $csvdata[$r][$fields["Tier" . $i]];

   $query = ("SELECT name FROM base_categories WHERE name = '".$tier."' AND id = '".$tieroffset."'");
   $result = mysql_query($query);
   $result_array = mysql_fetch_array($result);

   if (empty($result_array)) {

       if($tier != null){
       $queryInsert = "INSERT INTO base_categories (parent_id,name)
                        VALUES ('" . $tieroffset . "', '" . mysql_real_escape_string($csvdata[$r][$fields["Tier" . $i]]) . "')";
       }

        mysql_query($queryInsert);

        print_r($queryInsert);
   }

   $i++;
}while ($i <= 6 || $check != FALSE);
echo'    >>>END PRODUCT
';

A: Use mysql_num_rows function to check the number of rows returned by the query.
if (empty($result_array)) {

to
if (mysql_num_rows($result) == 0 ) {

A: mysql_fetch_array returns FALSE if there are no more rows and always use mysql_real_escape_string or PDO to avoid SQL Injection.
$result = mysql_query($query);
if($result)
 {
  if(($result_array = mysql_fetch_array($result)) //while
   {
    //code
   }
  }

A: First a small return question:
If your {parent_id, name} combination cannot contain duplicates why are they not a unique constraint???
If you add that you are sure never to get a duplicate key in those two columns. If they are they only colums you could also make them the primary key together.
Next if you have done that you could suffice with just one query
$query = "INSERT INTO base_categories (parent_id, name) VALUES('" .
         $tieroffset . "', '" .
         mysql_real_escape_string($csvdata[$r][$fields["Tier" . $i]]) . "')
         ON DUPLICATE KEY UPDATE name = name;

ON DUPLICATE KEY UPDATE updates your old record when an UNIQUE constraint OR PRIMARY KEY constraint fails. This way you only have to run one query in stead of two.


text:
Q: Android: DEFAULT activity showing up instead of LAUNCHER I am making a simple Android Application, which consists of only two activities, .Password and .Adder
<activity
        android:name=".Adder"
        android:label="@string/title_activity_adder" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Password"
        android:label="@string/title_activity_adder" >
        <intent-filter>
            <action android:name="android.intent.action.PASSWORD" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

The .Password activity is set as the LAUNCHER but when I run it, the .Adder Activity shows us instead.
I have the .xml and .java file for both the activity properly connected by setContentView() and Eclipse is not reporting any kind of error in any file at all.
The Password Activity checks for the correct password and switches control to the Adder Activity:
Intent openStartingPoint = new Intent("com.example.pointsadder.MAIN");
startActivity(openStartingPoint);

A: You don t have to write intent filter to each activity. Correct xml:
<activity
    android:name=".Adder"
    android:label="@string/title_activity_adder" >
</activity>
<activity
    android:name=".Password"
    android:label="@string/title_activity_adder" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

A: Change this:
<activity
    android:name=".Password"
    android:label="@string/title_activity_adder" >
    <intent-filter>
        <action android:name="android.intent.action.PASSWORD" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

to this:
<activity
    android:name=".Password"
    android:label="@string/title_activity_adder" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

And modify this as shown:
<activity
    android:name=".Adder"
    android:label="@string/title_activity_adder" >
</activity>

Refer to this link: http://developer.android.com/guide/topics/manifest/manifest-intro.html#iconlabel for more details.


text:
Q: Adding array as object value based on duplicate in column So, let's say the table I'm looping thorugh is looking like this:

Each unique value in the second column should be an object and where
one of the keys should contain all values on the corresponding rows.
Something like this:
skillMatrix[0]: {val: 2, agents: ['val1', 'val2', 'val3'}

This is as far as I come, I'm stuck..
    for (i = 0; i < q.length; i++) {
        skillMatrix[i] = {}
    }

$.ajax(getSkills).done(function (res) {

                var sg;

    $(res).find('td:nth-child(3)').each(function(){

                a = $(this).parent().find('td:nth-child(2)').text();
                a = a.split('.');

                if(a[1] == '') {
                first = a[3];
                last = a[2];
                }
                else {
                first = a[2];
                last = a[1];
                }
                reJoin = last + ' ' + first;

                var sg = $(this);
                sg = sg.text().split('_');
                sg = sg[3];

                for (i = 0; i < q.length; i++) {
                    if (q[i] == sg) {
                    skillMatrix[i].group = sg;
                    skillMatrix[i].ag = reJoin;
                    }
                }
    })

})

A: First of all, you should collect the unique value of each row, you could do it by selecting each row & add the text of the second column if it's not in the array that will contain all these unique values. This code will solve this problem:
var arr=[];
    $("tr").each(function(){
      if(!arr.includes($(this).find('td:eq(1)').text())){
        arr.push($(this).find('td:eq(1)').text());
      }
    })

Then select foreach of this values the td that contains the i-th value of the declared array arr: $("tr td:nth-child(2):contains("+arr[i]+")").
After that foreach selected elements, get its parent then search for the first colum that contains the agent: $(this).parent().find("td:eq(0)").text().
Combain all these in an Js object, these will give the following demo:

var arr=[];

$("tr").each(function(){
  if(!arr.includes($(this).find('td:eq(1)').text())){
    arr.push($(this).find('td:eq(1)').text());
  }
})
  var obj={};
for(var i=0;i<arr.length;i++)
{
var agents=[];
$("tr td:nth-child(2):contains("+arr[i]+")").each(function(){

agents.push($(this).parent().find("td:eq(0)").text());

});

obj[i]= {val: arr[i], agents:agents};
}

console.log(obj);
td{
border:solid 1px;
}

      value 1
      2

      value 2
      3

      value 3
      2

      value 4
      1


text:
Q: control mouse location on pageload I have a webpage that display a slider (almost all screen) and that slider will stop when the mouse pointer is over it. I want the mouse pointer display on the top of page (where it is not over the div)
I know javascript cannot control mouse but I want to the mouse pointer is moved (displayed) outside a div after pageload.
Is there any way to do that or any solution?
Thank you

A: I think your best bet is to not have the script enabled that stops the slider when the page load. Then:

*

*detect the mouse location on page load

*if it happens to outside the slider, enable the slider-stopping script

*if it happens to be over the slider, register a script that will enable the slider stopping script once the mouse is moved outside the slider


text:
Q: What does photon-limited imaging mean? The following link is about Photon-Limited Imaging,
https://engineering.purdue.edu/ChanGroup/project_QIS.html.
Is there any definition of Photon-Limited Imaging.
From the paper Photon-Limited Object Detection using Non-local Feature Matching and Knowledge Distillation, it mentions that Photon-limited imaging refers to image acquisition under a condition where the number of measured photons is very low. The fundamental limit is attributed to the Poisson process of the photon arrivals. This randomness is present even if the sensor is perfect – no read noise, no dark current, and has a uniform pixel response.
However, photon transfer curve shows that read noise dominates the total noise at the start.
The above figure is from the link https://www.edn.com/digital-camera-design-part-5-basic-noise-considerations-for-cmos-image-sensors/?_ga=2.182323620.2008979889.1647429375-317472058.1647429364.
Is the read noise smaller than the photon shot noise in low light with technological advance in the CMOS image sensor?

A: Put simply, it means that the Poisson distribution of incoming photons (or any particle stream) when there are very few total photons present is the primary source of image noise/blur.  As you probably know, the Poisson $SNR = Const*\sqrt(N)$ , or equivalently the StdDev  $\sigma = Const*\sqrt(N))$ .  This hold not only for the arrival rate, as is done when computing electrical current shot noise, but for the spatial distribution over the image.
When the photon count gets larger, the spot size, or, more accurately, the spot centroid,  is limited either by the diffraction limit (Airy Disk for a circular lens aperture) or by the geometric spot size if the optical system is of relatively low quality.


text:
Q: Is there any reason not to give a VM an odd number of CPU cores? I'm worried that setting the number of CPU cores to an odd number could reduce performance or stability. Are there any situations where this could be true?

A: In regards to stability: I can't think of any reason an odd number is less stable than an even one.  I did an experiment in college where I ran a computationally intense multi-threaded program (in C) on a VM and changed the number of cores from 1 through 8 and measured the process run time.  The results were mostly linear, as long as the process is configured to take full advantage of the number of cores.  I can't think of any reason why the guest OS would have an issue either, nor should any guest processes since they get their processor time from the guest OS.
Performance might be slightly better if you stick to even numbers since some processor architectures are designed to share a cache between two cores.  Hence, the odd core being used by the VM would have to share its cache with the host.  But even that is a shaky theory since the VM software itself is never guaranteed to always get the same cores and cache between time slices.  At this point, we are splitting hairs.  For example, if you have a 4 core host, and you can't decide whether to give 2 or 3 cores to the VM, the slightly less optimum odd number of 3 will still run faster than a VM of 2.  In this example, you might as well assign 4 cores to the VM.  The host OS will only give up the time slices it can afford, so as long as you're not running huge processes on the host simultaneously, the VM should run fine.


text:
Q: Filter in datatable
I do demo on http://www.primefaces.org/showcase-labs/ui/datatableFiltering.jsf but i want to move combobox to New location or i don't want it appear in new line, it mean the combobox stay in same line with the title's label!
Pls help me, thanks all suggest!

A: You can do the following to have the filter in the same line. First add filterStyleClass attribute to the column:
<p:column headerText="Manufacturer" filterBy="#{car.manufacturer}"
          filterOptions="#{tableBean.manufacturerOptions}"
          filterMatchMode="exact" filterStyleClass="inlineFilter">
        <h:outputText value="#{car.manufacturer}" />
    </p:column>

And then addd folowwing CSS rule:
.ui-column-filter.inlineFilter {
    display: inline;
    margin-left: 4px;
}


text:
Q: Display character differently in Vim via Vimrc Currently in my vimrc I have the following line:
au BufWinEnter * call matchadd('SpecialKey', '[              ]')

Between the brackets are various Unicode space characters. This highlights Unicode spaces so that I can tell them apart from normal ones (I have a few documents that I use em-spaces in quite heavily).
However, I was wondering if there is some way to display a character as another character in Vim? This way I could display wide spaces as two normal space characters, for instance, but when writing out the file the appropriate Unicode space character would be written. I know this is possible for tabs and whitespace errors with list and listchars, but I'd like a way to display any character as any other character (or string).

A: You are looking for the conceal feature.
See :help conceal.


text:
Q: In Xdebug v3 if I change a breakpoint while step debugging I get nginx 502 Bad Gateway I'm running PHP 7.4 in Docker. I am able to step debug just fine, however, unlike in Xdebug v2 if I add a breakpoint or remove a breakpoint while step debugging I am getting a 502 Bad Gateway message from nginx and the step debugging session just dies.
Am I missing a setting for Xdebug v3 in order to set new breakpoints or remove breakpoints while step debugging without killing the session?
php.ini settings
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.discover_client_host=true
xdebug.max_nesting_level=1500

Environment variable for Xdebug session set in docker:
XDEBUG_SESSION: docker

A: It's Xdebug issue: https://bugs.xdebug.org/view.php?id=1897 (https://bugs.xdebug.org/view.php?id=1899 is a duplicate of that).
Says fixed for next Xdebug v3.0.1 (you can build from sources if you can and need it now).
UPDATE 2020-12-04: Xdebug 3.0.1 has been released.


text:
Q: Highest occurrence in an array or first selected I'm trying to get the highest occurrence of a array value, and if there's an equal occurrence, I should get the first selected value of the equal occurrences.
Example:
var array = ['25', '50', 'a', 'a', 'b', 'c']
In this case I should get a
var array = ['75', '100', 'a', 'b', 'b', 'a']
In this case I also should get a
I've done my fair share of searching and found a couple of helpfull posts, these for example:

*

*Get the element with the highest occurrence in an array

*Find the most frequent item of an array (not just strings)
Somehow I can't seem to modify these examples to work for my case.
Right now I'm using the code below, but its returning the last selected equal occurrence, instead of the first. (credit https://stackoverflow.com/users/1238344/emissary)
function mostFrequent(array){
  return array.sort(function(a,b){
    return array.filter(function(v){ return v===a }).length
      - array.filter(function(v){ return v===b }).length
  }).pop();
}

Any help with this is welcome.

A: You could use something like this:
function mostFrequent(array) {
    var map = array.map(function(a) {
        return array.filter(function(b) {
            return a === b;
        }).length;
    });

    return array[map.indexOf(Math.max.apply(null, map))];
}

First it creates a map of occurrences of all the values. Next just check with Math.max which one is the highest. Check the indexOf for the first value that has that highest occurences and return the value of that index in the original array.
ES2015
If ES2015 is an option, you could use this one. It's less code.
function mostFrequent(array) {
    let map = array.map((a) => array.filter((b) => a === b).length);

    return array[map.indexOf(Math.max.apply(null, map))];
}

And if you're in a place where even the spread operator is allowed (NodeJS v5 and up, Chrome 54) you could replace Math.max.apply(null, map) for Math.max(...map)!

A: Try this:

const mostFrequent = arr => {
  let maxCount = 0;
  const occurrences = new Map();
  arr.forEach(x => {
    const count = occurrences.has(x) ? occurrences.get(x) + 1 : 1;
    occurrences.set(x, count);
    maxCount = count > maxCount ? count : maxCount;
  });
  return Array.from(occurrences).find(([element, count]) => count === maxCount)[0];
};

console.log(mostFrequent(['25', '50', 'a', 'a', 'b', 'c']));
console.log(mostFrequent(['75', '100', 'a', 'b', 'b', 'a']));

It basically the same solution as in Get the element with the highest occurrence in an array, only the last line is significant: instead of returning the last maxElement, it returns the first element in the occurrences map that has the same count as maxCount.

A: Beside the given solutions, this proposal has a complexity of O(n) - a single loop only.
Basically there are two objects, one hash table and one result set, which are maintained through iteration.

function getValue(array) {
    var count = 0,
        index = -1;

    array.forEach(function (a, i) {
        this[a] = this[a] || { count: 0, index: i };
        this[a].count++;
        if (this[a].count > count) {
            count = this[a].count;
            index = this[a].index;
            return;
        }
        if (this[a].count === count && this[a].index < index) {
            index = this[a].index;
        }
    }, Object.create(null));
    return array[index];
}

console.log(getValue(['25', '50', 'a', 'a', 'b', 'c']));
console.log(getValue(['25', '50', 'a', 'b', 'b', 'a', 'c']));

A: EDITED: new jsfiddle.
Like this: https://jsfiddle.net/Ldohv125/1/
var array = ['75', '100', 'b', 'b', 'a', 'a'];
var mf = 1;
var m = 0;
var item;
for (var i=0; i<array.length; i++){
    for (var j=i; j<array.length; j++) {
        if (array[i] == array[j])
            m++;
        if (mf<m){
            mf=m;
            item = array[i];
        }
     }
     m=0;
}
alert(item);


text:
Q: MySQL Should I frequently update date field even if the value is unchanged? Upon user's every login the last login date is updated.
UPDATE `last_login` SET `date`= CURDATE() WHERE `user_id` = $login

If user logs in 10 times in one day, then the date field will be updated 10 times with absolutely the same date.
Question: Is there any performance benefit if, before updating the date, I check if the value in the that field is different from CURDATE(), and only in this case update it?
It will reduce number of unnecessary updates, but will add extra trip to DB for every separate log in.

A: Simply add a condition for that
  UPDATE `last_login`
  SET `date`= CURDATE()
  WHERE `user_id` = $login
  AND `date` <> CURDATE()       << that one

That will update only when its not the same date

It will reduce number of unnecessary updates, but will add extra trip to DB for every separate log in

No its not an extra trip, you're already making that trip. That adds no significant performance overhead since supposedly that user_id has to be primary or atleast an index and will return only 1 row for that comparison.


text:
Q: MSSQL Obtain the last entries added in the last 30 seconds? I want to obtain the last entries in the last 30 seconds from a MSSQL database.
In Mysql you do:
SELECT * FROM table WHERE datetime > (now() - interval 30 second)
How to do that in MSSQL?

A: DATEDIFF is your solution here.
SELECT
    *
FROM
    [table]
WHERE
    DATEDIFF(second, [datetime], GETDATE()) < 30

A: You can use GETDATE() in combindation with DATEADD:
SELECT * FROM table WHERE datetime > (DATEADD(second,-30,getdate()))

A: Use DATEADD()
DATEADD(SECOND,-30,GETDATE())

A: Using dateadd with a negative integer will give you the data you are asking for
DATEADD (Transact-SQL)

SELECT
    *
FROM
    table
WHERE
    datetime >= DATEADD(SECOND,-30,datetime)


text:
Q: Proof $p(x),p'(x), p''(x),p'''(x)$ from a basis por polynomials of degree three I need to proof that given a polynomial $p(x)$ of degree three, the set $\left\{p(x),p'(x), p''(x),p'''(x)\right\}$ from a basis. Let $p(x)=a_0+a_1x+a_2x^2+a_3x^3$, with $a_3\neq 0$. I calculated the derivatives
$p'(x)= a_1+2a_2x+3a_2x^2$,
$p''(x)=2a_2+6a_3x$, and
$p'''(x)=6a_3$.
This set will be a basis if this system has a solution
$\left( \begin{matrix}
a_0 & a_1 & 2a_2 & 6a_3 \\
a_1 & 2a_2 & 6a_3 & 0 \\
a_2 & 3a_3 & 0 & 0 \\
a_3 & 0 & 0 & 0 \\
 \end{matrix} \right|\left.  \begin{matrix}a_0\\a_1\\a_2\\ a_3 \end{matrix}\right)$
And that's true because the determinant of this matrix is $103a_3^4$, i.e, is different of zero since $a_3\neq 0$.
That's correct?

A: Your idea is correct.
Another possible approach would be using the fact that polynomials of different degrees are always linearly independent.

A: You should use $(b_0,b_1,b_2,b_3)$ for the last column, since you want to show that $A$ is invertible; you need that $Ax=b$ has a unique solution for any $b$.
And to make the determinant easier, you may switch the rows.

A: We don't need matrices to note$$\begin{align}6a_3&=p^{\prime\prime\prime},\\6a_3x&=p^{\prime\prime}-\frac{a_2}{3a_3}p^{\prime\prime\prime},\\3a_2x^2&=p^\prime-\frac{a_1}{6a_3}p^{\prime\prime\prime}-\frac{a_2}{3a_3}(p^{\prime\prime}-\frac{a_2}{3a_3}p^{\prime\prime\prime}),\\a_3x^3&=p-\frac{a_0}{6a_3}p^{\prime\prime\prime}-\frac{a_1}{6a_3}(p^{\prime\prime}-\frac{a_2}{3a_3}p^{\prime\prime\prime})-\frac13\left(p^\prime-\frac{a_1}{6a_3}p^{\prime\prime\prime}-\frac{a_2}{3a_3}(p^{\prime\prime}-\frac{a_2}{3a_3}p^{\prime\prime\prime})\right).\end{align}$$


text:
Q: Image segmentation to locate trees has anyone a suggestion which segmentation-tool is best suited for this task.
I'm looking for a fast tool to do this approx 1km²/day the faster the better of course.
I've tried Orfeo's "meanshift" and "exact large meanshift" as well as "watershed", "meanshift" has offered me the best results so far but the whole process is about 5 days for 0.6km² so i'm looking for a faster way.
spatial resolution is 5-10cm
It doesn't matter if it's with orfeo, saga, grass or just python.

A: Most segmentation processes require a lot of processing time, but if you need 5 days for 0.6km² you must have a very high spatial resolution image. By resampling to a coarser pixel size before you run the segmentation algorithm, you should be able to run a lot faster. For trees, 25 cm or even 50 cm is often enough (depending on the tree type).


text:
Q: new version of FF changed order for attributes in input I have expected that order for atributes in elements can be changed despite the order in html (only FF 43.0.1). Example:

<input type="checkbox" data-type="can-be-also-empty"/>

Please, run snippet in Chrome an then in FF.
Result from devtools:
<input data-type="can-be-also-empty" type="checkbox"/> - FF
<input type="checkbox" data-type="can-be-also-empty"/> - Chrome
This can be affected with using angular. Custom directives guide

Angular normalizes an element's tag and attribute name to determine which elements match which directives
The normalization process is as follows: Strip x- and data- from the front of the element/attributes.

Thats why i think, if data-type atributes going first in element, angular stripping data- and it affecting type="checkbox" to type="can-be-also-empty".
Next snippet can show better, what i mean:

angular.module('app', []).directive('example', function(){
  return {
    template: '<input type="checkbox" data-type="eny-value" ng-model="value"/><p>{{value}}</p>',
    restrict: 'E',
    link: function($scope){
      $scope.value = false;
    }
  }
})
<!DOCTYPE html>
<html ng-app='app'>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script>
  <example></example>
</body>
</html>

Also try to run it in FF and Chrome, expression will not be evalueted in FF.
Next step, to move data-type="eny-value" before type. Now it is not working in any browser.

A: The problem comes from how AngularJS matches directives. In this particular case, it's about input[checkbox] it's matches comes from the type attribute. According to AngularJS docs for directives, it can be matched from both type and data-type, so when angular normalize the data-type, depending on the order of the attributes, it overides de previous value (aka checkbox).
This behaviour causes input[checkbox] to never work as expected, so then ngModel never receives a value of the checked field.
The best approach is to not use such thing, don't use attributes that matches with angularjs normalization.


text:
Q: Sqlite insert overwriting record I am trying to create a .NET application that will be storing information in a SQLite file. The issue I am running into is once the SQL command is executed, there is only one record visible, as if the current row is being overwritten.
Table creation:
bool pathExist = Directory.Exists(appdataPath + "OnCallDB.sqlite");

if (!pathExist)
{
    SQLiteConnection.CreateFile(appdataPath + "OnCallDB.sqlite");
    SQLiteConnection dbNewConnection = new SQLiteConnection("Data Source=" + appdataPath + "OnCallDB.sqlite;Version=3;");
    dbNewConnection.Open();
    string sqlTableCreation = "CREATE TABLE Calls (Id Integer PRIMARY KEY, name varchar(30), ticket varchar(20), phone varchar(20), day varchar(20), start_time varchar(20), end_time varchar(20), raw_time varchar(20), weighted_time varchar(20), date DATETIME, notes varchar(255))";
    SQLiteCommand command = new SQLiteCommand(sqlTableCreation, dbNewConnection);
    command.ExecuteNonQuery();
    dbNewConnection.Close();
}

Insert statement:
SQLiteCommand insertCommand = new SQLiteCommand("INSERT INTO Calls ([name], [ticket], [phone], [day], [start_time], [end_time], [raw_time], [weighted_time], [date], [notes])"+
    "VALUES(@name, @ticket, @phone, @day, @start_time, @end_time, @raw_time, @weighted_time, @date, @notes)",connection);

insertCommand.Parameters.AddWithValue("@name", name);
insertCommand.Parameters.AddWithValue("@ticket", ticket);
insertCommand.Parameters.AddWithValue("@phone", phone);
insertCommand.Parameters.AddWithValue("@day", day);
insertCommand.Parameters.AddWithValue("@start_time", start_time);
insertCommand.Parameters.AddWithValue("@end_time", end_time);
insertCommand.Parameters.AddWithValue("@raw_time", raw_time);
insertCommand.Parameters.AddWithValue("@weighted_time", weighted_time);
insertCommand.Parameters.AddWithValue("@date", date);
insertCommand.Parameters.AddWithValue("@notes", notes);

try
{
    connection.Open();
    insertCommand.ExecuteNonQuery();
    connection.Close();
}
catch(Exception ex)
{
    throw new Exception(ex.Message);
}

I have ran the command manually to the SQL file and inserts a new row. When I run the above SQLite command, it replaces the row. As far as I can tell. I have looked at the file creation date and time and it appears that the file is just being modified and not replaced.

A: The issue was not with the SQL statement. The issue was with how the file was being created


text: Q: Google cloud Vision and Clarifai doesn't Support tagging for 360 degree images and videos I'm working on image processing. So far Google Cloud Vision and Clarifai are the best API's to detect objects from images and videos, but both API's doesn't support object detection from 360 degree images and videos. Is there any solution for this problem ?


text:
Q: Android encryption not working (PBKDF2WithHmacSHA256 encryption with AES/CBC/PKCS7Padding) I am trying to write an encryption code using Cipher Algorithm "AES/CBC/PKCS7Padding", HMAC algorithm "HmacSHA256" and key derivation algorithm "PBKDF2WithHmacSHA256" with the help of android JNCryptor. But it shows:
CryptorException: Failed to generate key from password using PBKDF2WithHmacSHA256
and
NoSuchAlgorithmException: SecretKeyFactory PBKDF2WithHmacSHA256 implementation not found
 try {
   SecretKeyFactory factory = SecretKeyFactory
     .getInstance(KEY_DERIVATION_ALGORITHM);
   SecretKey tmp = factory.generateSecret(new PBEKeySpec(password,
     salt, getPBKDFIterations(), AES_256_KEY_SIZE * 8));
   return new SecretKeySpec(tmp.getEncoded(), AES_NAME);
  } catch (GeneralSecurityException e) {
   throw new CryptorException(String.format(
     "Failed to generate key from password using %s.",
     KEY_DERIVATION_ALGORITHM), e);
  }

any help will be appreciated.

A: Apologies for commenting and not realising you were talking about my software, JNCryptor.
You could take a look at a fork of the project, https://github.com/t0mm13b/AndroJNCryptor, which has attempted to make several Android-related improvements to the code. I believe your problem may be addressed in that code base.
As far as I know, there is no Android provider available that offers an algorithm named PBKDF2WithHmacSHA256. Quite frustrating!


text:
Q: NFS NAS disc space only being given to one sub-directory I am having a problaem with the disc space on my 3TB NAS seeming to be split between sub-directories outside my control. No quotas have been set, and when they fill up the errors are not "quota exceeded" but "not enough disk space for this operation". After some investigation and experiment I am at a loss as to how to change this.
The device is an old WD MyCloud that I am now managing directly via the shell, because of the nightmare of getting it to work with Windows 10 (because of Microsofts SMB lockdown and the lack of a real solution from WD even with the latest firmware).
I tried changing the SMB .conf files but to no avail so instead am running it as an NFS server. This works OK when mounted as a disc drive though am having trouble getting it to be stable as a network location. The underlying system is Debian Linux running on an ARM-based machine with 256MD RAM and a 3TB disc.
Looking at the top level /nfs folder, it claims to have only 1.9GB of disc space. The vast majority of the space is sitting under a /nfs/Music folder.
Running df -f from the terminal gets me:

As I understand it, this shows the c. 1.9 GB showing up on a 'root' storage device and the vast majority showing up as 'sda4' mounted under the /nfs/Music directory.
I have no idea how this happened or how to change it so that all the various directories under the NFS directory will share the space according need. Help would be appreciated.


text:
Q: Create a rds instance using python: having status always = creating Im trying to create a rds instance using python.
I have this code below to create an instance and then I want to show my print "Instance is now running" when the instance have status available.
The problem is that, when appears the  available status in aws managment console, in my console application still appears always  status = creating and the code dont get out of while loop:
The result Im having:
    ....
    creating
    233
    creating
    234
    ...

The code:
instance = conn.create_dbinstance(...)

print "Waiting for instance to be up and running"

status = instance.status
inc = 0
while status != 'available':
    sleep(5)
    status = instance.status
    print status
    inc=inc +1
    print inc

if status == 'available':
    print "Instance is now running"

Do you see why this can be happening?

A: The boto docs aren't always clear about when results such as DBInstance.status are fetched on-demand via the API vs. being returned from an earlier, cached lookup. I'm betting that here, the instance.status call you are using is just returning the same (cached) result each time.
Try
status = conn.get_all_dbinstances(instance_id=instance.id)[0].status

instead of
status = instance.status

inside your while loop.

A: Python program to print all RDS Instances and there Status.
import boto.rds

#Connection url : Required region, access_key, secret_access_key
conn = boto.rds.connect_to_region('ap-south-1', aws_access_key_id='<aws access key>', aws_secret_access_key='<aws secret key>')

#dbinstances will have all database instances name
dbinstances = conn.get_all_dbinstances()

#We can iterate and print one by one db instance name and status.
for rds_db in dbinstances:
    print(rds_db,' = ', rds_db.status)


text:
Q: Nautilus cannot handle "sftp" locations via x11 I'm logging into my home computer (Ubuntu 10.04) via ssh, and now I want to open a remote connection (one that is stored in my bookmarks).
Nautilus tells me "Nautilus cannot handle "sftp" locations via x11".
Why might this be?

A: I had a similar problem when I removed the package gvfs-backends and solved the problem by reinstalling that package.  Nautilus recommends, but is not dependent on gvfs-backends, which it appears to use for the virtual file system that is created to allow you to navigate an ftp server as a drive.


text:
Q: Fixed position text annotation on facets I having some trouble in text annotation using ggplot2. I hope someone here, can help me out.
I want to annotate differing text to fix position on all faceted plots. I could not find any solutions, how to do this when I use "free_y" scale.
I used this code:
library(ggplot2)
library(grid)

## Data.
d1 = data.frame(sim1 = runif(100), n1 = 500, y1 = runif(100),
                group1 = rep(c("A", "B"), each = 250))
d2 = d1[!duplicated(d1$group1), ]
## Consistent number for all plot.
grob1 <- grobTree(textGrob(paste("N = ", d2[, 2]),
                           x = 0.01, y = 0.95, hjust = 0,
                           gp = gpar(col = "black", fontsize = 13,
                                     fontface = "bold")))
## Varying number for facets.
grob2 <- grobTree(textGrob(d2$sim1, x = 0.01, y = 0.85, hjust = 0,
                           gp = gpar(col = "black", fontsize = 13,
                                     fontface = "bold")))
grob3 <- grobTree(textGrob(d2$y1, x = 0.01, y = 0.75, hjust = 0,
                           gp = gpar(col = "black", fontsize = 13,
                                     fontface = "bold")))
## Plot.
ggplot(d1, aes(log2(sim1))) +
  geom_density() +
  scale_x_continuous("") +
  scale_y_continuous("") +
  facet_wrap(~ group1, ncol = 1, scales = "free_y") +
  annotation_custom(grob1) +
  annotation_custom(grob2) +
  annotation_custom(grob3)

However, it always annotates the first element to all plots.

A: Well, I agree with @baptiste. Here is an idea -- first create a data frame.
ann_text = data.frame(x= c(...), value= c(...), lab=c(...) )

In this, first two vectors will locate the positions and last one is vector of labels. Then use --
geom_text(data = ann_text, aes(label=lab), size= 5, colour = "red", fontface= ...)

etc.


text:
Q: Render JPEG2000 Compressed Tiff in DotNet Ran into this problem a few years ago and posted a question. Was able to puzzle something together calling a python script but this is suboptimal as I need to now scale this up to a much larger volume of image conversion.
Does anyone know of a way to do this in pure DotNet core, without using the old windows image API's ?
Thank


text:
Q: Upgrading linux-headers-server and linux-image-server fails apt-get upgradetold me that packages linux-headers-server linux-image-server were kept back, and thus this answer lead me to run apt-get install linux-headers-server linux-image-server.
However, the command outputs the following:
Reading package lists... Done
Building dependency tree
Reading state information... Done
linux-headers-server is already the newest version.
linux-image-server is already the newest version.
You might want to run `apt-get -f install' to correct these:
The following packages have unmet dependencies:
  linux-image-server: Depends: linux-image-2.6.32-37-server but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

apt-get -f install:
apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following extra packages will be installed:
  linux-image-2.6.32-37-server
Suggested packages:
  fdutils linux-doc-2.6.32 linux-source-2.6.32 linux-tools
The following NEW packages will be installed:
  linux-image-2.6.32-37-server
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
Need to get 0B/31.8MB of archives.
After this operation, 128MB of additional disk space will be used.
Do you want to continue [Y/n]?
(Reading database ... 106547 files and directories currently installed.)
Unpacking linux-image-2.6.32-37-server (from .../linux-image-2.6.32-37-server_2.6.32-37.81_amd64.deb) ...
Done.
dpkg: error processing /var/cache/apt/archives/linux-image-2.6.32-37-server_2.6.32-37.81_amd64.deb (--unpack):
 failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb during `./boot/vmlinuz-2.6.32-37-server': No space left on device
dpkg-deb: subprocess paste killed by signal (Broken pipe)
Running postrm hook script /usr/sbin/update-grub.
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-2.6.32-32-server
Found initrd image: /boot/initrd.img-2.6.32-32-server
Found linux image: /boot/vmlinuz-2.6.32-31-server
Found initrd image: /boot/initrd.img-2.6.32-31-server
Found linux image: /boot/vmlinuz-2.6.32-30-server
Found initrd image: /boot/initrd.img-2.6.32-30-server
Found linux image: /boot/vmlinuz-2.6.32-28-server
Found initrd image: /boot/initrd.img-2.6.32-28-server
Found linux image: /boot/vmlinuz-2.6.32-25-server
Found initrd image: /boot/initrd.img-2.6.32-25-server
Found linux image: /boot/vmlinuz-2.6.32-24-server
Found memtest86+ image: /memtest86+.bin
done
Errors were encountered while processing:
 /var/cache/apt/archives/linux-image-2.6.32-37-server_2.6.32-37.81_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

What do I do?
Update:
/boot contains the following items:
-rw-r--r-- 1 root root 631K 2010-09-16 20:55 abi-2.6.32-24-server
-rw-r--r-- 1 root root 632K 2010-10-16 22:51 abi-2.6.32-25-server
-rw-r--r-- 1 root root 632K 2011-01-11 01:42 abi-2.6.32-28-server
-rw-r--r-- 1 root root 632K 2011-03-02 03:02 abi-2.6.32-30-server
-rw-r--r-- 1 root root 632K 2011-04-09 01:07 abi-2.6.32-31-server
-rw-r--r-- 1 root root 632K 2011-04-21 00:53 abi-2.6.32-32-server
-rw-r--r-- 1 root root 108K 2010-09-16 20:55 config-2.6.32-24-server
-rw-r--r-- 1 root root 109K 2010-10-16 22:51 config-2.6.32-25-server
-rw-r--r-- 1 root root 109K 2011-01-11 01:42 config-2.6.32-28-server
-rw-r--r-- 1 root root 109K 2011-03-02 03:02 config-2.6.32-30-server
-rw-r--r-- 1 root root 109K 2011-04-09 01:07 config-2.6.32-31-server
-rw-r--r-- 1 root root 109K 2011-04-21 00:53 config-2.6.32-32-server
drwxr-xr-x 3 root root 6.0K 2011-12-23 10:03 grub
-rw-r--r-- 1 root root 7.9M 2011-01-30 15:55 initrd.img-2.6.32-25-server
-rw-r--r-- 1 root root 7.9M 2011-03-04 12:00 initrd.img-2.6.32-28-server
-rw-r--r-- 1 root root 7.9M 2011-03-24 17:40 initrd.img-2.6.32-30-server
-rw-r--r-- 1 root root 7.9M 2011-05-07 14:59 initrd.img-2.6.32-31-server
-rw-r--r-- 1 root root 7.9M 2011-09-25 10:45 initrd.img-2.6.32-32-server
drwx------ 2 root root  12K 2010-08-16 11:16 lost+found
-rw-r--r-- 1 root root 157K 2010-03-23 10:40 memtest86+.bin
-rw-r--r-- 1 root root 2.1M 2010-10-16 22:51 System.map-2.6.32-25-server
-rw-r--r-- 1 root root 2.1M 2011-01-11 01:42 System.map-2.6.32-28-server
-rw-r--r-- 1 root root 2.1M 2011-03-02 03:02 System.map-2.6.32-30-server
-rw-r--r-- 1 root root 2.1M 2011-04-09 01:07 System.map-2.6.32-31-server
-rw-r--r-- 1 root root 2.1M 2011-04-21 00:53 System.map-2.6.32-32-server
-rw-r--r-- 1 root root 1.4K 2010-09-16 20:58 vmcoreinfo-2.6.32-24-server
-rw-r--r-- 1 root root 1.4K 2010-10-16 22:53 vmcoreinfo-2.6.32-25-server
-rw-r--r-- 1 root root 1.4K 2011-01-11 01:43 vmcoreinfo-2.6.32-28-server
-rw-r--r-- 1 root root 1.4K 2011-03-02 03:08 vmcoreinfo-2.6.32-30-server
-rw-r--r-- 1 root root 1.4K 2011-04-09 01:13 vmcoreinfo-2.6.32-31-server
-rw-r--r-- 1 root root 1.4K 2011-04-21 00:54 vmcoreinfo-2.6.32-32-server
-rw-r--r-- 1 root root 4.0M 2010-09-16 20:55 vmlinuz-2.6.32-24-server
-rw-r--r-- 1 root root 4.0M 2010-10-16 22:51 vmlinuz-2.6.32-25-server
-rw-r--r-- 1 root root 4.0M 2011-01-11 01:42 vmlinuz-2.6.32-28-server
-rw-r--r-- 1 root root 4.0M 2011-03-02 03:02 vmlinuz-2.6.32-30-server
-rw-r--r-- 1 root root 4.0M 2011-04-09 01:07 vmlinuz-2.6.32-31-server
-rw-r--r-- 1 root root 4.0M 2011-04-21 00:53 vmlinuz-2.6.32-32-server

A: This is the error line:
failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb during `./boot/vmlinuz-2.6.32-37-server': No space left on device

A: You should run sudo apt-get autoremove to clean up the /boot/ partition. This should give you enough disk space left to do a sudo apt-get dist-upgrade, which will upgrade the held-back packages. Once this is finished upgrading, you'll need to reboot for the new kernel to be loaded.


text:
Q: Detect setting value of a field with getElementById(field_name).value and intercept/override it I don't have a provision to not invoke the JS that tries to set a value of a field using:
getElementById(field_name).value = 'someValue'

So, as an alternative, I'm trying to see if there's a way to intercept/override the JS that sets the value of the field in the html and try to restrict it if certain conditions are met.
Please let me know if it's possible?
It may seem that this question is a duplicate of this and this but it's not. Those question's solution wants a change in the code, which is not an option for me.

A: I'm afraid you can't, so if you really cannot change the code setting it, you're stuck with the really ugly option of polling it and watching for changes. E.g., something vaguely like this:
function polledInterceptor(id, callback) {
    var element = document.getElementById(id);
    var value = element.value;
    var timer = setInterval(function() {
        if (value !== element.value) {
            value = callback(element, value);
            if (value !== null) {
                element.value = value;
            }
        }
    }, 30); // 30 = 30ms
    return {
        stop: function() {
            clearTimeout(timer);
        }
    };
}

...and then use it like this:
var poller = polledInterceptor("field_name", function(element, oldValue) {
    var newValue = element.value;
    // ...decide what to do...
    return "someValue"; // or return null to leave the value unchanged
});

when ready to stop:
poller.stop();


text:
Q: Build Nirgam using g++ Hi I am trying to build the nirgam software using Debian in VMware environment. When I issue command make I end up in an error as given below.
g++: error: unrecognized command line option '-W1,-soname,application/lib/App_send.so'
make: *** [application/lib/App_send.so] Error 1

The snippets from the makefile is given below,
application/lib/%.so : application/src/%.o
    $(CC) -shared -W1,-soname,$@ -o $@ $<

router/lib/%.so : router/src/%.o
    $(CC) -shared -W1,-soname,$@ -o $@ $<

Kindly let me know where I am going wrong.
Many thanks for your suggestions.

A: You have copied the makefile wrong, the option is not -W1 but -Wl with the letter l (lower-case L) and not the digit 1.


text:
Q: How to segment periods above and below zero for a plot in R I have created a random walk function which runs for a certain period of time. When I plot the walk, it goes to values which are above and below zero. Im wondering if there is a way for me to find the parts of the graph which are above zero. When I run the function, I get this output :
      Time     Steps    Time intervals
[1,]    0        0           34
[2,]   34        2           24
[3,]   58        4           35
[4,]   93        2           29
[5,]  122        0           37
[6,]  159        1           29
[7,]  188        3           35
[8,]  223        0           29
[9,]  252        -1          28
[10,] 280        -4

So in this case, the first positive segment is between rows 1 - 5 or between times 0 and 122. The other is between rows 6-8 or between times 159 - 223. This is a small segment of the entire output, so there are a number of positive and negative segments. What I'm struggling with, is code that will count the number of positive segments. In this case the value would be 2, but with the full output there are a lot more. Additionally, I'm wondering if there is a way to directly reference each segment. For instance, if there are 5 positive segments, is there a way for me to directly reference the last positive segment, and say calculate its duration by summing the respective time intervals. I don't really have any idea of how to do this, so any help would be greatly appreciated. Thank you !!


text:
Q: How to declare PHP (web) and ruby (worker) in Procfile I'm trying to create a facebook web app (i need the web to be PHP) with a worker to process tasks vie the messaging queue add on ( i need it in Rube - i think..).
When i added a Gemfile, heroku stopped identifying my app as PHP at all.
So i am hoping that adding 'web: "PHP declaration"' to the procfile will solve my problem, but cant seem to find documentation on how to do that.
http://blog.heroku.com/archives/2011/6/20/the_new_heroku_1_process_model_procfile/
https://devcenter.heroku.com/articles/procfile
is there a different way to achieve my goal?
Any suggestions are more than welcome :)

A: Is the ruby code separate to the php? Are they in the same file?


text:
Q: Evolution mail says I have 700 mails but my inbox is empty My inbox is empty when I try to link gmail to evolution mail client,  anyone can help?

A: Found the solution,  I turned on "lesser secure" on my gmail account and everything works.
Here is the link:
https://www.google.com/settings/security/lesssecureapps
Simply click activate


text:
Q: Can VS 2010 check/update header files automatically? That's pretty much my question: can VS 2010 check and update header files in C++ code automatically? And can VS 2010 automatically generate a cpp file from a header file, saving you the time to copy the function definitions from the header file? I mean, can it figure that there's no implementation for some method and generate an empty stub from the declaration found in the header file?
Thanks!
CFP.

A: No this feature does not exist in the Visual Studio C++ implementation.  Changes to a header file must be manually propagated to the source file and vice versa.


text:
Q: If I'm using password manager provided by Apple on my iPhone, what would happen if I lose that iPhone? I just realized something, so I'm curious to know the answer. I bought an iPhone and seem to like the password manager that is built into it. I set up all my email passwords (Gmail and all) in it, as well as all my other logins with random passwords generated by that password manager.
But then it dawned on me, what would happen if I lose that iPhone?
PS. I do not have any other Apple devices.

A: Two things

*

*For the finder of the iPhone - they would have a locked phone and could not get any information unless they guessed your PIN. Even better would be for you to log in to the iCloud website from another machine (which could be your PC) and use Find My.. to say the phone is lost and then even the PIN would fail.

In Settings->Touch ID there is an option to erase your phone after 10 failed attempts at your PIN.
Find my Phone has to be turned on - it is in Settings->Apple Id

*For you - you are no worse off than before you have to remember all your passwords.

I use a third party password manager (in my case 1password but there are others) so I can use the passwords on a PC as well as my iPhone.


text:
Q: reclassify fields in one column of a table depending on criteria I have the following table:
person       drug
------       -----
1            Y
2            Y
2            other
3            X
4            X
5            X
5            other
6            other
7            Z

However, if there is a person where they have a drug x,y,z (it will only be one distinct choice) plus 'other' - then I want to remove the row that contains other
This would mean that someone with an 'X' and 'other' would remove the row conatining 'other', but anyone with only 'other' will stay as 'other'. i.e.
person       drug
------       -----
1            Y
2            Y
3            X
4            X
5            X
6            other
7            Z

where person 6 only has other, so stays that way, but persons 2 and 5 have the 'other' rows removed because they have other drug choices (x,y or z).
Thanks very much for any help.

A: It is unclear whether you want this removed in the results of a query or in the data itself.  To return results without this row from a query, which can be written like this:
select t.*
from t
where not (t.drug = 'other' and
           exists (select 1 from t t2 where t2.person = t.person and t2.drug = 'x')
          )

To handle any of 'x', 'y', or 'z', change the last statement to t2.drug in ('x', 'y', 'z').


text:
Q: Handling Select2 with Selenium webdriver I've been banging my head against the wall trying to select a option from a ajax enabled select2 select list with the selenium webdriver. I've managed to get it working with the IE webdriver but not firefox. Here is my hacky solution for IE
 public static void SetSelect2Option(this IWebDriver driver, By locator, string subContainerClass, string searchTerm, TimeSpan? ajaxWaitTimeSpan = null)
    {
        var select2Product = driver.FindElement(locator);
        select2Product.Click();
        var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));
        searchBox.SendKeys(searchTerm);
        if (ajaxWaitTimeSpan != null)
        {
            driver.Manage().Timeouts().ImplicitlyWait(ajaxWaitTimeSpan.Value);
        }
        var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li")).First();
        selectedItem.Click();
        selectedItem.SendKeys(Keys.Enter);
    }

In Firefox, this solution works up until the point of the SendKeys call where it just hangs and moves on to the next step without actually firing select2's events to populate the selected item.
I've also tired using the http://code.google.com/p/selenium/wiki/AdvancedUserInteractions api with similar results.
Has anyone run into a similar issue before?

A: I've spent some time to get it working in FF, Chrome and IE8-11.

*

*Click the drop arrow

*Click the required li

Here is my simplified code:
[FindsBy(How = How.ClassName, Using = "select2-arrow")]
private IWebElement Selector { get; set; }

private void selectItem(string itemText)
{
    Selector.Click();  // open the drop
    var drop = Driver.FindElement(By.Id("select2-drop"));    // exists when open only
    var item = drop.FindElement(By.XPath(String.Format("//li[contains(translate(., '{0}', '{1}'), '{1}')]", itemText.ToUpper(), itemText.ToLower())));
    item.Click();
}

A: I used the below code to select the desired option and it worked. This must also be faster than performing multiple clicks.
String script = "$('select#yearSelector').trigger($.Event('change',{val:'" + year + "'}))";
((JavascriptExecutor) driver).executeScript(script);

And, in Python, if this one-liner doesn't work, try splitting it into it's components:
 value = ['a', 'b', 'c']
 script = "var elem = $('select#tradingMarketSelect'); "
 script += "elem.val(%s); " % value
 script += "elem.change();"
 self.driver.execute_script(script)

A: Could you please show us the locators as well? Here is what I tested without any issues.
Note

*

*To open select box, use css selector #s2id_e1 .select2-choice, or equivalent XPath.

*Make sure #select2-drop is the visible one, by css selector #select2-drop:not([style*='display: none']), or equivalent XPath.

*Make sure to click the selectable item using subContainerClass + .select2-results li.select2-result-selectable, or equivalent XPath.

var driver = new FirefoxDriver();
driver.Url = "http://ivaynberg.github.io/select2/";

var select2Product = driver.FindElement(By.CssSelector("#s2id_e1 .select2-choice"));
select2Product.Click();

string subContainerClass = "#select2-drop:not([style*='display: none'])";
var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));
searchBox.SendKeys("Ohio");

var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li.select2-result-selectable")).First();
selectedItem.Click();

A: Here's my code(Getting/Displaying):
Getting select2 available elements(Results):
public List<WebElement> getDataFromSelect2(String elementXpath)
{
    WebElement select2Element = driver.findElement(By.xpath(elementXpath));
    select2Element.click();

    WebDriverWait webDriverWait = new WebDriverWait(driver, 90);
    webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//ul[@class='select2-results']//div")));

    WebElement select2ElementResults=driver.findElement(By.xpath("//div[@id='select2-drop']/ul[@class='select2-results']"));
    List<WebElement> selectResultsAsListCollection = select2ElementResults.findElements(By.tagName("div"));

    return selectResultsAsListCollection;
}

Displaying select2 available elements(Results)
Using select2 with id(attribute) of: s2id_autogen1:
List<WebElement> select2Results = getDataFromSelect2("//input[@id='s2id_autogen1']");

for(WebElement item: select2Results)
{
    System.out.println(item.getText());
}

A: Here's a solid, reusable solution that handles the additional problem of interacting with multiple select2 dropdowns on one page.
For some reason, the webdriver was not considering the element to send the search value to as visible, even though you could see it on screen and the cursor was in it.  That's what the 'if displayed' test checks for. Then it uses a different selector.
Its a function that you can send the ID of the field you want to interact with (less the standard s2id_) and the value to select (or at least enough of it to make the selection.)
The extra thread.sleep()s were just to help me watch it. I don't think they affect the outcome.
public void SelectDropDownOption(string dropDownID, string option)
    {
        for (int second = 0; ; second++)
        {
            if (second >= 60) Assert.Fail("timeout");
            try
            {
                if (driver.FindElement(By.CssSelector("div[ID^=s2id_" + dropDownID + "]>a.select2-choice")).Displayed) break;
            }
            catch (Exception)
            { }
            Thread.Sleep(1000);
        }

        driver.FindElement(By.CssSelector("div[ID^=s2id_" + dropDownID + "]>a.select2-choice")).Click();
        Thread.Sleep(1000);

        if (driver.FindElement(By.CssSelector("input.select2-input.select2-focused")).Displayed == true)
        {
            driver.FindElement(By.CssSelector("input.select2-input.select2-focused")).SendKeys(option);
            Thread.Sleep(500);
            driver.FindElement(By.CssSelector("input.select2-input.select2-focused")).SendKeys(Keys.Enter);
            Thread.Sleep(500);
        }
        else
        {
            driver.FindElement(By.CssSelector("input.select2-focusser.select2-offscreen")).SendKeys(option);
            Thread.Sleep(500);
            driver.FindElement(By.CssSelector("input.select2-focusser.select2-offscreen")).SendKeys(Keys.Enter);
            Thread.Sleep(500);
        }

    }

A: protected void SelectOptionForSelect2(IWebDriver driver, string id, string text)
{
  var element = driver.FindElement(By.Id(id)).FindElement(By.XPath("following-sibling::*[1]"));
  element.Click();

  element = driver.FindElement(By.CssSelector("input[type=search]"));
  element.SendKeys(text);

  Thread.Sleep(1000);
  element.SendKeys(Keys.Enter);
}

A: Try opting for webdriver javascript execution. Below is a handy C# method.
// usings
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

// method
public static void SetSelect2Option_JSExample(this IWebDriver driver, string select2Id, string value)
{
    IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver;
    string js = "$('#" + select2Id + "').val('" + value + "').trigger('change');";
    string jsOutput = (string)jsExecutor.ExecuteScript(js);
}

A: For 2022 readers... Use the SelectElement Class to interact with select2's:
(csharp)

IWebElement select2Element = _webDriver.FindElement(By.Id("select2"));

var select2 = new SelectElement(select2Element);

select2.SelectByText("foo");

//example of getting an item from the list
var selectOptions= select2.Options.Select(x => x.Text).ToList();


text:
Q: Result of x % 10 in Java could anyone tell me what  is the output of (x modulus 10) in java; if x is a positive integer number from 1 (inclusive) to 9 (inclusive) ? I wrote this code to see what it could be but got nothing:
   for(int i=1;i<10;++i)
    {
      int y = (i%10);
      System.out.println("y is:" + y);
     }

A: If you want to test Java code and don't have access to a development environment, you can still use a public service like ideone.com. I did that for you over here. Your program prints
y is:1
y is:2
y is:3
y is:4
y is:5
y is:6
y is:7
y is:8
y is:9

A: You should go this output:
y is:1
y is:2
y is:3
y is:4
y is:5
y is:6
y is:7
y is:8
y is:9

basically if you have y % x and 0 <= y < x the  y % x = x.
Otherwise, y % x = y - ( y / x).

A: X%10 , read as x modulo 10, gives the remainder of the operation x/10.
I.e.
For eg:
If x=11

Then x%10 =1

If x=1

Then x%10 = 1

A: For integer x the result of x % 10 is an integer between -9 and 9 (both inclusive).
From the JLS:

The binary % operator is said to yield the remainder of its operands
  from an implied division; the left-hand operand is the dividend and
  the right-hand operand is the divisor.
In C and C++, the remainder operator accepts only integral operands,
  but in the Java programming language, it also accepts floating-point
  operands.
The remainder operation for operands that are integers after binary
  numeric promotion (§5.6.2) produces a result value such that
  (a/b)*b+(a%b) is equal to a.
This identity holds even in the special case that the dividend is the
  negative integer of largest possible magnitude for its type and the
  divisor is -1 (the remainder is 0).
It follows from this rule that the result of the remainder operation
  can be negative only if the dividend is negative, and can be positive
  only if the dividend is positive. Moreover, the magnitude of the
  result is always less than the magnitude of the divisor.


text:
Q: Ubuntu 12.04 does not recognise CD ~$ wodim --devices
wodim: Overview of accessible drives (1 found) :
-------------------------------------------------------------------------
 0  dev='/dev/sg1'  rwrw-- : 'MATSHITA' 'DVD-RAM UJ8B1AS'
-------------------------------------------------------------------------

But I don't find access to CD.
Kindly let me know how to rip the CD.
When I try to mount, it gives error.
~$ mount /dev/sg1
can't find /dev/sg1 in /etc/fstab or /etc/mtab

A: If the CD is not showing up in the graphical user interface, then try mounting it via the terminal
sudo mount /dev/sg1

If that doesn't work, then my suggestion would be to update your fstab file. It's relatively complicated, so let me know if mounting the CD manually doesn't work, and I'll post a tutorial on editing your fstab file.
But if the cd DOES show up, you want to rip the cd, you'll need software to do so. I suggest you search for "CD rip, or CD ripping" in the Ubuntu Software Centre.
Cheers!

A: Try using the following command:
ls -alhrt /dev/* | tail -n 30

looking date-wise, you can get the result of name of the usb devices. For me, following output was produced:
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:2 -> ../ram2
lrwxrwxrwx  1 root root    8 Apr 29 03:26 1:14 -> ../ram14
lrwxrwxrwx  1 root root    8 Apr 29 03:26 7:0 -> ../loop0
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:3 -> ../ram3
lrwxrwxrwx  1 root root    8 Apr 29 03:26 1:15 -> ../ram15
lrwxrwxrwx  1 root root    8 Apr 29 03:26 7:2 -> ../loop2
lrwxrwxrwx  1 root root    8 Apr 29 03:26 1:11 -> ../ram11
lrwxrwxrwx  1 root root    8 Apr 29 03:26 1:10 -> ../ram10
lrwxrwxrwx  1 root root    8 Apr 29 03:26 7:5 -> ../loop5
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:8 -> ../ram8
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:9 -> ../ram9
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:7 -> ../ram7
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:5 -> ../ram5
lrwxrwxrwx  1 root root    8 Apr 29 03:26 7:4 -> ../loop4
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:4 -> ../ram4
lrwxrwxrwx  1 root root    7 Apr 29 03:26 1:6 -> ../ram6
lrwxrwxrwx  1 root root    8 Apr 29 03:26 7:7 -> ../loop7
lrwxrwxrwx  1 root root    8 Apr 29 03:26 7:6 -> ../loop6
lrwxrwxrwx  1 root root    6 Apr 29 03:26 8:0 -> ../sda
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:9 -> ../sda9
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:2 -> ../sda2
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:4 -> ../sda4
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:6 -> ../sda6
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:3 -> ../sda3
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:7 -> ../sda7
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:8 -> ../sda8
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:5 -> ../sda5
lrwxrwxrwx  1 root root    7 Apr 29 03:26 8:1 -> ../sda1
drwxr-xr-x 16 root root 4.2K Apr 29 03:26 ..
drwxr-xr-x  2 root root  720 Apr 29  2012 .

from there, get the name of the usb device, let's for the time sake call it "usbdev".
Then enter the following command to mount it.
mount -t ext3 /dev/usbdev /media/USB_Bkup

A: In a shell (Crtl-Alt-T to open one) type:
sudo lshw -C disk

This should show you all disk devices including DVD/CDROM drives. They will be noted with their logical names included. lshw should be installed but sudo apt-get install lshw will install it if it is not.


text:
Q: meet a/the target of . . .? Should the definite or indefinite article be used in the following? The target in question is mentioned for the first time in the passage, yet it seems to be quite specific.

Currently, the Ministry of Economic Affairs' Bureau of Energy (BOE) has come up with a new two-year plan to promote the installation of solar PV facilities such as rooftop solar panels and ground-mounted solar panels. It aims to meet a/the target of 3.7 GW by the end of 2019, and 6.5 GW by the end of 2020.

I'd appreciate your help.


text:
Q: Difference of minute between two dateTime I need to find the difference in minutes between these two dateTime in such format which is written. I get this error, please help:
Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/09/2020 01:00:19 AM) at position 0 (2):
$datetime1 = new DateTime('27/09/2020 01:00:19 AM');
                            $datetime2 = new DateTime('27/09/2020 01:00:19 AM');
                            $interval = $datetime1->diff($datetime2);
                            echo $interval->format('%hh %im');

A: When parsing date formats, php follows specific rules :
If the date separator is /, then php will try to use either the American format mm/dd/y or the notation YY/mm/dd
You can specify the date/time format while creating the object using DateTime::createFromFormat() :
$datetime1 = DateTime::createFromFormat('d/m/Y g:i:s a', '27/09/2020 01:00:19 AM');
$datetime2 = DateTime::createFromFormat('d/m/Y g:i:s a', '27/09/2020 01:00:19 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh %im');

This outputs :
0h 0m

Fiddle

A: You can do like this:
$datetime1 = new DateTime(str_replace('/','-','27/09/2020 01:00:19 AM'));
$datetime2 = new DateTime(str_replace('/','-','27/09/2020 01:00:19 AM'));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh %im');


text:
Q: searching in a part of word with Sphinx I need to configure Sphinx to search for parts of word, not whole. It's written on the official site, that I should use directives
'min_infix_len', 'min_prefix_len' and 'enable_star'. Actually, all registered in the config file.
But search in a word part doesn't work.
* in the beginning or end of a word is not helping.
source src1
{

  type= mysql
  sql_host= localhost
  sql_user= root
  sql_pass=
  sql_db= ajax
  sql_port= 3306

  sql_query= \
    SELECT id, bookauthor FROM authors
    sql_query_info= SELECT * FROM authors WHERE id=$id
}

index index1
{
  source= src1
  path = /var/data/src1
  morphology =stem_en
  min_word_len = 1
  charset_type = sbcs
  enable_star=1
  min_infix_len =3
  min_prefix_len = 3
}

searchd
{
  listen = 9312
  log = /var/log/searchd.log
  query_log = /var/log/query.log
  pid_file = /var/log/searchd.pid
}

A: You can only implement one of them
min_infix_len =3
min_prefix_len = 3
Prefix is for *something
Infix can be used with everything..
Remove one of them


text:
Q: Catch url in CodeIgniter I am getting url like http://localhost/webpt/ipn/checkout/?token=EC-2YD51592ET0280122&PayerID=VNH3J2KQEK8AS and want to catach in my controller. in my controller code
function checkout($token = array()) {
        echo"<pre>";
        print_r($token);
        echo"</pre>";
    }

but it show empty array.

A: Ok I just set $config['uri_protocol'] = 'AUTO'; in config.php & use
echo ($_GET['token']); or print_r($this->input->get()); // print all the get values & it work fine thanks to all.

A: you can grab value of token by $this->input->get('token'); since it is passed in url following a question mark.

A: if you mean that you want to catch the param token,
you have two options :
format your url to be like
http://localhost/webpt/ipn/checkout/nouman
and you catch it in your controller like this :
function checkout($token) {
    echo $token;
}

or use $this->input->get('token')
function checkout() { // http://localhost/webpt/ipn/checkout/?token=8767&param2=333
 echo $this->input->get('token'); // echo the name param
 print_r($this->input->get()); // print all the get values
}


text:
Q: Impact of Mongo API projecion in Cosmos Request unit charge I can read from Microsoft documentation the RU is impacted due to document size as per the documentation. Is it the size of stored document or the retrieved document. I have a document with lot of entries under the nested level. If I retrieve only the property at level 1 will it reduce the RU?
For example the document is show below. Consider the association level has more than 15000 entries
{
"name": "hi",
"data":"demo",
"associations": [
{
"name": "assoc1"
},
{
"name": "assoc2"
},
{
"name": "assoc3"
},
{
"name": "assoc4"
},
{
"name": "assoc5"
}
]
}

Wil there a difference in RU between the two mongo queries considering the document size is 500KB?
Query without projection:

db.getCollection("demo").find({"name":"hi"})

Query with projection:
db.getCollection("demo").find( {"name":"hi"} , {"data":true} )

I noticed a change in RU between this two query. But I didn't see this mentioned in the document I searched.

A: If the query engine needs to traverse a large document to project results then it will consume more RU/s than when it doesn't.
The bigger issue I think is a document with an array of more than 15K items. Unbounded or super large arrays is generally not a good pattern for Cosmos DB, especially if they have asymmetric update patterns because updates will replace the entire document.


text:
Q: Set inputrangefilter for EditText I currently have this class below. It can set an InputrangeFilter for any number and an edittext will always be between these two numbers. Now I have thought that it would be useful to make a value that is greater than max be automatically replaced my the maximum. I have tried
if (input>max) {return String.valueOf(max);}

But this just writes max into the Textedit instead of clearing the input before. Is there anything I can do to fix that?
public class InputFilterMinMax implements InputFilter {

        private int min, max;

        public InputFilterMinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }

        public InputFilterMinMax(String min, String max) {
            this.min = Integer.parseInt(min);
            this.max = Integer.parseInt(max);
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
                // Remove the string out of destination that is to be replaced
                String newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
                // Add the new string in
                newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
                int input = Integer.parseInt(newVal);
                if (isInRange(min, max, input))
                    return null;
            } catch (NumberFormatException nfe) { }
            return "";
        }

        private boolean isInRange(int a, int b, int c) {
            return b > a ? c >= a && c <= b : c >= b && c <= a;
        }
    }


text:
Q: Smooth transition of v-if/else height in Vue.js I have a component that loads data and then displays it. The user can modify the module which triggers new data to load. While data is loading a loading state is shown.  I would like to smoothly transition between these states using animate.css.  I have it roughly working, but there is still some jumpiness to it.  How can you get the height of the element to smoothly scale on changing state?
JS:
new Vue({
  el: '#demo',
  data: {
    show: true
  },
  methods: {
    loadData() {
        this.show = !this.show
      setTimeout(() => {
        this.show = !this.show
      }, 1000);
    }
  }
})

HTML:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">

  <button v-on:click="loadData()">
    Toggle
  </button>
  <transition
    appear-active-class="animated fadeIn"
    enter-active-class="animated fadeIn"
    leave-active-class="animated fadeOutDown faster"
    mode="out-in"
  >

Loading

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In urna metus, pulvinar a dapibus nec, mattis eu nunc. Sed sed lorem id quam tincidunt accumsan. Nam pharetra, nunc facilisis malesuada tincidunt, nulla mi molestie neque, quis dictum dolor dolor a mi. Suspendisse sed est mollis risus vehicula viverra ac in nunc. Duis cursus mauris vitae sapien tincidunt, sit amet sodales dui mattis. Aliquam dui magna, sagittis at tristique et, consequat at sapien. Quisque ac bibendum urna, et aliquet orci. Ut vitae ipsum id odio consectetur eleifend a nec dui. Suspendisse nulla quam, suscipit in pretium id, dignissim sit amet tortor. Aliquam aliquam, leo et tincidunt venenatis, neque purus cursus elit, ac commodo quam leo at ligula.

  </transition>

https://jsfiddle.net/2ud5s1ne/11/

A: Shameless plug, I created vue-smooth-reflow for this exact use case.
Here's a demo: https://jsfiddle.net/guanzo/snyvoxec/1/
new Vue({
  el: '#demo',
  mixins: [SmoothReflow],
  data: {
    show: true
  },
    mounted(){
        this.$smoothReflow()
    },
  methods: {
    loadData() {
        this.show = !this.show
      setTimeout(() => {
        this.show = !this.show
      }, 1000);
    }
  }
})