text:
Q: Python 3.8.3 incompatible with tensorflow I recently installed python with the version 3.8.3 and upgraded pip to 20.1.1. According to enter link description here, conda install -c conda-forge tensorflow should work. However, I get this result
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - tensorflow -> python[version='3.5.*|3.6.*|>=3.5,<3.6.0a0|>=3.6,<3.7.0a0|>=3.7,<3.8.0a0|3.7.*']

Your python: python=3.8

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

since I use
(base) C:\Users\ivan>python --version
Python 3.8.3

(base) C:\Users\ivan>pip --version
pip 20.1.1 from C:\Users\ivan\anaconda3\lib\site-packages\pip (python 3.8)

I wonder if it is possible to solve this issue without downgrading.  For users of anaconda 2020.07, python 3.8 is used by default. Downgrading it will break anaconda.

A: People have reported  problems using tensorflow with python 3.8, it is best to use 3.7.  You are incorrect about breaking Anaconda. Here is what to do.
In Anaconda home page click on environments. At the bottom left of the page click on create. A window will appear. Give the new environment a name (say python3.7). In the drop down menu select 3.7. Now a new environment is created using python 3.7. Now in the conda terminal type conda activate python3.7. Then use conda to install tensorflow. It will install version 2.1.1, the cuda toolkit version 10.1.243 and cudnn version 7.6.5. Note conda can only install tensorflow up to version 2.1.1. If you want tensorflow 2.2 install it with pip using pip install tensorflow ==2.2.0.  after you have installed 2.1. The cuda toolkit and cudnn work with version 2.2. Now use pip or conda to install any other packages you need in your python3.7 environment and you should be good to go!


text:
Q: Golang file upload to s3 using OS Open I am trying to upload an Image to my s3 account using Golang and the amazon s3 api . I can get the imagine uploaded if I hard code the direct path such as
file, err :=  os.Open("/Users/JohnSmith/Documents/pictures/cars.jpg")
    defer file.Close()
    if err != nil {
        fmt.Printf("err opening file: %s", err)
    }

if I hard code the file path like that then the picture will be uploaded to my s3 account . However that approach is not good as I can't obviously hard code the direct image path to every image that I want to upload . My question is how can I upload images without having to Hardcode the path . This will be apart of an API where users will upload images so I clearly can not have a hard coded path . This is my code first the HTML
<form method="post" enctype="multipart/form-data"  action="profile_image">

Image Upload

<input type="file" name="file" id="file"/>

 <input type="submit" value="Upload Image">

</form>

then this is my HTTP Post function method
func UploadProfile(w http.ResponseWriter, r *http.Request) {

    r.ParseForm()
      var resultt string
    resultt = "Hi"

    sess, _ := session.NewSession(&aws.Config{
        Region:      aws.String("us-west-2"),
        Credentials: credentials.NewStaticCredentials(aws_access_key_id,aws_secret_access_key, ""),

    })
    svc := s3.New(sess)

file, err :=  os.Open("Users/JohnSmith/Documents/pictures/cars.jpg")
defer file.Close()
if err != nil {
    fmt.Printf("err opening file: %s", err)
}

fileInfo, _ := file.Stat()
size := fileInfo.Size()
buffer := make([]byte, size) // read file content to buffer

file.Read(buffer)
fileBytes := bytes.NewReader(buffer)
fileType := http.DetectContentType(buffer)
path := file.Name()
params := &s3.PutObjectInput{
    Bucket: aws.String("my-bucket"),
    Key: aws.String(path),
    Body: fileBytes,
    ContentLength: aws.Int64(size),
    ContentType: aws.String(fileType),
}
resp, err := svc.PutObject(params)
if err != nil {
    fmt.Printf("bad response: %s", err)
}
fmt.Printf("response %s", awsutil.StringValue(resp))

}

That is my full code above however when I try to do something such as
file, err :=  os.Open("file")
    defer file.Close()
    if err != nil {
        fmt.Printf("err opening file: %s", err)
    }

I get the following error
http: panic serving [::1]:55454: runtime error: invalid memory address or nil pointer dereference
goroutine 7 [running]:
err opening file: open file: no such file or directorynet/http.(*conn).serve.func1(0xc420076e80)

I can't use absolute path (filepath.Abs()) because some of the files will be outside of the GoPath and as stated other users will be uploading. Is there anyway that I can get a relative path ..

A: After POST to your API, images are temporarily saved in a OS's temp directory (different for different OS's) by default. To get this directory you can use, for example:
func GetTempLoc(filename string) string {
    return strings.TrimRight(os.TempDir(), "/") + "/" + filename
}

Where:

*

*filename is a header.Filename, i.e. file name received in your POST request. In Gin-Gonic framework you get it in your request handler as:

file, header, err := c.Request.FormFile("file")
if err != nil {
    return out, err
}
defer file.Close()

Example: https://github.com/gin-gonic/gin#another-example-upload-file.
I'm sure in your framework there will be an analogue.

*

