text:
Q: ConnectionRefusedError When Try to Load Dataset in Jupyter Notebook i'm new in jupyter notebook. I'm trying to load dataset from url in jupyter. This is my code.
import pandas
url = "http://archive.ics.uci.edu/ml/machine-learning-databases/00244/fertility_Diagnosis.txt"
names = ['season', 'age', 'childish-diseases', 'accident', 'surgical-intervention', 'high-fevers', 'alcohol-consumption', 'smoking-habit', 'hours-sitting-per-day', 'output']
dataset = pandas.read_csv(url, names=names)

I've tried different link access but still got the same error.
I am getting the following error.
ConnectionRefusedError                    Traceback (most recent call last)
D:\Programs\anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)
   1349             try:
-> 1350                 h.request(req.get_method(), req.selector, req.data, headers,
   1351                           encode_chunked=req.has_header('Transfer-encoding'))

D:\Programs\anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
   1239         """Send a complete request to the server."""
-> 1240         self._send_request(method, url, body, headers, encode_chunked)
   1241

D:\Programs\anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1285             body = _encode(body, 'body')
-> 1286         self.endheaders(body, encode_chunked=encode_chunked)
   1287

D:\Programs\anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
   1234             raise CannotSendHeader()
-> 1235         self._send_output(message_body, encode_chunked=encode_chunked)
   1236

D:\Programs\anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
   1005         del self._buffer[:]
-> 1006         self.send(msg)
   1007

D:\Programs\anaconda3\lib\http\client.py in send(self, data)
    945             if self.auto_open:
--> 946                 self.connect()
    947             else:

D:\Programs\anaconda3\lib\http\client.py in connect(self)
    916         """Connect to the host and port specified in __init__."""
--> 917         self.sock = self._create_connection(
    918             (self.host,self.port), self.timeout, self.source_address)

D:\Programs\anaconda3\lib\socket.py in create_connection(address, timeout, source_address)
    807         try:
--> 808             raise err
    809         finally:

D:\Programs\anaconda3\lib\socket.py in create_connection(address, timeout, source_address)
    795                 sock.bind(source_address)
--> 796             sock.connect(sa)
    797             # Break explicitly a reference cycle

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
<ipython-input-14-38b195ec6fe4> in <module>
      4 url = "http://archive.ics.uci.edu/ml/machine-learning-databases/00244/fertility_Diagnosis.txt"
      5 names = ['season', 'age', 'childish-diseases', 'accident', 'surgical-intervention', 'high-fevers', 'alcohol-consumption', 'smoking-habit', 'hours-sitting-per-day', 'output']
----> 6 dataset = pandas.read_csv(url, names=names)

D:\Programs\anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
    674         )
    675
--> 676         return _read(filepath_or_buffer, kwds)
    677
    678     parser_f.__name__ = name

D:\Programs\anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    428     # though mypy handling of conditional imports is difficult.
    429     # See https://github.com/python/mypy/issues/1297
--> 430     fp_or_buf, _, compression, should_close = get_filepath_or_buffer(
    431         filepath_or_buffer, encoding, compression
    432     )

D:\Programs\anaconda3\lib\site-packages\pandas\io\common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression, mode)
    170
    171     if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer):
--> 172         req = urlopen(filepath_or_buffer)
    173         content_encoding = req.headers.get("Content-Encoding", None)
    174         if content_encoding == "gzip":

D:\Programs\anaconda3\lib\site-packages\pandas\io\common.py in urlopen(*args, **kwargs)
    139     import urllib.request
    140
--> 141     return urllib.request.urlopen(*args, **kwargs)
    142
    143

D:\Programs\anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223
    224 def install_opener(opener):

D:\Programs\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    523
    524         sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method())
--> 525         response = self._open(req, data)
    526
    527         # post-process response

D:\Programs\anaconda3\lib\urllib\request.py in _open(self, req, data)
    540
    541         protocol = req.type
--> 542         result = self._call_chain(self.handle_open, protocol, protocol +
    543                                   '_open', req)
    544         if result:

D:\Programs\anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
    500         for handler in handlers:
    501             func = getattr(handler, meth_name)
--> 502             result = func(*args)
    503             if result is not None:
    504                 return result

D:\Programs\anaconda3\lib\urllib\request.py in http_open(self, req)
   1377
   1378     def http_open(self, req):
-> 1379         return self.do_open(http.client.HTTPConnection, req)
   1380
   1381     http_request = AbstractHTTPHandler.do_request_

D:\Programs\anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)
   1351                           encode_chunked=req.has_header('Transfer-encoding'))
   1352             except OSError as err: # timeout error
-> 1353                 raise URLError(err)
   1354             r = h.getresponse()
   1355         except:

URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>

Note: the url of dataset is active and accessible, python version 3.8, anaconda version 3 (2020)
Can anyone tell me how to solve this? Thank you~


text:
Q: How to implement full text search in amazon s3 bucket? I have a bucket on S3 in which i have large amount of text,pdf,doc files.each files has a different name.
I want to search some text within a that files .
For the example, I have a files as per below :

*

*abc/myfolder/abac.txt

*abc/myfolder/abacpfd.pdf

*abc/myfolder/abacpfd.doc

& I want to search text like "I am human" in the above files. if text contains in that files then return file name
How to achieve this ? Is it even possible with c# ?

A: Amazon S3 does not provide any services that relate to the content of objects.
You will need to run some form of software that scans and indexes the content of the S3 files (eg Elasticsearch).

A: Here's a tutorial which uses Tika (for PDF OCR) and OpenSearch (for search engine) to search the contents of PDF files within an S3 bucket:
import boto3
from tika import parser
from opensearchpy import OpenSearch
from config import *
import sys

# opensearch object
os = OpenSearch(opensearch_uri)

s3_file_name="prescription.pdf"
bucket_name="mixpeek-demo"

def download_file():
    """Download the file
    :param str s3_file_name: name of s3 file
    :param str bucket_name: bucket name of where the s3 file is stored
    """

    # s3 boto3 client instantiation
    s3_client = boto3.client(
        's3',
        aws_access_key_id=aws_access_key_id,
        aws_secret_access_key=aws_secret_access_key,
        region_name=region_name
    )

    # open in memory
    with open(s3_file_name, 'wb') as file:
        s3_client.download_fileobj(
            bucket_name,
            s3_file_name,
            file
        )
        print("file downloaded")
        # parse the file
        parsed_pdf_content = parser.from_file(s3_file_name)['content']
        print("file contents extracted")
        # insert parsed pdf content into elasticsearch
        insert_into_search_engine(s3_file_name, parsed_pdf_content)
        print("file contents inserted into search engine")

def insert_into_search_engine(s3_file_name, parsed_pdf_content):
    """Download the file
    :param str s3_file_name: name of s3 file
    :param str parsed_pdf_content: extracted contents of PDF file
    """
    doc = {
        "filename": s3_file_name,
        "parsed_pdf_content": parsed_pdf_content
    }
    # insert
    resp = os.index(
        index = index_name,
        body = doc,
        id = 1,
        refresh = True
    )
    print('\nAdding document:')
    print(resp)

def create_index():
    """Create the index
    """
    index_body = {
        'settings': {
            'index': {
                'number_of_shards': 1
            }
        }
    }
    response = os.indices.create(index_name, body=index_body)
    print('\nCreating index:')
    print(response)

if __name__ == '__main__':
    globals()[sys.argv[1]]()

full tutorial: https://medium.com/@mixpeek/search-text-from-pdf-files-stored-in-an-s3-bucket-2f10947eebd3
Corresponding github repo: https://github.com/mixpeek/pdf-search-s3

A: Exactly, I had this problem, but somehow I had solved it without using a search approach. If I couldn't find a solution, I was going to try this open source project: filestash

redpajama_set_name: RedPajamaStackExchange


text:
Q: Public variabes are unable to fetch its values after using @Refreshscope I was able to get the public variable assigned in my one of configuration class. But after using the annotation @Refreshscope Im getting null value instead of actual. Im getting the value when using the getter but not getting while accessing like,

@Autowired
ConfigProps configProps;

    @RestController
    public class MessageRestController {
    @RequestMapping("/name")
      String getName() {
        return configProps.name;
      }
    }

My Configuration class is looks like below,
@Component
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
@Getter

public class ConfigProps {

    @Value("${config.name}")
    public name;

}

The issue is comes only when annotating the class with @RefreshScope for Spring Config Client. Thank u very much for help in advance.

A: One issue with your current implementation is that you are using a public field to store the value injected by the @Value annotation. When using the @RefreshScope annotation, the values of the fields are not refreshed automatically, and you need to use getters to retrieve the updated values.
To fix this issue, you can change the public field to a private field and add a getter method to retrieve the value
@RefreshScope
public class PropConfigs {

  @Value("${config.name}")
  private String name;

  @Value("${config.salary}")
  private String salary;

  public String getName() {
    return name;
  }

  public String getSalary() {
    return salary;
  }
}


text:
Q: AWS changed the way a service works. What is the right way to handle questions about this in certification exams? example:
Previously we could attach an IAM role to an EC2 instance only at launch time. Now, EC2 service allows you to attach an IAM role to an existing instance

A: The AWS Certification Exams have a policy of only referencing new services after they have been available for at least 6 months. This not only give students a chance to learn new features/services, but also allows time for exam revisions.
Updating exams can take a lot of time because new questions need to be written, reviewed, tested on a sample of students, then released.
In situations where a question becomes invalid, questions would be removed quickly once it is realised that a situation has changed and a question is no longer valid.
It is also unlikely that there would be a question on such a minor detail as the one you mention in your question. An exam might test your understanding of how IAM Roles can be assigned to an instance as a way of passing credentials to an application, but it is unlikely to test a minor detail such as the fact that it could (previously) only be assigned at initial launch.


