text:
Q: Paypal sandbox test credit card numbers Paypal support forums keep mentioning about getting a credit card number automatically. However, it does not show any credit card information automatically anymore - I tried 100 times.
I searched on internet, a famous link paypalobjects.com popups and all the credit card numbers have been linked to the maximum accounts.
How and where do I find a fake Visa/Master Credit card number that I can use for sandbox paypal account?
I am so screwed up! Please help!

A: The fake CC numbers used in the sandbox are displayed in the test accounts setup.
See the top half of page 22 here: https://cms.paypal.com/cms_content/TR/tr_TR/files/developer/PP_Sandbox_UserGuide.pdf


text:
Q: Flash Builder code completion not working when targeting different player API I'm using FlashBuilder 4.6 to build an application that targets different Flash Players. I mainly use the 4.5.1 SDK because I want to allow users with older Flash Players to be able to use my application while benefiting from the Spark framework. SDK 4.6 requires FP 11.2, so that throws out too many users.
That means I can target Flash Players from version 10.2 and up. My application uses audio and video, so I want users that have newer Flash Players to benefit from the newer features. For example, 10.3 supports Acoustic Echo Cancellation. So, if my HTML wrapper detects 10.3 or up, the version with AEC is loaded.
To be able to target FP 10.3's new API's, I had to download playerglobal.swc for 10.3 and put it in the libs directory of my SDK. And set the compiler option 'use specific version' to 10.3.0 and I added the compiler directive -swf-version=12. That works fine, the application compiles and the features work.
However, syntax highlighting and code completion in Flash Builder still do not seem to know about the new classes and methods in 10.3, for example Microphone.getEnhancedMicrophone(). So, it seems that the code completion module doesn't use playerglobal.swc to get it's information from.
My question is this: how can I tell FlashBuilder's code completion about the newer player API?

A: Apache Flex 4.9.0 released a few weeks back will allow you to target Flash Player 10.2 and up.
Look in README for instructions on how to compile for other any versions of the Flash Player (by default it's 11.1). There are also some scripts in the ide directory in the develop branch (in SVN) that can make setting the minimum Flash Player version a little easier.
Apache Flex 4.9.0 can be downloaded from:
http://flex.apache.org/
But I suggest you use the installer to download and create an SDK. It can be found here:
http://flex.apache.org/installer.html
The code completion should work and is based off what is contained in your flex-config.xml (in the frameworks directory of the SDK). Check that these two lines are correct.
<!-- Specifies the minimum player version that will run the compiled SWF. -->
<target-player>11.1<target-player>

<!-- Specifies the version of the compiled SWF -->
<swf-version>14<swf-version>

ie Set to 10.3 and 12 in your case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using JavaScript to add input text to an li, but only adding certain words Right now I'm working on a menu project where customers input text, and it sends what they wrote into a separate ul in a separate div, sort of like a shopping cart menu.
Everything works fine, but I realized I can type anything I want into this div, including gibberish, and it will show up. I'd like to make an array of allowed words (ex: Pasta, Milk, Eggs, etc.), but I'm struggling to think of a way to write that. I was thinking of using an if statement but not sure exactly how I'd write it. Any help would be appreciated.

function addLi() {
  let input    = document.getElementById("input").value;
  let listNode = document.getElementById("list");
  let liNode   = document.createElement("li");
  let txtNode  = document.createTextNode(input);
  liNode.appendChild(txtNode);
  listNode.appendChild(liNode);
}

Added Items

A: Create an array of allowed terms, and inside your function check whether the value entered is in that list:

const whiteList = ['pasta', 'milk', 'apples'];

function addLi() {
  let input = document.getElementById("input").value;
  if (whiteList.includes(input.toLowerCase())) {
    const listNode = document.getElementById("list");
    const liNode = document.createElement("li");
    const txtNode = document.createTextNode(input);
    liNode.appendChild(txtNode);
    listNode.appendChild(liNode);
  }
}

document.getElementById('addItem').addEventListener('click', addLi);

Added Items

  <input type="text" id="input"> <button type="button" id="addItem">Add Item</button>


text:
Q: How does compression of lossless images work?
Compression level: Since compression is not lossy, the only reason to
  use a compression level less than 9 would be a too long time to
  compress file on a slow computer. Nothing to fear from decompression:
  it is as quick whatever the compression level.

https://docs.gimp.org/2.2/en/gimp-images-out.html
GIMP suggests using compression for lossless .png images, "compressed" images are saved using the same file type. If I set compression level to 0 when saving the image is several times larger than the original image. How does "lossless compression" work and do I lose quality by using it?

A: Lossless compression is part of the PNG standard and is similar to using the compression portion of ZIP or a utility like GZip on an image. PNG compression does not cause loss of quality. However, the amount of compression is highly dependent on the type of image (photograph vs. cartoon) and the content. The resulting file will also normally be much larger than a file generated by a lossy algorithm like JPEG where the reduction of space comes at the cost of image quality.
And none of this is specific to GIMP - any image manipulation program that can save as PNG or JPEG, e.g. Adobe Photoshop, will do the same thing with similar results.


text:
Q: "La subconsulta ha devuelto más de un valor" al intentar ejecutar código SELECT Nombre,Apellido,Documento
FROM Staff
WHERE Nombre=(SELECT Nombre FROM Asignaturas WHERE Nombre LIKE ('%UX%'))

Msg 512, Level 16, State 1, Line 105
La subconsulta ha devuelto más de un valor, lo que no es correcto cuando va a continuación de =, !=, <, <=, >, >= o cuando se utiliza como expresión.

A: Si te devuelve mas de un resultado los operadores de comparacion = != > < >= <= van a fallar. Salvo que uses LIMIT 1 en la subconsulta
SELECT Nombre,Apellido,Documento
FROM Staff
WHERE Nombre=(SELECT Nombre FROM Asignaturas WHERE Nombre LIKE ('%UX%')  LIMIT 1)

Pueder hacer esto
SELECT Nombre,Apellido,Documento
FROM Staff s
WHERE EXISTS (SELECT *
              FROM Asignaturas a
              WHERE a.Nombre LIKE ('%UX%')
              AND a.Nombre = s.Nombre)

O puedes hacer
SELECT Nombre,Apellido,Documento
FROM Staff
WHERE Nombre IN (SELECT Nombre FROM Asignaturas WHERE Nombre LIKE ('%UX%'))

Tambien por la negativa con NOT EXISTS y NOT IN


text:
Q: CompletableFuture return all finished result after timeout I want to have a list of comletablefutures I want to wait. With following code.
  public static <T> CompletableFuture<List<T>> finishAllQuery(
  List<CompletableFuture<T>> futures) {
CompletableFuture<Void> allDoneFuture =
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
return allDoneFuture.thenApply(
    v -> futures.stream().filter(Objects::nonNull)
        .map(future -> future.join())
        .collect(Collectors.toList())
);
  }
CompletableFuture<List<Result>> allResponse = finishAllQuery(futures);
allResponse.get(5, milliseconds)

The problem is that among all the futures, some of them can be slow, I want that after the expiration time, the get method return with all completed results. Is there a way to do that?
Thanks a lot.

A: This should be handled by finishAllQuery itself. E.g., starting with Java 9, you can use
public static <T> CompletableFuture<List<T>> finishAllQuery(
    List<CompletableFuture<T>> futures, long timeOut, TimeUnit unit) {

    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
        .completeOnTimeout(null, timeOut, unit)
        .thenApply(v -> futures.stream()
            .filter(CompletableFuture::isDone)
            .map(CompletableFuture::join)
            .collect(Collectors.toList()));
}

With completeOnTimeout, we can force the completion of the future with a predefined value after the timeout elapsed. Here, we just use null, as the result value of allOf doesn't matter anyway.
We just have to add a filter condition, to skip all futures which are not completed yet, as otherwise, join would block the thread.
This can be used like
CompletableFuture<List<Result>> allResponse
    = finishAllQuery(futures, 5, TimeUnit.MILLISECONDS);
List<Result> list = allResponse.join(); // will wait at most 5 milliseconds

For Java 8, we can use
static <T> CompletableFuture<T> completeOnTimeout(
    CompletableFuture<T> cf, T value, long timeOut, TimeUnit unit) {

    ScheduledExecutorService e = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<Boolean> job = e.schedule(() -> cf.complete(value), timeOut, unit);
    return cf.whenComplete((x,y) -> { job.cancel(false); e.shutdown(); });
}

for the missing feature, which requires a small rewrite:
public static <T> CompletableFuture<List<T>> finishAllQuery(
    List<CompletableFuture<T>> futures, long timeOut, TimeUnit unit) {
    return completeOnTimeout(
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])),
        null, timeOut, unit)
        .thenApply(v -> futures.stream()
            .filter(CompletableFuture::isDone)
            .map(CompletableFuture::join)
            .collect(Collectors.toList()));
}

The way, the caller uses the method, doesn't change.
For production use, it's worth rewriting the completeOnTimeout method to reuse the ScheduledExecutorService, but this also requires adding shutdown code or a thread factory creating daemon threads. With Java 9 or newer, you get that for free.

A: If you don't necessarily want all futures to complete, then you should not use allOf(). You can instead use CompletionService and then use the poll() method with timeout. So the flow will be:

*

*Wrap your ExcecutorService in a CompletionService

*Submit N tasks to CompletionService. Then poll for individual tasks with timeout. Something like:

elapsedTime = 0;
availableTime = 5ms;
completedFutures = List();
while (elapsedTime < availableTime):
    remainingTime = availableTime - elapsedTime;
    startTime = currentTime();
    completedFutures.add(CompletionService.poll(timeout=remainingTime));
    elapsedTime += (currentTime() - startTime)


text:
Q: performance of pandas custom business day offset For a ton of dates, I need to compute the next business day, where I account for holidays.
Currently, I'm using something like the code below:
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar

cal = USFederalHolidayCalendar()
bday_offset = lambda n: pd.datetools.offsets.CustomBusinessDay(n, calendar=cal)

mydate = pd.to_datetime("12/24/2014")
%timeit with_holiday = mydate + bday_offset(1)
%timeit without_holiday = mydate + pd.datetools.offsets.BDay(1)

On my computer, the with_holiday line runs in ~12 milliseconds; and the without_holiday line runs in ~15 microseconds.
Is there any way to make the bday_offset function faster?

A: I think the way you are implementing it via lambda is slowing it down.  Consider this method (taken more or less straight from the documentaion )
from pandas.tseries.offsets import CustomBusinessDay
bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
mydate + bday_us