*os.TempDir() is a function go give you a temp folder (details: https://golang.org/pkg/os/#TempDir).

*TrimRight is used to ensure result of os.TempDir is consistent on different OSs

And then you use it as
file, err := os.Open(GetTempLoc(fileName))
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kernel Dev In assembly & C I am trying to create a simple kernel using assembly and C on linux using bochs. The problem that each time I try calling the c code from the assembly code the emulator gives me an error and resets the simulation. when I start in the 16 bit real mode I use this code
global _start

[bits 16]

_start:

mov [BOOT_DRIVE] , dl

mov bp , 0x7000
mov sp , bp

mov bx , 0x0000 ;load 5 sectors to 0x0000(ES):0x9000(BX)
mov es , bx
mov bx , KERNEL_OFFSET
mov dh , 15
mov dl , [BOOT_DRIVE]
call disk_load

mov dx , [es:KERNEL_OFFSET]
call print_hex

call switch_to_pm

jmp $

and after switching to the protected mode this is the code
[bits 32]
extern kmain

begin_pm:

;print a char to vram for testing and it is printed, this means the switch has suceeded
mov ebx , VRAM_ADDRESS
mov al , 'H'
mov [ebx] , al
mov al , 0x07
inc ebx
mov [ebx] , al

call kmain

jmp $

and the c function basically does nothing just an empty one
about the commands I am using I use these
nasm $asm_file_name.asm -f elf -o $asm_file_name.o
gcc -ffreestanding -c $c_file_name.c -o $c_file_name.o
ld -o $c_file_name.bin -Ttext 0x7c00 $asm_file_name.o $c_file_name.o --oformat binary
dd status=noxfer conv=notrunc if=$c_file_name.bin of=$floppy_name.img

I don't where is the problem. Any ideas ?
Note:
I am using the following GDT and switch_to_pm functions
    ;GDT
gdt_start:

    gdt_null:
        dd 0x0
        dd 0x0

    gdt_code: ;the code segment descriptor
        ; base = 0x0 , limit = 0xfffff ,
        ; 1 st flags : ( present )1 ( privilege )00 ( descriptor type )1 -> 1001 b
        ; type flags : ( code )1 ( conforming )0 ( readable )1 ( accessed )0 -> 1010 b
        ; 2 nd flags : ( granularity )1 (32 - bit default )1 (64 - bit seg )0 ( AVL )0 -> 1100 b
        dw 0xffff
        ; Limit (bits 0 -15)
        dw 0x0
        ; Base (bits 0 -15)
        db 0x0
        ; Base ( bits 16 -23)
        db 10011010b ; 1st flags , type flags
        db 11001111b ; 2nd flags , Limit (bits 16 -19)
        db 0x0
        ; Base ( bits 24 -31)

    gdt_data: ; the data segment descriptor
        ; Same as code segment except for the type flags :
        ; type flags : ( code )0 ( expand down )0 ( writable )1 ( accessed )0 -> 0010 b
        dw 0xffff
        ; Limit ( bits 0 -15)
        dw 0x0
        ; Base ( bits 0 -15)
        db 0x0
        ; Base ( bits 16 -23)
        db 10010010b ; 1 st flags , type flags
        db 11001111b ; 2 nd flags , Limit ( bits 16 -19)
        db 0x0
        ; Base ( bits 24 -31)

    gdt_end:
    ; The reason for putting a label at the end of the
    ; GDT is so we can have the assembler calculate
    ; the size of the GDT for the GDT decriptor ( below )
    ; GDT descriptior
    gdt_descriptor:
        dw gdt_end - gdt_start - 1
        dd gdt_start

    ; Size of our GDT , always less one
    ; of the true size
    ; Start address of our GDT
    ; Define some handy constants for the GDT segment descriptor offsets , which
    ; are what segment registers must contain when in protected mode. For example ,
    ; when we set DS = 0 x10 in PM , the CPU knows that we mean it to use the
    ; segment described at offset 0 x10 ( i.e. 16 bytes ) in our GDT , which in our
    ; case is the DATA segment (0 x0 -> NULL ; 0 x08 -> CODE ; 0 x10 -> DATA )
    CODE_SEG equ gdt_code - gdt_start
    DATA_SEG equ gdt_data - gdt_start
[bits 16]

switch_to_pm:

cli
lgdt[gdt_descriptor]

mov eax , cr0
or eax , 0x1
mov cr0 , eax

jmp CODE_SEG:init_pm

[bits 32]

init_pm:

mov ax , DATA_SEG
mov ds , ax
mov ss , ax
mov es , ax
mov fs , ax
mov gs , ax

mov ebp , 0x9000
mov esp , ebp

jmp begin_pm

A: call kmain will try to find the function at the address as if the whole code was loaded at 0x7c00. However, the code in its entirety is loaded from disk into 0x9000. Thus you need to ask the linker to fix up the address it uses as the address for kmain.
Or even better, as @AlexeyFrunze suggests, load the code starting from the second sector into the place in memory directly after where the first sector is loaded by BIOS.


text:
Q: Using MAP_POPULATE for writing to file My application writes dumps huge files to disk. For various reasons it is more convenient to use mmap and memory writes than using the fwrite interface.
The slow part of writing writing to a file in this way are page faults. Using mmap with MAP_POPULATE is supposed to help; from the man page:
MAP_POPULATE (since Linux 2.5.46)
    Populate (prefault) page tables for a mapping.  For a file mapping, this causes read-ahead on the file.  This will help  to
    reduce blocking on page faults later.  MAP_POPULATE is supported for private mappings only since Linux 2.6.23.

(To answer the obvious question: I've tested this on relatively recent kernels, on 4.15 and 5.1).
However, this does not seem to reduce pagefaults while writing to the mapped file.
Minimal example code: test.c:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>

static int exit_with_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main() {
    const size_t len = 1UL << 30;
    const char *fname = "/tmp/foobar-huge.txt";

    int f = open(fname, O_RDWR|O_CREAT|O_EXCL, 0644);
    if(f == -1) {
        exit_with_error("open");
    }
    int ret = ftruncate(f, len);
    if(ret == -1) {
        exit_with_error("ftruncate");
    }
    void *mem = mmap(NULL, len, PROT_WRITE|PROT_READ, MAP_SHARED|MAP_POPULATE, f, 0);
    if(mem == MAP_FAILED) {
        exit_with_error("mmap");
    }
    ret = close(f);
    if(ret == -1) {
        exit_with_error("close");
    }

    memset(mem, 'f', len);
}

When running this under a profiler or using perf stat it's clearly visible that the memset at the end triggers (many) pagefaults.
In fact, this program is slower when MAP_POPULATE is passed, on my machine ~1.8s vs ~1.6s without MAP_POPULATE. The difference simply seems to be the time it takes to do the populate, the number of page faults that perf stat reports is identical.
A last observation is that this behaves as expected when I read from the file, instead of writing -- in this case the MAP_POPULATE reduces the number of pagefaults to almost zero and helps to improve performance drastically.
Is this the expected behavior for MAP_POPULATE? Am I doing something wrong?

A: Because although the pages have been prefaulted by MAP_POPULATE, they are not dirty pages. Therefore, when writing to these pages, the CoW page faults would be triggered to set the page entries as dirty and writable.


text:
Q: Is there representation $A\to End_k(k)$ where $A$ is central simple quaternion algebra over $k$? Sorry  for my bad English.
Let $k$ be commutative field (if  necessary $k=\mathbb{Q}_p$).
$End_k(k):=\{f:k\to k~|~ f$ is $k$-algebra homomorphism$\}$

Is there  representation $A\to End_k(k)$ where $A$ is central simple quaternion algebra over $k$?

I'm reading concerned about abelian varieties, and in this book there is little representation for proof, but I don't study about representation theory.
Please tell me.


text:
Q: Ionic / AngularJS - defer vertical scroll event to parent element I have content like this:
<ion-content delegate-handle="mainScroll">
  <ion-scroll delegate-handle="horizontalScroll" direction="x">
  </ion-scroll>
  <ion-scroll delegate-handle="horizontalScroll" direction="x">
  </ion-scroll>
  <ion-scroll delegate-handle="horizontalScroll" direction="x">
  </ion-scroll>
</ion-content>

Basically what I want is multiple horizontal scrollers (ion-scroll) inside a parent container (ion-content) which scrolls vertically.  The trouble is that trying to grab onto the horizontal scroller and drag it vertically doesn't work, so I need to somehow defer that event to the parent.
I see the delegate function:
<ion-scroll delegate-handle="horizontalScroll" direction="x" on-scroll="delegateScroll()">
</ion-scroll>

$scope.delegateScroll = function() {
  // what do I do here?
}

But I'm not sure how to grab that event and do something useful with it.  Help?

A: Solved my own problem.  It's way more complicated than I thought it would be, but it works.  See the codepen below.
http://codepen.io/anon/pen/BoGkA
angular.module('ionicApp', ['ionic'])
.controller('MyCtrl', function($scope, $ionicScrollDelegate, $timeout) {
  $timeout(function(){
    return false; // <--- comment this to "fix" the problem
    var sv = $ionicScrollDelegate.$getByHandle('horizontal').getScrollView();

    var container = sv.__container;

    var originaltouchStart = sv.touchStart;
    var originalmouseDown = sv.mouseDown;
    var originaltouchMove = sv.touchMove;
    var originalmouseMove = sv.mouseMove;

    container.removeEventListener('touchstart', sv.touchStart);
    container.removeEventListener('mousedown', sv.mouseDown);
    document.removeEventListener('touchmove', sv.touchMove);
    document.removeEventListener('mousemove', sv.mousemove);

    sv.touchStart = function(e) {
      e.preventDefault = function(){}
      originaltouchStart.apply(sv, [e]);
    }

    sv.touchMove = function(e) {
      e.preventDefault = function(){}
      originaltouchMove.apply(sv, [e]);
    }

    sv.mouseDown = function(e) {
      e.preventDefault = function(){}
      originalmouseDown.apply(sv, [e]);
    }

    sv.mouseMove = function(e) {
      e.preventDefault = function(){}
      originalmouseMove.apply(sv, [e]);
    }

    container.addEventListener("touchstart", sv.touchStart, false);
    container.addEventListener("mousedown", sv.mouseDown, false);
    document.addEventListener("touchmove", sv.touchMove, false);
    document.addEventListener("mousemove", sv.mouseMove, false);
  });
});


text:
Q: how can I find the branch points and cut? For $f(z)=\sqrt{z^3+8}$, I need to find all branch points and branch cuts, not in the disk $|z|<2$, which make the function single-valued.
Here I started with $z=-2,1-i\sqrt{3},1+i\sqrt{3}$ are branch points, then I rewrite the function as
$f(z)=\sqrt{r_1e^{iθ_1}*r_2e^{iθ_2}*r_3e^{iθ_3}}$ but here I'm stuck. Also I guess the branch cuts will be $[-2,1-i\sqrt{3}]$, $[-2,1+i\sqrt{3}]$, $[1+i\sqrt{3},1-i\sqrt{3}]$ but I need to find other branch cuts outside this disk so I have no idea. Any comments?


text:
Q: upload files with same name to aws s3 Below is an example for my scenario,
1) User uploads file named 'sample-file.pdf' from UI with presigned url.
2) User again uploads file with same name 'sample-file.pdf'
3) I want both files to stay on the same location with newly uploaded file name appended as (1). So for example, the newly uploaded file name will be 'sample-file(1).pdf'.
4) If the user uploads same file name again, just number will be incremented and all files will be at same location/folder in s3 bucket.
Is there any easy and quick solution to this problem.
Thanks,
Yogesh

A: .
├── test1.txt
├── test2.txt
├── test3.txt
└── test4.txt

$ for i in $(ls); do echo $1 && aws s3 cp ./$i s3://your_s3bucket_name/$i; done

so you can use a small bash script loop to do it...
So if you have whitespaces in your filename. You can try this instead:
#!/bin/sh

find .  -type file -name "*" -print0 | while IFS= read -r -d '' file; do
  #  echo $file
    KEY=$(basename "$file")
    echo $KEY
    echo aws s3api put-object --bucket iamtestingiamtesting --key '"'$KEY'"' --body $file
    aws s3api put-object --bucket iamtestingiamtesting --key '"'$KEY'"' --body $file
done

Also normally this easiest way is to use aws s3 sycn
aws s3 sync ./local_dir s3://your_s3_bucket --delete //  Files that exist in the destination but not in the source are deleted during sync.

or you can use aws s3 cp
aws s3 cp ./local_dir  s3://your_s3_bucket --recursive