text:
Q: Setup Alpine mirror in Artifactory to keep packages available removed from official repositories I'm using Artifactory as a docker registry.
I have a few docker images based on Alpine Linux and its packages.
I pin the exact version of each Alpine package I install in these images because:

*

*I want repeatable builds

*I don't want applications running within these images to suddenly break because of a regression in a newer version of a package that was installed "behind the scenes" when building the image

I found out that Artifactory offers Alpine repositories.
By setting up a Alpine virtual repository containing a Alpine remote repository pointing to the official Alpine mirror, Artifactory should define a remote cache that should store the Alpine packages I install from within my images.
After that, I can configure my Alpine-based docker images to use Artifactory has the alpine package repository.
In this way, if a package I previously installed when building an image gets removed from the official Alpine repositories is removed, I should still be able to build the image, as it would resolve the package from the alpine remote cache in Artifactory.
Furthermore, does anyone know if it's possible to backup the remote-cache?

A: You need to store the cache somewhere in Artifactory so that if some files are deleted in the official Alpine repo you will still be able to use it thru the Artifactory? And to do so, I would recommend performing the copy of the files from the cache to the Alpine local repository and you can automate the things using the createcopy user plugin by copying from cache to local repository and integrate the local as well as the remote in the same virtual repository.


text:
Q: Find conditions over $U$ such that optimization over a convex cone generated by $U$ is equal to optimization over $U$. We considerer the following optimization problem
$$
\left\{\begin{array}{cl} \max\limits_{x\in\mathcal{C}} & f(x) \\[2pt]
\text{s.t.} & \mathcal{A}x-b \in K \end{array}   \right. \tag{1}
$$
where $f:\mathbb{R}^{n}\rightarrow \mathbb{R}$ and $\mathcal{A}:\mathbb{R}^{n}\rightarrow \mathbb{R}^{m}$ are linear functions non-zero, $b\in\mathbb{R}^{m}$, $\mathcal{C}$ is a convex cone in $\mathbb{R}^{n}$ and $K$ is a closed convex cone in $\mathbb{R}^{m}$.
Question: I need to find conditions over a set $U\subset\mathbb{R}^{n}$ such that if $\mathcal{C}$ is the convex cone generated by $U$, then  problem $(1)$ is equivalent to the following problem
$$
\left\{\begin{array}{cl} \max\limits_{x\in U} & f(x) \\[2pt]
\text{s.t.} & \mathcal{A}x-b \in K \end{array}   \right. \tag{2}
?$$


text:
Q: Double sound android package project.kalmas;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;

public class one extends Activity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
    }

    public void onclick2(View view)
    {
        Intent i=new Intent("project.two");
        startActivity(i);
    }
    public void onclick3(View view)
    {
        MediaPlayer mp= MediaPlayer.create(this,R.raw.one);
        if(mp.isPlaying()){
            mp.stop();
        } else {
            mp.start();
        }

    }

}
When i click button it play sound then again i click button to stop it wont stop and play sound again which results in double sound playing at one time.Please help

A: You are creating a new MediaPlayer with every click, instead of keeping a reference to the first one. The MediaPlayer that is playing the sound is different than the MediaPlayer that you are calling isPlaying() on. You need to turn the mp variable into a field so you can keep a reference to it.
I imagine something like this would work:
public class one extends Activity {

    MediaPlayer mp;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
        mp = MediaPlayer.create(this,R.raw.one);
    }

    public void onclick2(View view)
    {
        Intent i=new Intent("project.two");
        startActivity(i);
    }
    public void onclick3(View view)
    {

        if(mp.isPlaying()){
            mp.stop();
        } else {
            mp.start();
        }

    }
}


text:
Q: Can we show a popup before check-in a document inside SharePoint site if a record exists inside datavese We have a SharePoint document library which have this settings:-

Now we want to get the current folder ID >> and after the user click on the built-in check-in button and before doing the actual check-in >> to check if an items with the same folder ID exists inside data-verse >> If so to show a popup to confirm the check-in action. this is the built-in check-in action, which we want to show a popup after clicking on the check-in button:-

Any suggestions how we can achieve this? I can develop SPFX,Remote event receivers and so on.. but not sure which appraoch i need to follow?
Thanks


text:
Q: SVG images blink when their order is updating in Chrome I have a weird problem. I have a script that loads images into the SVG, and then user can manually update they order by clicking on them: the clicked image goes up in the SVG tree.
The problem is that in Chrome all images blink when their order in the tree is changing. However, Firefox and Safari work with no blinking. Moreover, I have a copy of this script on the other domain and it doesn't blink there too.
Is it possible that the blinking is caused by some domain-related issue? In both cases images are on the same domain as the page. I use Chrome 18.

A: You can call suspendRedraw() method on any element in SVG when you need to make complex manipulations or when you encounter bugs like you are describing. And when you're done with manipulations call unsuspendRedraw() on the same element to let browser rerender the image. I would call the methods on the parent element of your images.


text:
Q: Backup stops because of claim 'Computer name changed', which is it not true Using Ubuntu 16.04, deja-dup 34.2, and duplicity 0.7.06.
To start a weekly backup I connected the usual external drive with the usual computer, gave the password and received the halt message:

The existing backup is of a computer named correctname, but the current computer name is correctname.lan. If this is unexpected, you should back up to a different location.
Cancel/Continue

This is unexpected. Not because I plugged the external drive into the wrong computer, but because the name of the computer is indeed correct. Checked with uname -n.
I am not quite inclined to back up in a different location, because I would not want to have this issue happen again with other names/computers. Fresh backups are time-consuming, among other considerations.
The questions arise: how comes that deja-dup/duplicity is making up this name? how to fix this?
Added. By clicking on Continue you do perform an incremental backup. Still the halt message is an unnecessary stop in the procedure to avoid if possible.

A: Using Ubuntu 19.10, deja-dup 40.1, duplicity 0.8.04.

The questions arise: how comes that deja-dup/duplicity is making up this name?

According to bug reports (ranging as far back as 2010), it's a bug in duplicity affecting deja-dup. Duplicity prefers the fully-qualified domain name (FQDN) for the backup's computer name.

*

*The way the FQDN lookup is performed is affected by both your computer's network  configuration, and the way the network the computer is connected to behaves.

*In particular, external network changes can therefore break backups.1 This includes moving the computer from one network to another.

See

*

*https://bugs.launchpad.net/deja-dup/+bug/1268182

*https://bugs.launchpad.net/duplicity/+bug/667885

how to fix this?

The bug reports hints at editing /etc/hosts in various ways. Here's what I changed, with mycomputer being my chosen name. Note that order seems to matter.

/etc/hosts (ipv6 addresses omitted)
Original:
127.0.0.1   localhost
127.0.1.1   mycomputer

Modified:
127.0.0.1   mycomputer localhost
127.0.1.1   mycomputer

As soon as I saved the file, an automatic backup started. It worked as expected.2,3
See

*

*https://bugs.launchpad.net/deja-dup/+bug/1086068

*Deja Dup resolves host name incorrectly, adds ISP hostname

*What is the use of /etc/hosts?

1 My backups broke around the time when my ISP upgraded their infrastructure in my area to ipv6. Started seeing "hostnamed changed" with hostnames such as dynamic-xxxx-yyyy-zzzz.area-123.example.com.
2 Tried to verify by reverting the file and rebooting, but backup still works so unsure if it actually fixes the problem, or just triggers deja-dup/duplicity "the right way". Might be related to DHCP timeouts (7 days) in the ISP-owned router, or some other setting I changed. Am posting the answer anyways, but might have to revise if it stops working in a week.3
3 It has now been more than one week since writing this answer.2 Both starting a backup and verifying backups succeeded. Also rebooted and started another backup, which also succeeded. It seems the suggested fix works so far, at least for myself on my machine and in my network environment.


text:
Q: Ubuntu 20.04 - Static and default routes via netplan I am brand new to Linux. I only started 'playing' yesterday, so please forgive my lack of knowledge.
I have built a linux server with 2 network cards. Outside interface (ens192) for all Internet traffic and an INSIDE interface (ens160) for all internal traffic. All interfaces are STATIC.
I would like a single default route to be on the OUTSIDE (ens192)
I would like to route all other networks INSIDE (ens160)
Please see below what I have attempted to build so far.
network:
version: 2
renderer: networkd
ethernets:
  ens160:
      dhcp4: no
      dhcp6: no
      addresses: [172.24.0.50/23]
      gateway4: 172.24.0.5
      routes:
      - to: 10.0.0.0/8
        via: 172.24.0.5
      - to: 172.23.0.0/19
        via: 172.24.0.5
      - to: 172.17.10.0/24
        via: 172.24.0.5

I am currently receiving this error - /etc/netplan/50-cloud-init.yaml:15:1: Invalid YAML: tabs are not allowed for indent:
- to: 172.17.10.0/24
I have received this error with a previous configuration.
** (generate:5240): WARNING **: 10:16:53.463: Problem encountered while validating default route consistency.Please set up multiple routing tables and use routing-policy instead.
Error: Conflicting default route declarations for IPv4 (table: main, metric: default), first declared in ens192 but also in ens160
I am at a complete loss on what to do here.
Please help.