Out[13]: Timestamp('2014-12-26 00:00:00')

The first part is slow, but you only need to do it once.  The second part is very fast though.
%timeit bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
10 loops, best of 3: 66.5 ms per loop

%timeit mydate + bday_us
10000 loops, best of 3: 44 µs per loop

To get apples to apples, here are the other timings on my machine:
%timeit with_holiday = mydate + bday_offset(1)
10 loops, best of 3: 23.1 ms per loop

%timeit without_holiday = mydate + pd.datetools.offsets.BDay(1)
10000 loops, best of 3: 36.6 µs per loop


text:
Q: UIImagePickerController camera type returning black image I am struggling with UIImagePickerController as when i open camera and take image it show black screen in IOS 7 as this is working fine in ios 6, i have tried some other links what says but its not working, please help me with this...
and i am getting this error too
<Error>: CGAffineTransformInvert: singular matrix.

and now i got something ..
Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.

when i just click on take image button

 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (buttonIndex == 0) {

                if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {

                    NSString *mediaType = AVMediaTypeVideo; // Or AVMediaTypeAudio

                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];

                // This status is normally not visible—the AVCaptureDevice class methods for discovering devices do not return devices the user is restricted from accessing.
                if(authStatus == AVAuthorizationStatusRestricted){
                    NSLog(@"Restricted");
                }

                // The user has explicitly denied permission for media capture.
                else if(authStatus == AVAuthorizationStatusDenied){
                    NSLog(@"Denied");
                }

                // The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question.
                else if(authStatus == AVAuthorizationStatusAuthorized){
                    NSLog(@"Authorized");

                    if  ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
                        UIImagePickerController *imagePickerCamera =[[UIImagePickerController alloc] init];
                        imagePickerCamera.delegate = self;
                        imagePickerCamera.allowsEditing = YES;
                        imagePickerCamera.sourceType = UIImagePickerControllerSourceTypeCamera;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self presentViewController:imagePickerCamera  animated:YES completion:^{}];
                        });

                    } else {

                        NSString *errorString = [NSString stringWithFormat:@"This device does not support this feature."];
                        UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Alert" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [errorAlert show];
                    }
                }

                // Explicit user permission is required for media capture, but the user has not yet granted or denied such permission.
                else if(authStatus == AVAuthorizationStatusNotDetermined){

                    [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
                        if(granted){
                            NSLog(@"Granted access to %@", mediaType);
                        }
                        else {
                            NSLog(@"Not granted access to %@", mediaType);
                        }
                    }];

                }

                else {
                    NSLog(@"Unknown authorization status");
                }
            }

            else {
                if  ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImagePickerController *imagePickerCamera =[[UIImagePickerController alloc] init];
                    imagePickerCamera.delegate = self;
                    imagePickerCamera.mediaTypes = @[(NSString *) kUTTypeImage];
                    imagePickerCamera.allowsEditing = YES;
                    imagePickerCamera.sourceType = UIImagePickerControllerSourceTypeCamera;
                        [self presentViewController:imagePickerCamera  animated:YES completion:nil];
                    });
                } else {

                    NSString *errorString = [NSString stringWithFormat:@"This device does not support this feature."];
                    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Alert" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [errorAlert show];
                }
            }

        } else if (buttonIndex == 1) {

            if  ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *imagePickerAlbum =[[UIImagePickerController alloc] init];
                imagePickerAlbum.delegate = self;
                imagePickerAlbum.mediaTypes = @[(NSString *) kUTTypeImage];
                imagePickerAlbum.allowsEditing = YES;
                imagePickerAlbum.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

                [self presentViewController:imagePickerAlbum animated:YES completion:nil];
            } else {

                NSString *errorString = [NSString stringWithFormat:@"This device does not support this feature."];
                UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Alert" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [errorAlert show];
            }
        }
    });
}

    - (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {

[picker dismissModalViewControllerAnimated:YES];
_upLoadimage = info[UIImagePickerControllerEditedImage];

}

A: I had the same problem with camera.  My screen to modify or editing camera image was appearing black.  The log showed me same error (CGAffineTransformInvert xx ). I did a lot of checks to determine or know where is the error.
In my application I use the component SVProgessHUD to show alerts and messages.  Commenting lines with this use corrects the problem. I have updated to the last version of the component (1.0)  and the error CGAffineTransformInvert disappears.


text:
Q: Ansible Azure - Error CanceledAndSupersededDueToAnotherOperation One of my playbook is executed by multiple instances and if ansible should ignore if the rule or group already exists. But I'm getting this error instead. Any idea why I get this error and how I can prevent it?

Error creating/updating security group testing_cloudshell_sg_201 - Azure Error: Canceled\nMessage: Operation was canceled.\nException Details:\n\tError Code: CanceledAndSupersededDueToAnotherOperation
Operation PutNetworkSecurityGroupOperation (ce212e6d-2196-4e0f-9d52-9433535be288) was canceled and superseded by operation PutNetworkSecurityGroupOperation (2c9b8db1-30f3-4486-965e-3449b4572858)

Here is a sample of playbook which gets executed by multiple instances.
  - name: create Azure security group
    # create a security group for the vpc
    azure_rm_securitygroup:
      resource_group: "{{ resource_group }}"
      location: "{{ azure_vm_region }}"
      purge_rules: no
      name: "{{ sg_name }}"
      rules: >-
        {{
          sg_rules.splitlines()
          | map('split', ',')
          | json_query("[*].{
            name: [0],
            protocol: [1],
            source_port_range: [2],
            destination_port_range: [3],
            source_address_prefix: [4],
            destination_address_prefix: [5],
            priority: [6],
            access: 'Allow',
            direction: 'Inbound'
          }")
        }}
      tags:
        Name: "{{ sg_name }}"
    register: azure_security_group_results

  - name: Update Azure security group with static Rule
    azure_rm_securitygroup:
      resource_group: "{{ resource_group }}"
      location: "{{ azure_vm_region }}"
      purge_rules: no
      name: "{{ sg_name }}"
      rules:
          - name: AWX-SSH
            protocol: Tcp
            source_port_range: "*"
            destination_port_range: 22
            source_address_prefix: "{{ sg_ssh_cidr }}"
            destination_address_prefix: "*"
            priority: 299
            access: "Allow"
            direction: "Inbound"
    register: azure_security_group_results_2


text:
Q: Building Haddock documentation without compiling the source I'm working on a Haskell library that contains parts that target WebAssembly (WASM) using Asterius. These parts can't be compiled with the normal ghc and for that reason we have flags that exclude/include the WASM parts.
Trying to build the documentation with Asterius' ahc-cabal new-haddock fails. It seems to revert to the normal ghc for the Haddock command.
My question is: Can I build the Haddock documentation without compiling the source it describes?

Excerpts of my file that might be relevante:
Section of my cabal file:
flag wasm
  description:         Eanbles builds targeting WASM.
  default:             False
  manual:              True

library
  exposed-modules:     Boardgame
  build-depends:       base >= 4.12 && < 5.0
  if flag(wasm)
    exposed-modules:   Boardgame.Web
    build-depends:
        aeson >= 1.4 && < 1.6
      , asterius-prelude == 0.0.1
      , scientific >= 0.3 && < 0.4
    CPP-options:       "-DWASM"

Section of Boardgame.hs:
#ifdef WASM
import Data.Aeson (ToJSON(toJSON), Value(Number, Null))
import Data.Scientific (fromFloatDigits)
#endif

-- | Represents one of the two players.
data Player = Player1 | Player2
  deriving (Show, Eq)

#ifdef WASM
instance ToJSON Player where
  toJSON = Number . fromFloatDigits . fromIntegral . playerToInt
#endif

Section of Boardgame/Web.hs:
module Boardgame.Web (
    addWebGame
) where

foreign import javascript "wrapper" jsMakeCallback :: IO () -> IO JSVal
foreign import javascript "boardgame.games[$1] = $2" jsSetGame :: JSVal -> JSVal -> IO ()

-- | Adds a named game to the list of games accessible from JavaScript.
addWebGame :: (ToJSON a, ToJSON c, FromJSON c, PositionalGame a c) => String -> a -> IO ()
addWebGame name startState = do
  callback <- jsMakeCallback $ playWeb startState
  jsSetGame (jsonToJSVal name) callback

My main file (Boardgame.hs) contains code "hidden" behind the WASM flag but no of code has any documentation. Boardgame/Web.hs is only included when the WASM flag is specified and has some functions with documentation.
I want to build the documentation for all documented functions in both Boardgame.hs and Boardgame/Web.hs.

A: Instead of excluding your module Boardgame/Web.hs, which contains the imports that GHC can't process, entirely when the WASM flag is set, you could use CPP in Boardgame/Web.hs to conditionally set all non-GHC-compatible symbols to undefined.
The way I would do it is to move all type signatures to the top of the module, and make two sets of definitions, like so:
module Boardgame.Web (
    addWebGame
) where

addWebGame :: (ToJSON a, ToJSON c, FromJSON c, PositionalGame a c) => String -> a -> IO ()
-- other signatures...

#ifdef WASM
foreign import javascript "wrapper" jsMakeCallback :: IO () -> IO JSVal
foreign import javascript "boardgame.games[$1] = $2" jsSetGame :: JSVal -> JSVal -> IO ()

addWebGame name startState = do
  callback <- jsMakeCallback $ playWeb startState
  jsSetGame (jsonToJSVal name) callback

-- other definitions...

#else

addWebGame = undefined

#endif

Boardgame.Web should then be imported unconditionally.
This should build with GHC. It will obviously error without doing anything useful if run, but it's enough to let cabal/haddock extract the documentation.
The downside is changing the way you structure your code.
I'm sure this can be automated with something like an awk script, but it's beyond me.
Alternatively, if it's just the FFI declarations that are the problem, you could do this much simpler (and more automably):
module Boardgame.Web (
    addWebGame
) where

#ifdef WASM
foreign import javascript "wrapper" jsMakeCallback :: IO () -> IO JSVal
foreign import javascript "boardgame.games[$1] = $2" jsSetGame :: JSVal -> JSVal -> IO ()

#else
jsMakeCallback = undefined
jsSetGame = undefined
#endif

-- addWebGame and others unmodified.

To get you started with automating, a command like cat Boardgame/Web.hs | sed "s/foreign import javascript \"[^\"]*\" \([^ ]*\).*/\1 = undefined/" will extract a list of javascript imports and convert them into undefined assignments.
Happy Haskelling!


text:
Q: How to put a string fith first r characters bold in ListBox Tkinter? I tried to put a string in ListBox in Tkinter using ANSI escape sequence "\033[1m" before, and using ANSI escape sequence "\033[0m" after .
l = Listbox(root, width=33,font = ('Arial', 15))
a="aaaabc"
l.insert(END,"\033[1m" + a[0:r] + "\033[0m"+a[r:]")

What I got is
SyntaxError: f-string expression part cannot include a backslash

A: You cannot use ANSI escape sequences in the listbox, nor is there any way to change the attributes of only some characters in an item.
If you need to have rich formatting, you will need to use a widget that supports rich formatting. The only practical choice is a Text widget, which means you'll have to supply your own bindings to make it behave like a listbox.


text:
Q: Proper way to restrict text input values (e.g. only numbers) Is it possible to implement an input that allows to type only numbers inside without manual handling of event.target.value?
In React, it is possible to define value property and afterwards input change will be basically bound to the value (not possible to modify it without value change). See example. And it works just fine without any efforts.
In Angular 2 it is possible to define [value], but it will just set the value initially, and afterwards input is not prevented from the modifications.
I was playing around with ngModel and [value] / (input), see example.
But in both implementation there is essential problem:

*

*when you type 10 (model value is 10; input value is 10) - correct

*when you type 10d afterwards (model value is 10 - not modified, all non-digits has been removed; input value is 10d) - incorrect, because the model value is the same as before

*when you type 10d3 - (model value is 103; input value is 103) - correct

How to do that simple (from the first glance) component, without manually handling event.target.value?...
UPDATE I am not looking for native HTML5 input[number] element here. Numbers input here is just for the example - there could be way more tasks when i need to restrict input text.
Moreover, input[number] is 1) not restricting me from typing 10ddd and 2) (less important) contains arrows that i do not need.
And the problem here is to prevent user from typing something beyond the restricted values, instead of allow to input anything and validate it afterwards