A: What you can do is create an S3 Event on Object Create that sends the event to a lambda.  The logic of the lambda would.
if object name doesn't not contain (#)
then
   copy name.ext to name(#).ext
end if

A: There is no simple, out of the box solution that I'm aware of.
The biggest challenge you have here is that you are using pre-signed URLs. When you use a pre-signed URL, the user of the pre-signed URL cannot dictate the filename in S3; instead, the creator of the pre-signed URL dictates it in advance.
So, one way to solve this is that the generator of the pre-signed URL (I'm assuming that's done programmatically through awscli scripting or similar) should first check for the presence of an existing object with the desired key (and any versioned variants) then return a pre-signed URL for the object with the next free version number, as needed. If the object does not yet exist, then just return a regular pre-signed URL without the version number. This is not ideal, especially if multiple clients are calling the script concurrently, but it could work in a simple scenario.


text:
Q: Change Terminal.app's Default Shell to BASH How can I change Terminal.app's default shell to BASH?
For some reason, my friend's Mac (10.6.6) defaults to using TCSH instead of BASH. The obvious remedy is to choose /bin/bash as the command to open shells with (as below), but then it fails to load .bashrc and .bash_profile (even if I give a --source or --rcfile parameter).

How can I switch it to use bash the right way?

A: By using chsh from Terminal. It changes default shell for user. Alternatively you may setup Terminal to use /bin/bash -l ... this will cause BASH to behave as login shell, i.e. it will read .bash_profile.

A: Open System Preferences, select user and right click on its name.
"Advanced options..." will appear. Change shell there.
If you're die hard Apple user, you probably will have to enable right click first.
Depending on your computer model, it can be done under Trackpad or Mouse Preferences.

A: As of Mac OS X Lion 10.7, Terminal will create login shells even if you choose a custom shell in Startup preferences. So your initial problem should no longer be an issue on Lion. (Although I recommend setting the shell via System Preferences to ensure it's set for the user account and not just for the Terminal application.)


text: Q: Incorrect Z Value in Slope and hillshade Raster from QGIS I have to create a TIFF for hillshade and Slope from data obtained by Eiva software, basically a XYZ file. When I drop in the XYZ or TIFF exported from Eiva and try to create the layers they seem ok but when I drop back into Eiva the Z values have changed quite drastically, like 90m. It is not just a case of the Z value being opposite values in Eiva as this wouldn't match.


text:
Q: Is my directive using a defining or isolate or child scope? I am learning directive module of Angular.js and how to create your own diectives.
I am reading a book "Mastering AngularJS Directives by Josh Kurz".
Here I went though one example, but didn't understood much.
This is the code below,
<!DOCTYPE html>

    <title>Recipe 02 example 01</title>

    <link rel="stylesheet" href="D:\Rahul Shivsharan\JavaScript-Framework\BootstrapCSS\bootstrap-3.2.0-dist\css\bootstrap.css"></link>
    <link rel="stylesheet" href="D:\Rahul Shivsharan\JavaScript-Framework\BootstrapCSS\bootstrap-3.2.0-dist\css\bootstrap-theme.css"></link>

{{actorName}}

From the above example you can see,
I have created three directives "bb-string", "bb-two-string" and "bb-expression".
After reading the book, what I understood is all the directives are having defining scope.
What I understood from the the term defining scope is that "The scope which a directive gets from its parent directive".
So whether I understood properly, or is it that the directive "bb-string" has an isolate scope, and the directive "bb-two-string" has a defining scope. ?
If all the directives are using "defining scope" so are these scope inherited from controller "myCtrl" scope ?
And last questing,
the directive "bb-expression" has a code,
scope.term = scope.term();

what does "scope.term()" mean, were does the term function came from ?
this is the link for the live example.
First directive example

A: All of your directives in your example use isolated scope as you defined a scope object in directive definitions. If you haven't used scope parameter, then directive's scope will be a child scope of where ever they called from. Difference between each three case is how you use the arguments passed to your directives.
In the first directive you passed an attribute using @, so you only pass a value to your directive from outside. If you change the value of the passed argument it does not affect the value of the given parameter outside your directive. So you can think of it as one-way binding.
Your second directive uses two-way binding by using = sign. So when you change the passed argument in your directive, changes are reflected back to the outer scope which passed this value into your directive.
Your third directive passed the argument as an expression by using &. With this approach you can pass functions to your directive and call these functions in your directive. So in your example, you assign the return value of the passed in function to your scope by the given statement $scope.term = $scope.term();


text:
Q: hide custom tabbar when push I have a customized tabbar in my app. I want to hide my tabbar when pushing another viewcontroller.
Currently I implemented as this(The original tabbar has been hidden):
myViewController.hidesBottomBarWhenPushed = YES;
((CustomTabBarController *)self.tabBarController).customTabBar.hidden = YES;
[self.navigationController pushViewController:lookBookViewController animated:YES];

But when it is being pushed, it hides my customTabBar immediately. So you can see a black bottom bar in  first viewcontroller. Is there a way to fix this problem?
Thanks.

A: put your these code in - (void)viewDidDisappear:(BOOL)animated;
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    myViewController.hidesBottomBarWhenPushed = YES;
    ((CustomTabBarController *)self.tabBarController).customTabBar.hidden = YES;
}

you can design like this

and then you need not to hide the tabbar , if you want to hide it , you can use my above code , I think if you design like this , the hide effect will be you want


text:
Q: Android Spinner using Arraylist not working CityBeans.java
this is my bean used in cityArrayList
public class CityBeans implements Serializable {
        private int ;
        private String name;
        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

Home.java
 public class Home extends BaseActivity {

          private ProgressDialog dialog;
          private SectionsPagerAdapter mSectionsPagerAdapter;
          private TextView tap1, tap2;
          private String cityUrl ="http://arabnewtech.org/zoodre/public/api/locations/city/3";
          private Spinner citySpinner;
          private ArrayList<CityBeans> cityBeansList;

           @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (WrapContentViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // Create Tabs Handelation
    tabsHandel();

    // Initialize Views
    initViews();

    // City Spinner
    getCityData();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

        public void getCityData() {

        dialog = new ProgressDialog(Home.this);
        dialog.setMessage("Waiting ....");
        dialog.show();

        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        client.get(cityUrl, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                //Log.d("---Error---", responseString);
                dialog.dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                dialog.dismiss();
                Log.d("---result---", responseString);
                try {
                    JSONObject jo = new JSONObject(responseString);
                    JSONArray jo_result = jo.getJSONArray("result");
                    cityBeansList = new ArrayList<CityBeans>();
                    for (int i = 0; i < jo_result.length(); i++) {

                        CityBeans cityBean = new CityBeans();

                        JSONObject my_jo = jo_result.getJSONObject(i);
                        cityBean.setId(my_jo.getInt("id"));
                        cityBean.setName(my_jo.getString("name"));
                        cityBeansList.add(cityBean);
                    }

                    ArrayAdapter<CityBeans> adapter;
                    adapter = new ArrayAdapter<CityBeans>(Home.this, android.R.layout.simple_spinner_item, cityBeansList);
                    //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    citySpinner.setAdapter(adapter);

                } catch (Exception e) {
                    Log.i("---Result Error","Here We found error");
                    e.printStackTrace();
                }
            }
        });
    }
      }

Fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.arabnewtech.a22.zoodrealstate.Home$PlaceholderFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/spinner1">

        <Spinner
            android:id="@+id/cityID"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"></Spinner>

        <Spinner
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:layout_height="wrap_content"></Spinner>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/spinner2"
        android:layout_below="@id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Spinner
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"></Spinner>

        <Spinner
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:layout_height="wrap_content"></Spinner>
    </LinearLayout>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/ColorYellow"
        android:layout_below="@+id/spinner2"
        android:text="بحث"/>

</RelativeLayout>

A: Here is a example.
This layout created for spinner design. I stored id, and name like you.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtApplyID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

    <TextView
        android:id="@+id/txtApplyName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorBlack"
        android:textSize="18sp"
        android:layout_gravity="center_horizontal"
        />

</LinearLayout>

like your City Beans.
public class Apply
{
        private String _id;
        private String _name;

        public Apply(String id, String name)
        {
            this._id = id;
            this._name = name;
        }

        public String GetID()
        {
            return this._id;
        }

        public String GetName()
        {
            return this._name;
        }
}

custom ApplyAdapter for spinner
public class ApplyAdapter extends BaseAdapter {

        private LayoutInflater layoutInflater;
        private List<Apply> applyList;

        public ApplyAdapter(Activity activity, List<Apply> applyList)
        {
            this.layoutInflater =    (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.applyList = applyList;
        }

        @Override
        public int getCount() {
            return this.applyList.size();
        }

        @Override
        public Object getItem(int position) {
            return this.applyList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View viewerino;
            viewerino = this.layoutInflater.inflate(R.layout.spinner_apply_item, null);
  //my layout file spinner_apply_item you have to create.
            TextView id = (TextView)viewerino.findViewById(R.id.txtApplyID);
            TextView name = (TextView)viewerino.findViewById(R.id.txtApplyName);
            Apply apply = this.applyList.get(position);
            id.setText(apply.GetID());
            name.setText(apply.GetName());
            return viewerino;
        }
    }

and call it in your activity.
ApplyAdapter applyAdapter = new ApplyAdapter(MainActivity.this,this.applyList);
this.spnApply.setAdapter(applyAdapter);

there is a part of my activity layout.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout          xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.volkan.dkbilisim.MainActivity">

        <RelativeLayout
            android:id="@+id/mainRltHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/relative_design"
            android:layout_marginTop="10dp"
            >

             <Spinner
                android:id="@+id/mainSpinner"
                android:layout_width="wrap_content"
                android:layout_height="30dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="8dp"
                android:gravity="center"
                android:layout_alignParentRight="true"
                ></Spinner>

</RelativeLayout>

    </RelativeLayout>


text:
Q: Pixel position of UIImageView in coordinate system I am trapped in an interesting situation where I have values 1.4, 1.4 for x,y of rect so which pixel dot will it start putting the imageview from.. and why.. any documentation link ?
Any light on it please.
Thanks.

A: This is not something taken from any doc, but this is what happens with a quick code, ran on iOS 7 with an iPhone with retina :
view = [[UIView alloc] initWithFrame:CGRectMake(10, 50, 20, 20)];
view.backgroundColor = [UIColor greenColor];
[self.view addSubview:view];

view2 = [[UIView alloc] initWithFrame:CGRectMake(10.4, 70, 20, 20)];
view2.backgroundColor = [UIColor redColor];
[self.view addSubview:view2];

view3 = [[UIView alloc] initWithFrame:CGRectMake(11, 90, 20, 20)];
view3.backgroundColor = [UIColor blueColor];
[self.view addSubview:view3];

The first view is the reference. I know for sure from the code that its x origin is at 20px.
Be careful here, 10 points is x=20px, and 11 points is x=22px, because of the retina @2x resolution. You speak in points in code, and have a pixels result on screen.
I tried changing progressively the x coordinate. Here is what I found :

*

*9.75 < x <= 10.25 : the red square starts at x = 20px (green and red are aligned left).

*10.25 < x <= 10.75 : the red square starts at x = 21px (red is not aligned with green or blue).

*10.75 < x <= 11.25 : the red square starts at x = 22px (green and blue are aligned left).
This is based on my own observation from a quick simulation. I haven't searched for any official reference though.
Here is an image with 3 positions : 10.1, 10.4 and 10.8


text:
Q: Complicated C cast explanation I'm trying to figure out what the following code in C does?
((void(*)())buf)();

where 'buf' is a char array.

A: It casts buf to a function pointer of type void(*)() (A function returning nothing/void and taking unspecified arguments) and calls it.
The ANSI standard does not really allow the casting of normal data pointers to function pointers, but your platform may allow it.

A: I tend to use the "cdecl" command when I come across a mind boggling declaration. Example:
[me@machine]$ cdecl
Type `help' or `?' for help
cdecl> explain (void(*)())buf
cast buf into pointer to function returning void

Although there are cases where I do wish that there's a tool out there that explains the output of "cdecl" :/

A: This casts buf to the type void (*)(), a pointer to a function that takes unspecified parameters and returns nothing.  Then it calls the function at that address (the two rightmost parentheses).

A: Let's take it one step at a time.
void(*)()

This is a pointer to a function that takes unspecified arguments and has no return value.
(void(*)())buf

simply casts buf to this function pointer type. Finally,
((void(*)())buf)();

calls this function.
So the entire statement is "interpret buf as a pointer to a void function without arguments, and call that function."

A: It casts buf into a function pointer, that takes unspecified arguments, and calls it.

A:
((void(*)())buf)();
 \------------/         cast `buf` to
 \---------/            type: pointer to function accepting a fixed but
                              unspecified number of arguments and
                              returning void
\----------------/      and call that "function"

A: I would guess that in many circumstances, it crashes the machine.
Otherwise, it treats the array as a pointer to a function that returns void and invokes it.

A: You might find "expert c programming" a good read - unpacking this kind of thing is in one of the chapters, if I remember right.  It's a long time since I read it, but I remember thinking it was worth the effort at the time.
http://www.amazon.com/Expert-Programming-Peter-van-Linden/dp/0131774298

A: There is an online version of the 'cdecl' tool that lsc mentioned that you might find useful : http://www.cdecl.org/

A: calls a function pointer. the function has no arguments.
Function Pointer - Wikipedia


text:
Q: stm32: How to configurate SWV on software part without autogenerated code, HAL or LL I am currently working on a library that abstracts the use of a stm board (specifically the NUCLEO-H723ZG) and we are on the profiling phase. I did get to make the profiling with the SWV after a big headache with the SB26 bridge that comes with the aforementioned board, using the auto generated code from stm32cubeIDE.
Now i need to do the same but abstracting the auto generated code from the stm32cubeIDE into a method that does all the configuration for you, but i cannot pin point what is really missing. I already have copied the SystemClock config, the PeriphCommonClock config, both SCB_Enable Cache and the MPU_Config (and yes both are using the same copy of the ioc configuration). Any ideas of what i could be missing?
I tried to profile an autogenerated main.c and after some configuration it worked perfectly.
Then i tried to do the same with a main.cpp and copying the methods form the autogenerated main one by one (just to see whose were needed) and after copying them all it didn t work. The code executes and the live expressions work. The configurations are the same on the .ioc and the debugging.
I m now looking for the minimum necessary for an SWV configuration method, preferably non dependant from HAL.


text:
Q: Is this nameof() truly a recursive call? I'm making a ConfigurationSection in C# right now. I decided to take advantage of some C# 6 features by using nameof(PropertyName) instead of hard coded strings.
However, I'm getting a weird result from Resharper about a recursive call.
Here's an example:

I can see why it might give this warning, as the property is being referenced within itself. I'm not convinced however that this is actually recursive.
Is there anything I have to worry about with this call?

A: Unless this[string] calls CoreApiRootUrl, then it's not recursive.
You're right that nameof(...) doesn't actually make a call at all.
I've just validated that I see the same bug (with R# 10.0.1) in a small test class:
public class Bug
{
    public string this[string x] => "";

    public string Foo
    {
        get { return this[nameof(Foo)]; } // Warning here
    }
}

Oddly enough, if I change Foo to an expression-bodied property:
public string Foo => this[nameof(Foo)];

I don't see the warning.
Definitely a R# bug - file it with Jetbrains.


text:
Q: Implementing Pan without Zooming on XYPlot (androidplot 1.2.2) I would like to implement pan on my plot without zooming, by setting a origin value smaller than may lower boundaries on domain axis.
My code so far :
this.panZoom = PanZoom.attach(plot);
this.panZoom.setPan(PanZoom.Pan.HORIZONTAL);
this.panZoom.setZoom(null);
this.panZoom.setDelegate(this);

this.plot.setUserDomainOrigin(0);
this.plot.setDomainBoundaries(5, 20);
this.plot.setDomainStep(StepMode.INCREMENT_BY_VAL, 2);

By doing this, my plot starts well at 5 but won't move when I scroll..
I'm migrating my project to androidPlot 1.2.2 and it was working with 0.9.7
Thanks!

A: This appears to be a limitation in Androidplot 1.2.2 (Will be fixed in the next release - tracked by this bug report.)
For now you can add this implementation of PanZoom in your project:
package com.androidplot.xy;

import android.graphics.RectF;
import android.graphics.PointF;
import android.util.*;
import android.view.*;

import com.androidplot.*;

import java.util.*;

/**
 * Enables basic pan/zoom touch behavior for an {@link XYPlot}.
 * By default boundaries set on the associated plot will define the scroll/zoom extents as well as
 * initial state of the plot's visible area.  If you wish to specify a scrollable / zoomable area
 * that is greater than or less than the plot's boundaries, use
 * {@link #setDomainBoundaries(Number, Number)} and
 * {@link #setRangeBoundaries(Number, Number)}
 * TODO: zoom using dynamic center point
 * TODO: stretch both mode
 */
public class PanZoom implements View.OnTouchListener {

    protected static final float MIN_DIST_2_FING = 5f;
    protected static final int FIRST_FINGER = 0;
    protected static final int SECOND_FINGER = 1;

    private XYPlot plot;
    private Pan pan;
    private Zoom zoom;
    private boolean isEnabled = true;

    private DragState dragState = DragState.NONE;
    RectRegion limits = new RectRegion();
    RectRegion previousLimits = new RectRegion();
    private PointF firstFingerPos;

    // rectangle created by the space between two fingers
    private RectF fingersRect;
    private View.OnTouchListener delegate;

    // Definition of the touch states
    protected enum DragState {
        NONE,
        ONE_FINGER,
        TWO_FINGERS
    }

    public enum Pan {
        NONE,
        HORIZONTAL,
        VERTICAL,
        BOTH
    }

    public enum Zoom {

        /**
         * Comletely disable panning
         */
        NONE,

        /**
         * Zoom on the horizontal axis only
         */
        STRETCH_HORIZONTAL,

        /**
         * Zoom on the vertical axis only
         */
        STRETCH_VERTICAL,

        /**
         * Zoom on the vertical axis by the vertical distance between each finger, while zooming
         * on the horizontal axis by the horizantal distance between each finger.
         */
        STRETCH_BOTH,

        /**
         * Zoom each axis by the same amount, specifically the total distance between each finger.
         */
        SCALE
    }

    protected PanZoom(XYPlot plot, Pan pan, Zoom zoom) {
        this.plot = plot;
        this.pan = pan;
        this.zoom = zoom;
    }

    /**
     * Convenience method for enabling pan/zoom behavior on an instance of {@link XYPlot}, using
     * a default behavior of {@link Pan#BOTH} and {@link Zoom#SCALE}.
     * Use {@link PanZoom#attach(XYPlot, Pan, Zoom)} for finer grain control of this behavior.
     * @param plot
     * @return
     */
    public static PanZoom attach(XYPlot plot) {
        return attach(plot, Pan.BOTH, Zoom.SCALE);
    }

    public static PanZoom attach(XYPlot plot, Pan pan, Zoom zoom) {
        PanZoom pz = new PanZoom(plot, pan, zoom);
        plot.setOnTouchListener(pz);
        return pz;
    }

    public boolean isEnabled() {
        return isEnabled;
    }

    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    /**
     * Set the boundaries by which domain pan/zoom calculations will abide; differs from an {@link XYPlot}'s boundaries
     * in that those boundaries define the plot's starting state.
     * @param lowerBoundary
     * @param upperBoundary
     */
    public void setDomainBoundaries(final Number lowerBoundary, final Number upperBoundary) {
        limits.setMinX(lowerBoundary);
        limits.setMaxX(upperBoundary);
    }

    /**
     * Sets the range boundaries by which pan/zoom calculations will abide.
     * @param lowerBoundary
     * @param upperBoundary
     */
    public void setRangeBoundaries(final Number lowerBoundary, final Number upperBoundary) {
        limits.setMinY(lowerBoundary);
        limits.setMaxY(upperBoundary);
    }

    @Override
    public boolean onTouch(final View view, final MotionEvent event) {
        boolean isConsumed = false;
        if (delegate != null) {
            isConsumed = delegate.onTouch(view, event);
        }
        if (isEnabled() && !isConsumed) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN: // start gesture
                    firstFingerPos = new PointF(event.getX(), event.getY());
                    Log.d("PanZoom", "ONE_FINGER set");
                    dragState = DragState.ONE_FINGER;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN: // second finger
                {
                    fingersRect = fingerDistance(event);
                    Log.d("PanZoom", "ACTION_POINTER_DOWN - distance: " + fingersRect.width());
                    // the distance check is done to avoid false alarms
                    if (fingersRect.width() > MIN_DIST_2_FING || fingersRect.width() < -MIN_DIST_2_FING) {
                        Log.d("PanZoom", "TWO_FINGERS set");
                        dragState = DragState.TWO_FINGERS;
                    }
                    break;
                }
                case MotionEvent.ACTION_POINTER_UP: // end zoom
                    dragState = DragState.NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (dragState == DragState.ONE_FINGER) {
                        Log.d("PanZoom", "ACTION_MOVE - one finger");
                        pan(event);
                    } else if (dragState == DragState.TWO_FINGERS) {
                        Log.d("PanZoom", "ACTION_MOVE - two fingers");
                        zoom(event);
                    }
                    break;
            }
        }
        // we're forced to consume the event here as not consuming it will prevent future calls:
        return true;
    }

    /**
     * Calculates the distance between two finger motion events.
     * @param firstFingerX
     * @param firstFingerY
     * @param secondFingerX
     * @param secondFingerY
     * @return
     */
    protected RectF fingerDistance(float firstFingerX, float firstFingerY, float secondFingerX, float secondFingerY) {
        final float left = firstFingerX > secondFingerX ? secondFingerX : firstFingerX;
        final float right = firstFingerX > secondFingerX ? firstFingerX : secondFingerX;
        final float top = firstFingerY > secondFingerY ? secondFingerY : firstFingerY;
        final float bottom = firstFingerY > secondFingerY ? firstFingerY : secondFingerY;
        return new RectF(left, top, right, bottom);
    }

    /**
     * Calculates the distance between two finger motion events.
     * @param evt
     * @return
     */
    protected RectF fingerDistance(final MotionEvent evt) {
        return fingerDistance(
                evt.getX(FIRST_FINGER),
                evt.getY(FIRST_FINGER),
                evt.getX(SECOND_FINGER),
                evt.getY(SECOND_FINGER));
    }

    protected Number getMinXLimit() {
        if (limits.getMinX() == null) {
            limits.setMinX(plot.getBounds().getMinX().floatValue());
            previousLimits.setMinX(limits.getMinX());
        }
        return limits.getMinX();
    }

    protected Number getMaxXLimit() {
        if (limits.getMaxX() == null) {
            limits.setMaxX(plot.getBounds().getMaxX().floatValue());
            previousLimits.setMaxX(limits.getMaxX());
        }
        return limits.getMaxX();
    }

    protected Number getMinYLimit() {
        if (limits.getMinY() == null) {
            limits.setMinY(plot.getBounds().getMinY().floatValue());
            previousLimits.setMinY(limits.getMinY());
        }
        return limits.getMinY();
    }

    protected Number getMaxYLimit() {
        if (limits.getMaxY() == null) {
            limits.setMaxY(plot.getBounds().getMaxY().floatValue());
            previousLimits.setMaxY(limits.getMaxY());
        }
        return limits.getMaxY();
    }

    protected Number getLastMinX() {
        if (previousLimits.getMinX() == null) {
            previousLimits.setMinX(plot.getBounds().getMinX().floatValue());
        }
        return previousLimits.getMinX();
    }

    protected Number getLastMaxX() {
        if (previousLimits.getMaxX() == null) {
            previousLimits.setMaxX(plot.getBounds().getMaxX().floatValue());
        }
        return previousLimits.getMaxX();
    }

    protected Number getLastMinY() {
        if (previousLimits.getMinY() == null) {
            previousLimits.setMinY(plot.getBounds().getMinY().floatValue());
        }
        return previousLimits.getMinY();
    }

    private Number getLastMaxY() {
        if (previousLimits.getMaxY() == null) {
            previousLimits.setMaxY(plot.getBounds().getMaxY().floatValue());
        }
        return previousLimits.getMaxY();
    }

    protected void pan(final MotionEvent motionEvent) {
        if (pan == Pan.NONE) {
            return;
        }

        final PointF oldFirstFinger = firstFingerPos; //save old position of finger
        firstFingerPos = new PointF(motionEvent.getX(), motionEvent.getY()); //update finger position
        Region newBounds = new Region();
        if (EnumSet.of(Pan.HORIZONTAL, Pan.BOTH).contains(pan)) {
            calculatePan(oldFirstFinger, newBounds, true);
            plot.setDomainBoundaries(newBounds.getMin(), newBounds.getMax(), BoundaryMode.FIXED);
            previousLimits.setMinX(newBounds.getMin());
            previousLimits.setMaxX(newBounds.getMax());
        }
        if (EnumSet.of(Pan.VERTICAL, Pan.BOTH).contains(pan)) {
            calculatePan(oldFirstFinger, newBounds, false);
            plot.setRangeBoundaries(newBounds.getMin(), newBounds.getMax(), BoundaryMode.FIXED);
            previousLimits.setMinY(newBounds.getMin());
            previousLimits.setMaxY(newBounds.getMax());
        }
        plot.redraw();
    }

    protected void calculatePan(final PointF oldFirstFinger, Region bounds, final boolean horizontal) {
        final float offset;
        // multiply the absolute finger movement for a factor.
        // the factor is dependent on the calculated min and max
        if (horizontal) {
            bounds.setMin(getLastMinX());
            bounds.setMax(getLastMaxX());
            offset = (oldFirstFinger.x - firstFingerPos.x) *
                    ((bounds.getMax().floatValue() - bounds.getMin().floatValue()) / plot.getWidth());
        } else {
            bounds.setMin(getLastMinY());
            bounds.setMax(getLastMaxY());
            offset = -(oldFirstFinger.y - firstFingerPos.y) *
                    ((bounds.getMax().floatValue() - bounds.getMin().floatValue()) / plot.getHeight());
        }
        // move the calculated offset
        bounds.setMin(bounds.getMin().floatValue() + offset);
        bounds.setMax(bounds.getMax().floatValue() + offset);

        //get the distance between max and min
        final float diff = bounds.length().floatValue();

        //check if we reached the limit of panning
        if (horizontal) {
            if (bounds.getMin().floatValue() < getMinXLimit().floatValue()) {
                bounds.setMin(getMinXLimit());
                bounds.setMax(bounds.getMin().floatValue() + diff);
            }
            if (bounds.getMax().floatValue() > getMaxXLimit().floatValue()) {
                bounds.setMax(getMaxXLimit());
                bounds.setMin(bounds.getMax().floatValue() - diff);
            }
        } else {
            if (bounds.getMin().floatValue() < getMinYLimit().floatValue()) {
                bounds.setMin(getMinYLimit());
                bounds.setMax(bounds.getMin().floatValue() + diff);
            }
            if (bounds.getMax().floatValue() > getMaxYLimit().floatValue()) {
                bounds.setMax(getMaxYLimit());
                bounds.setMin(bounds.getMax().floatValue() - diff);
            }
        }
    }

    protected boolean isValidScale(float scale) {
        if (Float.isInfinite(scale) || Float.isNaN(scale) || scale > -0.001 && scale < 0.001) {
            return false;
        }
        return true;
    }

    protected void zoom(final MotionEvent motionEvent) {
        if (zoom == Zoom.NONE) {
            return;
        }
        final RectF oldFingersRect = fingersRect;
        final RectF newFingersRect = fingerDistance(motionEvent);
        fingersRect = newFingersRect;
        RectF newRect = new RectF();

        float scaleX = 1;
        float scaleY = 1;
        switch (zoom) {
            case STRETCH_HORIZONTAL:
                scaleX = oldFingersRect.width() / fingersRect.width();
                if (!isValidScale(scaleX)) {
                    return;
                }
                break;
            case STRETCH_VERTICAL:
                scaleY = oldFingersRect.height() / fingersRect.height();
                if (!isValidScale(scaleY)) {
                    return;
                }
                break;
            case STRETCH_BOTH:
                scaleX = oldFingersRect.width() / fingersRect.width();
                scaleY = oldFingersRect.height() / fingersRect.height();
                if (!isValidScale(scaleX) || !isValidScale(scaleY)) {
                    return;
                }
                break;
            case SCALE:
                float sc1 = (float) Math.hypot(oldFingersRect.height(), oldFingersRect.width());
                float sc2 = (float) Math.hypot(fingersRect.height(), fingersRect.width());
                float sc = sc1 / sc2;
                scaleX = sc;
                scaleY = sc;
                if (!isValidScale(scaleX) || !isValidScale(scaleY)) {
                    return;
                }
                break;
        }

        if (EnumSet.of(
                Zoom.STRETCH_HORIZONTAL,
                Zoom.STRETCH_BOTH,
                Zoom.SCALE).contains(zoom)) {
            calculateZoom(newRect, scaleX, true);
            plot.setDomainBoundaries(newRect.left, newRect.right, BoundaryMode.FIXED);
            previousLimits.setMinX(newRect.left);
            previousLimits.setMaxX(newRect.right);
        }
        if (EnumSet.of(
                Zoom.STRETCH_VERTICAL,
                Zoom.STRETCH_BOTH,
                Zoom.SCALE).contains(zoom)) {
            calculateZoom(newRect, scaleY, false);
            plot.setRangeBoundaries(newRect.top, newRect.bottom, BoundaryMode.FIXED);
            previousLimits.setMinY(newRect.top);
            previousLimits.setMaxY(newRect.bottom);
        }
        plot.redraw();
    }

    protected void calculateZoom(RectF newRect, float scale, boolean isHorizontal) {

        final float calcMax;
        final float span;
        if (isHorizontal) {
            calcMax = getLastMaxX().floatValue();
            span = calcMax - getLastMinX().floatValue();
        } else {
            calcMax = getLastMaxY().floatValue();
            span = calcMax - getLastMinY().floatValue();
        }

        final float midPoint = calcMax - (span / 2.0f);
        final float offset = span * scale / 2.0f;

        if (isHorizontal) {
            newRect.left = midPoint - offset;
            newRect.right = midPoint + offset;
            if (newRect.left < getMinXLimit().floatValue()) {
                newRect.left = getMinXLimit().floatValue();
            }
            if (newRect.right > getMaxXLimit().floatValue()) {
                newRect.right = getMaxXLimit().floatValue();
            }
        } else {
            newRect.top = midPoint - offset;
            newRect.bottom = midPoint + offset;
            if (newRect.top < getMinYLimit().floatValue()) {
                newRect.top = getMinYLimit().floatValue();
            }
            if (newRect.bottom > getMaxYLimit().floatValue()) {
                newRect.bottom = getMaxYLimit().floatValue();
            }
        }
    }

    public Pan getPan() {
        return pan;
    }

    public void setPan(Pan pan) {
        this.pan = pan;
    }

    public Zoom getZoom() {
        return zoom;
    }

    public void setZoom(Zoom zoom) {
        this.zoom = zoom;
    }

    public View.OnTouchListener getDelegate() {
        return delegate;
    }

    /**
     * Set a delegate to receive onTouch calls before this class does.  If the delegate wishes
     * to consume the event, it should return true, otherwise it should return false.  Returning
     * false will not prevent future onTouch events from filtering through the delegate as it normally
     * would when attaching directly to an instance of {@link View}.
     * @param delegate
     */
    public void setDelegate(View.OnTouchListener delegate) {
        this.delegate = delegate;
    }

    public void reset() {
        this.previousLimits = new RectRegion();
        this.firstFingerPos = null;
        this.fingersRect = null;
    }
}