A: There is most likely an error in your yaml-code, probably a tab instead of a space at the last route.
If you edit the file in vim you can use the :set list -command to see what characters that hides there. To get back use the :set nolist -command.


text:
Q: Multiple Authentication Models in Django I am working on a project where I need to have 3 types of Users.

*

*Staff (for admin,superadmin like stuff)

*Dealers

*Customers
i have created 3 models using AbstractBaseUser class . I also created separate model managers for each .
models.py
class Staff(AbstractBaseUser):
USERNAME_FIELD = 'email'
# fields

class Customer(common_modelfields):
USERNAME_FIELD = 'email'
# customer specific fields

class Dealer(common_modelfields):
USERNAME_FIELD = 'email'
# dealer specific fields

after getting through this Django Multiple Auth Models
i made a custom authentication backend authentication.py as follows:
from .models import Staff,Customer,Dealer

var_model = ""
class authentication_models_backends(object):
def authenticate(self, request, email=None, password=None):
    global var_model
    if "admin" in request.path:
        var_model = Staff
    elif "customer" in request.path:
        var_model = Customer
    elif "dealer" in request.path:
        var_model = Dealer
    else :
        return "no_model_found"
   # authenticate user based on request object
    try:
        validated_email = email.lower()
        if var_model.objects.filter(email=validated_email).exists():
            user = var_model.objects.get(email = validated_email)
            if user.check_password(password):
                return user
            else:
                return "invalid password"
        else:
            return "email not found"
    except var_model.DoesNotExist:
        return None

def get_user(self, user_id):
    # logic to get user
    try:
        return var_model.objects.get(pk=user_id)
    except var_model.DoesNotExist:
        return None

in settings.py
AUTH_USER_MODEL = 'account.Staff'

AUTHENTICATION_BACKENDS = ['account.authentication.authentication_models_backends',]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_simplejwt.authentication.JWTAuthentication',#(user not found error)
)}

SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': False,

'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,

'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',}

api URL which i hit with GET request by postman
path("customerprofileview/", customer_profile_view.as_view(),name='customerprofileview'),
path("dealerprofileview/", dealer_profile_view.as_view(),name='dealerprofileview'),

here is a View with Serializer :
class customer_profile_view(APIView):
renderer_classes = [apirenderer]
permission_classes = [IsAuthenticated]
def get(self,request,format=None):
    try:
        serializer_object = customer_profile_serializer(request.user)
    except:
        pass
    return Response(serializer_object.data,status=status.HTTP_200_OK)

class customer_profile_serializer(serializers.ModelSerializer):
class Meta:
    model = Customer
    fields = ['id','full_name','email','unique_id','full_number','house_no','locality','state']

however django is looking only for the model mentioned in AUTH_USER_MODEL,if user is not an instance of AUTH_USER_MODEL's value then it throws user_not_found error . Hence, Not searching in AUTHENTICATION_BACKENDS.
i am assigning token to user on login via simple-jwt RefreshToken method and i want to get the logged in user details from models according to request - as you can see the logic in authentication.py .
i got stuck at this point . please help me to proceed further
EDIT : i forgot to mention earlier that i am not using django.contrib.auth's authenticate method to authenticate users.

A: I'm not sure why you need three models for user authentication. You can use one model with roles defined.
class User(AbstractBaseUser):
...
...
...
CUSTOMER = 'customer'
STAFF = 'staff'
DEALER = 'dealer'
USER_ROLES= [
        (CUSTOMER, 'customer'),
        (STAFF, 'staff'),
        (DEALER, 'dealer'),
    ]
user = models.CharField(max_length=10, choices=USER_ROLES, default="your-default")


text:
Q: Match numbers that are not following an alphabet and place them in a capturing group (globally) For example, if I have text like this:
"hello800 more text 1234 and 567"