A: Tested Answer By me:
form.html
<input type="text" (keypress)="restrictNumeric($event)">

form.component.ts:
public restrictNumeric(e) {
  let input;
  if (e.metaKey || e.ctrlKey) {
    return true;
  }
  if (e.which === 32) {
   return false;
  }
  if (e.which === 0) {
   return true;
  }
  if (e.which < 33) {
    return true;
  }
  input = String.fromCharCode(e.which);
  return !!/[\d\s]/.test(input);
 }

A: You can use the HTML5 input of type number
It does not accept any characters in its declaration
<input type="number" [(model)]='myvar' min=0 max=100 step=5 />

Here is an example of its usage with angular 2 [(model)]
http://www.webpackbin.com/VJNUNF0M-

A: In HTML in <input> field write: (keypress)="onlyNumberKey($event)"
and in ts file write:
onlyNumberKey(event) {
    return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}

A: In component.ts add this function
_keyUp(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.key);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
}

In your template use the following
<input(keyup)="_keyUp($event)">

This will catch the input before angular2 catches the event.

A: After did lot of research finally I create a function which full fill the requirement.
The function which I created restrict all special character and allow only alphabets and number.. and that function works fine for both either you did copy paste and typing both.
Hope it works :)
 public inputValidator(event: any) {
    //console.log(event.target.value);
    const pattern = /^[a-zA-Z0-9]*$/;
    //let inputChar = String.fromCharCode(event.charCode)
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^a-zA-Z0-9]/g, "");
      // invalid character, prevent input

    }
  }

     <input type="text" [(ngModel)]="abc.abc" (input)="inputValidator($event)" />

How you use -
1) Add above method in your class component of ts file.
2) Call method inputValidator($event) on input event..

A: A few of the answers did not work for me so I took the best bits from some of the answers (thanks guys) and created an Angular 5 Directive that should do the job (and more) for you. It maybe not perfect but it offers flexibility.
import { Directive, HostListener, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
selector: '[appInputMask]'
})
export class InputMaskDirective {
@Input('appInputMask') inputType: string;

showMsg = false;
pattern: RegExp;

private regexMap = { // add your own
integer: /^[0-9 ]*$/g,
float: /^[+-]?([0-9]*[.])?[0-9]+$/g,
words: /([A-z]*\\s)*/g,
point25: /^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$/g,
badBoys: /^[^{}*+£$%\\^-_]+$/g
};

constructor(public el: ElementRef, public renderer: Renderer2) { };

@HostListener('keypress', ['$event']) onInput(e) {
this.pattern = this.regexMap[this.inputType]
const inputChar = e.key;
this.pattern.lastIndex = 0; // dont know why but had to add this

if (this.pattern.test(inputChar)) {
   // success
  this.renderer.setStyle(this.el.nativeElement, 'color', 'green');
  this.badBoyAlert('black');
} else {

  this.badBoyAlert('black');
   //do something her to indicate invalid character
  this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
  e.preventDefault();

}

  }
  badBoyAlert(color: string) {
    setTimeout(() => {
      this.showMsg = true;
      this.renderer.setStyle(this.el.nativeElement, 'color', color);
    }, 2000)
  }

  }

HTML
    <input class="form-control" appInputMask="badBoys">

A: <input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" ondragstart="return false;" ondrop="return false;">

Input filed only accept numbers, But it's temporary fix only.

A: The inputmask plugin does the best job of this. Its extremely flexible in that you can supply whatever regex you like to restrict input. It also does not require JQuery.
Step 1: Install the plugin:
npm install --save inputmask

Step2: create a directive to wrap the input mask:
import {Directive, ElementRef, Input} from '@angular/core';
import * as Inputmask from 'inputmask';

@Directive({
  selector: '[app-restrict-input]',
})
export class RestrictInputDirective {

  // map of some of the regex strings I'm using (TODO: add your own)
  private regexMap = {
    integer: '^[0-9]*$',
    float: '^[+-]?([0-9]*[.])?[0-9]+$',
    words: '([A-z]*\\s)*',
    point25: '^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$'
  };

  constructor(private el: ElementRef) {}

  @Input('app-restrict-input')
  public set defineInputType(type: string) {
    Inputmask({regex: this.regexMap[type], placeholder: ''})
      .mask(this.el.nativeElement);
  }

}

Step 3:
<input type="text" app-restrict-input="integer">

Check out their github docs for more information.

A: I think this will solve your problem. I created one directive which filters input from the user and restricts number or text which you want.
This solution is for up to Ionic-3 and Angular-4 users.
import { Directive, HostListener, Input } from '@angular/core';
import { Platform } from 'ionic-angular';

/**
 * Generated class for the AlphabateInputDirective directive.
 *
 * See https://angular.io/api/core/Directive for more info on Angular
 * Directives.
 */
@Directive({
  selector: '[keyboard-input-handler]' // Attribute selector
})
export class IonicKeyboardInputHandler {

  @Input("type") inputType: string;

  isNumeric: boolean = true;
  str: string = "";
  arr: any = [];

  constructor(
    public platForm: Platform
  ) {
    console.log('Hello IonicKeyboardInputHandler Directive');
  }

  @HostListener('keyup', ['$event']) onInputStart(e) {

    this.str = e.target.value + '';

    this.arr = this.str.split('');

    this.isNumeric = this.inputType == "number" ? true : false;

    if(e.target.value.split('.').length === 2){
      return false;
    }

    if(this.isNumeric){
      e.target.value = parseInt(this.arr.filter( c => isFinite(c)).join(''));
    }
    else
      e.target.value = this.arr.filter( c => !isFinite(c)).join('');

    return true;

  }

}

A: In html:
 <input (keypress)="onlyNumber(event)"/>

In Component:
onlyNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

A: I think a custom ControlValueAccessor is the best option.
Not tested but as far as I remember, this should work:
<input [(ngModel)]="value" pattern="[0-9]">

A: Anoher one
<form [formGroup]="myForm" novalidate>
    <input type="text" class="form-control" id="data" name="data"
           formControlName="input3" #item (input)="change(item.value)">
</form>
{{myForm.value |json}}

change(value:string)
  {
    let lastchar = value.substr(value.length - 1);
    if (!(new RegExp('[0-9]').test(lastchar)))
    {
      value=value.substr(0,value.length-1);
      this.myForm.controls["input3"].setValue(value);

    }
  }

if you use from driven template
  <input type="text" class="form-control" id="data" name="data"
       [(ngModel)]="data" #item (input)="change(item)">
   {{data}}

change(item:any)
  {
    let value=item.value;
    let lastchar = value.substr(value.length - 1);
    if (!(new RegExp('[0-9]').test(lastchar)))
    {
      value=value.substr(0,value.length-1);
      item.value=this.data=value;
    }
  }

Update As @BikashBishwokarma comment, this not work if you insert a character in middle. We can change the function by some like
  change(item:any)
  {
    let value=item.value;
    let pos=item.selectionStart;
    if (!(new RegExp('^[0-9]+$').test(value)))
    {
      item.value=this.data=value.replace(/[^0-9]+/g, '');
      item.selectionStart = item.selectionEnd = pos-1;
    }
  }

See, how mainten the cursor position

A: Below is working solution using NgModel
Add variable
 public Phone:string;

In html add
      <input class="input-width" [(ngModel)]="Phone" (keyup)="keyUpEvent($event)"
      type="text" class="form-control" placeholder="Enter Mobile Number">

In Ts file
   keyUpEvent(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.keyCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      if(this.Phone.length>0)
      {
        this.Phone= this.Phone.substr(0,this.Phone.length-1);
      }
    }
  }

A: To catch all the event surrounding model changes,
can consider using
<input (ngModelChange)="inputFilter($event)"/>

It will detect copy / paste, keyup, any condition that changes the value of the model.
And then:
inputFilter(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
}

A: I use this one:

import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';

@Directive({
    selector: '[ngModel][onlyNumber]',
    host: {
        "(input)": 'onInputChange($event)'
    }
})
export class OnlyNumberDirective {

    @Input() onlyNumber: boolean;
    @Output() ngModelChange: EventEmitter<any> = new EventEmitter()

    constructor(public el: ElementRef) {
    }

    public onInputChange($event){
        if ($event.target.value == '-') {
            return;
        }

        if ($event.target.value && $event.target.value.endsWith('.')) {
            return;
        }

        $event.target.value = this.parseNumber($event.target.value);
        $event.target.dispatchEvent(new Event('input'));
    }

    @HostListener('blur', ['$event'])
    public onBlur(event: Event) {
        if (!this.onlyNumber) {
            return;
        }

        this.el.nativeElement.value = this.parseNumber(this.el.nativeElement.value);
        this.el.nativeElement.dispatchEvent(new Event('input'));
    }