Don't forget to change the class name to avoid a collision with the existing PanZoom implementation.
If you want to constrain the starting window bounds to a sub-section of your data, set those boundaries on the XYPlot instance as normal.  Then, configure the PanZoom instance with the absolute boundaries for panning and zooming, typically the min/max values of the series attached to your plot.
Also, if you need to change the visible window after your initial setup in onCreate (result of a user pressing a reset button, etc.)  you'll also need to invoke PanZoom.reset() to wipe out it's internal state.  This step may  not be necessary in the official release implementation.


text:
Q: publishing notification from a thread running continuously in a service I have a service and in that service i have a thread. The thread has a Runnable. From the runnable i am try to publish notification but i am getting this error.
The method setLatestEventInfo(Context, CharSequence, CharSequence, PendingIntent) in the type Notification is not applicable for the arguments (new Runnable(){}, CharSequence, CharSequence, PendingIntent)

If i try to publish from outside the thread, everything works fine.
My application continuously gets a response from the server. When there is updated data from the server and the app is not running a new notification is created. To avoid running on the main thread, i created a new thread.

A: Referencing this inside a Runnable does not refer to the instance of Context (your Service or Activity) but to the Runnable instance.
Try the following:
final Context context = this;
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        ...
        setLatestInfo(context, charsequence1, charsequence2, pendingIntent);
    }
}