It should match 1234 and 567, and not 800 (since it is following hello's o, which is not a number).
It is similar to what programming languages do, for example, in JavaScript, abc123 is a variable, while 50 alone, not following text, is treated as a number.
Please do have in mind that I want to negate only characters from the set [A-Za-z] and not others. For example, +33 and -33 should still return 33.
My first trial was to match a NOT set:
[^A-Za-z]([0-9]+)

That didn't work at all.
My second trial was to reverse the string and to use a negative lookahead:
/([0-9]+)(?![A-Za-z])/g

It works only if there is 1 digit. 1a does not match the 1 (and that's good), but 123a matches the 12 (and that's bad).

A: you can try the following regex
\b\d+\b

you can check the demo here
additionally if you want to match +33 also you can try the regex
\b[+-]*\d+\b

demo

A: Try this \b(\d+?)\b

*

*\b Checks for word boundaries (spaces, endlines, etc..)

*\d Checks for numbers

Demo Here

A:

var str = "hello800 more text 1234 and 567 blah blah +33 end";
var result = str.match(/\b\d+\b/g);
console.log(result);

Explanation:
\b  : word boundary, make sure we don't have letter or digit before
\d+ : 1 or more digits
\b  : word boundary, make sure we don't have letter or digit after


text:
Q: How to demonstrate the subset definition? I'm having a hard time trying to demonstrate the definition of a subset, which is :
$S \subseteq T \Leftrightarrow (S \subset T) \vee (S = T)$
I always end up by expending the definitions of $\subset$ and $=$ in Boolean algebra, resulting into this complicated situation.
Any way to solve it by staying in the Set theory? Or in Boolean algebra?

A: You're on the right way!
Your definition of $S \subset T$ as $\forall x (x \in S \rightarrow x \in T) \land \exists x (x \in T \land \neg x \in S)$ should work fine.
For $S = T$ you can use $\forall x (x \in S \leftrightarrow x \in T)$
And for $S \subseteq T$ you can use $\forall x (x \in S \rightarrow x \in T)$
Using these definitions, you should be able to prove $S \subseteq T \leftrightarrow (S \subset T \lor S =T)$ just fine.


text:
Q: Links to documents not opening in application I have links to a few documents on my home navigation across the top and left side of my page.  When I click on the document link on my navigation it asks me to save or open the document.  It use to behave as if I clicked on the document link it would open in the application.  If I go to the library where the documents are located the document opens in the application.  It should work both ways if I click on the document link from the side or top navigation.  There is also no error that appears just doesn't open in the application.  BTW I did not change any settings...etc. it just stopped working.
Has anyone else experienced this problem before?

A: If you didn't make any changes, try it on other browser. Then check the Document Library Settings > Advanced Settings:

Manual from this question
Your links in nav are not changed until you do that, but doc library has common settings for it's documents.

A: Per my test, when i click on the document link on the navigation, or when i open the document link directly, it asks me to save or open the document.
This link will open the link in client application, change the link in the following format and compare the results:
ms-word:ofe|u|https://someurl.sharepoint.com/sites/site1/Shared%20Documents/WordDoc1.docx
When we go to the library where the documents are located, the document opens in the client application, it is because "SharePoint OpenDocuments Class" managed addon works fine.


text:
Q: CentOS 6.4 Minimal + how to configure jenkins jobs via xml? I need to create a Build Server in CentOS 6.4 Minimal I sucessfully installed:

*

*Java compiler (OpenJDK 1.7.0)

*Git or Mercurial

*Maven

*Jenkins

Now I need to to the following:
At given intervals (eg daily at midnight) is the latest revision in the version control system (tip, HEAD, ...) compiled with Maven. In addition, Java Docs and packages (jar, war) need to be created.
Then Jenkins with all tests conducted and reported.

*

*Make sure there is a report of previous builds

*Ensure that the Java Docs and packages can be downloaded (jars, wars, ...) of the latest build

I can't use a GUI on CentOS Minimal so I need to configure the job in xml files? Could please someone show me the way... I'm not a linux server guru.

A: It's a bit impractical to configure Jenkins via XML by hand, because Jenkins' configuration is spread over multiple files, and the format of the configuration files changes between releases.
Given that Jenkins is a web application, you should be able to visit port 8080 (Jenkins' default port, assuming you didn't change it) on the server where you installed Jenkins (e.g. http://mycentosserver.example.com:8080), and configure it via the web interface.
If you're unable to access the web interface because of a firewall or similar, but you are able to SSH to the server (presumably you can, given that you were able to install stuff on it), you could set up an SSH tunnel to forward a port on your local machine to port 8080 on the server. For example, from your local machine, run the following command. You will then be able to access Jenkins on your local machine at http://localhost:28080 . If you're on Windows, you can use Putty to do the same thing.
ssh -L 28080:127.0.0.1:8080 mycentosserver.example.com

If you can't access the web app directly, and you can't SSH tunnel, I'd recommend setting up Jenkins on a server where you can access the web app, configuring it, and copying the XML config files from /var/lib/jenkins on that server across to your Centos server.


text:
Q: Use local WIFI network Database from Android app I want to read a .sqlite database that i have in my Windows Pc from my app and use it there. How can i do this?
Both devices are connected to the same network by WiFi.
My app is now taking the DB from the sd card, so i have all the code for handling it. I just need to read it from my PC.
Thank you on advance!

A: I suggest you to make a wrapper. It's a proxy between your app and your DB and its job is to intercept requests from your app, make some requests on your DB then returns the result (e.g. a PHP script which receive and send JSON messages).
IMHO, it's not a good idea to deal directly with the DB (for security and fiability reasons).


text:
Q: LabelEncoding a permutation of combination of columns I'd like to create class labels for a permutation of two columns using sklearn's LabelEncoder(). How do I achieve the following behavior?
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv("data.csv", sep=",")
df
#    A    B
# 0  1  Yes
# 1  2   No
# 2  3  Yes
# 3  4  Yes

I'd like to have the permutation of combination of A && B rather than encoding these two columns separately:
df['A'].astype('category')
#Categories (4, int64): [1, 2, 3, 4, ]

df['B'].astype('category')
#Categories (2, object): ['Yes','No']

#Column C should have 4 * 2 classes:
(1,Yes)=1  (1,No)=5
(2,Yes)=2  (2,No)=6
(3,Yes)=3  (3,No)=7
(4,Yes)=4  (4,No)=8

#Newdf
#    A    B  C
# 0  1  Yes  1
# 1  2   No  6
# 2  3  Yes  3
# 3  4  Yes  4

A: We can create the mapping df with cross merge
out = df.merge(df[['B']].drop_duplicates().merge(df['A'].drop_duplicates(),how='cross').assign(C=lambda x : x.index+1))
Out[415]:
   A    B  C
0  1  Yes  1
1  2   No  6
2  3  Yes  3
3  4  Yes  4

More info
df[['B']].drop_duplicates().merge(df['A'].drop_duplicates(),how='cross').assign(C=lambda x : x.index+1)
Out[417]:
     B  A  C
0  Yes  1  1
1  Yes  2  2
2  Yes  3  3
3  Yes  4  4
4   No  1  5
5   No  2  6
6   No  3  7
7   No  4  8

A: You can create additional column merging values from 2 columns into one tuple. But LabelEncoder cannot encode the tuples, so additionally you need to get hash() of the tuple:
df['AB'] = df.apply(lambda row: hash((row['A'], row['B'])), axis=1)
le = LabelEncoder()
df['C'] = le.fit_transform(df['AB'])

However, if you want to preserve the exact labels order (that you specified), using LabelEncoder() doesn't make sense. You can simply compute the C column like that:
df['C'] = df['A'] + (df['B']=='No') * df['A'].max()

Output:
    A   B   C
0   1   Yes 1
1   2   No  6
2   3   Yes 3
3   4   Yes 4

EDIT:
If you want to keep the labels for missed combinations (e.g. (2, 'Yes')) and need a solution for arbitrary number of classes, you can use 2 LabelEncoder():
leA = LabelEncoder()
leB = LabelEncoder()
leA.fit(df['A'])
leB.fit(df['B'])
df['C'] = leA.transform(df['A']) + leA.classes_.size
leB.transform(df['B']) + 1 # if you want labels to start from 1

But in this case you cannot preserve the custom order, the list of labels will be automatically sorted, e.g. [1,2,3,4] and ['No','Yes'].
Output:
    A   B   C
0   1   Yes 5
1   2   No  2
2   3   Yes 7
3   4   Yes 8


text:
Q: What url encoding web browser uses? What url encoding a web browser uses while submitting data to server?
with my application i use HttpUtility.UrlEncode(string data)
but do not get result as i get with web browser.
My application submit some text data to forum.
When i am submitting data with web browser (Google Chrome) the exact text i can see submitted to server but when i am submitting using my application it showing some character different.
So is this necessary to submit any data to server must be url encoded?
---Edit---
        data = HttpUtility.UrlEncode(textBox1.Text);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.CookieContainer = cookieContainer;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5";
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        request.Headers.Add("Accept-Charset", "ISO-8859-2,utf-8;q=0.7,*;q=0.7");
        request.Headers.Add("Accept-Encoding", "gzip, deflate");
        request.Headers.Add("Accept-Language", "pl,en-us;q=0.7,en;q=0.3");
        request.Method = "POST";
        byte[] byteArray = new byte[256];
        ASCIIEncoding ascii = new ASCIIEncoding();
        byteArray = ascii.GetBytes(data);

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

and data in textbox1 is like this.
¦=¦=¦¦=¦=¦
RUNTIME………..: 2h:13m:15s
RELEASE SIZE……: 16,2GB
VIDEO CODEC…….: x264, 2pass,

A: You generally only have to URLEncode if you want to include a URL reserved charatcer (?, &, etc.) in a url parameter.


text:
Q: Pandas, loop through each row of a column and append string to next column previous row I've done this task through Excel, but it has taken a hell of a long time to run across the 300,000 rows of data so I was hoping I could get it done a lot faster using python.
What I have is like the following data frame,
               PartID   Notes
0                 1       Fiv
1                 2       Six
2                 3       Pot
3                 4       Lep
4           Date is       New

The issue is I have been given a file where PartID has strings in it so index 4 has 'Date is' which should be in the Notes section. In Excel, what I did was use the value function to change everything to values so that the numbers became values while text were changed to be empty. I then used a macro to say if the row below is empty, then append the data to the Notes column in the row above and the output would look like below
               PartID  Notes
0                 1      Fiv
1                 2      Six
2                 3      Pot
3                 4 Lep Date is
4                 5      New

Is there a way to do the same thing in Python using pandas?
Thanks!

A: I think you need, pd.to_numeric and pd.Series.shift
a=df['PartID'].shift(-1).fillna('')

b=df['Notes']+a.loc[pd.to_numeric(a,errors='coerce').isnull()]

df['Notes']=b.combine_first(df['Notes'])

df['PartID']=np.arange(1,len(df['Notes'])+1)
print(df)
PartID  Notes
    1      Fiv
    2      Six
    3      Pot
    4     Lep Date is
    5      New


text:
Q: git --global switch related to one user or all user? Suppose I have two users A and B in my Linux system. I am logged in as user A. If i configure an option using the --global switch like this
git config --global user.name "my name"

Will this set option only for user A? Or it will affect both users: A and user B?

A: --global is user level. It writes to $HOME/.gitconfig.
--system is global for the whole operating system. It writes to $(prefix)/etc/.gitconfig.
man git config for more details.

A: --global only affects the .gitconfig file under the current user home directory, so it will only apply to user A but not user B.
For all users, there is --system option.
--global
    For writing options: write to global ~/.gitconfig file rather than the repository .git/config.

    For reading options: read only from global ~/.gitconfig rather than from all available files.

--system
    For writing options: write to system-wide $(prefix)/etc/gitconfig rather than the repository .git/config.

    For reading options: read only from system-wide $(prefix)/etc/gitconfig rather than from all available files.

A: According to Git documentation, Git uses a series of configuration files to determine non-default behavior that you may want. The first place Git looks for these values is in an /etc/gitconfig file, which contains values for every user on the system and all of their repositories. If you pass the option --system to git config, it reads and writes from this file specifically.
The next place Git looks is the ~/.gitconfig file, which is specific to each user. You can make Git read and write to this file by passing the --global option.
Finally, Git looks for configuration values in the config file in the Git directory (.git/config) of whatever repository you're currently using. These values are specific to that single repository. Each level overwrites values in the previous level, so values in .git/config trump those in /etc/gitconfig, for instance.
So by doing
   git config --global user.name "my name"

it changes the settings/configurations only for the current user.

A: --global is the option to for configuring stuff for the current user. It stores data into you home directory in ~/.gitconfig by default, or ./.config/git/config if the file exists and ~/.gitconfig does not.
--system is the option for all users, you probably need root access to use it and it stores data into /etc/gitconfig.
If you don't use any of them, that's the repo specific config going into .git/config.
See the OPTIONS section of git config's documentation for details.
If there are conflicts for a certain parameter, the smaller scope config wins.

A: It's about the global settings for the current user (the one you're logged in as)


text:
Q: Converting a Static SQL Query into Dynamic SQL on a Stored Procedure I have written a Stored Procedure like this,
Alter PROCEDURE sp_bestReviewer_report
                (
                @StartingLetter AS VARCHAR(1),
                @CountsReq AS DECIMAL(3),
                @ReqRev AS INT
                @RequiredColumn AS SYSNAME
                )
        AS
        BEGIN
            SELECT TOP(@ReqRev) @RequiredColumn, Count(Reviewer) AS Total FROM [reviews_not_sent] WHERE LEFT(Reviewer,1) = @StartingLetter
            GROUP BY (Reviewer)
            HAVING (Count(Reviewer) > @CountsReq OR Count(Reviewer) < @CountsReq)
            ORDER BY
            Total DESC;
        END;

I am trying to pass @RequiredColumn (the required column) dynamically as a parameter to the stored procedure.
How Can I do this.

A: You need dynamic SQL to pass in a column name:
BEGIN
    DECLARE @sql NVARCHAR(MAX);
    SET @sql = '
SELECT TOP (@ReqRev) [RequiredColumn], Count(Reviewer) AS Total
FROM [reviews_not_sent]
WHERE LEFT(Reviewer, 1) = @StartingLetter
GROUP BY Reviewer
HAVING Count(Reviewer) <> @CountsReq
ORDER BY Total DESC
';

    SET @sql = REPLACE(@sql, '[RequiredColumn]', QUOTENAME(@RequiredColumn));

    EXEC sp_executesql @sql,
                       N'@ReqRev int, @StartingLetter VARCHAR(1), @CountsReq DECIMAL(3)',
                       @ReqRev=@ReqRev, @StartingLetter=@StartingLetter, @CountsReq=@CountsReq;
END;


text:
Q: MySQL Date Format I have a field on my HTML form which asks the user to type the date as dd/mm/yyyy. I then run a PHP script that saves the data to a mySQL database, or it would if I could sort out an issue I have with the date format.
I know that by default the mySQL database saves dates as yyyy-mm-dd, but could someone perhaps tell me please how I can continue to keep the user input date format as dd/mm/yyyy but then when it hits the database it is correctly converted to the mySQL date format.

A: Use PHP to run your formatting.  Before you insert it into the database, re-format the data for MySQL:
$mydate = new DateTime($userdate);
$mydate = $mydate->format("Y-m-d");

If you need to get it from the database, just change the date format back in a similar fashion.

A: I also came across this issue. My solution was to convert the string the user inputs to a Unix Timestamp and then using PHPs date() function to convert it to the MySQL-compliant format.
To convert the string to a Unix Timestamp, you could use strtotime or if you're familier with object oriented programming the DateTime::createFromFormat factory function. From my experience: strtotime will do the job.
Now you need to convert the timestamp you get back to the MySQL format. This is pretty straightforward:
$sqldate = date("Y-m-d", $timestamp);

A: The format of mysql is indeed  'YYYY-MM-DD'.
I suggest something like the following (untested):
$userInput = '24/12/2004';
date('c',  date_parse($userInput));

The sane thing to do would be to use prepared statements and send the date directly to the prepared statement. Alas, Php-MySQL prepared statements don't allow for a date type.

A: Try this:
php > list($d,$m,$y) = explode("/","28/04/2011");
php > echo date("Y-m-d",mktime(0,0,0,$m,$d,$y));
2011-04-28

A: You can do it by creating a simple function - something like this for example:
function convertDate2Sql($date = null) {
    if (!empty($date)) {
        $date = explode("/", $date);
        return implode("-", array_reverse($date));
    }
}

Obviously you have to make sure that if you are using different date format i.e. US one which has month before the day, then you'll have to manually rearrange the values inside of the $date array after using explode() function, but if it's in the same format as you've stated above then using array_reverse() will do the trick.

A: I found a jquery that allowed me to set the format of the date, enabling me to set the standard of the data stored in my database.


text:
Q: Getting MAX datetime event from multiple tables, and outputing a simple list of most recent events by ID I have a table:

and multiple other tables - consider them purchases, in this example:

And would like an output table to show the most recent purchase (NB that there may be multiple instances of a purchase within each table), by id from the main table:

The id can be a customer number, for example.
I've tried using OUTER APPLY on each purchase table, getting the TOP 1 by datetime desc, then getting the max value from the OUTER APPLY tables, but I would not get the table name - eg. Apples, just the datetime.
Another idea was to UNION all of the purchase tables together in a join with the main table (by id), and pick out the top 1 datetime and a table name, but I don't think this would be very efficient for a lot of rows:
    SELECT MT.id, MT.gender, MT.age,
        b.Name as LastPurchase, b.dt as LastPurchaseDateTime
    FROM MainTable MT
    LEFT JOIN (
    SELECT id, Name, MAX(dt) FROM
    (
    SELECT id, 'Apples' as Name, ApplesDateTime as dt FROM ApplesTable
    UNION
    SELECT id, 'Pears' as Name, PearsDateTime as dt FROM PearsTable
    UNION
    SELECT id, 'Bananas' as Name, BananasDateTime as dt FROM BananasTable
    )a
    GROUP BY etc
    )b

Does anyone have a more sensible idea?
Many thanks in advance.

A: I would go for a lateral join:
select m.*, x.*
from maintable m
outer apply (
    select top (1) x.*
    from (
        select id, 'apples' as name, applesdatetime as dt from applestable
        union all select id, 'pears', pearsdatetime from pearstable
        union all select id, 'bananas', bananasdatetime from bananastable
    ) x
    where x.id = m.id
    order by dt desc
) x

A: I would suggest apply:
SELECT MT.id, mt.gender, mt.age, p.*
FROM MainTable MT OUTER APPLY
     (SELECT p.name, p.dt
      FROM (SELECT id, 'Apples' as Name, ApplesDateTime as dt FROM ApplesTable
            UNION ALL
            SELECT id, 'Pears' as Name, PearsDateTime as dt FROM PearsTable
            UNION ALL
            SELECT id, 'Bananas' as Name, BananasDateTime as dt FROM BananasTable
           ) p
       WHERE p.id = mt.id
       ORDER BY dt DESC
      ) p


text:
Q: How to find installed app version through automated script? I have a requirement to find the version of an app installed in mobile device and if the version is not latest then install latest version.
Here how do i automate to find installed app version? I am using appium & selenium to automate my scripts.

A: if you want to find android  app version you can do it using shell command
String cmd = "adb shell dumpsys package your.app.package.name.here |grep versionName";
Process process = null;
try {
     process = Runtime.getRuntime().exec(cmd);
     String appVersion = new BufferedReader(new InputStreamReader(process.getInputStream())).readLine();
        System.out.println("appVersion = "+appVersion);
    } catch (IOException e) {
        e.printStackTrace();
    }

For more info check this stackoverflow question


text:
Q: Javascript/HTML/JQuery: Stop Rendering further part of the page if condition is not met I have html code which uses bootstrap library. This code loads some part of the page and calls JavaScript methods depending on the user activity.
Now, I want to stop loading the page i.e. stop running html code if the below condition is met and show error message "xyz".
Condition: I get the value of one id from the page like var = $('a[id=abc]')[0].innerText and if some value is present, render the page or load the page otherwise show the message.
How do I write the above condition in my page.


text:
Q: How to make the lightning port of iphone output 5V power? like OTG on android phones How to make the lightning port of iPhone output 5V power?

How to make the lightning port of iPhone output 5V power?
Just like the android phone, if I connect the ID pin to the ground then the phone will work as a USB host, after that it will output 5V power (the so-called OTG - On The Go usb).

update
I don't know why some people cast opposing votes to this the question.
And I think this a quite normal question that many people can face. Perhaps you should check this product: Sandisk iXpad https://www.sandisk.com/ixpandflashdrive2

I just confuse how these devices can output power by the lightning port.

A: Your question is vastly answered by:
https://apple.stackexchange.com/questions/119707/how-much-power-can-be-drawn-from-the-lightning-connector-by-a-external-device

Since Apple doesn't publicly commit to power levels or even pin
  compatibility on the lightning connector, anyone interested in
  learning how hardware should be designed to work with Apple's dock
  connectors could choose to join the MFI program:
https://developer.apple.com/programs/mfi/ As a developer, Apple will
  provide you with detailed hardware requirements, schematics and even
  technical support. I haven't seen anyone take a current meter and volt
  meter to the devices and post publicly, but wanted to make you aware
  of one official avenue to get this sort of information across all of
  Apple's iOS product line wether they use the 30 pin dock connector,
  the lightning dock connector or some of the other specific iPod
  connectors.
quoting: Additionally, the pin out for lightning connectors requires
  an authentication chip according to wikipedia, so getting power
  out of a lightning device involves software authentication before
  power will flow.
The article describing 8 pins that are active, indicates that when power flows into the phone (the
  opposite of your use), pins 1 and 5 are ground and power respectively.
  However, until your cable identifies itself to iOS, no power will be
  provided.

A: Since Apple even communicates with USB Chargers, I would say you may need a Thunderbolt Controller.
Mouser link


text:
Q: Retrieve unknown number of GET values and put in one database row I'm trying to make a small project for house automation. Basically my hardware call a php (v5.6) script hosted on my WIFI router (gl-ar150) in order to transmit and storage the data in a SQLite (v3) database.
Due to the evolution of needs, I do not know how many values will be sent in the future but not more than 50.
Basically I'm doing it in this way. Getting the variables with $_GET, and it seems pretty:
$id = $_GET[ch];
BUT, I'm preparing an SQL request, ugly part
$db->prepare('UPDATE history SET div = div+1, val1=val1+?, val2=val2+?, val3=val3+?, val4=val4+?, val5=val5+? WHERE date='.$date[last_minute]);
Then I'm binding it in a foreach loop, pretty enough
$i++;
 $upd->bindValue($i,$val);
I'm looking for a solution for the ugly part refactoring. Before I'm starting to do some awful string manipulations. It's allowed to entry zero or null values into database, it's also allowed to modify the get method.
Thanks in advance.


text:
Q: Open the same Activity with new parameteres I searched a lot before asking my question and tried many ways but none of them worked with me.
I'm making a radio player ! so i have a listview containing a list of radio station every items contains some information with the link to be played when i click on the item.
So, when a click on item i create a new activity containing a player( the player will start a new service who will play the stream)
when i click back to the listview the activity of the player is removed from the stack.
when i click on the notification the application crashes because the activity is not found.
I've tried to override the BackButton ,but when i click back the apps return to the home screen :
@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

i tried adding some flags to the intent before starting ! but it won't work either !!
So , i'm completly blocked  ,can't find any method to handle this problem
Thanks for your help !
If you want some source code please tell me i will update my post!
thanks
Update : the log :
07-27 00:02:20.650: E/dalvikvm(9406): The following issues were seen:
07-27 00:02:22.390: E/AndroidRuntime(9406): FATAL EXCEPTION: main
07-27 00:02:22.390: E/AndroidRuntime(9406): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.MSoft.socialradio/com.MSoft.socialradio.StationListenActivity}: java.lang.NullPointerException
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.ActivityThread.access$700(ActivityThread.java:150)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.os.Looper.loop(Looper.java:176)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.ActivityThread.main(ActivityThread.java:5279)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at java.lang.reflect.Method.invokeNative(Native Method)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at java.lang.reflect.Method.invoke(Method.java:511)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at dalvik.system.NativeStart.main(Native Method)
07-27 00:02:22.390: E/AndroidRuntime(9406): Caused by: java.lang.NullPointerException
07-27 00:02:22.390: E/AndroidRuntime(9406):     at com.MSoft.socialradio.StationListenActivity.onCreate(StationListenActivity.java:91)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.Activity.performCreate(Activity.java:5267)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
07-27 00:02:22.390: E/AndroidRuntime(9406):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
07-27 00:02:22.390: E/AndroidRuntime(9406):     ... 11 more
07-27 00:02:31.900: E/AndroidRuntime(10122): FATAL EXCEPTION: main
07-27 00:02:31.900: E/AndroidRuntime(10122): java.lang.RuntimeException: Unable to start service com.MSoft.socialradio.MyMediaPlayerService@210972d0 with null: java.lang.NullPointerException
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2757)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.app.ActivityThread.access$2000(ActivityThread.java:150)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1383)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.os.Looper.loop(Looper.java:176)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.app.ActivityThread.main(ActivityThread.java:5279)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at java.lang.reflect.Method.invokeNative(Native Method)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at java.lang.reflect.Method.invoke(Method.java:511)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at dalvik.system.NativeStart.main(Native Method)
07-27 00:02:31.900: E/AndroidRuntime(10122): Caused by: java.lang.NullPointerException
07-27 00:02:31.900: E/AndroidRuntime(10122):    at com.MSoft.socialradio.MyMediaPlayerService.onStartCommand(MyMediaPlayerService.java:51)
07-27 00:02:31.900: E/AndroidRuntime(10122):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2740)
07-27 00:02:31.900: E/AndroidRuntime(10122):    ... 10 more