    private parseNumber(input: any): any {
        let trimmed = input.replace(/[^0-9\.-]+/g, '');
        let parsedNumber = parseFloat(trimmed);

        return !isNaN(parsedNumber) ? parsedNumber : '';
    }

}

and usage is following
<input onlyNumbers="true" ... />

A: This is the best solution i was able to solve so far (Works even Angular 10):
HTML:
  <input type="text" (input)="inputValidator($event)">

TS file:
  public inputValidator(event: any) {
        const pattern = /^[0-9]*$/;
        if (!pattern.test(event.target.value)) {//enter only numeric
          event.target.value = event.target.value.replace(/[^0-9]/g, "");
        }
        if(event.target.value == 0){  //avoid 0
          event.target.value = event.target.value.replace(event.target.value,"");
        }
        if(event.target.value > 100000){//to block user enter more than 1000000
          event.target.value = event.target.value.replace(event.target.value,event.target.value.slice(0,6));
        }
      }

A: For floats input
HTML:
<input [(ngModel)]="cost"
       (keyup)="_keyUp($event)"
       (keydown)="_keyDown($event)"
       (blur)="_OnBlur($event)" class="form-control"
>

TS file:
  //avoid repeating characters when pressing and holding the key
  _keyDown(event: any) {
    if (event.repeat) event.preventDefault();
  }

  _keyUp(event: any) {
    const pattern = /^[-]?([0-9]*[.])?[0-9]+$/;

    if( //allows the writing of the first time of the character
      (event.key == "-" || event.key == ".") &&
      (this.cost.indexOf(event.key) == this.cost.lastIndexOf(event.key))
    ) return true;

    if (!pattern.test(this.cost)) {
      this.cost=this.cost.slice(0,-1);
    }
  }

  //clean the wrong characters when exiting the input
  _OnBlur(event: any) {
    if (this.cost.length>0){
      if (this.cost.slice(-1)=="." || this.cost.slice(-1)=="-") {
        this.cost=this.cost.slice(0,-1);
      }
      if(this.cost.slice(0,1)==".") this.cost="0"+this.cost
    }
  }

A: In component

const onlyNumberAllow =(e)=> {
const re = /[0-9]+/g;
if (!re.test(e.key)) {
  e.preventDefault();
}}

In HTML--
<input
  type="text"
  maxLength="10"
  name="mobile"
  placeholder="Phone Number"
  value={values.mobile?.replace(undefined, "")}
  invalid={touched.mobile && !!errors.mobile}
  onChange={handleChange}
  onKeyPress={(e) => onlyNumberAllow(e)}
 />


text:
Q: How can I tell whether push notification is not registered yet or has been turned off? More specificly, I want to know if the push notification settings for my app are available in the Settings App.
If they are available, I want to open it from my app (using deep link).
I they are not, I want to ask the user to register for push notifications in my app.
I tried checking UIApplication.shared.isRegisteredForRemoteNotifications, but it returned false for both cases.
I need to support iOS 9 and above.

A: You don't need permission to register for remote notifications; you can just do it.
What you do need permission for is to display notifications.  The permission request is the same, whether you want to display local or remote notifications.


text:
Q: ICEfaces 2.0 and h:commandButton method not called, with ice:commandButton everything is ok I'm trying to use ace:fileEntry to upload a picture, as I read this component requires a submit from h:commandButton in order to start downloading. My problem is that when I switched my ice:commandButton with h:, my managed bean (which is in Conversation Scope) gets created again (@PostConstruct called) and the method in h:commandButton and also the fileEntryListener aren't called anymore.
And as another problem that might be causing this is that when I first enter my page the managed bean gets created and I call conversation begin, but when I do a second request (from a commandLink) the managed bean is created again, and a new conversation is started, after that you can play how long do you want the managed bean doesn't get created again.
Back to my initial question, if I have ice:commandButton the managed bean ins't created again, if it's with h: it gets created again.
And to add a little bit more fun in it, if I remove the rendered attribute (which resolves to true) from ace:fileEntry the fileEntryListener is called, but the action from h:commandButton isn't called no matter what.
I tried to add explicit ids to the components, tried to change ice:form with h:form .. nothing. Please Help.
Ps: why ICEfaces 2 can't work with all ice components, why does it requires h:commandButton, instead of ice:commandButton, why the new JSF 2.0 stuff with f:selectItems backed by a regular list isn't working with ice:selectOneMenu, works just with h:selectOneMenu ? What's up with ICEfaces ? And why CDI doesn't work as expected, with Seam 2 also I had problems with conversations called twice .. ps2: if I don't navigate to another view ?cid=1 isn't present in the URL.

A: Now, with ace:fileEntry and h:commandButton, the reason why the ice:commandButton can not be used is because that is an AJAX component, and browsers will not upload files in an AJAX submit. Even with HTML5 it is not automatic, and new File and XmlHttpRequest APIs must be used. In an HTML4 browser, only a full page, full form, submit will upload the file contents, and only h:commandButton operates that way. For more details, you can see this explained near the top of the page at:
http://wiki.icefaces.org/display/ICE/FileEntry
With our ice: components, which are extended variants of the h: components, such as ice:selectOneMenu, they are lacking some new JSF 2 features because we have been focusing on our newer Advanced Component Environment, due to customer demand for rich client-side components. As well, the focus was on maintaining backwards compatibility with the ice: components, to ease customer migration from ICEfaces 1.8.x to ICEfaces 2.x, and less so to be altering those components' behaviours. But we are still actively maintaining and improving the ice: components, and will be adding the new features soon. Feel free to create any enhancement requests in our Jira system, and to vote on any existing entries, as this does guide our development priorities.
http://jira.icefaces.org/

*

*Mark Collette