A: It looks like the Context you defined is the problem. you should have the context of an activity or an application.


text:
Q: System.FormatException while Reading File Visual Studio puts me an Exception on this line but why ?
 RechenKontostand = Convert.ToDouble(File.ReadAllText(pathkonto));

The Exception is:

System.FormatException wrong Format

If you need more Code just ask!
Nothin of the other answers solve my Problem so it isn´t a duplicate

A: Because the string passed to Convert.ToDouble was not in an acceptable format. When you pass a string to this method, it ends up calling double.Parse
The documentation explains that a FormatException is raised when:

s does not represent a number in a valid format.


text:
Q: Why is my AngularJS code not working? Please can you help me fix this script:
var newsFeed = angular.module('newsFeed', []);

var newsFeedModule = angular.module('newsFeed');

newsFeedModule.controller('newsFeedController', function($scope) {
    $scope.posterWidth = 100;
    $scope.posterHeight = 60;

});

html:

    {{ 2+3 }}
    {{ posterWidth }}

I made a simple AngularJS Script that is going to display the variable and expressions as above. But the values are not being calculated. I have tried a few times and you can see the JSFiddle below.
JSFIDDLE

A: In JSFiddle you need to to click on the JAVASCRIPT Button and need to select angular 1.4.8 in Frameworks & Extensions dropdown and then select No wrap in head option in Load type dropdown .... now it will work