The service Player:
package com.MSoft.socialradio;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class MyMediaPlayerService extends Service implements OnPreparedListener, OnErrorListener, OnBufferingUpdateListener {

    Timer timer ;
    TextView songName;
    String GetSongInfo;
    MetadataTask metaTask=null;
    private MediaPlayer mediaPlayer = null;
    private boolean      isPlaying = false;
    String url;
    private static int classID = 579; // just a number

    public static String START_PLAY = "START_PLAY";
    final static String MY_ACTION = "IcyData";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getBooleanExtra(START_PLAY, false)) {
            url=intent.getStringExtra("url");
            play();

        }
        return Service.START_STICKY;
    }

    private void play() {
        if (!isPlaying) {
            isPlaying = true;

            Intent intent = new Intent(this, StationListenActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

            PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

            Notification notification = new Notification.Builder(getApplicationContext())
                .setContentTitle("Social Radio")
                .setContentText("Now Playing:under Construction")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pi)
                .build();

            /*mediaPlayer = MediaPlayer.create(this, R.raw.rehab); // change this for your file
            mediaPlayer.setLooping(true); // this will make it loop forever
            mediaPlayer.start();*/
            //url = "http://ice.abradio.cz:80/hit90128.mp3"; // your URL here
            Log.i("play","playing:"+url);
            try {
                 mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.setVolume(100, 100);
                    mediaPlayer.setDataSource(url);
                    mediaPlayer.setOnPreparedListener(this);
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnErrorListener(this);

                    mediaPlayer.setOnBufferingUpdateListener(this);
            } catch (Exception e) {

            }

            startForeground(classID, notification);
        }
    }

    @Override
    public void onDestroy() {
        Log.i("on Destory","Stopping");
        stop();
        //timer.cancel();
    }

    private void stop() {
        if (isPlaying) {
            Log.i("on Destory","Stopping");
            isPlaying = false;
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            stopForeground(true);
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer arg0) {
        mediaPlayer.start();
        StartTimer();
    }
    public InputStream OpenHttpPOSTConnection(String url) {
        InputStream inputStream = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // ---the key/value pairs to post to the server---

            HttpResponse httpResponse = httpclient.execute(httpPost);

            inputStream = httpResponse.getEntity().getContent();

        } catch (ConnectTimeoutException e) {
            Log.d("OpenHttpPOSTConnection TIMEOUT", e.getLocalizedMessage());
        } catch (Exception e) {
            Log.d("OpenHttpPOSTConnection", e.getLocalizedMessage());
        }
        return inputStream;
    }
    public void StartTimer()
    {
        try {
            final URL Url = new URL(url);
            Log.i("StartTimer",url);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    while(mediaPlayer!=null)
                    {
                    try {
                        Log.i("StartTimer","Sending:");

                        metaTask=new MetadataTask();
                        metaTask.execute(Url);
                        Intent intent_braodcast = new Intent();
                        intent_braodcast.setAction(MY_ACTION);

                           intent_braodcast.putExtra("DATAPASSED", GetSongInfo);

                           sendBroadcast(intent_braodcast);
                           Log.i("StartTimer","Sending:");
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    }
                }
            }).start();

        } catch (Exception e) {
            Log.i("StartTimer Exception","");
        }

    }
    protected class MetadataTask extends AsyncTask<URL, Void, IcyStreamMeta> {
        protected  IcyStreamMeta streamMeta;

        @Override
        protected IcyStreamMeta doInBackground(URL... urls) {

            try {
                if (OpenHttpPOSTConnection(urls[0].toString()) == null) {
                    //songName.setText("Error in connection");

                    throw new Exception("Error network");
                }
                streamMeta = new IcyStreamMeta(urls[0]);
                if (streamMeta == null) {
                    //songName.setText("Error in connection");
                    throw new Exception("Error in connection");
                }
                streamMeta.refreshMeta();
            } catch (IOException e) {
                // TODO: Handle
                Log.e(MetadataTask.class.toString(), e.getMessage());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.i("ExceptionDoinBackground", e.getLocalizedMessage());
            }
            return streamMeta;
        }

        @Override
        protected void onPostExecute(IcyStreamMeta result) {
            //super.onPostExecute(result);
            try {
                if (streamMeta.GetFullData() == "")
                    GetSongInfo="No Icy Data";
                else {
                    GetSongInfo=streamMeta.GetFullData();
                    //songName.setText(streamMeta.GetFullData());
                    Log.i("Onposteexecute", streamMeta.GetFullData());
                }

                // txtArtist.setText(streamMeta.getArtist());
                // txtTitle.setText(streamMeta.getTitle());
            } catch (IOException e) {
                // TODO: Handle
                Log.e(MetadataTask.class.toString(), e.getMessage());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

A: You are starting the service the first time adding the url, so in the line MyMediaPlayerService.java:51 works fine. When you start the service from the nofitication, you are not setting a url in the arguments. The service intent:
Intent intent = new Intent(this, StationListenActivity.class);
should have the url


text:
Q: Update progressView in UITableView based on indexpath I am working on a audio player app that should allow the user to click on a button on the UITableViewCell in a UITableView to play a song, then they can see the progression of the song on the progress bar. I don't want to create an object for each cell, I think that would cause me to lose significant efficiency, so instead I am using the dequeueReusableCell() function to initialize the cells based on data from excel.
For some reason, when I call my function updateProgress(), which should update the progressView value equal to the cell's AudioPlayer's current time, I get the error:
*** Assertion failure in -[UITableView _dequeueReusableCellWithIdentifier:forIndexPath:usingPresentationValues:]
A timer is used to run updateProgres() every .5 seconds, which is my way of checking if the btnPressed bool is true of false (maybe there is a better way of doing this?). The only functions I am using to handle the whole process are segueBtn(), which is in my TableViewCell.swift class, updateProgress(), which is in my TableView.swift class, and viewDidLoad() in my ViewController.swift class. Here are those functions:
ViewController.swift:
override func viewDidLoad()
{
    super.viewDidLoad()
    parseCSV()
    Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(FirstViewController.updateProgress), userInfo: nil, repeats: true)
}

func updateProgress() {
    if btnPressed == true {
        // Isolate Current Cell
        cell = tableView(myTableView, cellForRowAt: cellIndex) as! CustomTableViewCell
        if audioPlayer.isPlaying {
            cell.progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: true)
        }
        else {
            cell.progressView.setProgress(Float(audioPlayer.currentTime), animated: false)
        }
    }
}

TableViewCell.swift:
@IBAction func segueBtn(_ sender: Any) {
    do
    {
        cellIndex = (indexPath)!
        let audioPath = Bundle.main.path(forResource: songs[(indexPath?.row)!], ofType: ".mp3")
        try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        audioPlayer.prepareToPlay()

        // Indicates to updateProgress() that audio player is set up
        btnPressed = true
        audioPlayer.play()
    }
    catch
    {
        print ("Audio Player was not set up correctly")
    }
}

Is there any way that I can update the progressView of the correct cell using this strategy?


text:
Q: Maven: Cannot execute shell script here is how i am trying to execute a shell script
          <plugin>
                <artifactId>exec-maven-plugin</artifactId>
                <groupId>org.codehaus.mojo</groupId>
                <executions>
                    <execution><!-- Build Python Executable -->
                        <id>Build Python</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <configuration>
                            <executable>${basedir}/scripts/buildPython.sh</executable>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <executable>chmod</executable>
                    <arguments>
                        <argument>+x</argument>
                        <argument>${basedir}/scripts/buildPython.sh</argument>
                    </arguments>
                </configuration>
            </plugin>

but i get
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.5.0:exec (Build Python) on project packaging: Command execution failed. Cannot run program "/ajbfiausbf/scripts/buildPython.sh" (in directory "/ajbfiausbf`"): error=13, Permission denied -> [Help 1]

what am i doing wrong?

A: From your errors, I can see

error=13, Permission denied

Try giving permission to the buildPython.sh using ant plugin chmod task to see if it solves the problem. See below,
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.8</version>
            <executions>
                <execution>
                    <id>build</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <target>
                            <echo>run chmod in ${basedir}</echo>
                            <chmod file="${basedir}/scripts/buildPython.sh" perm="ugo+rx"/>
                        </target>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Permanently, give permission using .gitattributes for git or svn:executable property for subversion.
Thanks


text:
Q: How to retrieve the set of images from server and store it in documents directory in iOS? I want to retrieve a folder containing 10 images from server, then store that folder in my document directory. I did some code, but when I run it, I am getting the image urls, not the images themselves. Can anyone help me out?
My code:
-(void)viewWillAppear:(BOOL)animated
{

NSMutableData *receivingData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:@"http://Someurl.filesCount.php"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];

   NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

[receivingData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;

{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
printf("\n the path is :%s",[path UTF8String]);

NSString *zipPath = [path stringByAppendingPathComponent:@"filesCount.php"];

[receivingData writeToFile:zipPath options:0 error:&error];

        NSString *documentsDirectoryPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"filesCount"];
        NSLog(@"the path %@",documentsDirectoryPath);

}

A: I made this function in my previous project. You need to pass your imageView and serverUrl, then its automatically show image in your imageView and save image to temp directory, when you want again to fetch same image, then next time it take image from disk.
+(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{

NSFileManager *fileManager =[NSFileManager defaultManager];

NSString* theFileName = [NSString stringWithFormat:@"%@.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];

imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
    frameToCenter.origin.x = 0;

// center vertically
if (frameToCenter.size.height < boundsSize.height)
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
    frameToCenter.origin.y = 0;

actView.frame = frameToCenter;

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{

    NSData *dataFromFile = nil;
    NSData *dataFromUrl = nil;

    dataFromFile = [fileManager contentsAtPath:fileName];
    if(dataFromFile==nil){
        dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
    }

    dispatch_sync(dispatch_get_main_queue(), ^{

        if(dataFromFile!=nil){
            imgView.image = [UIImage imageWithData:dataFromFile];
        }else if(dataFromUrl!=nil){
            imgView.image = [UIImage imageWithData:dataFromUrl];
            // NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];

            BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
            if(filecreationSuccess == NO){
                NSLog(@"Failed to create the html file");
            }

        }else{
            imgView.image = [UIImage imageNamed:@"NO_Image.png"];
            imgView.tag = 105;
        }
        [actView removeFromSuperview];
        [actView release];
    });
});

}

A: If you'll showing the images loaded from server on UI, then
try SDWebImageView,  can be used with UIButton or UIImageView, very easy and efficient.
example,
[yourImageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Read how to use it?
Okay, now for multiple images, you may need to run a loop, if you've a common base url for all your pictures (on server) something like http://yoururl/server/pictures/1.png will be replace by 2.png 3.png ... n.png, or you get different urls for pictures need to pass that url, you can load it into imageview objects, and later save them into document directory (remember, SDWebImageView by default doing this work for you). You can turn this off too.
P.S. It will load images once and stored into local (in cache) it self, next time when you pass the same image url, it won't load from server and directly load the image from local.

A: Try using this code.
 NSURL* url = [NSURL URLWithString:@"http://imageAddress.com"];
 NSURLRequest* request = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
    NSData * data,
    NSError * error) {
if (!error){
        // do whatever you want with directory or store images.
    NSImage* image = [[NSImage alloc] initWithData:data];

}

}];

A: Use this code to download the image using URL and store in document directory. Iterate the logic for set of images to download and store.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *imageURL = @"http://sampleUrl";
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];

        NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Image1.png"]];
        if(image != NULL)
        {
            //Store the image in Document
            NSData *imageData = UIImagePNGRepresentation(image);
            [imageData writeToFile: imagePath atomically:YES];
        }