A: I'm Mark Collette from the ICEfaces component team, and hopefully I can answer some of your questions.
Most of your issues seem more related to CDI integration than problems with the components themselves. I know that the symptoms change depending on which component you use, but I think that's because the ice: components use AJAX and the h: components do not. Many times integration issues with other frameworks are more observable in AJAX interactions than in full page GET/POST interactions. So your issues may be due to either our CDI integration, or your application's configuration. So please review our documentation on using ICEfaces with CDI, and if you you still experience any issues, I recommend posting the details to our forums.
http://wiki.icefaces.org/display/ICE/Using+ICEfaces+with+CDI
http://www.icefaces.org/JForum/forums/list.page
[Sorry, but this forum is not letting me post more than 2 links, so I'll split the rest of my message into another post, and hopefully that will work]

*

*Mark Collette


text:
Q: Use dependant subscriptions in Iron-router WaitOn and use them in helper functions When doing the following implementation , i get problems because it's look like the data is not available in client side:
In The global configuration of Iron-router , i subscribe to "notifications" publication .
Then i fetch the notifications, and i collect the IDs of elements based on type.
Then i subscribe to the publications using the collected IDs.
In a template that displays the notifications details, i loop over notifications via Notifications.find() , and then depending on the type of notifications, i do :
Questions.findOne(_id) or Answers.findOne(_id) by i am getting undefined exception when i try to access the elements fields.
Router.configure({
      layoutTemplate: 'layout',
      loadingTemplate: 'loading',
      waitOn: function() {
      Meteor.subscribe('notifications', function() {
      var notifications = Notifications.find().fetch();
        var questionsIds = _.map(_.filter(notifications, function (notif) {
        return notif.targetObjectType == 'QUESTION';
      }), function(q) { return q.targetObjectId});

     var answersIds = _.map(_.filter(notifications, function (notif) {
     return notif.targetObjectType == 'ANSWER';
     }), function(q) { return q.targetObjectId});

     Meteor.subscribe('notificationsAnswers', answersIds);
     Meteor.subscribe('notificationsQuestions', questionsIds);

How is it possible to wait for the "nested" subscriptions to be ready to use them in helper functions ?

A: Just a thought, have you tried using Deps.autorun ('notificationsAnswers' with a Session variable), and on your function notifications return along with Session.set()?
So you only waitOn Questions, and once find the q.targetObjectId, set the Session of answer will then trigger its subscription according.

A: The solution is to move this code :
var notifications = Notifications.find().fetch();
        var questionsIds = _.map(_.filter(notifications, function (notif) {
        return notif.targetObjectType == 'QUESTION';
      }), function(q) { return q.targetObjectId});

     var answersIds = _.map(_.filter(notifications, function (notif) {
     return notif.targetObjectType == 'ANSWER';
     }), function(q) { return q.targetObjectId});

     Meteor.subscribe('notificationsAnswers', answersIds);
     Meteor.subscribe('notificationsQuestions', questionsIds);

to a onBeforeAction hook in the same global iron-router config like this :
onBeforeAction : function() {

var notifications = Notifications.find().fetch();
        var questionsIds = _.map(_.filter(notifications, function (notif) {
        return notif.targetObjectType == 'QUESTION';
      }), function(q) { return q.targetObjectId});

     var answersIds = _.map(_.filter(notifications, function (notif) {
     return notif.targetObjectType == 'ANSWER';
     }), function(q) { return q.targetObjectId});

     Meteor.subscribe('notificationsAnswers', answersIds);
     Meteor.subscribe('notificationsQuestions', questionsIds);
}


text:
Q: How to append a string from dictionary? X = corpus.get("Andrew Shapiro")

testsite_array = []

with X as my_file:

    for line in my_file:

        testsite_array.append(line)

where corpus is a dictonary and Andrew Shapiro is an item in it. It gives me following error.
  File "C:/Users/Vrushab PC/Downloads/Dissertation/untitled0.py", line 71, in <module>

 with X as my_file:

AttributeError: __enter__

A: In order to use the with statement, the object, X in this case, the object must have implemented the enter method and exit method. The whole point is that it allow for the object to clean it's self up even in the case of an exception. Think try:except:finally done much more cleanly.
In order to answer your question though, I would need to know what you expected X to be. You named your temporary placeholder for it as my_file so is X supposed to be a file path that you want to open or something?
A full example of what you are attempting to do would be helpful.
Generally though, you would use the with statement for doing things like opening files like this:
with open(X, 'r') as my_file:
    ...
Tahoe


text:
Q: How to change font size of segmented control and prevent it from changing back to default size after changing segment I am using the following code to implement and subsequently change the font size of each segment in the UISegmented Control
//Set up segment control
UISegmentedControl *tempSegmentControl = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"Friends",@"Popular", nil]];
tempSegmentControl.frame = CGRectMake(-8, -1, 336, 30);

self.segmentControl = tempSegmentControl;
[self.segmentControl setWidth:168 forSegmentAtIndex:0];
[self.segmentControl setWidth:168 forSegmentAtIndex:1];
self.segmentControl.selectedSegmentIndex = 0;
[self.segmentControl addTarget:self action:@selector(toggleControls:) forControlEvents:UIControlEventValueChanged];
[self.segmentControl setSegmentedControlStyle:UISegmentedControlStylePlain];

//TO CHANGE FONT SIZE OF EACH SEGMENT
for (id segment in [self.segmentControl subviews])
{
    for (id label in [segment subviews])
    {
        if ([label isKindOfClass:[UILabel class]])
        {
            [label setTextAlignment:UITextAlignmentCenter];
            [label setFont:[UIFont boldSystemFontOfSize:14]];
        }
    }
}

This works initially (see screenshot below)

However, after I click on the "popular" tab (inactive tab), the font size seem to return to their original default font size

What can I do to prevent the font size from changing back to the default size?

A: Probably not the cleanest way, but it works if you run the for-loop on the 'value Changed' event of the UISegmentedControl control.
Update:
This is the proper way, available in iOS 5 and later:
NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:14], UITextAttributeFont, nil];
[self.segmentControl setTitleTextAttributes:textAttributes forState:UIControlStateNormal];

A: http://chris-software.com/index.php/tag/uisegmentedcontrol/
check out this its ans
codeButton.segmentedControlStyle = UISegmentedControlStyleBar;
codeButton.momentary = YES;


text:
Q: Starting batch file via Paramiko on hpc-system leads to an error message I want to start a calculation on a HPC system (Linux; slurm) via batch file. When I log in via a remote client (MobaXterm) and start the batch file with the command sbatch start.sh everything is executed as planned. But if I connect via Python script (using Paramiko) I get the error message

ansys221: command not found

for a module loaded in the batch file.
My conclusions:

*

*The ssh connection is working as it should (datatransfer to filesystem on hpc works)

*The sbtach command starts the right batch-file (the selected job name appears in the job queue)

*The modules are available on the hpc system (batch file starts calculation correctly when run via MobaXterm)

I use the following Python code:
from paramiko import SSHClient
client = SSHClient()
client.load_system_host_keys()
client.connect(url, username, password)
ssh_stdin, ssh_stdout, ssh_stderr = client.exec_command(sbatch start.sh)
ssh_stdout.channel.recv_exit_status()
lines = ssh_stdout.readlines()
for line in lines:
    print(line)
client.close()

Why does different behavior appear when the batch file is started via ssh connection?


text:
Q: iOS schedule push notifications I want to schedule push notifications, I mean that my app can send notifications to users every certain time interval, for example every 24 hours sends a notification.
How can I do this? Do I have to use a server?

A: You can use SDK like https://onesignal.com/ (REST architecture) or create your own simple CRON based server. It's up to you.
Or one more possibility (not free) is to use Task Scheduling on Google Compute Engine. Google App Engine provides a Cron service. Using this service for scheduling and Google Cloud Pub/Sub for distributed messaging, you can build an application to reliably schedule tasks across a fleet of Compute Engine instances.


text:
Q: Recalculate image map after window resize I have an interesting problem:
My girfriend (painter...) wants to have a web page like this:

*

*The first page is just an image, through all screen - with no slider etc. So there is a problem of resizing images for different resolutions.

*On this image are some windows, where a user can navigate through the rest of the page.

SOLUTIONS:

*

*So, for the first problem there is a nice solution - jquery. It works great, no problem.

*For the second problem, there is image maps, which works fine.
PROBLEM:
How do I combine the first and second solutions? The only problem I haven't found a solution for yet is how to dynamically calculate imagemap coordinates for a polygonal shape. (ie whatever the screen resolution is, the imagemap properties will always stay at the right spot).
For rectangle shapes I found this. What about poly shape?
Does somebody have some ideas on how to accomplish this?

A: You can use JQuery plugin ImageMapster for your image-maps.
This plugin can dinamically re-count areas after resizig and have other usefull features.
And ever if you deside to write own solution, I suppose explore the code of the plugin can help you with your resizing task.

A: The solution should be the same as it is for the rect shape, because you're just scaling co-ordinates in both cases.
A point is a point, and both shapes are made up of points.


text:
Q: Multisite admin on completely different Codeigniter install.. Duplicate content? I am using codeigniter for three of my websites. I use a seperate install for each as I am under the belief that as they grow they will each need there own server, and this setup just seems easier.
I am developing the adming backend for these three sites, and decided the best way to do this would be a fourth CI install on a completely different server/domain for security.
This way each morning I can login, see all the stats and admin tasks required for all of my sites, and I can conduct them from one place.
The problem with this is a requirement for duplicate code.. code from the models of each of my sites needs to in part be duplicated in the admin site.
Less than ideal, but does this really matter? Is there a better way around?
Thanks

A: Well.. in my understanding, if u are going 3 different websites on 3 different servers, it is anyways going to have you manage duplicate code (if required) on 3 different servers. But if all are going to be on same server, then u can create HMVC architecture like spark where u can centralize all the duplicating code and then use it as and where required. This way you will be saved of the duplicate coding.
Other way around was something a crud and not tested solution, that you say its only the 4th application where u need to have the code from all other 3 applications, then u can create softlinks to the codes and try. May be that can help u solve your problem.

A: CodeIgniter 2.* allows third-party packages, that can be anywhere on the server. If you have all your sites on different servers it could be a problem, but if you have them on one, you can use the to have shared code. Third-party packages are similar to modules, but do not have any routing.
For further information refer to this topic by Phil Sturgeon and to CodeIgniter user guide


text:
Q: How to batch reverse geocode in R? I am trying to get zipcode for lat-long coordinates in new york region
I tried to use reverse geocoder API from google but its limited to 2500 hits per day so can process my data frame in batch.
Next, I tried using the library(zipcode) with dataset zip code but could not match latitude longitude with the coordinates of train data set as all lat-long coordinates are not in the dataset.
Further though of using KNN to predict zipcode for the dataset but can't get correct results.
zipcode_latlon = zipcode[zipcode$state=="NY",c(1,4,5)]
train_latlon = train_data[,c("latitude","longitude")]
zip1 = rep(10007, nrow(train_latlon))
zip1 = as.character(zip1)
train_latlon = cbind(zip1, train_latlon)
colnames(train_latlon) = c("zip","latitude","longitude")
knn_fit = knn(zipcode_latlon, train_latlon,zipcode_latlon$zip, k=1)

Need to know how I can get zipcodes from lat long in batch, any method would be good in R.

A: I think you are going about this the wrong way.  You can find the zip codes of lat/lon coordinates without a geocoder - all you need is to download the US zipcodes shapefile here and then do a spatial join:
library(sp)
library(rgdal)

#import zips shapefile and transform CRS
zips <- readOGR("cb_2015_us_zcta510_500k.shp")
zips <- spTransform(zips, CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))

#here is a sample with three cities in New York State and their coordinates
df <- as.data.frame(matrix(nrow = 3, ncol =3))
colnames(df) <- c("lat", "lon", "city")

df$lon <- c(43.0481, 43.1610, 42.8864)
df$lat <- c(-76.1474, -77.6109,-78.8784)
df$city <- c("Syracuse", "Rochester", "Buffalo")

df
       lat     lon      city
1 -76.1474 43.0481  Syracuse
2 -77.6109 43.1610 Rochester
3 -78.8784 42.8864   Buffalo

#extract only the lon/lat
xy <- df[,c(1,2)]

#transform coordinates into a SpatialPointsDataFrame
spdf <- SpatialPointsDataFrame(coords = xy, data = df, proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))

#subset only the zipcodes in which points are found
zips_subset <- zips[spdf, ]

#NOTE: the column in zips_subset containing zipcodes is ZCTA5CE10
#use over() to overlay points in polygons and then add that to the original dataframe

df$zip <- over(spdf, zips_subset[,"ZCTA5CE10"])

And voila! You have the zipcode of each point
df
       lat     lon      city ZCTA5CE10
1 -76.1474 43.0481  Syracuse     13202
2 -77.6109 43.1610 Rochester     14604
3 -78.8784 42.8864   Buffalo     14202


text:
Q: SQL query to identify rows not contained contained in another table across multiple subsets I have two tables as seen below.
Table 1:
Day Group
---------
1   A
1   B
1   C
2   B
2   C
2   D
3   C
3   D
3   E

Table 2:
Group
-------
A
B
C
D
E

I would like to create a SQL query that identifies each Group that exists in Table 2 but does not exist in Table 1 partitioned by Day.
The desired result would look like this:
Day Group
---------
1   D
1   E
2   A
2   E
3   A
3   B

A: Use a cross join to generate all combinations and then weed out what you have:
select d.day, t1.group
from (select distinct day from table1) d cross join
     table2 g left join
     table1 t1
     on t1.day = d.day and t1.group = g.group
where t1.day is null;

A: SELECT
    *
FROM
    (
        SELECT DISTINCT
            Day
        FROM
            Table1
    ) AS Days
    ,
    Table2
WHERE
    NOT EXISTS (
        SELECT
            *
        FROM
            Table1
        WHERE
            Table1.day=Days.Day AND
            Table1.Group=Table2.Group
    )


text:
Q: Endless scroll using QuiltView in android I am using the QuiltView to display the data(Text, images and video) and I also want endless scroll in this.
As much as i understand the QuiltView is basically using the GridLayout not GridView.
Is this correct?
If QuiltView is using the GridLayout then can I use OnScrollListener?
Is there anyone have the example of QuiltView with Endless scroll.


text:
Q: what do you call a guy that treats people differently in his or her own interests A guy may annoy a good-tempered person many times,but when he or she comes to a person that is colder and smarter, they tend to treat them with more respect. Sometimes they treat others nicely when they are in need of them. They just treat others in a way they want to, according to the person's social status, characteristics, importance and influence.
What do you call this kind of person? Snobby, diplomatic or something else?

A: The word diplomatic is not a good fit. It implies that a person is careful not to offend other people, and you have said that this guy annoys people.
The word snobby might fit. A snob (snobby person) is polite or welcoming to people they think are important, and rude or dismissive to people they think are unimportant. But that does not necessarily mean that he or she is acting "in his or her own interests". First, a snob might be acting that way out of habit, instead of doing it as a deliberate strategy to get what they want. Second, many snobs see themselves as part of the "important" group, so they may already have what they want.
Here are some other suggestions that might fit:

*