JSFIDDLE

A: working example
https://jsfiddle.net/yeLm5j8u/3/
<!DOCTYPE html>

    {{ 2+3 }}
    {{ posterWidth }}

A: You do need to include AngularJS!


text:
Q: Onclick background value change to HTML tag in CSS I have my page setup and navigation in order. I also have my background image appearing correctly. Now my goal is to make the background image change onclick.
My background is achieved in a "general.css" style sheet
html {
  background: url(../images/bg1.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

My navigation have its own "nav.css" and "nav.js" and the current click function is
$('#action1').click(
    function(){
        if ($('#inner1').height() == 0 )
        $('#inner1').animate({height:'250'},800);
        else  if ($('#inner1').height() == 250 )
        $('#inner1').animate({height:'0'},800);
    }
);

I would like when you click action1, action2, or action3 it changes the url of the image under the html style to a UNIQUE background. I will have 3 separate backgrounds for each onclick. (below)
background: url(../images/bg1.jpg) no-repeat center center fixed;

If anyone could give me some tips on how to change just the URL value onclick it would be much appreciated. I need the background url to change but not the other styles. Last example below.
html {
  background: url(   CHANGE THIS VALUE ONCLICK   ) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

A: Have you tried using jQuery's CSS function?
So adding a line such as this to the click listener could work:
$('html').css("background-image", "url(../images/bg1.jpg)");


text:
Q: How to refer to other XML file within a XPath 3 query I am using the XML editor Pathology for Mac. It is based on Panthro, an open-source implementation of XPath 3.0 in Objective-C/Cocoa.
I want to make a query over the file "Bookstore.xml" referencing to other XML file ("Bookstore2.xml"):
doc("Bookstore.xml")//Magazine[Title = doc("Bookstore2.xml")//Book/Title]

But the program says "Call to unknown function: doc()". How do I refer to other XML files? What am I missing?
BTW, I checked other answers like this one. But I did not get anything clear.
Many thx.

A: Developer of Pathology here. Sorry, but Panthro – the XPath engine which I developed myself and which powers Pathology – doesn't support the doc() function.
The biggest reason I haven't implemented this function is that Pathology is primarily sold through the Mac App Store, and therefore must be a "sandboxed app" according to Apple's rather strict rules for Mac App Store apps. Sandboxed apps cannot open arbitrary files on your Mac without direct user intervention via the GUI, but that's exactly what the doc() function does.
Basically, the doc() function is inherently incompatible with the concept of a sandboxed Mac app, and since the purpose of Panthro is to power Pathology, and Pathology is a Mac app sold via the Mac App Store, I've avoided implementing doc() to avoid this inherent incompatibility.
I know this is not a very satisfying answer, but the situation is a difficult one. Apple's "sandboxing" restrictions have benefits and drawbacks. Unfortunately, this is one of the drawbacks.


text:
Q: why doesn't this erlang code work? fib(N)->
       P1 = spawn(fun concFib:conFib/0),
       P2 = spawn(fun concFib:conFib/0),
       X=rpc(P1,N-2),Y=rpc(P2,N-1),X+Y.

conFib()->
       receive
               {Client,N} -> Client ! regfib(N)
       end.

rpc(Pid,Request)->
       case erlang:is_process_alive(Pid) of
               true -> begin
                                       Pid ! {self(),Request},
                                       receive
                                               {Pid,Respond} -> Respond
                                       end
                               end;
               false -> io:format("~w process is dead.",[Pid])
       end.

regfib(N)->
       case N<2 of
               true -> 1;
               false -> regfib(N,1,1,1)
       end.

regfib(N,N,X,_)-> X ;
regfib(N,M,X,Y)-> regfib(N,M+1,X+Y,X).

The idea is to divide the fib(N) process into two process one calculates fib(N-2) and the other one calc. fib(N-1) concurrently as fib(N)=fib(N-1)+fib(N-2). when i run the previous code nothing happen and the cursor stop as in finite loop or waiting for not arriving result.
plzzz i need help i'm a new Erlang programmer,thanks in advance :)

A: In your conFib you send an integer, but await a tuple in rpc. Should change it to:
conFib()->
       receive
               {Client,N} -> Client ! {self(), regfib(N)}
       end.

You can evade such situations by using timeout with after in your receives.

A: To make the computation parallel you could do something like:
fib(N)->
       P1 = spawn(fun test:conFib/0),
       P2 = spawn(fun test:conFib/0),
       P1 ! {self(), N - 2},
       P2 ! {self(), N - 1},
       receive
         {_, R1} -> R1
       end,
       receive
         {_, R2} -> R2
       end,
        R1 + R2.

The important part is that you send both of the requests before waiting for the answers.
The part waiting for the answers could of course be done in a more beautiful way.


text:
Q: SSD Drive - external vs Internal I have 2 computers, a faster iMac at work (i5) and an old macbook (C2DUO 2.0Ghz) at home.
The macbook at home has a SSD drive in it, I upgraded it and it's performance is really great.
Now I was wondering, instead of having to my macbook to work everyday, would be worth it to take the SSD out and boot into it from an external case?? This way I only need to take the drive and just plug it in.
I only have an uSB2 case.

A: Yes, you can do it. Depending on the quirks of OS/X you may need to different OS installations on the SSD. That would be slightly more space using, but not a real problem.
However USB2 is slow. Sequential transfer rates via the USB2 bus are about 35MB/second, way slows than a HDD or a SSD.  You would gain some performance gain on random IOs, but I expect the nett result to be a lot slower.
Now if you can replace the external USB casing with something faster (e.g. eSATA or thunderbolt) then: Yes, it will work and be a lot faster.


text:
Q: flagship Merchent Account Payment gateway hello i have to integrate flagship merchant services on my project.But i don't have any idea about this.if any person any idea about this or have any api regarding this please let me know .I have also integrate reoccurring payment service in this.So if any body has worked on this payment express please provide me the api or the flow so i can integrate this as soon as possible
My project is in php so need api in php

A: I believe you're referring to this Flagship Merchant Services. According to their FAQ, you need an Internet merchant account with them before they'll provide you with the First Data Global Gateway API to interface with their payment gateway.
I worked on similiar integration code with a local credit card processing provider and they only provide the interface API only when the client has signed up an account with the provider. Presumably, it's for security purposes (at least security through obscurity)


text:
Q: overriding function calls from SVML The Xeon-Phi Knights Landing cores have a fast exp2 instruction vexp2pd (intrinsic _mm512_exp2a23_pd). The Intel C++ compiler can vectorize the exp function using the Short Vector Math Library (SVML) which comes with the compiler.  Specifically, it calls the fuction __svml_exp8.
However, when I step through a debugger I don't see that __svml_exp8 uses the vexp2pd instruction. It is a complication function with many FMA operations. I understand that vexp2pd is less accurate than exp but if I use -fp-model fast=1 (the default) or fp-model fast=2 I expect the compiler to use this instruction but it does not.
I have two questions.

*

*Is there a way to get the compiler to use vexp2pd?

*How do I safely override the call to __svml_exp8?

As to the second question this is what I have done so far.
//exp(x) = exp2(log2(e)*x)
extern "C" __m512d __svml_exp8(__m512d x) {
    return _mm512_exp2a23_pd(_mm512_mul_pd(_mm512_set1_pd(M_LOG2E), x));
}

Is this safe? Is there a better solution e.g. one that inlines the function? In the test code below this is about 3 times faster than if I don't override.
//https://godbolt.org/g/adI11c
//icpc -O3 -xMIC-AVX512 foo.cpp
#include <math.h>
#include <stdio.h>
#include <x86intrin.h>

extern "C" __m512d __svml_exp8(__m512d x) {
  //exp(x) = exp2(log2(e)*x)
  return _mm512_exp2a23_pd(_mm512_mul_pd(_mm512_set1_pd(M_LOG2E), x));
}

void foo(double * __restrict x, double * __restrict y) {
  __assume_aligned(x, 64);
  __assume_aligned(y, 64);
  for(int i=0; i<1024; i++) y[i] = exp(x[i]);
}

int main(void) {
  double x[1024], y[1024];
  for(int i=0; i<1024; i++) x[i] = 1.0*i;
  for(int r=0; r<1000000; r++) foo(x,y);
  double sum=0;
  //for(int i=0; i<1024; i++) sum+=y[i];
  for(int i=0; i<8; i++) printf("%f ", y[i]); puts("");
  //printf("%lf",sum);
}

A: ICC will generate vexp2pd but only under very much relaxed math requirements as specified by targeted -fimf* switches.
#include <math.h>

void vfoo(int n, double * a, double * r)
{
    int i;
    #pragma simd
    for ( i = 0; i < n; i++ )
    {
        r[i] = exp(a[i]);
    }
}

E.g. compile with -xMIC-AVX512 -fimf-domain-exclusion=1 -fimf-accuracy-bits=22
..B1.12:
        vmovups   (%rsi,%rax,8), %zmm0
        vmulpd    .L_2il0floatpacket.2(%rip){1to8}, %zmm0, %zmm1
        vexp2pd   %zmm1, %zmm2
        vmovupd   %zmm2, (%rcx,%rax,8)
        addq      $8, %rax
        cmpq      %r8, %rax
        jb        ..B1.12

Please be sure to understand the accuracy implications as not only the end result is only about 22 bits accurate, but the vexp2pd also flushes to zero any denormalized results irrespective of the FTZ/DAZ bits set in the MXCSR.
To the second question: "How do I safely override the call to __svml_exp8?"
Your approach is generally not safe. SVML routines are internal to Intel Compiler and rely on custom calling conventions, so a generic routine with the same name can potentially clobber more registers than a library routine would, and you may end up in a hard-to-debug ABI mismatch.
A better way of providing your own vector functions would be to utilize #pragma omp declare simd, e.g. see https://software.intel.com/en-us/node/524514 and possibly the vector_variant attribute if prefer coding with intrinsics, see https://software.intel.com/en-us/node/523350. Just don't try to override standard math names or you'll get an error.


text:
Q: Git, repo, and keeping things in sync I've searched the site for answers to this, and while I've learned a lot, I still have an issue that maybe someone can help with.
Our deb team has an internal Android repository forked from a google branch. We have to work with a customer, so I've set up a cron job to sync the repo on a customer-accessible machine. This makes the internal repository the master.
Now, of course, I have the customer needing to push updates, and they only have access to the external server. This leads to a conundrum: if I don't use "repo sync" to maintain the external repository staying in sync with the internal, it will effectively blow away any changes the customer pushes to the external repository mirror.
The most logical solution would be to make the external the master and force the internal to sync off of it, but I don't think I can convince the deb team to do that.
I've thought about post-commit hooks to sync with the internal, but it seems like they work only on an individual git repository, and I'd have to find all of the .git/post-commit files to make the change.
Is there any easier way to make this happen?

A: You should consider the external repo a fork of the internal repo and merge your results at appropriate times.
It really depends how you are working together with your external team.
But I assume you are working on similar code, so you would be merging back to the internal repo after a code review(?).
Your internal team is also working on forks of the repos, just locally.  They may or may not have access to push directly to the repo - not sure.
You have to decide on your merge strategy, what gatekeeper you have between the repos, if none, then you should setup 2 post-receive hooks, one on the internal and the other on the external to keep the two repos in constant sync (initiate a pull/push to/from the other repo).
If you get an error in the hooks, you will have to manually correct the issue most likely - so remember to shoot out emails.


text:
Q: Google Actions - Disabling "Sign in required for welcome intent" doesn't work I'm developing a Google Action, and while I was implementing account linking, I turned on the "Sign in required for welcome intent" checkbox in the API.AI settings panel.
So the user flow was:

User: Talk to cool app
-> User gets the account linking message

Now that my setup is working, I want to postpone account linking to be requested on a specific action in my app, and not on the welcome intent.
So what I want to happen is (fictive dialog :) ):

User: Talk to cool app
My app: Hi, I am cool app, what can I do for
you?
User: Be cool
My app: I am so cool. Would you like to link
accounts?
User: Yes
--> User gets the account linking message

I disabled the checkbox, but the app is still requesting to link on the welcome intent. Is it a bug in API.AI? Is it possible at all to ask for account linking in a later stage in the app? And if so, how?

But this is still happening:


text:
Q: Reasons for filament LED bulb failure? I recently purchased a filament LED bulb. However, when installed (AC 220V), it wasn't working well: it had a very low light. But sometimes (~ every 5min) it lights up for a few seconds at its normal power.
If the LED was really broken it wouldn't emit at full power, even for a short time. So what can be other problem to check?
NB: Doesn't seem to be a bad contact, it was very deeply plugged in the socket, and other bulbs work well in the socket.


text:
Q: Dynamically loaded assembly in Silverlight calles DllImprot which locks the file I've quite specific problem with my Silvelight 5 application:
I've application which dynamically loads Silverlight libraries (could be many) and those libraries are callings methods via dllimport.
The reason: application for different scanning devices. Silverlight library is for logic, C++ library is from producer and connects with device. Could be many silverlight libraries and they must be load in runtime.
Problem: after loading Silverlight library and scanning - I can't access file with C++ library. Why I must ? If user tries to pick scanner, I calculate hash code of library to check if there's newer version on the server.
My implementation:
ViewModel is calling method to get current scanner class:
 using (var stream = new IsolatedStorageFileStream(scanner.DirectoryName + Path.DirectorySeparatorChar + scanner.ScannerLibraryName, System.IO.FileMode.Open, store))
    {
      AssemblyPart assemblyPart = new AssemblyPart();
      Assembly assembly = assemblyPart.Load(stream);
      return (Scanner)assembly.CreateInstance(scanner.ClassName);
    }

Later there's scanning:
        this.userScanner.LoadProducerLibrary();
        result = userScanner.ScanDocument();
        this.userScanner.FreeProducerLibrary();

LoadProducerLibrary calls:
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string lpFileName);

ScanDocument calls some third part methods also via dllimport.
FreeProducerLibray calls:
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)] /* unnecessary, isn't it? */
public static extern bool FreeLibrary(IntPtr hModule);