text:
Q: Assign App pool to site in IIS6 using c# I am trying to create and assign application pool to a website in IIS6 and IIS7 using c#. I managed to do this for IIS7 using Microsoft.Web.Administration; but since its not supported in IIS6 i want to accomplish this using System.DirectoryServices;. I have managed to create the application pool but the assigning application pool does not work.
Here is what I have so far...
   private static string DefaultAppPool = "DefaultAppPool";
   public static void SetApplicationPoolIIS6(string websiteName)
    {
        string metabasePath = "IIS://localhost/W3SVC";

        string appPoolName = GetSavedApplicationPoolName(websiteName);

        if (string.IsNullOrEmpty(appPoolName) || appPoolName.Equals(DefaultAppPool))
            appPoolName = websiteName + "AppPool";

        bool isAppPoolCreated = IsAppPoolCreatedIIS6(websiteName, appPoolName);

        if (!isAppPoolCreated)
            CreateApplicationPoolIIS6(appPoolName, metabasePath);

        DirectoryEntry w3svc = new DirectoryEntry(metabasePath);
        w3svc.RefreshCache();

        foreach (DirectoryEntry item in w3svc.Children)
        {
            string siteName = item.Properties["ServerComment"].Value == null ? "" : item.Properties["ServerComment"].Value.ToString();

            if (string.IsNullOrEmpty(siteName))
                continue;

            if (siteName.Equals(websiteName))
            {
                item.Invoke("Stop", null);
                item.Properties["AppPoolId"].Value = appPoolName;
                item.CommitChanges();
                item.Invoke("Start", null);
                break;
            }
        }

        w3svc.CommitChanges();

        DirectoryEntry w3svc2 = new DirectoryEntry(metabasePath);
        w3svc2.RefreshCache();
        SaveWebSiteSettingsIIS6(websiteName, appPoolName);
    }