*A flatterer is a person who gives other people lots of fake praise because they want they other people to do them favors.

*A weak or unimportant person who tries very hard to earn the favor of stronger or more important people is a sycophant, toady, bootlicker, brownnoser, or ass-kisser.

*A person who only cares about themselves, and does not care about other people, is a narcissist. We could also call them egocentric, self-centered, self-absorbed, self-serving, or simply selfish.

*A person who keeps convincing other people to give them things, while giving nothing in return themselves, is a leech, sponge, mooch, freeloader, parasite or user.

Almost all of these words are insults, and a few of them (e.g. brownnoser and ass-kisser) are rather crude. So be careful how you use them.


text:
Q: Correlation of $x + E(y\mid x)$ and $y + E(x\mid y)$ is bigger than the correlation of $x$ and $y$ Suppose $x$ and $y$ are random variables with positive variance.  Let $\rho_{x,y} \in [-1,1]$ denote their (Pearson) correlation coefficient.  Let $\mathbb{E}(x\mid y)$ denote the conditional expectation of $x$ given $y$ and similarly $\mathbb{E}(y\mid x)$ is the conditional expectation of $y$ given $x$.  Construct two functions:
$$\lambda(x) \equiv x + \mathbb{E}(y\mid x) \text{ and } \mu(y) \equiv y + \mathbb{E}(x\mid y).$$
We can thus think of $\lambda$ and $\mu$ themselves as random variables. Assume the variances of both $\lambda$ and $\mu$ are strictly positive.
Let $\rho_{\lambda,\mu}$ be the correlation coefficient for these random variables.
Conjecture: $\rho_{x,y} \le \rho_{\lambda,\mu}$.
I've spent some time trying to prove this.  It is easy to show when the conditional expectations are linear, e.g. when $x$ and $y$ are jointly normal.  In that case, $|\rho_{x,y}| = |\rho_{\lambda,\mu}|$.  I've also used Monte Carlo to construct many examples where $x$ and $y$ are discrete.  I have not found a counterexample.  I feel like this must be a known result, but my google skills have failed me.  Any ideas are appreciated.