After that, I've a method in different viewmodel which tries to open producer library file to calculate hash code and I get "Cannot access the file, because it is being used by another process".
I've tried to calculate hash code in Scanner class (dynamically load assembly) and it was all right so I suspect it is this process. But why FreeLibrary is not enough ?
Could You point me with some advises ? Should I try to dispose somehow userScanner field ?

A:
ScanDocument calls some third part methods also via dllimport.

You left the most important code out of the question, but that statement is enough to diagnose your problem.  The pinvoke marshaller also calls LoadLibrary() on the DLL.  So the reference count for the DLL is two.  Your FreeLibrary() call does not unload it and the file stays locked.
You can hack around that by calling FreeLibrary() one more time.  That will unload the DLL but that also arms a time-bomb in your program.  You cannot safely make these calls again.  The pinvoke marshaller is still convinced that the DLL is loaded so it will not re-generate the stubs that it generated for the imported functions.  They point to the addresses where the functions used to be loaded, not where they are loaded now.  It will seem to work, particularly when you do this in an artificial test.  But sooner or later, the DLL cannot get reloaded at the same address again because the address space for it was used for something else and your program will fail with a hard crash.
If you want to make this work then you cannot use [DllImport] for these methods.  You must instead do the work that the pinvoke marshaller does and call GetProcAddress() for every entrypoint you use and make it callable with Marshal.GetDelegateForFunctionPointer(), using delegates you declared that match the native function signature.  Works, it is not pretty.
The better alternative is to use a separate helper process that makes these calls and interop with it.  Now it is safe, letting that helper process terminate ensures that the pinvoke stubs are gone and the DLL is unlocked.  Not sure what's practical in Silverlight, it wasn't really designed with process interop high on the feature list.  No Process class, that puts a chink in the approach.


text:
Q: How to list all methods in a Java class with regex is there any way to search all methods in Java class with regex?

A: (public|protected|private|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;])

With this you can, but search before ask, because i only have used the search to find this answer ^^.

A: I think you're looking for reflection - see this tutorial for help. Only through reflection can you access information about loaded classes - unless you're thinking of loading in the .java file and analyzing its text.


text:
Q: Prevent Eclipse from converting @ character in  javadoc tags to @ I have a Javadoc comments for one of my package (package-info.java) that basically looks like this:

/**
 *

 * {@code
 * // Some comments...
 * final Foo<Integer> foo = new Foo<>(0);
 * }
 *

 *
 */
package com.holt.mypackage;