Any idea why the below lines don't assign the created app pool ?
item.Properties["AppPoolId"].Value = appPoolName;
item.CommitChanges();

Any help is much appreciated. Thank you.


text:
Q: Includegraphics doesn't show the figure. Overleaf v2 I'm working on overleaf v2.
I wrote :
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[utf8]{inputenc}  % Accents codés dans la fonte
\usepackage[frenchb]{babel}  % Les traductions françaises
\usepackage{amsmath}
\usepackage{graphicx}
\graphicspath{ {./images/} }
 \usepackage{amsfonts}
 \usepackage{biblatex}
\begin{document}
....
\begin{figure}
\centering
\includegraphics{comp_W_log.jpg}
\caption{\textit{On compare la fonction de Lambert à $\log(x)-1$ dans un certain interval}}
\label{fig:my_label}
\end{figure}
 ....
\end{document}

But I just get, after compiling :

Can you help me plz ?
Edit: png didn't work either

A: It looks like your editor could be set to 'draft mode' on Overleaf (this skips compiling images to render a PDF faster). You can turn it off on the dropdown menu on the Recompile button:

Hope this does the trick, if you still see issues it could be worth writing to Overleaf support, at support@overleaf.com (I work there)


text:
Q: REGEX Get last 6 digits from string I am trying to get the last 6 digits from the strings that look like this
1234-56789 -- last 6 digits would be 456789
12345/6789 -- last 6 digits would be 456789
1234567-89 -- last 6 digits would be 456789
123-456789 -- last 6 digits would be 456789
This \d.{6}+$ regex gives me the numbers with characters - and /.
Output for 1234-56789 is 4-56789. So how can i get 456789 without characters - and /?
Best regards

A: I agree with @oram. First you can find the problamatic charcater with \D, replace with "" (empty string) and then get the final string with \d{6}$.

A: *

*One problem with this is that not all regex engines are created
equal. So if Python supports it, Java may not.

*Another is that I am unaware of being able to exclude a group of
characters from a subgroup and combine the results  (although there could be brute force solutions that result in long regexes).
But keeping with the keep it simple principle, here is a solution in Java that could be adapted to other languages
      String[] data =
            { "1234-56789", "12345/6789", "1234567-89", "123-456789", "12-223"
            };
      for (String s : data) {
         String temp = s.replaceAll("[/-]", "");
         String lastSix = "String too short";
         if (temp.length() >= 6) {
            lastSix = temp.substring(temp.length() - 6, temp.length());
         }
         System.out.println(lastSix);
      }


text:
Q: Unable to add dll file reference to F# project in VS2008 I can't seem to add a reference to a DLL file in F#.  It might be a bug with Visual Studio.
I attempted to add a reference to my F# project by clicking on "Add Reference" ->  "browse".  I found my DLL, and when I attempted to add it, nothing happened. The window didn't even close to confirm my selection.  Help please.

A: Are you adding a reference to a managed DLL?
Anyways, if you can, make a small repro and send it to fsbugs AT microsoft dot com.
Edit: Here's the list of known issues with the F# Sept CTP.

A: I think there are some known issues when the DLL is produced by Managed C++, however I don't know the details. In any case, sending a bug report to the F# team as Michael suggests is the best thing to do.

A: Adding a reference to the F# project never works for me, i need to debug the project, then i reference the resultant dll found in the debug folders. This usually does the trick for me.
When I reference the project it always tells me that there is no dll.