text:
Q: Cannot start mysql-server on Amazon Linux 2 due to dependency issues I'm trying to install MySQL on a Amazon Linux 2 server and I can't seem to get past this dependency issue (prevents server pkgs etc being installed thus preventing me from starting a mysql-server.
Commands I ran are below:
sudo wget https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm
sudo rpm -Uvh mysql80-community-release-el8-1.noarch.rpm
sudo yum install mysql-server
sudo yum provides */libmysqlclient.so.18
sudo yum install mariadb-libs-5.5.68-1.amzn2.x86_64
sudo systemctl status mysqld
sudo systemctl start mysqld

The following errors I receive when attempting sudo yum install mysql-server and sudo status mysql-server:
sudo yum install mysql-server
sudo systemctl status mysql-server
No clue how to proceed from here, haven't been able to find any helpful resources online, would be very grateful if someone here could help me install and get the MySQL server up and running, as this is something I'm struggling with for work.
Kindest regards.

A: Amazon Linux may have been based on Centos in the past, but it's a standalone distro. Don't treat it like Centos or things will go badly. My experience over the years with AL / AL2 is that it's much more difficult to install software and get support, so I don't use it any more except for the simplest use cases. I prefer Ubuntu, the software available and support are MUCH better.
If your server is new and easily replaced I'd discard it and create a new one before going forward. If not you need to roll back the changes you made above before trying again.
If you must use AL2, Amazon has a tutorial for installing MariaDB here. It doesn't use external repos so if that will work for you give it a go.
Otherwise follow an AL2 / MySQL8 tutorial rather than a Centos tutorial. I've found a couple on Google here and here, but I can't vouch for either.


text:
Q: Using HTTPOnly Cookie Returned from API in React app I am working on my first React application which consumes a REST API. Certain information within the API isn't accessible unless authorized by logging in, and the API returns an HTTPOnly cookie as a response upon a successful POST request to the login endpoint; I'm using axios, to accomplish this. It's possible to view the cookie within the network tab of the browser and it also successfully logged to the console, but I'm unsure of how I can actually store the information returned from the API within my react app. The cookie vanishes from the browser when I leave the page after logging in. Is there a way I can implement this cookie into the React App's memory/state so it can be sent and used upon future requests in the application? I've scoured for a few days and seen various methods to access a returned JWT, but most of them include using LocalStorage which isn't secure or are from deprecated tutorials many years ago. After logging in, the JWT returned from the API will need to be sent back upon future requests, which will also be made using axios.
All help is much appreciated.

A: You can configure the expiry of the HttpOnly cookie. It sounds like your server is currently storing the JWTs in HttpOnly session cookies. If you are using Chrome, you can confirm this by looking at the "Expires / Max-Age" column in the Application tab. If it is a session cookie, the field will be unspecified, and the cookie disappears once you end your browsing session. If you set the expiry of the HttpOnly cookie to say a year, then the cookie persists across browsing sessions.


text: Q: How to detect that Fabric canvas was changed Is there an easy way to detect that any objects in a canvas were added/changed/deleted? A method like canvas.wasChanged(). I need to detect that after re-creating a canvas with loadFromJSON.


text:
Q: css and javascript is not working properly for rails 5 project I am trying to implement a template page in my rails project where it would place all images side by side and when you hover you get the effect of the first image where the square is highlighted with a search symbol and when you click on the search symbol a larger image shows like the second photo. and I cannot figure out why I have all the files I need and have changed the coding to work in rails. It is supposed to look like the image below:

Here is the html code:

 All
 |

 Identity
 |

 Web Design
 |

 Graphic
 |

 Logo

Design Object 01

Web Design

And here are the files it requires:

        <link rel="stylesheet" href="assets/plugins/animate.css">
        <link rel="stylesheet" href="assets/plugins/line-icons/line-icons.css">
        <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="assets/plugins/cube-portfolio/cubeportfolio/css/cubeportfolio.min.css">
        <link rel="stylesheet" href="assets/plugins/cube-portfolio/cubeportfolio/custom/custom-cubeportfolio.css">

Now on my end this is what I am getting:

Also here is the html output from my end when I left click and view source it looks very similar to what is above which sort of tells me that something is not right with the css and js files like they are not being loaded into the project :

Design Object 01

Web Design

Here is the actual code in rails:

            <%= image_tag "creative/main/img3.jpg"%>

<%= link_to "assets/creative/main/img3.jpg", :class => "cbp-lightbox", data_title: "Design Object" do %>
                            <%end%>

Design Object 01

Web Design

In my asset pipeline I am using all the files I need (arrows pointing to the files):
Javascript
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require creative/bootstrap.min
//= require creative/animated-headline
//= require creative/back-to-top
//= require creative/smoothScroll
//= require creative/jquery.cubeportfolio.min <------------------------------------------
//= require creative/app
//= require creative/jquery.backstretch.min
//= require creative/backstretch-ini
//= require creative/fancy-box
//= require creative/cube-portfolio-3-ns <------------------------------------------
//= require creative/jquery-migrate
//= require creative/jquery.counterup.min
//= require creative/jquery.fancybox
//= require creative/jquery.parallax
//= require creative/jquery.themepunch.tools.min
//= require creative/jquery.themepunch.revolution.min
//= require creative/modernizr
//= require creative/owl-carousel
//= require creative/owl.carousel
//= require creative/revolution-slider
//= require creative/style-switcher
//= require creative/waypoints.min
//= require creative/wow.min
//= require creative/jquery-ui.min
//= require creative/jquery.validate.min
//= require creative/jquery.maskedinput.min
//= require creative/jquery.mCustomScrollbar.concat.min
//= require creative/reg
//= require creative/checkout
//= require creative/datepicker
//= require gmaps/google
//= require creative/infobox
//= require creative/custom
//= require turbolinks
//= require lodash
//= require_self

CSS
/*
 *= require jquery-ui
 *= require creative/bootstrap.min
 *= require font-awesome
 *= require creative/line-icons
 *= require creative/animated-headline
 *= require creative/animate
 *= require creative/cubeportfolio.min <------------------------------------------
 *= require creative/custom-cubeportfolio <------------------------------------------
 *= require creative/custom
 *= require creative/dark
 *= require creative/default
 *= require creative/footer-v1
 *= require creative/header-v6
 *= require creative/jquery.fancybox
 *= require creative/owl.carousel
 *= require creative/parallax-slider
 *= require creative/settings
 *= require creative/style
 *= require creative/app
 *= require creative/blocks
 *= require creative/page_log_reg_v1
 *= require creative/page_about
 *= require creative/jquery.mCustomScrollbar
 *= require creative/sky-forms
 *= require creative/custom-sky-forms

 *= require_self
*/

I cannot figure out why it is not working as the first image any help would be great.


text:
Q: How to create edit and delete for table that receiving data in mysql? I want to show all post from database with table, with the ability to delete and edit posts from the database.
It's my code:

        ID
        Author Name
        Author ID
        Date
        Title
        Content

        <?php
        // Check connection
        if (!can_connectToDBwithConstant()) {
            return FALSE;
        }
        // Create connection
        $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $query = mysqli_query($con, "SELECT ID,post_author_name,post_author_id,post_date,post_title,post_content FROM  `wp_posts`");
            //php loop to load all post
            while ($row = mysqli_fetch_array($query)):
                $id = $row['ID'];
                $authorName = $row['post_author_name'];
                $authorID = $row['post_author_id'];
                $date = $row['post_date'];
                $title = $row['post_title'];
                $content = $row['post_content'];
        ?>

        <?php echo $id; ?>
        <?php echo $authorName; ?>
        <?php echo $authorID; ?>
        <?php echo $date; ?>
        <?php echo $title; ?>
        <?php echo $content; ?>
        Edit | Delete

    <?php endwhile; mysqli_close($con); ?>

The problem is: How do we know which ones are selected posts to edit it or delete it?How can I do it?

A: There are a lot of ways to solve this, one of them is by taggin the Edit and Delete labels or some other element ( td, tr or taking the value from the id field you already have). Here's a very simple (not the best but it can give a very clear idea of what the deal is with this things):

    <button id="edit_<?php echo $id ?>">Edit</button>
    <button id="delete_<?php echo $id ?>">Delete</button>

By this you can extrac the id value from button using Jquery o javascript.

A: It's very simple.
You should be having a php script at server end to process the deletion of any post with a given ID.
Like if you are not using OOP, get the ID of the post to be deleted via $_GET or $_POST and then process deletion query and then redirect to the listing page.

<?php
    // Check connection
    if (!can_connectToDBwithConstant()) {
        return FALSE;
    }
    // Create connection
    $deleteID = $_GET['id'];
    $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    $query = mysqli_query($con, "DELETE from TABLE_NAME where id_column = '".$deleteID."'");
header('Location: listin.php');
?>

And in the listing code -
<a href="www.hostname.com/process_delete.php?id=<?php echo $row["id"]; ?>"


text:
Q: Reversing a linked list(Iterative method) I am writing a code for reversing a linked list in python.
The following code does not pass the test case:
class ListNode(object):
    def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution(object):
    def reverseList(self, head)
        prev, curr = None, head
        while curr:
            curr.next = prev
            prev = curr
            curr = curr.next
        return prev

while this code passes:
class Solution(object):
    def reverseList(self, head):  # Iterative
        prev, curr = None, head
        while curr:
            curr.next, prev, curr = prev, curr, curr.next
        return prev

What is the difference between the two?

A: In your unrolled code, by the time you get to the last line, curr.next has been overwritten with prev.  It no longer has its original value.  Both prev and curr will point to the old prev.


text:
Q: How to increase the size of / with unallocated hdd space So, I had run out of space on / (which was initially 9.3 GB). So I had some un-allocated space on my hdd (/dev/sda) that I wanted to assign to the / partition, which is also: /dev/sda1.
For reference this is how my HDD is laid out:
→ sudo fdisk -l

Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00081f45

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048    19531775     9764864   83  Linux
/dev/sda2        19533822   625141759   302803969    5  Extended
/dev/sda5        19533824    34172927     7319552   82  Linux swap / Solaris
/dev/sda6        34174976   443774975   204800000   83  Linux

→ sudo sfdisk -l

Disk /dev/sda: 38913 cylinders, 255 heads, 63 sectors/track
Warning: extended partition does not start at a cylinder boundary.
DOS and Linux will interpret the contents differently.
Units = cylinders of 8225280 bytes, blocks of 1024 bytes, counting from 0

   Device Boot Start     End   #cyls    #blocks   Id  System
/dev/sda1   *      0+   1215-   1216-   9764864   83  Linux
/dev/sda2       1215+  38913-  37698- 302803969    5  Extended
/dev/sda3          0       -       0          0    0  Empty
/dev/sda4          0       -       0          0    0  Empty
/dev/sda5       1215+   2127-    912-   7319552   82  Linux swap / Solaris
/dev/sda6       2127+  27623-  25497- 204800000   83  Linux

There is approximately 85~90 GB that is available to be allocated to my / partition.
Edit: I have gone for option two, and created a partition: /dev/sda7
→ sudo sfdisk -d /dev/sda
Warning: extended partition does not start at a cylinder boundary.
DOS and Linux will interpret the contents differently.
# partition table of /dev/sda
unit: sectors

/dev/sda1 : start=     2048, size= 19529728, Id=83, bootable
/dev/sda2 : start= 19533822, size=605607938, Id= 5
/dev/sda3 : start=        0, size=        0, Id= 0
/dev/sda4 : start=        0, size=        0, Id= 0
/dev/sda5 : start= 19533824, size= 14639104, Id=82
/dev/sda6 : start= 34174976, size=409600000, Id=83
/dev/sda7 : start=443777024, size=181364736, Id=83

A: Linux provide many partitioning tools to re-size or shrink the partition that also without any data loss,It is possible to resize a partition using Gparted in a easy and a convenient way.As its a opensource and free download.
To modify the partition with Gparted, it has to be downloaded then burned into a blank CD. This CD will be used as a bootable CD in order to resize the partition on Linux.
Follow these easy instructions to resize a partition using Gparted on Linux without losing any data. The process may take some time to complete....
you can go through this page for whole description and re-sizing...
Happy to help

A: That's not going to be easy. With classical partitions you need consecutive free space. You cannot add it up all over the disk.
The fun gets even bigger by your extended partition beginning directly after the first one. There are two possibilities:

*

*extend the partition (in a narrower sense; limited to adding about 7GiB)

*create a bigger partition in the free space, copy the contents of / and use sda1 for something different.

extending the partition
You have to delete sda5 (and create a new partition for swap in the free space) and change the beginning of the extended partition and the end of sda1.
You should save the output of sfdisk -d /dev/sda to a file (backup this to some external storage!) and adapt the values. You may add that output to your question, then we can help you with that.


text:
Q: Number of close votes required and low traffic tags I don't believe the number of close votes required is working on low traffic and less popular tags.

*

*Fewer questions are read, therefore fewer close votes issued

*Less people have enough rep to close (by their 'low frequency' nature these tags don't generate much reputation for the users that follow them)

*Some people (even with enough rep) don't close questions anyway
Having said that, I can't think of a rule that can improve this situation that isn't subject to abuse. Anyone else seen this or have ideas?
Edit: I'm seeing this on the Stack Overflow sharepoint tag. Here are examples over the last five days. Most of these have one close vote (mine):
Belongs on Server Fault:

*

*How does a MOSS web front end route search requests to query servers?

*Cannot login to WSS 3.0 site using forms authentication

*Verify SP2 Install for MOSS?
Belongs on Super User:

*

*Does anyone know of any good software for SharePoint email filing

*Lookup field in Edit in Datasheet mode in sharepoint doesn't work
Duplicate:

*

*https://stackoverflow.com/questions/1289297/sharepoint-developer-pre-screening-test
Edit 2: Is this what the belongs-on... tags should be used for? To alert other users with higher rep to close these questions?

A: If something needs to be closed, you can always rile up the clientele here on Meta or flag a mod and they'll come by and close it. Marc loves breaking out the ban hammer.

A: If you think something needs to be closed, you can flag it for moderator attention. Moderators can then decide whether or not we want to listen to you. It only takes one mod vote to close anything as opposed to the 5 regular users.
I can say that once there becomes a larger userbase of 3,000+ users, it is increasingly unlikely that mods will take any action on a question unless it is blatantly necessary. The whole idea is for you guys to start policing yourselves once you hit the 3,000 reputation mark, so that we don't have to monitor every single question and close it ourselves.

A: Personally, I don't feel the problem is as bad as you make it out to be, at least on SO which has been around long enough to have many, many 3k+ users.  Do you have any examples of this?  Say, a question that has been around for a few days despite being obviously in need of closing?
Even if there are such questions, if they are obvious enough, flagging for moderator attention should work.  If it's a gray area, then you're probably out of luck.  Just put your vote to close in, maybe drop a comment explaining your opinion in case other people come by later, and move on.


text:
Q: Http Posting An Image From Iphone NSMutableString *url = [[NSMutableString alloc] init];
    [url appendString:@"uploadImage.do"];
NSData *imageData = UIImageJPEGRepresentation(selectedImage,1.0);

// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];

/*
 add some header info now
 we always need a boundary when we post a file
 also we need to set the content type

 You might want to generate a random boundary.. this is just the same
 as my output from wireshark on a valid html post
 */
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"nickname\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:appDelegate.userName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:appDelegate.passWord] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userImage\"\r\n\r\n" ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userImage\"; filename=\"Default.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[NSData dataWithData:imageData]];
//[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

// now lets make the connection to the web
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {

    receivedData=[[NSMutableData data] retain];

}
else {

    NSLog(@"Failed");

}

i am using this code to upload an image to server. i am doing as stated below
NSData *imageData = UIImageJPEGRepresentation(selectedImage,1.0);
i am getting nsdata object which is not nill. but if i post it the server side i am getting null been sent as params.
any help

A: i have found out a way for doing this.
save the image you got in your local directory and then send it as a file by giving its full path......


text:
Q: Xpath - Find specific element, print all elements of that node Given the following Xpath to an element
/std:Batch/BatchSection/ContractPartner/Contractor/Contract/contractNumber

How can I print out all subelements of the node Contract
where sequenceNumber= 12345?
I tried
xmllint --xpath "string(/std:Batch/BatchSection/ContractPartner/Contractor/Contract/contractNumber[contractNumber='12345'])" test.xml

However, that is an invalid XPath expression. How to fix that?
Example input:
<std:Batch xmlns:std="http://www.test.com/contractBatch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <year>2020</year>
  <batchType>3</batchType>
  <runDate>2020-04-11</runDate>
  <text>Datatest</text>
  <jobInfo>Test</jobInfo>
  <BatchSection>
    <addedAtDate>2020-04-11</addedAtDate>
    <ContractPartner>
      <contractDealerAG>44444</contractDealerAG>
      <contractorType/>
      <isoCountry>NL</isoCountry>
      <language>EN</language>
      <Contractor>
        <contractor>44444</contractor>
        <Contract>
          <contractor>44444</contractor>
          <sequenceNumber>12345</sequenceNumber>
          <info1>abcd</info1>
        </Contract>
      </Contractor>
    </ContractPartner>
  </BatchSection>
</std:Batch>

Desired output (where sequenceNumber=12345):
    <Contract>
      <contractor>44444</contractor>
      <sequenceNumber>12345</sequenceNumber>
      <info1>abcd</info1>
   </Contract>

A: You have to deal with the dreaded namespaces, unfortunately... Try it like this:
xmllint --xpath "//*[local-name()='Contract'] [.//*[local-name()='sequenceNumber'][./text()='12345']]" test.xml

and see if it works.

A: I'm assuming you mean sequenceNumber, as per xml example, if that's the case then you may need to do something like this to return the node Contract:
xmllint --xpath "//sequenceNumber[.="12345"]/.." test.xml


text:
Q: Cannot access iis website from internal network I'm facing with the following IIS issue:
From DC01 and external networks, i can access the website with the external domain like: https://app.domain.com/application
But from AS01 and workstations on the LAN, i cannot access the website with the external domainname
Setup:
DC01 (192.168.1.2) < domaincontroller with DNS (a record is added: app.domain.com to external IP)
AS01 (192.168.1.4) < ISS and website running on this machine
The whole firewall is temporary disabled
I hope someone can help me with this. Thanks in advance
Disabled firewall
Add DNS a record


text:
Q: PHP append json with $ to http request body $body->append('{"stage_id": "43"}');

I would like to make the "43" dynamic and use a $variable for the value: How should look the Syntax look like?

A: This will help you
$body->append('{"stage_id": $variable}');

A: First of all you have to declare a variable and assign your dynamic value in it as per your requirement.
$variable = Value;   // if value is number like 0,1,2,3,4 or anything.
$variable = "value"; // if value is string put it inside ' or " quotes.

Now you can use your value as a variable:
body->append("{'stage_id': '$variable'}");

A: You can use just like this:
<?php
    $var = 43;
    $array = array('stage_id'=>$var);
    $json = json_encode($array);
    $body->append($json);
?>


text:
Q: Differences between 'root account credentials' and 'IAM user credentials' What are the differences between 'root account credentials' and 'IAM user credentials'?
and one more question:
According to the description, it's recommended using 'IAM user credentials' but unable to access in S3 using 'IAM user credentials'
Can you explain why this is?

A: From Amazon:

All AWS accounts have root account credentials. These credentials
  allow full access to all resources in the account. Because you can't
  control the privileges of the root account credentials, you should
  store them in a safe place and instead use AWS Identity and Access
  Management (IAM) user credentials for day-to-day interaction with AWS.
With IAM, you can securely control access to AWS services and
  resources for users in your AWS account. For example, if you require
  administrator-level permissions, you can create an IAM user, grant
  that user full access, and then use those credentials to interact with
  AWS. Later, if you need to revoke or modify your permissions, you can
  delete or modify any policies that are associated with that IAM user.

Your second question is still open: Unable to access any S3 resource when using IAM user credentials?

A: There are some things that you can do with a Root account that you can not do with an Administrator. For example, you can't create or delete account wide Budgets or enable MFA delete on as S3 bucket.

A: Your root credentials are your credentials through which you have signed up providing your card and billing details.
IAM user accounts are user accounts which you can create for individual services offered by AWS.
Assume this scenario, you are the CEO of a product company and you signup for AWS providing your mail address, card and billing details and you have developers working for you, developing apps, deploying them in AWS. You cannot share your AWS account(your root credentials), which you just created, to your developer or devops and ask them to deploy apps. This is a huge security risk for you. Instead you create IAM users, attach group level policies or user level policies and share these IAM accounts with them. Group level and user level policies restrict and authorize individual IAM users to AWS services under your user account. It is extremely important that you understand and make use of IAM for your AWS account.
http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_Introduction.html
IAM S3 Access: If you authorize and assign an IAM user with required policies it should work well. You can simulate an IAM user's policy using https://policysim.aws.amazon.com/home/index.jsp (please login first).
hope this helps


text:
Q: Converting Unicode to HTML entity in PHP array I have issues with unicode characters returning a string null within an array. This array is creating in PHP and echoed which json_encode. The problem exists within "name".
The initial object looks like:
[{"ID":"147","First Name":"Tom","Last Name":"Bishai","Registered Table Number":"34","Email Address":"tombishai@gmail.com","Phone Number":"07921130704","Amount":"800","MadeFrom":"34","Type of Transaction":"bid","Number":"22","name":null,"Gift Aid":"Yes","PIN":"1261"}]

I have used a function from another question which looks like this:
    function utf8ize($d) {
      if(is_array($d)) {
        foreach($d as $k => $v) {
          $d[$k] = utf8ize($v);
        }
      }  else if(is_string($d)) {
        return utf8_encode($d);
      }
      return $d;
    }
echo json_encode(utf8ize($arr));

This now returns a string (within the array) which looks like:
[{"ID":"147","First Name":"Tom","Last Name":"Bishai","Registered Table Number":"34","Email Address":"tombishai@gmail.com","Phone Number":"07921130704","Amount":"800","MadeFrom":"34","Type of Transaction":"bid","Number":"22","name":"JOAN MIRO \u0096 COMPOSITION IX","Gift Aid":"Yes","PIN":"1261"}]

Now I am having trouble converting this to a html entity. It will also need to apply to any other unicode characters that may appear in the database. Any help?
Many thanks!
UPDATE:
Just doesn't seem to work with em dash/en dash. I haven't gone through all of the unicode characters though.


text:
Q: Why would .NET SerialPort ReadByte() block for full timeout if data arrives after it is called Running on Windows 10 with .NET 4.7.2 and virtual serial ports, I have a SerialPort DataReceived handler that looks like:
private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    _serialPort.ReadTimeout = 10000;
    while (true)
    {
        try
        {
            var nextByte = _serialPort.ReadByte();
            Debug.WriteLine(((byte)nextByte).ToString("X2"));
            continue;
        }
        catch (TimeoutException)
        {
        }

        break;
    }
}

If I write a byte to the port it appears immediately in the debug window, and because of the while loop and continue, ReadByte() is called again where it will block until the 10 second timeout elapses.  If I write more data to the port during that time, ReadByte() does not return immediately.  Instead, it continues to block until the full timeout has elapsed, and only then returns the newly written byte.
Why would it not return as soon as new data is available?


text:
Q: Bounding the solution of convex optimization problem Let $\beta \in \mathbb{R}^K$, and assume that $\alpha \in [0,1]$. Let $\bar{\beta} = \frac{1}{K} \sum_{i=1}^K \beta_i$ denote the mean of $\beta$, and let $\tilde{\beta}$ denote a median of $\beta$. Assuming $\bar{\beta} \leq \tilde{\beta}$, I wish to show that the solution $\hat{t}$ of the convex optimization problem:
$$\underset{t \in \mathbb{R}}{\text{arg min}} \sum_{i=1}^K \left(\frac{1}{2}(1-\alpha)(\beta_i - t)^2 + \alpha|\beta_i - t| \right),$$
is bounded such that $\bar{\beta} \leq \hat{t} \leq \tilde{\beta}$ for all $\alpha \in [0,1]$.
I have, without any luck, tried to find an explicit formula for $\hat{t}$ by simply differentiating the objective function with respect to $t$ and equating to zero, which yields
$$t = \bar{\beta} + \frac{\alpha}{K(1-\alpha)} \sum_{i=1}^K \text{sign}(\beta_i-t),$$
from which point I am stuck. It is clear that $\sum_{i=1}^K \text{sign}(\beta_i-t) \in [-K, K]$, putting lower and upper bounds on $t$, but I am not sure if this helps me at all.
In particular, I am unsure if this approach is even worth pursuing, or if there is an easier way of showing the inequalities, that does not rely on finding an/the explicit solution?


text:
Q: python testing a decorated decorator through a mock
This question is a follow-up to this brilliant answer on decorators in Python :
I use the given "snippet to make any decorator accept generically any argument".
Then I have this (here simplified) decorator:
@decorator_with_args
def has_permission_from_kwarg(func, *args, **kwargs):
    """Decorator to check simple access/view rights by the kwarg."""
    def wrapper(*args_1, **kwargs_1):
        if 'kwarg' in kwargs_1:
            kwarg = kwargs_1['kwarg']
        else:
            raise HTTP403Error()

        return func(*args_1, **kwargs_1)

    return wrapper

*

*Working with this decorator, no problem it does the job very well.

*Testing a similar decorator that does not require absolutely the kwargs, same outcome.

*But testing this decorator with the following mock does not work:
def test_can_access_kwarg(self):
    """Test simple permission decorator."""
    func = Mock(return_value='OK')
    decorated_func = has_permission_from_slug()(func(kwarg=self.kwarg))
    # It will raise at the following line, whereas the kwarg is provided...
    response = decorated_func()
    self.assertTrue(func.called)
    self.assertEqual(response, 'OK')

It returns me the exception I am raising when I do not have a 'kwarg' keyword-argument...
Does anyone has a clue how to test (by mocking would be preferable) such a decorator decorated by another decorator that requires the access to one of the keyword arguments passed to the function ?

A: decorated_func = has_permission_from_slug()(func(kwarg=self.kwarg))

This will:

*

*Execute func(kwarg=self.kwarg)

*Generate an instance of the actual decorator.

*Call the decorator on the result of the func-call (i.e. the result).

*Return the wrapper which will then later try to call the results from step 3 (which would fail).
response = decorated_func()
This will then call the returned wrapper with no arguments, so **kwargs_1 is empty. Also, if you wrapper wouldn't raise an exception in this case, the subsequent call of func(..) would throw an exception because the return value of func (the original one) is probably not callable (see above).
What you probably want to do instead, or at least what your decorator supports, is this:
decorated_func = has_permission_from_kwarg()(func)
response = decorated_func(kwarg=self.kwarg)

Or, if you want to pass your kwarg in the decorator like this:
decorated_func = has_permission_from_kwarg(kwarg=self.kwarg)(func)
response = decorated_func()

Then you need to adjust or decorator to actually use kwargs, and not kwargs_1 in the check (the latter are the arguments to the decorated function).

I'm testing your original decorator definition (with no changes) and the decorator_with_args as defined in the linked answer with the following code:
class HTTP403Error (Exception):
    pass

def func (*args, **kwargs):
    print('func {}; {}'.format(args, kwargs))

my_kwarg = 'foo'
decorated_func = has_permission_from_kwarg()(func)
decorated_func(kwarg=my_kwarg)
decorated_func(not_kwarg=my_kwarg)

As expected, I get func (); {'kwarg': 'foo'} printed for the first call, and a HTTP403 exception for the second.


text:
Q: Intersection of ideals,why $\bigcap _{\alpha \in A}\:I_{\alpha }\:=\sum _{\alpha \in A}\:I_{\alpha }\:=\left\{a_{\alpha _1}+...+a_{\alpha _n}\right\}$ We've been given the definition of intersection of ideals, that it is equal to:
$$\bigcap _{\alpha \in A}\:I_{\alpha }\:=\sum _{\alpha \in A}\:I_{\alpha }\:=\left\{a_{\alpha _1}+...+a_{\alpha _n}\::\:n\in \mathbb{N},\:a_{\alpha _i}\in I_{\alpha _i}\right\}$$
I see that those $a_{\alpha _i}$ are arbitrary elements of Ideals $I_{\alpha }$, but let's say that for every element $a_{\alpha _i}$ except $a_{\alpha _1}$ we have $a_{\alpha _i}$ = 0. Then $a_{\alpha _1}$ would be an element of $\bigcap _{\alpha \in A}\:I_{\alpha }$, but it doesn't have to be true that $\forall _{i\:}a_{\alpha _1}\in \:I_{\alpha _i}$.
So what's the deal here?

A: Your doubts are completely justified. Take a very simple example: $\mathbb{Z}$ as the  ring, $A=\{1,2\}$ and $I_1=(2),I_2=(3)$ the ideals generated by the primes $2$ and $3$ respectively. Clearly $I_1\cap I_2=(6)$, but $I_1+I_2=\{2x+3y:x,y\in\mathbb{Z}\}$. Obviously $I_1\cap I_2\subsetneq I_1+I_2$, since e.g. $2\in I_1+I_2$. So there must be something wrong with the "definition" that you got.