I also have enabled Save Actions with a Format all lines in the project properties. Each time I save the file, Eclipse replace {@code with:

* {
*   @code

...completely breaking my Javadoc.

I tried using
 and  manually, but then the Maven javadoc plugin complains about invalid characters < and > in HTML (due to Foo<>). If I disable Save Actions, everything works well from Eclipse to Maven.

Is there a way to tell Eclipse not to replace such characters?

A: As specified here you have to "turn of the Format Java code snippets inside 'pre' tag setting":

*

*Window > Preferences

*Java > Code Style > Formatter

*If you do not have a custom profile click on New...

*Edit...

*Comments > Uncheck Format Java code snippets ...
As a result Eclipse IDE won't format the content of
 tags anymore.
If you still want to benefit from formatting I advise you to use the  tag. You just have to escape the <> characters properly as shown below:
/**
 *

 *
 * // Some comments...
 * final Foo<Integer> foo = new Foo<>(0);
 * }
 *
 *

 *
 */
package com.holt.mypackage;

See this SO answer.


text:
Q: tkinter entry boxes - optional input I have four entry boxes in my gui and whatever information I put in there, .get() works as it should. The problem starts further below on the conditions. The reason for these entry boxes is the filtering of a dataframe
The first condition has several conditions within with OR (|). These conditions are packed as "conditionORall", the other conditions have one condition at the time. The goal is to filter a dataframe based on user input. With this code, this works only if I fill out all four entry boxes as the conditions are with (&). I want to be able to for e.g. search for all data prior the end date of 20220101. An the result should be all data upon the given date, without entering more boxes. Right now it results in a blank sheet if I leave one entry box blank.
Is there a way to set these entry boxes somehow as default=True so it considers all information if left blank? for e.g. I also tried using (len(condition6) > 0 in order to create a final condition dynamically. But it just did not work. It is probably a very easy question but I couldn't figure it out in the past 6hrs. Thank you for you help.

namesec = namesec_execII.get().strip()
symbol = namesec_execII.get().strip()
start = start_execII.get().strip()
end = end_execII.get().strip()
segment = segment_execII.get().strip()

inputfile = 'testfile.pkl'
df = pd.read_pickle(inputfile)

conditionORall = ((df['namesec'] == namesec) | (df['localMnemonic'] == symbol) | (df['securityShortName'].str.contains(symbol)))
condition6 = (df['SegmentID'] == segment)
condition7 = (df['TradeDate'] >= start)
condition8 = (df['TradeDate'] <= end)

df = df.loc[(conditionORall) & (condition6) & (condition7) & (condition8)]

df.to_excel('result.xlsx', index=False)

namesec_execII=StringVar()
namesec_entry_execII = Entry(my_frame10,textvariable = namesec_execII, bg='white', font=('Helvetica',12, 'normal'))

start_execII=StringVar()
start_entry = Entry(my_frame10,textvariable = start_execII, bg='white', font=('Helvetica',12, 'normal'))

end_execII=StringVar()
end_entry = Entry(my_frame10,textvariable = end_execII, bg='white', font=('Helvetica',12, 'normal'))

segment_execII=StringVar()
segment_entry = Entry(my_frame10,textvariable = segment_execII, bg='white', font=('Helvetica',12, 'normal'))

A: If you want to make a filter optional, you can consider the default return value to be True unless the filter is non-empty. This can be done in the following way:
conditionORall = ((df['namesec'] == namesec) | (df['localMnemonic'] == symbol) | (df['securityShortName'].str.contains(symbol)))
condition6 = (df['SegmentID'] == segment) if segment != "" else True
condition7 = (df['TradeDate'] >= start) if start != "" else True
condition8 = (df['TradeDate'] <= end) if end != "" else True

df = df.loc[(conditionORall) & (condition6) & (condition7) & (condition8)]

You can use the same approach to add further optional filters in the future.


text:
Q: Leveraging SQL Server to store a counter I have a requirement to generate a unique caseid each time someone clicks on a button in a .Net windows application. My back-end is SQL Server 2008 R2.
Now this case id needs to be unique for each click by the users and it should start from 100 and keep incrementing.
Is it a bad practise to create a single column / single row table like let's say:
Table Counter: count int
That's all it will have. For each click in the button I will just keep incrementing it. Or is there a cleaner way?

A: You could create an int IDENTITY column in your table where the initial value is 100, and have it increment by one for each new row in the table. This is probably the most efficient (from a SQL Server perspective) way, and most concurrent friendly way, of doing it.


text:
Q: Large whitespace caused by hidden li items? I've got a menu that pops out of a list item.  Something to this effect:

                  Other - Common IT Tasks

Most common IT tasks.

                            Log a ticket

                            Map drives

                            Unlock a user

Immediately underneath this li item I have this:

        Back to top

When I don't hover over the li item it gives me this effect:

When I hover over this li item it gives me this effect:

Great the menu works, my issue is the gap between the word "Back to top" with the li item, it is fairly large.  I believe it is due to the invisible li items of the list.  For anyone interested, the CSS is something to this effect:
ul.topmenu, ul.topmenu ul {
  display: block;
  margin: 0;
  padding: 0;
}

ul.topmenu li {
  display: inline;
  list-style: none;
  margin: 0;
  padding-right: 1.5em;
}

ul.topmenu li ul {
  visibility: hidden; }

  ul.topmenu li.submenu:hover ul {
  visibility: visible;
}

Simple classic visibility is hidden unless you hover, however, the whitespace between the word "Back to top" with the list item is too large.

A: visibility: hidden only makes the element invisible, but does not remove it from the page flow.
display: none will hide the element and remove it from the page flow (so it won't take up any space or affect other elements in any way).

A: visibility : hidden only makes the element invisible, but does not remove it from the page flow. display: none will hide the element and remove it from the page flow (so it won't take up any space or affect other elements in any way)
ul.topmenu li ul
{
    display: none;
}

ul.topmenu li.submenu:hover ul
{
    display: block;
}

A: visibility:hidden do not show element, but still reserves space for it.
Try display:none

A: Use the CSS display: none rule instead of visibilty: hidden, because you want your tag to not be displayed at all, you don't want a blank space allocated in it's place (see). From the W3 docs:

Please note that a display of 'none' does not create an invisible box; it creates no box at all. CSS includes mechanisms that enable an element to generate boxes in the formatting structure that affect formatting but are not visible themselves.

Also, what does the W3 validator say about your HTML?


text:
Q: How to center terminal HTML Fairly self explanatory.
 <link href="C:\Users\Andre\Desktop\FOLDER\css\xterm.css" rel="stylesheet" />

*

*

Here is my css file that it's connected to and how I tried to center it, I realize it's a different type, so I wasn't sure how to go about it
#terminal{
    align-content:center;
}

Any help on centering this would be appreciated

A: #terminal {
    text-align: center;
}

A: Maybe try this :
#terminal{
    margin: auto;
    width : 300px;
}


text:
Q: Drupal - How To Edit Home Page Source Code? I'm new to Drupal so please bear with my beginner question.
i have this website that now i need to administer.
Unfortunately, it seems recently the website may have been hacked and hidden links been added into the home page (at the end, after footer).
i found it out when i view the page via Right Click > View Page Source
The hidden links is only added into the home page, not the other pages. However, i don't know how to open the home page's source code and edit to remove the links. i have go through every admin settings options available, i have tried google it as well, but none seems to be the answer.
ps. i have looked into the page.tpl.php on the server, nothing seems amiss there.
UPDATE
Thanks for all the help you have given!
I found the code inside theme.inc file. So once i remove this part of code, the website should be clean again, right? Please tell me if i need to do other things as this is my first time cleaning a hacked website (im really beginner at this)
In addition, i've performed a google search "site:websitename.com" and found that there are some unknown URL like "websitename.com/some-product-name". I've searched the nodes but found none related to it. And when clicked, the link redirect to another website altogether.
Really appreciate if you could guide me how to remove this as well.
Thank you!

A: *

*Try to open also html.tpl.php and (if exist) page--front.tpl.php. Also take a look to template.php

*Update parent theme (if any) to latest version. Change theme and see if you still have issue. If issue resolved see 3. Or else see 4.

*Download the whole theme to your local and search for some string of the bad code through all of the files strings

*Update drupal and all its modules to latest versions

If nothing helps - provide the link to the website, so I could see if there something which could guide me to the goal

A: If it is not in theme, it could be in a preprocess hook in pretty much any module, so search the whole project for a function having preprocess in it.
Another possibility are links injected by javascript so search all js files for the href of the malicious link (it costs nothing to actually search the whole project files for the target website in the href of these links).
You can do a global search loading the project sources in an IDE like eclipse/netbean... .
If the links are stocked in the database and not in the code, it will be tricky to find it, disable all modules one by one, switch to default theme, if nothing work replace current drupal core files with the ones from drupal.org in case they got corrupted (same version to avoid compatibility issues), so you can find which part of the site is causing this.
Good luck!

A: There are many things that could be the issue.

*

*Check your code base for the malicious code. If you have access to a
command line navigate to the document root and type grep -Hirn
"malicious-text-sample" *

*Search through your database for any content injections (they could
have added blocks, boxes, etc. The easiest way to do this is to use
a UI like PHPMyAdmin and search for a piece of the text.

*Inspect element on the page and see if it is a script that is being
inserted. You can usually do this by hitting f12 on the page in
question.


text:
Q: Is it safe using $Config{perlpath} in system/exec/open? Assume that I have following code to open filehandle:
open my $fh, "command1 | command2 |";

I found command1 may output that command2 can not handle well, so I'm trying to insert a perl filter between command1 and command2 to deal with them:
use Config;
open my $fh, "command1 | $Config{perlpath} -ple 'blah blah' | command2 |";

My questions are:

*

*Is it OK to use $Config{perlpath} in system call directly?

*Calling own perl binary seems nuts.  Are there any better solutions?

Thanks

A:
Is it OK to use $Config{perlpath} in system call directly?

Relatively. It's about as portable as the rest of your code (which already depends on running on something unix-ish). There's some security worry, but I'd say not a very large one because someone who can affect the value of that variable already has scope to cause havoc. $^X is probably safer in that regard. You might want to try quoting it using String::ShellQuote just for safety, since you can't bypass the shell in the midst of a pipeline.

Calling own perl binary seems nuts. Are there any better solutions?

Depends on your definition of "better". There's definitely another way around, which is to run both command1 and command2 separately, process command1's output in your original perl process, hand it to command2, and read command2's output. However, you have to be careful how you do it. There are two safe ways.
The first way is easier, but takes more time and memory: run command1 first, read and process all of its output into a string, then run command2 providing the buffered output as input. The best way to do this is to use IPC::Run to handle command2's input and output (and maybe both commands, just for consistency); if you try to just print all the data to command2's input handle and then read all the output you can deadlock, but IPC::Run will interleave reads and writes if necessary behind the scenes, and give you a nice easy interface.
The second way is more complicated but closer in behavior to the original: you need some kind of async framework like IO::Async or POE, using its classes for process construction, and set up handlers to communicate between them, do your filtering, and gather the output.
Here's a tested toy example of that (gist because it's a couple screenfuls of code) that does the equivalent of ls | perl -pe '$_ = uc' | rev, except with the middle part of the pipeline running in the parent perl process. You may never use it, but I thought it was worth illustrating.


text:
Q: JSF Restrict Page Access / Permissions - Error Parsing Issue I am trying to restrict certain pages in my web application to certain users, such as an administrator. However, I keep getting the following error:
Error Parsing: #{userSession.hasRole('ADMIN')}

I have tried several things but keep hitting a brick wall and was hoping someone may be able to shed some light.
My UserSession class has the following method:
public boolean hasRole(Role role)
{
    return roles.contains(role);
}

I am also using the following Bean and session scope:
@ManagedBean(name="userSession")
@SessionScoped

Then, in my view, I am using:
<p:tab rendered="#{userSession.hasRole('ADMIN')}" title="Admin">

My Role class:
public class Role {

    public enum RoleType {
        ADMIN, USER
    }

    private RoleType type;

    public setRoleType(RoleType type)
    {
        this.type = type;
    }

    public RoleType getRoleType(RoleType type)
    {
        return this.type;
    }
}

As I am using a VM it's difficult for me to copy and paste my code onto here, but here are some screenshots of the stack trace:
http://imgur.com/a/Ld8t2
Any help is greatly appreciated.


text:
Q: Is it possible to send two different Content-Type for downloading file using jax-rs POST method Is it possible to send two different Content-Type for POST method using post-man? Like, if the service is used for downloading excel file so in that case, @Consumes(MediaType.APPLICATION_JSON) is used for sending some user detail which is json structure and @Produces(MediaType.APPLICATION_OCTET_STREAM) is used for sending back the response as file.
NOTE: I don't want to use form-data, that is a constraint for this service.

A: On the client request, the Content-Type header is only for the type of data that is in the entity body. The Accept header is what you send for the type of data you want back.
On the server side, it is perfectly fine to do the following.
@POST
@Path("something")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response post(Model model) throws Exception {
    final InputStream in = new FileInputStream("path-to-file");
    StreamingOutput entity = new StreamingOutput() {
        @Override
        public void write(OutputStream out) {
            IOUtils.copy(in, out);
            out.flush();
        }
    };
    return Response.ok(entity)
            .header(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment;filename=somefile.xls")
            .build();
}

The request to this endpoint should look like
POST /api/something HTTP 1.1
Content-Type: application/json;charset=utf-8
Accept: application/octet-stream

{"the":"json", "entity":"body"}

See also:

*

*This post about purpose of @Produces and @Consumes and the role they play in content negotiation.

Aside
As an aside, consider using application/vnd.ms-excel as the Content-Type instead of application/octet-stream. This is already the standard MIME type for Microsoft Excel files1.  When using StreamingOutput as the response entity type, you can make the @Produces anything you want, as there is no real conversion needed.
In Postman, when you use the "Send and download" feature, you will notice that when the Content-Type is application/octet-stream, it will suggest the file extension of .bin when saving the file. But if you have the Content-Type as application/vnd.ms-excel, then the suggested extension is .xls, which is what it should be.

1. Incomplete list of MIME types