text:
Q: Solve general quadratic systems, or find rational points on a Fano variety Suppose we have $2n+1$ variables $\mathbf{x}=[x_0,x_1,x_2,\ldots,x_{2n}]^\mathsf{T}$ and $n$ symmetric matrices $(\mathbf{A}_1,\mathbf{A}_2,\ldots,\mathbf{A}_n)$ of dimension $(n+2)\times(n+2)$ and having coefficients in $\mathbb{Q}$. Define $\mathbf{u}={[1,x_0,x_1,x_2,\ldots,x_n]}^\mathsf{T}$, consider a system of $n$ quadratic equations
$$\begin{cases}\mathbf{u}^\mathsf{T}\mathbf{A}_1\mathbf{u}=x_{n+1}^2\\\mathbf{u}^\mathsf{T}\mathbf{A}_2\mathbf{u}=x_{n+2}^2\\\vdots\\\mathbf{u}^\mathsf{T}\mathbf{A}_n\mathbf{u}=x_{2n}^2\end{cases}$$
It is known that the solutions $\mathbf{x}$ of the above system form a $n+1$ dimensional Fano variety, which is rationally connected and is thus supposed to have a lot of rational points in $\mathbb{Q}$ (or at least in a finite extension of $\mathbb{Q}$).
However, instead of knowing how many rational solutions there are, I'd rather want to get some explicit rational solutions in $\mathbb{Q}$, provided that there is any.
This can be done by applying a generic rational point finding algorithm, which is somewhat useful when $n$ is small. However, the complexity grows exponentially with $n$ so it quickly becomes infeasible even for moderately large $n$ (e.g., $n=100$). I can also try to compute a Gröbner basis, but the complexity is even worse (double exponential) so it is not likely to give any help either.
I would like to know that, apart from those completely generic methods (exhaustive search, or Gröbner basis), is there any more efficient algorithm in finding rational solutions, that can take advantage of the fact that the defining equations are limited to quadratic forms and the resulting variety is rationally connected/Fano?
I am aware that the degree alone will not play an essential role as it is possible to convert any system of polynomials into system of quadratics, but I believe that being rationally connected really should mean something, or otherwise it will seem really strange to me, that despite of the variety being supposed to have a lot of rational points, and the rational points on it possess a particularly nice structure, I will have no way to do better in finding them than doing a generic search on a variety of generic type.
The algorithm is not required to be deterministic, nor is it required to prove the existence or non-existence of a rational solution. It would be acceptable as long as when there does exist rational solutions, it has a non-trivial success rate to find one (by non-trivial success rate I mean a success rate guaranteed to be larger than a positive absolute constant independent of $n$). It is not required to have completely polynomial complexity either. It would be acceptable as long as it runs in sub-exponential time and is capable of handling reasonably large $n$ like $n=100$.
If such an algorithm (of finding rational points in sub-exponential time) does not exist, then at least I would like to know an algorithm that, given two rational solutions $\mathbf{x}_1,\mathbf{x}_2$ of the above system, it constructs an explicit rational curve on the variety passing through those given points. Such a rational curve must exist (due to the very definition of being "rationally connected"), but instead of knowing "it must exist" I'd rather want to know an algorithm to explicitly compute it.
Does anyone has ideas on this? Any materials and references on explicit computations in rationally connected/Fano varieties are also much appreciated.


text:
Q: Google Play - Fully Shadowed apk I have an existing app on the PlayStore. I am releasing new version of the app as staged rollout. However, I am not able to publish the app due to "Fully Shadowed APK" error.

So far, I haven't found any documentation as to how to resolve this error. Anyone else faced this?

A: For me it worked the following way:

*

*First send a rollout only with the version you want to deactivate.

*Secondly, send a rollout with the version you want to publish to Beta.

Seems that under certain conditions Google Play cannot handle deactivating and publishing at the same time.

A: I had exactly the same issue and resolved it by using the following versionCode entry in config.xml:
<widget id="io.cordova.hellocordova"
  version="3.1.1"
  android-versionCode="3001001"

Here android-versionCode is critical. It must be an integer greater than the number associated with last APK that you have uploaded. Due to some reason my previous version had an additional zero in between creating a higher number which went unnoticed. Since I can't change that because its published I added a zero in the new versionCode and made it 3001001 instead of 300101.
Worked perfectly.
Hope that helps.

A: Got the same problem here, issue most probably brought by the new release manager.
It feels like that the previous release (the one already in prod) is somehow stuck in alpha, preventing the new one to be rolled out.
Google support contacted and waiting for resolution
(I'm working for an app with +25millions downloads, this issue is really something serious, hope google will take care of it really quickly)
In the meantime, we never used the beta channel, so we solved our problem by using it.

A: Easy way to handle this problem is something similar like,

Seems bugs on play store

A: We ran into this problem as well with split APKs. We assigned version code for each ABI with the following gradle (simplified):
ext.abiCodes = ['universal': 0, 'arm64-v8a': 1, 'armeabi-v7a': 2, 'x86': 3, 'x86_64': 4, ...]

android {

  applicationVariants.all { variant ->

    variant.outputs.each { output ->
      def abiName = output.getFilter(OutputFile.ABI)
      def abiVersionCode = project.ext.abiCodes.get(abiName)

      output.versionCodeOverride = variant.versionCode * 100 + abiVersionCode
      ...

With that we will have these APKs:
| ABI       | Version Code |
|-----------|--------------|
| universal | v100         |
| arm64-v8a | v101         |
| arm64-v7a | v102         |
| ...       | ...          |

And we got this "Fully Shadowed APK" error on APK v101. The reason is that any device that is on arm64-v8a will be able to install v102 since it is backward compatible.
Problem solved after we make the version code of armeabi-v8a higher than arm64-v7a.
ext.abiCodes = ['universal': 0, 'arm64-v7a': 1, 'armeabi-v8a': 2, 'x86': 3, 'x86_64': 4, ...]

You should watch out for this too.

A: Problem:
This APK will not be served to any users because it is completely shadowed by one or more APKs with higher version codes.
Resolution:
Remove this APK from your release or review the targeting and version codes of the APKs that you are including in this release.
I got the same error when I tried to update my app. The Project was old and was in Eclipse, I fixed it by decreasing targetsdkversion from 27 to 26, because imported, supported android lib was Android 7.1.1, I don't know how it worked, but it works for me. :D

A: in your release manager you see your last uploaded apk  and on your apk  you see the word retain click on it  scroll down page  then you see Deactivate option then click on it then upload your new apk again the n save to draft and review it then roll out and after that just wait .

A: Just remove you previous version from the console and upload the latest one then it will definitely work it won't try another time.

A: Update :-
Talked to a Googler working with Google Play console team regarding this issue. One misconception I had at the time was that you need to retain an APK if you want to have a staged rollout. I discussed this with him, and he clarified that it is not needed. Even in staged rollout, with no retained APK, Google  play will show an install option to users who visit the app's page. Hope this clears doubts for someone facing similar issues.
I was having the same problem and I fixed without clicking "Retain" for previous version and uploaded a new one and then "Start Rolling" button turn into clickable and done!! ^_^

A: The Play Console has a bug and that's why it doesn't work. This is the work around:
Say, you have two versions:

*

*Beta: 29

*Alpha: previously version 29, but now empty: 'Promoted to beta' it says. You want to upload version 30.

Then do this:

*

*Create a new Alpha release with version 30, and deactivate the previous APK. When you try to roll it out, it errors Fully shadowed APK.

*Go back a page and now remove version 30. Version 29 will be selected, click Save and Start roll out to Alpha. This only deactivates 29.

*Create a new Alpha release for 30, it should work now.

A: Note: this solution works for the time it was posted if doesn't work in the future don't consider it wrong because things changes with time.
You have to deactivate previous version while uploading a new APK that works for me. Simply deactivate previous versions and upload a new APK and roll it out for production.

A: For sure there is some kind of bug in Google Play Console. In our case we've uploaded the new APK directly in Production. Clicking on "Review" button leaded to the "Fully Shadowed apk" error message.
Then we've done the following with the APK that we wanted to publish and was uploaded as draft in Production:

*

*Delete it from Production.

*Upload it in Beta and then delete it.

*Upload it in Alpha and then delete it.

*Upload it again in Production.
After the last step the error message didn't appear again. It is not clear which of the steps helped to overcome the issue. Probably it is enough just to delete and upload it again, but I cannot be sure since I cannot reproduce it again.
I wish you luck! We all need it in this case :)

A: Just discard the current release then go back to create new release then select apk or aab file from your library(which apk or aab version was showing error) then save the file now you will not get error.

A: It says - other APKs have higher version code.  So you probably have a released APK that has a higher version code than your new APK.  So increase your new APK to a higher number.  You can see your other APK version codes on the android console.  And change in your config.xml in the widget section
<widget android-versionCode="999" id etc...>

A: Discard all the Apps and upload a new one with increasing Version Code.

A: That's the solution of this problem.
just disactivate the older version of the apk then you will be able to rollout the new version.

A: Our case is that we are pushing two APKs: Once for 32bit arm and one 64bit arm (due to Google's new requirements. We were seeing this same problem whenever the arm64-v8a APK had a smaller version code than the armeabi-v7a one.
Thus making sure that the arm64-v8a version had a higher versionCode than the armeabi-v7a version solved this problem for us.

A: You must build in this way to solve the problem
First: armeabi-v7a
Second: x86
Third: arm64-v8a
fourth: x86_64

Like this:
3000467 - armeabi-v7a
3000468 - x86
3000469 - arm64-v8a
3000470 - x86_64

A: If you previously retain any apps below the uploaded APK list in upload form , just deactivate it then goto 'review' your app. because if you retain any app it will not removed after uploaded another app , so the previous should be list in apps to deactivate table.

A: All I did was update the version and the bundle code. My version had been set at .13 and I changed it to 15. My Bundle was set to 13 and I changed it to 15. It let me post it fine after I did that. I am in open testing.

A: The problem occurs because you have to deactivate previous version of app. Now when uploading new version if there is retain option in old version do nothing just do the process and it will be done But if ther is option of deactivate in old version click that deactivate old version and now upload the app

A: The quickest solution to this is to remove the universal apk only if you face this issues in 2021 will uploading multiple apk to playstore .