text:
Q: How to remove double quotes from csv file When I open the generated csv file there are some unwanted double quotes in the column track_uri that I cannot remove. Please can you tell me how to remove them?
The code of the program is here:
import json
import csv
import os

input_data_dir = 'C:\\Users\\ProjectsDesktop\\dataset\\'
output_data_dir = 'C:\\Users\\Projects\\'

p_t_cols = ["pid", "track_uri"]
list_track_uri=[]

for filename in os.listdir(input_data_dir):
    if('.json' in filename):
        filepath = input_data_dir + filename
        print(filepath)
        data = json.load(open(filepath))
        playlists = data["playlists"]
        for p in playlists:
            line = [p["name"], p["collaborative"], p["pid"], p["modified_at"], p["num_tracks"], p["num_albums"], p["num_followers"]]

            pid = p["pid"]
            tracks = p["tracks"]
            for t in tracks:
                line = [t["artist_name"], t["track_uri"], t["artist_uri"], t["track_name"], t["album_uri"], t["duration_ms"], t["album_name"]]

                track_uri = t["track_uri"]

                line = [pid, track_uri]

                list_track_uri.append(track_uri)
uris= set(list_track_uri)

import random
final_uris=set(random.sample(uris, 500))
print(len(final_uris))
final_uris = ','.join(final_uris)

path=r'C:\\Users\\user\\Desktop\\ML Datasets\\'
filenames = os.listdir(path)
with open('submission.csv', mode='w', newline='', encoding='utf-8') as accounts:
    writer=csv.writer(accounts)

    for filename in sorted(filenames):
        if filename.startswith("challenge_set") and filename.endswith(".json"):
            fullpath = os.sep.join((path, filename))
            f = open(fullpath)
            js = f.read()
            f.close()
            mpd_slice = json.loads(js)
            writer.writerow(["pid",  "track_uri"])
            for playlist in mpd_slice["playlists"]:
                final_uris.replace('"', '')
                writer.writerow([playlist["pid"], final_uris])

Here is a screenshot from the output file

A: Change
writer.writerow([playlist["pid"], final_uris])

to
writer.writerow([playlist["pid"], *final_uris])

A: After a few hours I found the solution to this problem and I post it if anyone in the future will need it.
I changed this line into this by adding quotechar= " "
writer=csv.writer(accounts,  quotechar = " ")

Thank you all for your help.


text:
Q: Another word for someone who says everything is theirs What is a word for someone who says everything is his unless you pay half of it. My bf and I have been together for 3 years and I always sleep on one side of the bed and so I call it my side and he said that it's not my side because I didn't buy the bed. It's his.

A: I wouldn't say that there are any exact words to express this idea in English. Usually possession is fairly loose in English. We often use "have" or "my" for association, rather than actual ownership.
As such, one word you could use for him is "Pedantic", which means overly concerned with minor details or rules. "Pedantic" is often used for people who criticize the little things people say (such as "my side of the bed") because of a technicality (real or imagined). Especially if he often corrects little things you say for pointlessly small reasons, "pedantic" is probably a good word to use.

I told my friend to stop being so pedantic after he pointed out my third split infinitive.

Another good word, to point out that he is obsessed with owning things, is "materialistic". Quite simply, he's too focused on material things, and not enough on the important things.

Jack was so materialistic that, when he got into an accident, he cared more about his car than the other people.

A: I'd suggest that he is being a scrooge (as opposed to Scrooge)

In the English language, a scrooge – with a lowercase "s" – is a person who is unwilling to give to others. Others words with the same meaning are miserly and stingy. Scrooges are selfish, and not just at Christmas time or the holidays. Here is an example sentence: "Her father is such a scrooge."

Source

A: He has a trait of both being a niggard and inconsiderate. So, you say, he is niggardly inconsiderate.
niggardly: [Niggard and nigger wiki are etymologically unrelated words.]

Ungenerous with money, time, etc.; mean.

'he accused the Government of being unbelievably niggardly'

Inconsiderate:

careless of the rights or feelings of others

'it's inconsiderate of her to go away without telling us'

Here is an other example,
My boyfriend is a lot of fun and we get on really well, but he can be really selfish and niggardly inconsiderate.

A: Are you looking for the word possessive? Oxford Learner's Dictionary defines it as

not liking to lend things or share things with others

Example: Jimmy's very possessive about his toys.

redpajama_set_name: RedPajamaStackExchange


text:
Q: returned a response status of 415 Unsupported Media Type REST client I want to make a POST request to REST webservice and I want to pass customer java object with the POST request. But response shows 415 error code Unsupported Media type. My REST Client
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/cthix/rest/v1/m2");

Customer cust = new Customer();
cust.setId(101L);
ObjectMapper mapper = new ObjectMapper();
String jsonCustomer = mapper.writeValueAsString(cust);

ClientResponse restResponse = resource.accept("application/json").
                  post(ClientResponse.class,jsonCustomer);

                    System.out.println(restResponse.getStatus());
                    if(restResponse.getStatus()==200){
                        String output = restResponse.getEntity(String.class);
                        PrintWriter pw = response.getWriter();
                        pw.print(output);

                        pw.flush();
                        pw.close();
                    }

My REST SERVICE:
@Path(value = "/v1")
public class V1_status {
    @Path("/m2")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Customer returnCustomerDetails(Customer customer){
        Set<Integer> phones = new HashSet<Integer>();
        phones.add(123424541);
        phones.add(123432123);

        List hobbies= new ArrayList();
        hobbies.add("Swimming");
        hobbies.add("coding");;

        customer.setHobbies(hobbies);
        customer.setPhones(phones);
        customer.setCity("Noida");
        customer.setName("abhishek");
        return customer;
    }
}

Please guide how to fix it.

A: I actually got problem, the thing which I missed was: resource.type("application/json")
ClientResponse restResponse = resource.accept("application/json").type("application/json").post(ClientResponse.class,cust);

Two points which need to be paid attention:
1) No need to convert Customer object to Json manually.(if u convert also no issue at all)
2) No need to use @Consumes(MediaType.APPLICATION_JSON). if u even use it, no problem. This only tells, this method will accept this MediaType. If u dont use @Consumes annotation, REST Service method will try to consume it whatever format it is coming, and will try to parse the data coming from client to its appropriate Model object (in argument). If successfully parsed no problem. If data is not in appropriate format to sync with Model object. It will throw  exception. That's it.

A: The problem is that you are telling the service to consume JSON, the parameter customer is of type Customer, and in your REST client you are sending a string.
You need to

*

*Remove "@Consumes(MediaType.APPLICATION_JSON)" from your rest service

*In the client: sent a customer object (instead of its json representation)


text:
Q: Enabling OpenMPI support when compiling John the Ripper 1.8.0 I just made a VPN network between my VPS's and wanted them to run some John the Ripper tasks. I followed this manual, but since 1.8.0 version John the Ripper's Makefile does not have the following lines, which it refers to:
 CC = mpicc -DHAVE_MPI -DJOHN_MPI_BARRIER -DJOHN_MPI_ABORT`
 MPIOBJ = john-mpi.o

There's a legacy Makefile, which has the
 CC = mpicc -DHAVE_MPI

part, but, when I tried to compile with this, I see a lot of errors. I assume this legacy Makefile is not longer supported.
How can I enable OpenMPI support when compiling John the Ripper?
In case it matters, I am running Ubuntu.

A: Don't use that Makefile.
Do this:
./configure --enable-mpi

See if the report gave yes for OpenMPI
Then:
make -s


text:
Q: If $(M_{\lambda})$ be a chain of closed affine subspaces of $X$ $\Longrightarrow$ $\displaystyle \bigcap_{\lambda\in L} M_{\lambda}\neq \emptyset \;$? Let $X$ be a Banach space
Let $(M_{\lambda})_{\lambda \in L}$ be a chain of closed affine subspaces of $X$
We can say that $$\displaystyle \bigcap_{\lambda\in L} M_{\lambda}\neq \emptyset   \;\;?$$
affine subspace: translate of a linear subspace
chain: $\lambda_1 \neq \lambda_2$ , $M_{\lambda_1}\subset M_{\lambda_2}$ or $M_{\lambda_2}\subset M_{\lambda_1}$
Any hints would be appreciated.

A: Hint: consider $X=\ell_1$, $L=\mathbb N$, and $$M_n=\left\{(x_k)\in \ell_1: x_1=\dots=x_n=0, \ \sum_{k\in\mathbb N} x_k=1\right\},\quad n\in\mathbb N$$


text:
Q: Where is my PATH? When I run the following command, I see several paths and all looks well.
echo $PATH

However, I want to find out where these paths are stored.
I have looked for ~/.bash_profile and ~/.zshrc but they don't exist.

A: Try to look in /etc/profile.
"/etc/profile contains Linux system wide environment and startup programs. It is used by all users with bash, ksh, sh shell. Usually used to set PATH variable, user limits, and other settings for user. It only runs for login shell." (https://bash.cyberciti.biz/guide//etc/profile)


text:
Q: SQL Server - Counting total number of days user had active contracts I want to count the number of days while user had active contract based on table with start and end dates for each service contract. I want to count the time of any activity, no matter if the customer had 1 or 5 contracts active at same time.
+---------+-------------+------------+------------+
| USER_ID | CONTRACT_ID | START_DATE |  END_DATE  |
+---------+-------------+------------+------------+
|       1 |          14 | 18.02.2021 | 18.04.2022 |
|       1 |          13 | 02.01.2019 | 02.01.2020 |
|       1 |          12 | 01.01.2018 | 01.01.2019 |
|       1 |          11 | 13.02.2017 | 13.02.2019 |
|       2 |          23 | 19.06.2021 | 18.04.2022 |
|       2 |          22 | 01.07.2019 | 01.07.2020 |
|       2 |          21 | 19.01.2019 | 19.01.2020 |
+---------+-------------+------------+------------+

In result I want a table:
+---------+--------------------+
| USER_ID | DAYS_BEEING_ACTIVE |
+---------+--------------------+
|       1 |               1477 |
|       2 |                832 |
+---------+--------------------+

Where
1477 stands by 1053 (days from 13.02.2017 to 02.01.2020 - user had active contracts during this time) + 424 (days from 18.02.2021 to 18.04.2022)
832 stands by 529 (days from 19.01.2019 to 01.07.2020) + 303 (days from 19.06.2021 to 18.04.2022).
I tried some queries with joins, datediff's, case when conditions but nothing worked. I'll be grateful for any help.

A: If you don't have a Tally/Numbers table (highly recommended), you can use an ad-hoc tally/numbers table
Example or dbFiddle
Select User_ID
      ,Days = count(DISTINCT dateadd(DAY,N,Start_Date))
 from  YourTable A
 Join ( Select Top 10000 N=Row_Number() Over (Order By (Select NULL))
         From master..spt_values n1, master..spt_values n2
      ) B
  On N<=DateDiff(DAY,Start_Date,End_Date)
 Group By User_ID

Results
User_ID     Days
1           1477
2           832


text:
Q: Run deploy automatically when branch receives MR on Gitlab I want to run automatically my deploy job on Gitlab when my branch receives a merge by merge request. How can I do this?
deploy-tests:
  tags:
    - aws-sdk
  stage: deploy
  only:
    - stage
  cache: {}
  script:
    - cd ngapp
    - call npm ci
    - call npm run-script i18n
    - call npm run-script lint
    - call build.bat tests
    - copy .htaccess dist
    - copy Web.config dist
    - deploy.bat tests

A: If you want your pipeline to be executed when it receives an MR.
You need to pass the keyword merge_requests at your only clause. (https://docs.gitlab.com/ee/ci/yaml/#onlyrefs--exceptrefs)
Change
deploy-tests:
  tags:
    - aws-sdk
  stage: deploy
  only:
    - stage
  cache: {}
  script:
    - cd ngapp
    ...

To
deploy-tests:
  tags:
    - aws-sdk
  stage: deploy
  only:
    - merge_requests
    - stage
  cache: {}
  script:
    - cd ngapp
    ...


text:
Q: How to Loop through a If condition untill the user enter a required value, in Visual Basic Console.WriteLine("Please Enter the number")
Dim number As Integer = Console.ReadLine()

If (number=< 40) Then
    number = number* 10
ElseIf (number=< 150) Then
    number= number* 15
Else
    number= number* 26
End If
Console.WriteLine(number)

Dim total As Integer
Dim vALUE As Integer

   Console.WriteLine("Please, type 1 for x . Type 2 for y. Type 3 z")
vALUE = Console.ReadLine()

If vALUE = 1 Then
    Console.WriteLine("x")
    total = number* (106 / 100)

ElseIf vALUE = 2
    Console.WriteLine("y")
    total = number* (112 / 100)

ElseIf uSERvALUE = 3
    Console.WriteLine("z")
    total = number* (116 / 100)

Else
    Console.WriteLine("Sorry please re-enter the value")
    vALUE = Nothing

End If

End While
Please tell me how to repeat the if condition. In the else line I have displayed to the user to re-enter the value. Therefore I need to repeat the if condition until the value is 1 or 2 or 3.Please explain how to do I'm a newbie.

A: You can use infinite While-loop  ,and  put "Exit While" on the end of conditional statement you agreed , so there are few ways out from infinite loop.
For example , on your code:
Console.WriteLine("Please Enter the number")
    Dim number As Integer = Console.ReadLine()

    If (number=< 40) Then
        number = number* 10
    ElseIf (number=< 150) Then
        number= number* 15
    Else
        number= number* 26
    End If
    Console.WriteLine(number)

    Dim total As Integer
    Dim vALUE As Integer

'infinite loop until user input 1,2 or 3
While True

    Console.WriteLine("Please, type 1 for x . Type 2 for y. Type 3 z")
    vALUE = Console.ReadLine()

    If vALUE = 1 Then
        Console.WriteLine("x")
        total = number* (106 / 100)
        Exit While    'condition matched , break from While
    ElseIf vALUE = 2
        Console.WriteLine("y")
        total = number* (112 / 100)
        Exit While    'condition matched , break from While
    ElseIf uSERvALUE = 3
        Console.WriteLine("z")
        total = number* (116 / 100)
        Exit While    'condition matched , break from While
    Else
        Console.WriteLine("Sorry please re-enter the value")
        vALUE = Nothing

    End If

End While

'do further more you need


text:
Q: Is it better to have a Singleton than passing the same object around? I'm working on a natural language processing project (in C#), where I need to refer to words by their indices rather than the strings themselves to speed things up. For example, the sentence "i am what i am" should be stored as "0 1 2 0 1".
In this project, there are many classes that store sentences this way. To deal with this, I initially planned to implement a singleton class named Codebook for it, so that in any place in my project, whenever I needed to convert the string of a word to its index (or get string by index), all I need to say is Codebook.Instance.Convert(n) or something like that.
However, this causes trouble because I need to have several Codebooks for different use (e.g, one for Chinese, one for English, and even one for part-of-speech tagging labels), so I thought of another way to to it. At the very top of my project structure, I create an instance of Codebook, and then I pass it all around. In this way, almost every method that deals with sentences will have a Codebook parameter. Since in C#, passing an object is in the form of reference rather than its real content, all appearance of the Codebook objects all refer to the same one.
So my question is, will the second approach cause problem, if the Codebook object is passed multiple times? I am concerned because, the usage of index instead of string itself is intensive in my project. I know that the singleton approach is okay to deal with my problem, but as I said, I am not allowed to use that. So I need to know if the second approach is okay when say, there's a long chain of method invoking along which the same Codebook object should pass.

A: Normally I would suggest to use dependency injection through the constructor. Just pass the codebook to the constructor and keep a readonly reference in your class. This way you are sure you have the right code book in all your classes. A singleton approach would also deal with the problem, however it will be harder to test and maintain.
public class MyBusiness{
   public MyBusiness(Codebook codebook){
       Codebook = codebook;
   }

   private readonly Codebook Codebook;

  ...
}

A: You said above in one of the comments that since you need code book in different languages you can't use singleton. How about creating another class and having List of CodeBook (Or Dictionary with language as the key so you can fetch it appropriately) as one of its properties and make the new class as singleton. This way you always get the same object back but also have a collection of Codebooks.


text:
Q: "detail": "Authentication credentials were not provided." getting this error while posing uid and token I created class based view to access uid and token .
I wish to activate user that created. I am receiving the activation link via email. when I click on link I wish activate that user. But getting error 401 in response and {"detail":"Authentication credentials were not provided."} in content
Also I try by creating function- based view but giving same error
Class- Based view:
class UserActivationView(APIView):
def get (request , uid , token ):
    protocol = 'https://' if request.is_secure() else 'http://'
    web_url = protocol + request.get_host()
    post_url = web_url + "/auth/users/activate/"
    post_data = {'uid': uid, 'token': token}
    result = requests.post(post_url, data = post_data)
    content = result.text
    return Response(content)

Function-Based view
@api_view(["GET"])
@permission_classes([permissions.AllowAny])
def get (request , uid , token ):
    protocol = 'https://' if request.is_secure() else 'http://'
    web_url = protocol + request.get_host()
    post_url = web_url + "/auth/users/activate/"
    print("post_url :", post_url)
    post_data = {'uid': uid, 'token': token}
    print("post_data : ", post_data)
    result = requests.post(post_url, data = post_data)
    print("result : ",result)
    content = result.text
    print("content : ", content)
    return Response(content)

urls.py
urlpatterns = [
    # re_path(r'^auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', get),
    re_path(r'^auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', UserActivationView.as_view()),

]

settings.py
    DJOSER = {
    'ACTIVATION_URL': "auth/users/activate/" + '{uid}/{token}/',
    'SEND_ACTIVATION_EMAIL': True,
    'SEND_CONFIRMATION_EMAIL': True,
    'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
    'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
    'USER_CREATE_PASSWORD_RETYPE': True, #Designed to propote good programming practice
    'SET_PASSWORD_RETYPE': True, #Designed to propote good programming practice
    'PASSWORD_RESET_CONFIRM_RETYPE': True, #Designed to propote good programming practice
    'LOGOUT_ON_PASSWORD_CHANGE' : True, #Note : Logout only works with token based authentication. djoser 2.10
    'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system
    'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system
    'HIDE_USERS': True,
    'token': 'djoser.serializers.TokenSerializer',
    'token_create': 'djoser.serializers.TokenCreateSerializer',
    'LOGIN_FIELD': 'email', #Default: User.USERNAME_FIELD where User is the model set with Django's setting AUTH_USER_MODEL.
     'SERIALIZERS': {
         'user': 'user_profile.serializer.UserSerializer',
     },
}

urls.py
path("", include('app_user.urls')),
re_path(r'^auth/', include('djoser.urls')),
re_path(r'^auth/', include('djoser.urls.authtoken')),#For using django token

A: To make this request, you need to be authenticated. Try adding token to your authorization header.


text:
Q: Can Orchard CMS allow random internet people to register to my site? I'm about to start a new commission project and I think Orchard CMS is a good fit for what they're asking. More or less, at this point I'm still looking at my options.
Does Orchard allow people to register on my site?
According to the documentation, it seems that only Administrators can create users and assign roles to them. If this is the case, I can't use Orchard.
Maybe I missed something in the docs?

A: What you missed is the user settings. There is a checkbox there to allow people to register to the site. The topic you linked to is about user administration, it says nothing about who can register.


text:
Q: Updating BigQuery dataset access from C# I am working with BigQuery. I create a DataSet and I want to define access rights with C# language.
It's not clear to me how to do it.
In  GOOGLE web page https://cloud.google.com/bigquery/docs/dataset-access-controls is explained how to do it with some example for Java and Pyton (see below), but no example is provided for c#.
example in pyton:
dataset = client.get_dataset(dataset_id)  # Make an API request.

entry = bigquery.AccessEntry(
    role="READER",
    entity_type="userByEmail",
    entity_id="sample.bigquery.dev@gmail.com",
)

entries = list(dataset.access_entries)
entries.append(entry)
dataset.access_entries = entries

dataset = client.update_dataset(dataset, ["access_entries"])  # Make an API request.

full_dataset_id = "{}.{}".format(dataset.project, dataset.dataset_id)

Can anybody help please?

A: It's probably best to use the BigQueryDataset.Patch method, from the Google.Cloud.BigQuery.V2 package:
// Fetch the existing dataset
var client = BigQueryClient.Create(projectId);
var dataset = client.GetDataset(datasetId);

var accessList = dataset.Resource.Access ?? new List<AccessData>();
accessList.Add(new AccessData
{
    Role = "Reader",
    UserByEmail = "sample.bigquery.dev@gmail.com"
});
var patchedResource = new Dataset { Access = accessList };

// Push the changes back up to BigQuery
dataset.Patch(patchedResource, matchETag: true);

As an alternative, you can use Update to update the replace the dataset resource completely:
// Fetch the existing dataset
var client = BigQueryClient.Create(projectId);
var dataset = client.GetDataset(datasetId);

// Modify it in memory
var resource = dataset.Resource;
if (resource.Access is null)
{
    // If there's no access list yet, create one.
    resource.Access = new List<AccessData>();
}
var newAccess = new AccessData
{
    Role = "Reader",
    UserByEmail = "sample.bigquery.dev@gmail.com"
};
resource.Access.Add(newAccess);

// Push the changes back up to BigQuery
dataset.Update();

A: At the and I managed to make it work.
I used the same solution suggested by Jon Skeet, using the Patch method.
I attach my code here by.
public static bool GrantDatasetAccess(string dataSetId, bool online, string role, string email,
            string bigQueryJsonPath, string bigQueryScope, string projectId, clsLog log)
        {
        try
        {
            BigQueryClient client = GetBigQueryClient(online, bigQueryJsonPath, bigQueryScope, projectId);
            BigQueryDataset dataset = GetDataSet(online, dataSetId, bigQueryJsonPath, bigQueryScope, projectId, log);

            List<AccessData> accessList = new List<AccessData>();
            var accessData = new AccessData()
            {
                Role = role,
                GroupByEmail = null,
                UserByEmail = email,
                SpecialGroup = null,
                IamMember = null,
                Domain = null,
                View = null

            };
            accessList.Add(accessData);
            dataset.Resource.Access = accessList;
            dataset.Patch(dataset.Resource, true);
        }
        catch (Exception e)
        {
            log.ManageError("Error GetDataSet: {0}\nError: {1}", dataSetId, string.Concat(e.Message, "\n", e.StackTrace));
        }
        return true;
    }


text:
Q: (vb 2010) object continue moving, but stop when i hit a button. When i add a button the entire code stops I need to make an object continue moving when arrow keys are pressed, but stop when i hit a button. When I add a button the entire  code stops.
    Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Do While e.KeyCode = Keys.Left
        If PictureBox1.Left = 0 Then
            Exit Do
        End If
        PictureBox1.Left -= 1
    Loop
    Do While e.KeyCode = Keys.Right
        If PictureBox1.Left = 877 Then
            Exit Do
        End If
        PictureBox1.Left += 1
    Loop
    Do While e.KeyCode = Keys.Up

        If PictureBox1.Top = 0 Then
            Exit Do
        End If
        PictureBox1.Top -= 1
    Loop
    Do While e.KeyCode = Keys.Down

        If PictureBox1.Top = 420 Then
            Exit Do
        End If
        PictureBox1.Top += 1
    Loop
End Sub

A: Your app stops because it is stuck in the loop inside the KeyDown event for as long as the key is held down and never gets any idle time to process pending Windows Messages (such as repainting).
The easy, and incredibly bad, way to "fix" this would be to call Application.DoEvents inside each Loop.  This will manually tell your application to process the pending messages.  For any kind of serious work you want to avoid this method though, as it is a "Code Smell" that usually means you are doing something wrong.  For a well written application there is usually no reason to ever manually call Application.DoEvents.
You would be better off changing it to use a timer with a low interval that periodically checks the state of the keyboard and handles advancing the state of the application by one "tick" at a time.


text:
Q: PhotoVIewAttacher and PIcasso unzoom picture on fragment change Ok, so, I have implemented photoviewattacher and picasso into one imageview, when I swipe image 1 to change the picture to image 2 and try to get back, the image 1 is still zoomed where I left it. How to solve this? Here is the code:
private PhotoViewAttacher mAttacher;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout resource that'll be returned
    View rootView = inflater.inflate(R.layout.fragment_katalozi_slike, container, false);

    // Get the arguments that was supplied when
    // the fragment was instantiated in the
    // CustomPagerAdapter
    Bundle args = getArguments();
    final ImageView imageView = (ImageView) rootView.findViewById(R.id.imageViewAdapterZaListanjeKataloga);
    mAttacher = new PhotoViewAttacher(imageView);
    Callback imageLoadedCallback = new Callback() {

        @Override
        public void onSuccess() {
            if (mAttacher != null) {
                mAttacher.update();
            } else {
                mAttacher = new PhotoViewAttacher(imageView);
            }
        }

        @Override
        public void onError() {
            // TODO Auto-generated method stub

        }
    };

    Picasso.with(getActivity()).load(args.getString("url")).placeholder(R.drawable.load).error(R.drawable.error).into(imageView, imageLoadedCallback);

    ((TextView) rootView.findViewById(R.id.brojStranaNaSliciKataloga)).setText(String.valueOf(args.getInt("trenutnaStranica")) + "/" + String.valueOf(args.getInt("konacanBrojStranica")));
    ImageButton imageButton = (ImageButton) rootView.findViewById(R.id.shareButtonKatalozi);
    ImageButton locirajMe = (ImageButton) rootView.findViewById(R.id.locirajButtonKatalozi);
    final String zaShare = args.getString("linkKataloga");

    locirajMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getLatLng(String.valueOf(Static.prodavci.getId()));
        }
    });

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            shareIt(zaShare);
        }
    });

    return rootView;
}

A: You do
@Override
public void onDestroyView() {
    super.onDestroyView();
    mAttacher.cleanup();

}

worked for me.


text:
Q: Emacs Lisp Built-In Indentation Issue with Keywords Original

Say, I have a function like this:
(defun my-function ()
  "This is my function."
  :his-keyword xxx
  :her-keyword yyy
  (his-function)
  (her-function))

After applying Emacs built-in indentation for Emacs Lisp, I get:
(defun my-function ()
  "This is my function."
  :his-keyword xxx
   :her-keyword yyy
    (his-function)
    (her-function))

Of course I expected it to stay as it was, so looks like a bug to me. Does anyone know how to intercept this behavior? Or should I file a bug report? I'm on Emacs 24.3.
Update

I figured it out.
I've been extending the emacs-lisp-mode with my elisp-mode in order to add more syntax highlighting:
...

(define-derived-mode elisp-mode
  fundamental-mode
  "EL"
  "A major mode for Emacs Lisp."
  (emacs-lisp-mode)
  ...)

(provide 'elisp)

And then somewhere:
(require 'elisp)

(add-to-list
 'auto-mode-alist
 '("\\.el" . elisp-mode))

While elisp-mode was loading successfully, it turned out that emacs-lisp-mode did not load even though I've put (emacs-lisp-mode) into elisp-mode initialization (see above).
After changing to:
(define-derived-mode elisp-mode
  emacs-lisp-mode
  "EL"
  "A major mode for Emacs Lisp."
  ...)

emacs-lisp-mode turns on properly and the indentation finally behaves as expected. That was pretty subtle.
Although, the 2nd variant seems more natural and right, can anyone give me a clue why the 1st variant didn't work?

A: original question
I cannot reproduce this with emacs -q and emacs-lisp-mode, so something is wrong with your setup.
You will have to figure out what in your .emacs triggers this behavior, and then report the bug (if it contradicts the documented behavior).
reply to your edit
I think the difference is, more or less, similar to a class inheriting from another class:
(defclass c1 (c2))

and having a field of that class:
(defclass c1 () ((a :type c2)))

See also

*

*Defining Derived Modes

*Create new mode in emacs
You might also want to ask a separate question.


text:
Q: How do I test an instance variable in a controller? A couple of my mentors have told me to test a piece of code with controller spec even though the contents are being tested by some request specs. I am wondering if I can test whether an instance variable like @user can be set to someObject or nil from within an rspec controller test?
I've tried a couple different ways to test this so far, but my skills regarding rspec testing are to say the least, elementary. The first thing I tried was mocking out the current_user and the 'User.get_from_auth_user(current_user). The mocked object prints fine and outputs. The problem is... I want to be able to say something like expect(@user).to equal(mockedUser) but this never seems to work. I always get something like:
Expect does not equal received
expected is nil
received is { someMockedObject }

Here is the code I want to test.
class ApplicationController < ActionController::Base
  before_action :set_user

  def set_user
    return if current_user.nil?

    @user = User.get_from_auth_user(current_user)
  end
end

I want to know if I'm going down the right path or what would be the better alternative to fully test this chunk of code. I feel like the answer should be a simple one.

A: Your mentors are being stupid. While it can be good to understand controller specs as they are everywhere in legacy applications adding them to new applications is not a good practice.

For new Rails apps: we don't recommend adding the
  rails-controller-testing gem to your application. The official
  recommendation of the Rails team and the RSpec core team is to write
  request specs instead. Request specs allow you to focus on a single
  controller action, but unlike controller tests involve the router, the
  middleware stack, and both rack requests and responses. This adds
  realism to the test that you are writing, and helps avoid many of the
  issues that are common in controller specs.

DHH explains pretty well what is wrong with testing the instance variables of your controller and what you should be doing instead:

Testing what instance variables are set by your controller is a bad
  idea. That's grossly overstepping the boundaries of what the test
  should know about. You can test what cookies are set, what HTTP code
  is returned, how the view looks, or what mutations happened to the DB,
  but testing the innards of the controller is just not a good idea.

Which is why assigns was extracted to a separate gem. It all boils down to testing what your code does - not how it does it.
See:

*

*https://github.com/rspec/rspec-rails/issues/1838

*https://github.com/rails/rails/issues/22496

*https://github.com/rails/rails/issues/18950

A: Use assigns(:user) to get the instance variable @user. In your spec, @user is a variable on that test context, it's not the same @user from the controller.
https://relishapp.com/rspec/rspec-rails/docs/controller-specs

A: In addition to @chans and @arieljuod answers, it worth to mention in order to use assigns in your specs, you need to set up rails-controller-testing gem, because assigns is deprecated starting from Rails 5.
# File actionpack/lib/action_dispatch/testing/test_process.rb, line 6
def assigns(key = nil)
  raise NoMethodError,
    "assigns has been extracted to a gem. To continue using it,
    add `gem 'rails-controller-testing'` to your Gemfile."
end

A: The controller test case looks like this
describe 'GET #set_user' do
  let!(:mock_user) {
      @mockuserObj = { id: 1, name: "username" }
  }
  before(:each) do
    controller.instance_variable_set(:current_user, @mockuserObj)
    get :set_user
  end
  context 'when current_user is present' do
    it "sets the current user" do
      expect(assigns(:user)).to eq(@mockuserObj)
    end
  end
end


text:
Q: Using node 'fs' module and 'readdir' method using AMD I need to loop through a folder (the data folder in my application) and get file names in a javascript application. The application is not setup as a Node.js application per se ( although I have npm and node.js installed on my computer). It seems that the options to do this are limited. I am seeing either a php solution or a Node.JS solution using the File-System or fs module and the .readdir method. I have already run >>npm install file-system --save' to install the module and create anode-module` folder. However, my application is setup more AMD style to bring in modules and libraries like this:
require([...
    "dojo/json",
    "dojo/promise/all",
    "dojo/domReady!"], function(JSON,
    all) { ...

Can I just add "/node-modules/file-system" under my require([.. and file-system in function(... and start using the methods? Is there something I am missing here or an easier way to do this?

A: It sounds like you are describing UI code, but what you want to do is access some items on the file system.
You won't be able to access files in the file system from the browser - you would need to have a node.js service layer (if you want to use node.js) that can send that information to the UI via HTTP requests. Link about why JS does not have access to filesystem
For a node.js service to do that,  those modules are already available without any installation of additional modules
// index.js

var fs = require('fs');

// your logic here:

All you'd need to do to start that server side logic would be to run node index.js
Setting up a Web API goes a little beyond this post, but there are plenty of tutorials and frameworks and help for setting up a node.js server if you haven't done so before.
I'd recommend just trying it out with node.js since you already have it installed and experimenting a little bit to understand how it works.


text:
Q: What are the primary advantages of using Kernels in predicting continuous outcomes? Consider the linear model: $$y = X \theta + \epsilon $$ with $X$ inputs or features of inputs and $\theta$ a vector of parameters (and $\epsilon$ the error) with regularized error function $$ J(w)= \frac{1}{2} [X \theta - y]^T[X \theta - y] + \frac{\lambda}{2}\theta^T\theta.$$
The idea of kernels $k(x_i,x_j)$ is to define a similarity function between all observation pairs $i,j$ and summarize them in the Gram Matrix $K$. If we define $K=XX^T$, then $J(w)$ can be re-written as $$J(a)= \frac{1}{2}a^TKKa-a^TKt+\frac{1}{2}t^Tt+\frac{\lambda}{2}a^TKa$$ where $$a = (K + \lambda I_N)^{-1} t.$$
Finally a prediction for $y$ can be made as $$\hat{y}(x)=k(x)^T(K+\lambda I_N)^{-1}t.$$ I understand that, while it is amazing that we can eliminate the parameters completely from the prediction equation, the computational burden strongly increases because $K$ needs to be inverted and is of order $N \times N$.
What I do not understand is: what are the advantages of using a Kernel in this model?

A: The following is from Christopher M. Bishop's "Pattern Recognition and
Machine Learning" page 294 where $M$ represents the feature dimension:
"In the dual formulation, we determine the parameter vector a by inverting an
$N ×N$ matrix, whereas in the original parameter space formulation we had to invert an $M × M$ matrix in order to determine w. Because N is typically much larger than M, the dual formulation does not seem to be particularly useful. However, theadvantage of the dual formulation, as we shall see, is that it is expressed entirely interms of the kernel function $k(x, x)$. We can therefore work directly in terms of kernels and avoid the explicit introduction of the feature vector $\phi(x)$, which allows us implicitly to use feature spaces of high, even infinite, dimensionality."


text:
Q: How to pass data from activity to broadcastReceiver? i have code that calls a broadcast receiver, in the receiver, i try to get the extra data from the intent, but it's null.
so,
     Intent intent = new Intent(MainActivity.this, CallAlarm.class);
                          intent.putExtra("medicine", "kkk");

                          PendingIntent sender=PendingIntent.getBroadcast(
                                  MainActivity.this,0, intent, 0);

                          AlarmManager am;
                          am = (AlarmManager)getSystemService(ALARM_SERVICE);
                          am.set(AlarmManager.RTC_WAKEUP,
                                 c.getTimeInMillis(),
                                 sender
                                );

and in the BroadcastReceiver.onReceiver(),
    String name = i.getStringExtra("medicine");

but medicine is null. what am i missing?

A: Just create the PendingIntent with flag PendingIntent.FLAG_UPDATE_CURRENT,
 Intent intent = new Intent(MainActivity.this, CallAlarm.class);
 intent.putExtra("medicine", "kkk");
 PendingIntent sender=PendingIntent.getBroadcast(
                                  MainActivity.this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

This will enable you to pass the data to the BroadCastReceiver.

A: I was trying the above code, I get value always null. My broadcast receiver starts on bootup so apart from the above code I also add intent.setAction("android.intent.action.BOOT_COMPLETED");
Still it gives me null.


text:
Q: HTML image in a span tag align both at the bottom I have 2 images side by side, both in their  tag. The one image is smaller than the other, however, they are both "hooked" at the top of their bounding parent element (or their outer box element, not sure how to say this).

But I would like to place the second smaller image aligned at the bottom with the other image, not at the top... currently they look like this:

However, I would like them be aligned at the bottom, so that the second smaller image is on the same level at the bottom with the bigger image
Edit:
Sorry I forgot, they are both surrounded in an additional  tag from Angular js "ngx-admin" template.. maybe that has to do something with it?

A: Use vertical-align:bottom" into your second span:-

A: Did you try this?

A: I found it out myself...
Just had to add some manual snippet on the first one:
 bottom: 0; top:5px;

that did the trick and added some margin on top....
somehow margin-top or padding-top did not work either...


text:
Q: Безопасное хранение пароля Доброго времени суток.
Подскажите,как организовать безопасное хранение пароля от SMTP,чтобы ни в app.config?,ни при прогоне рефлетктором а-ля ILSpy,NET Reflector пароль не отображался?
Делал SecureString,но он отлично отображается через проги названные выше. После прогона конфига через aspnet_regiis теряется возможность использования на другой машине без манипуляций


text:
Q: How to implement a control system I have designed a Control System and don't know how to implement it.
I have modeled the physical system and have designed the control based on the State Space method.
The state space form is as follows: x' = Ax + Bu; y = Cx;
A, B, and C are matrices, x is the state vector, u is the input vector, and y is the output vector.
I designed the A, B, and C matrices in MATLAB, and want to implement it in C onto a micro-controller.
How do I actually implement my system now?
I am wanting to take two readings from a sensor that is measuring the system I attempting to control, send those two readings into my controller, and send one output back to my system.
I have designed the controller based on the dynamics of the system and techniques that are taught in an undergraduate level Automatic Control Systems class. Do the measured values go into the input vector?
And then I send the previously determined output value back into the system, and repeat for each sample?

A: Since you are implementing this system in a micro-controller, you would be better off converting your design from continuous time to discrete time.  You are going to  need analog to digital converters for you're inputs and digital to analog converters for your outputs.  The math should be simple to implement.  You're code will be based around a regular loop that samples inputs and updates outputs, not necessarily at the same rate as the system sampling rate.  You should make the timing through your control loop something that can be controlled with a parameter of some sort.  The dynamics of a discrete time control system are greatly affected by loop timing and delay.
I would recommend the following book: http://jeffreystevens25.blog.com/2012/10/26/online-applied-control-theory-for-embedded-systems/
Have fun!


text:
Q: SQL Pivot MIN( COUNT ( I have a complicated MS SQL 2005 query with a PIVOT in it...
I have data like this :
Data ( clients left join visits ):
ClientID VisitID ServiceID
1        34      5
1        36      2
1        36      5
1        45      2
1        48      2
1        60      2
2        44      1
3        48      2
3        78      3
3        79      2

And what I need is this:
ID [1] [2] [3] [4] [5]
1   0  1   0   0   1
2   1  0   0   0   0
3   0  1   1   0   0

The SQL Query I am using is this:
select * from
         (select clients.ClientID, clients.serviceID FROM clients left join visits on visit.cliendid=clients.clientid ) e
         pivot ( COUNT(serviceID) for serviceID in ([1],[2],...,[54]) ) p

But this SQL Query doesn't do what I want, instead it does this:
ID [1] [2] [3] [4] [5]
1   0  4   0   0   2
2   1  0   0   0   0
3   0  2   1   0   0

I need all of the data in the columns to be either 0 or 1, as in, 0 has never used this service, 1 has used this service...
How do I do this?
It would be awesome if I could do pivot ( Math.MIN ( COUNT(serviceID), 0 ) for ... or if I could do ( CASE (COUNT(serviceID) > 0 ) THEN 1 ELSE 0  for ...
but it won't let me.

A: SELECT  *
FROM    (
        SELECT  DISTINCT clients.ClientID, clients.serviceID
        FROM    clients
        ) e
PIVOT   (
        COUNT(serviceID)
        FOR serviceID in ([1],[2])
        ) p


text:
Q: Javascript. Convert MD5 hash into an integer Is it possible in Javascript to convert something like this: d131dd02c5e6eec4 693d9a0698aff95c 2fcab58712467eab 4004583eb8fb7f89, which is the result of an MD5 hash function, into an integer ?

A: May not be perfect, but this suited my needs
export function stringToIntHash(str, upperbound, lowerbound) {
  let result = 0;
  for (let i = 0; i < str.length; i++) {
    result = result + str.charCodeAt(i);
  }

  if (!lowerbound) lowerbound = 0;
  if (!upperbound) upperbound = 500;

  return (result % (upperbound - lowerbound)) + lowerbound;
}

A: Maybe this one https://github.com/lovell/farmhash ?
const farmhash = require('farmhash');
const hexDigest = crypto.createHash('md5').update().digest('hex');
farmhash.fingerprint64(hexDigest);

A: ES6 version, string to integer between 0-9:
string.split('').map(i => i.charCodeAt(0)).reduce((a, b) => a + b, 0) % 10

A: That looks like a hexadecimal number, so you could try using the parseInt function and pass in a base of sixteen:
var num = parseInt(string, 16);

Edit:  This method doesn't actually work.  See the comments for details.


text:
Q: Import module (without Gradle) to my Android Gradle project I have a project with Gradle and I want import an android module to my project. The problem is that this module has not Gradle. Is it possible import with build.gradle this module?
Thanks in advance!!

A: If you can compile your module into its own JAR then you can add it as a Gradle dependency using something like:
repositories {
  flatDir {
    dirs 'libs'
  }
}

dependencies {
  compile 'myjar:1.0@jar'
}

or
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
}

or
dependencies {
  compile files('libs/my-jar.jar')
}


text:
Q: Learning Java, want to be able to view class from webstite I am learning how to use Java and I want to make a text scroller for my website.
I have found a similar scroller that I want to add but I want to look at the code to see how it was done.
The applet can be found here: http://www.javascriptkit.com/java/java20.shtml
The problem is when I try to open the class file within notepad the encoding or text shows up with strange characters instead of showing me the code.
Please can someone let me know if there is any possible way of me seeing the code for this class.
Thanks

A: That is a class file meaning it is compiled code so you can not see it's source.
In order to see the source, you need the .java file which is the file which you compile to get the byte code.
It seems the site is just providing the compiled class, and you never know using it they might have some hidden functionality in the class as well e.g to send information to the owner servers etc.
EDIT:
So here is the de-compiled code of applet written by ProScroll version 2.3 by Slava Pestov
import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

public class ProScroll extends Applet
  implements Runnable
{
  private Thread thread;
  private Image image;
  private int scrollLength;
  private int scrolled;
  private int speed = 10;
  private int imgsWidth;
  private URL url;
  private String target;
  private Color bgColor;

  public void init()
  {
    int i = 12; int j = 0;

    String str2 = getParameter("TEXT");
    String str3 = getParameter("TEXTURL");

    if ((str2 == null) && (str3 == null)) {
      str2 = "No TEXT or TEXTURL parameter specified";
    }
    if (str3 != null)
    {
      localObject = new StringBuffer();
      try
      {
        InputStream localInputStream = new URL(str3)
          .openConnection().getInputStream();
        while (true)
        {
          int k = localInputStream.read();
          if (k == -1) break;
          if (k != 10) {
            if (k == 9) { ((StringBuffer)localObject).append(' '); continue; }
            ((StringBuffer)localObject).append((char)k);
          }
        }
        localInputStream.close();

        str2 = ((StringBuffer)localObject).toString();
      }
      catch (Exception localException1)
      {
        if (str2 == null) {
          str2 = "Error loading text from URL: " + localException1;
        }
      }
    }
    String str1 = getParameter("FONT");
    if (str1 == null) str1 = "TimesRoman";

    this.target = getParameter("TARGET");
    if (this.target == null) this.target = "_self";

    try
    {
      i = Integer.parseInt(getParameter("SIZE"));
    }
    catch (Exception localException2)
    {
    }

    Object localObject = getParameter("STYLE");
    if ("bold".equals(localObject)) j = 1;
    else if ("italic".equals(localObject)) j = 2;
    else if ("bolditalic".equals(localObject)) j = 3;

    String str4 = getParameter("SPEED");
    if ("slow".equals(str4)) this.speed = 20;
    else if ("medium".equals(str4)) this.speed = 15; else {
      this.speed = 10;
    }
    try
    {
      this.url = new URL(getDocumentBase(), getParameter("URL"));
    }
    catch (Exception localException3)
    {
    }

    this.bgColor = parseColorName(getParameter("BGCOLOR"), Color.black);

    Enumeration localEnumeration = parseAndLoadImages(getParameter("IMAGES"));

    Font localFont = new Font(str1, j, i);

    FontMetrics localFontMetrics = getToolkit().getFontMetrics(localFont);

    this.image = createImage(localFontMetrics.stringWidth(str2) + this.imgsWidth + size().width, size().height);

    this.scrolled = (-size().width);

    parseAndDrawText(this.image.getGraphics(), str2, localFontMetrics, localFont, localEnumeration);
  }

  private void parseAndDrawText(Graphics paramGraphics, String paramString, FontMetrics paramFontMetrics, Font paramFont, Enumeration paramEnumeration)
  {
    paramGraphics.setFont(paramFont);
    paramGraphics.setColor(this.bgColor);
    paramGraphics.fillRect(0, 0, this.image.getWidth(this), this.image.getHeight(this));
    paramGraphics.setColor(Color.white);

    StringBuffer localStringBuffer = new StringBuffer();
    int i = 0; int j = 0;

    for (int k = 0; k < paramString.length(); k++)
    {
      char c = paramString.charAt(k);

      if ((c == '#') && (j == 0))
      {
        if (i != 0)
        {
          paramGraphics.setColor(parseColorName(localStringBuffer.toString(), Color.white));
          localStringBuffer.setLength(0);
          i = 0;
        }
        else
        {
          i = 1;
        }
      }
      else if ((c == '$') && (i == 0) && (j == 0))
      {
        try
        {
          Image localImage = (Image)paramEnumeration.nextElement();
          paramGraphics.drawImage(localImage, this.scrollLength, 0, this);
          this.scrollLength += localImage.getWidth(this);
        }
        catch (Exception localException)
        {
        }
      }
      else if ((c == '/') && (j == 0))
      {
        j = 1;
      }
      else if (i != 0)
      {
        localStringBuffer.append(c);
      }
      else
      {
        if (j == 1) j = 0;
        paramGraphics.drawString(String.valueOf(c), this.scrollLength, paramFontMetrics.getAscent());
        this.scrollLength += paramFontMetrics.charWidth(c);
      }
    }
  }

  private Color parseColorName(String paramString, Color paramColor)
  {
    if ("red".equals(paramString)) return Color.red;
    if ("green".equals(paramString)) return Color.green;
    if ("blue".equals(paramString)) return Color.blue;
    if ("yellow".equals(paramString)) return Color.yellow;
    if ("orange".equals(paramString)) return Color.orange;
    if ("white".equals(paramString)) return Color.white;
    if ("lightGray".equals(paramString)) return Color.lightGray;
    if ("gray".equals(paramString)) return Color.gray;
    if ("darkGray".equals(paramString)) return Color.darkGray;
    if ("black".equals(paramString)) return Color.black;
    if ("cyan".equals(paramString)) return Color.cyan;
    if ("magenta".equals(paramString)) return Color.magenta;
    if ("pink".equals(paramString)) return Color.pink;
    return paramColor;
  }

  private Enumeration parseAndLoadImages(String paramString)
  {
    if (paramString == null) return null;

    int i = 0;
    Vector localVector = new Vector();
    StringTokenizer localStringTokenizer = new StringTokenizer(paramString);
    MediaTracker localMediaTracker = new MediaTracker(this);

    while (localStringTokenizer.hasMoreTokens())
    {
      try
      {
        Image localImage = getImage(new URL(getDocumentBase(), localStringTokenizer.nextToken()));
        localVector.addElement(localImage);
        localMediaTracker.addImage(localImage, i);
        localMediaTracker.waitForID(i++);
        this.imgsWidth += localImage.getWidth(this);
      }
      catch (Exception localException)
      {
      }
    }

    return localVector.elements();
  }

  public void start()
  {
    this.thread = new Thread(this);
    this.thread.start();
  }

  public void stop()
  {
    this.thread = null;
    this.scrolled = (-size().width);
  }

  public void run()
  {
    while (Thread.currentThread() == this.thread)
    {
      long l = System.currentTimeMillis();

      if (++this.scrolled > this.scrollLength) this.scrolled = (-size().width);

      repaint();
      try
      {
        Thread.sleep(Math.max(this.speed - (System.currentTimeMillis() - l), 0L));
      }
      catch (InterruptedException localInterruptedException)
      {
      }
    }
  }

  public boolean mouseEnter(Event paramEvent, int paramInt1, int paramInt2)
  {
    if (this.url != null) getAppletContext().showStatus("Link: " + this.url.toString());
    return true;
  }

  public boolean mouseExit(Event paramEvent, int paramInt1, int paramInt2)
  {
    if (this.url != null) getAppletContext().showStatus("");
    return true;
  }

  public boolean mouseUp(Event paramEvent, int paramInt1, int paramInt2)
  {
    if (this.url != null) getAppletContext().showDocument(this.url, this.target);
    return true;
  }

  public void update(Graphics paramGraphics)
  {
    paramGraphics.setColor(this.bgColor);
    if (this.scrolled < 0)
    {
      paramGraphics.setColor(this.bgColor);
      paramGraphics.fillRect(0, 0, -this.scrolled, size().height);
    }
    paramGraphics.drawImage(this.image, -this.scrolled, 0, this);
  }

  public void paint(Graphics paramGraphics)
  {
    update(paramGraphics);
  }

  public String getAppletInfo()
  {
    return "ProScroll version 2.3 by Slava Pestov";
  }
}

A: a java .class file is a compiled file that you cannot read with notepad.
if you want the source code you should try to ask it to the author of the article or you could decompile it.


text:
Q: SQLSTATE[HY000] General error: 1 Can't create/write to file /tmp/#sql I have a PHP project which is working with MariaDB/MySQL on a DirectAdmin machine.
It's a month that I receive this error while running a certain page in my application as below:
PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General error: 1 Can't create/write to file '/tmp/#sql...

When I restart the mysqld service on the server, everything goes well! I am sure that there is not any issue on the disk space. This is the current server status:
[root@srv1 ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        3.9G     0  3.9G   0% /dev
tmpfs           3.9G  880K  3.9G   1% /dev/shm
tmpfs           3.9G  390M  3.5G  10% /run
tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/vda1        42G   22G   18G  57% /
tmpfs           783M     0  783M   0% /run/user/0

What is your idea to solve this issue?

A: Your problem is that you do not have identified the temporary ones in the database, the simplest way is to delete the temporary ones from the entire system that are 14 days old
find /tmp -type f -mtime +14 -exec rm {} \;
find /var/tmp -type f -mtime +14 -exec rm {} \;

Check the size and clean package cache
du -sh /var/cache/apt/
sudo apt-get clean
service mysqld restart

there is little information for a very recurring problem


text:
Q: Are there one instance of ActivityManager for each activity in Android? I added a static field to ActivityManager and set it in my activity. When I exit my activity and enter again, I found that the value has been restored to defaults. I wonder if it means that there is an instance of activity manager for each activity?
Basically in ActivityManager I added the following things:
public static boolean s = false;
public void setS(boolean b) { s = b; }
public boolean getS() { return s; }

Then I compiled OS and in my app I use reflection to access the above methods. If I do not quit my app, then whatever get set in the setS method are reflected in the getS method. If I quit the app and enter again, then getS always return false. Wonder why?
Any help is appreciated!

A: ActivityManager Interact with the overall activities running in the system.
Save your value to SharedPreferences. You need to set value again onstart() and onresume() and save value to SharedPreferences in onStop(), onDestroy()
When you quit app all activities destroyed that the reason getS() function returns false because app restart and your boolean value set again.


text:
Q: How can black holes be observed to grow? If, from the reference frame of an observer at rest outside a black hole, it takes an infinite amount of time for an object to be observed to fall into a black hole, how can black holes ever be observed to grow in that reference frame?

A:
How can black holes be observed to grow?

Like a hailstone. See Kevin Brown's formation and growth of black holes. He says things like this:
"Incidentally, we should perhaps qualify our dismissal of the "frozen star" interpretation, because it does (arguably) give a servicable account of phenomena outside the event horizon, at least for an eternal static configuration. Historically the two most common conceptual models for general relativity have been the "geometric interpretation" (as originially conceived by Einstein) and the "field interpretation" (patterned after the quantum field theories of the other fundamental interactions). These two views are operationally equivalent outside event horizons, but they tend to lead to different conceptions of the limit of gravitational collapse. According to the field interpretation, a clock runs increasingly slowly as it approaches the event horizon (due to the strength of the field), and the natural "limit" of this process is that the clock asymptotically approaches "full stop" (i.e., running at a rate of zero). It continues to exist for the rest of time, but it's "frozen" due to the strength of the gravitational field..."
He doesn't favour this frozen-star interpretation, but if you read on, you realise that the alternative is where the infalling clock goes beyond future infinity into another region of spacetime. I don't buy that, so I prefer the frozen-star interpretation.

If, from the reference frame of an observer at rest outside a black hole, it takes an infinite amount of time for an object to be observed to fall into a black hole, how can black holes ever be observed to grow in that reference frame?

Very easily. The black hole is something like a hailstone. Water molecules can't pass through its surface, but they can alight upon its surface and be surrounded and buried by other water molecules. So the surface passes through them. So they effectively pass through the surface, and the hailstone grows. It's similar for infalling matter and the event horizon. They don't pass through the event horizon. The event horizon passes through them. When a star collapses, the event horizon grows from the centre out. You can see a mention of that in Friedwardt Winterberg's Gamma Ray Bursters paper.


text:
Q: Posted Variable behaves differently on Razorpay payment script I am trying to post customer and product details to Razorpay from a form. However, it does not trigger the same results as when I have the same variables in the receiving file. The code should be self explanatory;
The form
<form action="razorpay/index.php" method="POST">
Name: <input type="text" name="cname" required>

Phone : <input type="phone" name="cphone" required>

Email : <input type="email" name="cemail" required>

Address : <textarea cols="50" rows="10" name="caddress" required></textarea>
<input type="hidden" name="gtotal" value="<?php echo $gtotal;?>">
<input type="hidden" name="vcomp" value="<?php echo $vcomp;?>">
<input type="hidden" name="proddescr" value="<?php echo $proddescr;?>">
<input type="submit" name="prodetsub">

The PHP file receiving the posted variables
<?php

// If the below variables are not commented, the script works fine with the values

/*$_POST['prodetsub']="submit";
$_POST['gtotal']=8000;
$_POST['vcomp']="Chalo Bazaar";
$_POST['proddescr']="Product Description";
$_POST['cname']="Customer Name";
$_POST['cemail']="customer@email.com";
$_POST['caddress']="Customer Address, Line 1, Line 2, Line 3";
$_POST['cphone']="9999999999";
*/

///But if I try to receive the variables from the post as below, the variables are not passed to javascript and alerted.

if(isset($_POST['prodetsub'])){?>
<form action="charge.php" method="POST">
<?php
$gtotal=trim($_POST['gtotal']);
$vcomp=trim($_POST['vcomp']);
$proddescr=trim($_POST['proddescr']);
$cname=trim($_POST['cname']);
$cemail=trim($_POST['cemail']);
$caddress=trim($_POST['caddress']);
$cphone=trim($_POST['cphone']);
echo $cname."
";
echo $cemail."
";
echo $cphone."
";
echo $caddress."
";
echo $gtotal."
";
echo $vcomp."
";
echo $proddescr."
";
?>
<button id="rzp-button1">Pay</button>

  <input type="hidden" name="shopping_order_id" value="21">

</form>
<?php } else{echo "Nothing Submitted
";}?>

The variables echo perfectly in both cases. But they are not passed to the javascript in the case when it comes from the form. And so it does not trigger the alert in the javascript. However, when I activate the variables commented out at the top and have the values assigned in the same file, it works
I guess it is a small issue I am missing. But I have spent a lot of time trying to figure and have lost. Hope someone can see where I am going wrong.
EDIT :
I have json_encoded the variables now.
The Source Code shows values are properly output as follows
var x="30250";
var mn=""Chalo Bazaar"";
var d=""Unicorn Silver Colour. 4 Year old. In good Condition"";

    var cn=""Anit Gopinath"";
    alert(cn);
    var cem=""anitgopinath@gmail.com"";
    alert(cem);
    var cadd=""506\/C2, Panchganga,\r\nLok Upvan, Phase I, Pokhran II"";
    alert(cadd);
    var cph=""9833157945"";
    alert(cph);

The Chrome javascript console gives an error
"index.php:8 Uncaught SyntaxError: Unexpected identifier"
I am wondering whether it is the slash in the address that is crashing the javascript

A: Don't do this:
var cem="<?php echo $cemail;?>";

You're directly dumping text from PHP into a Javascript context, and can trivially introduce JS syntax errors, killing the ENTIRE


text:
Q: Add Row Numbers in Postgresql I have two questions. Both of these are for 1 table in a database.
I have a table "performance".
Name Info
x    12.5
y    9
z    10

How can I add a column Index in the table, as shown below?
My desired output is -
Index Name Info
0     x    12.5
1     y    9
2     z    10
.......

Assume that I have thousands of rows just like above in 1 table.
How can I insert row numbers in each row in postgresql database?
The second questions is how can I read the Index column one by one and print it on the screen?
I am using Python to interact with this database.
I want to use a function using row_number() to generate numbers and insert a column in the database tables.
Also, I am a newbie and learning databases. Please do not downvote this question. It is hurting me and I am unable to comment on other relevant posts. If possible please remove your negative votes.
Thanks!

A: You can add the column with the command alter table.
You can use serial pseudotype in a single alter table statement, example:
create table performance(name text, info numeric);
insert into performance values
('x', 12.5),
('y', 9),
('z', 10);

alter table performance add id serial;

select *
from performance;

 name | info | id
------+------+----
 x    | 12.5 |  1
 y    |    9 |  2
 z    |   10 |  3
(3 rows)

If you want the new column to be auto-increment, leave the table as is. If you do not want this, drop the sequence in this way:
alter table performance alter id drop default;
drop sequence performance_id_seq;


text:
Q: Image upload using Hibernate inside PostgreSQL I am working on a Spring-MVC application and I must use image upload for storing images in Database. I tried to go through examples on internet, but my overall observation is there is some argument regarding type of upload, and who manages it. Nevertheless, I am uploading the image from an HTML, saving it in Database as OID, using byte array with @Lob to save. I am unable to see the image preview when i use :
I will post code of how I have achieved it, kindly let me know whats wrong.
HTML code for image preview :

When I use product.getImage().toString in service, I get weird characters by 'B[jlkisf12', but only 12-13 of them, I imagine that is the path.
Entity :
@Column(name = "productimage")
byte[] productimage;  // With getters and setters

JSP file :
   <c:url var="add" value="/product/add"></c:url>
<form:form action="${add}" commandName="product">

        <c:if test="${!empty product.productname}">

                    <form:label path="productid">
                        <spring:message text="productid"/>
                    </form:label>

                    <form:input path="productid" readonly="true" size="8"  disabled="true" />
                    <form:hidden path="productid" />

        </c:if>

                <form:label path="productname">
                    <spring:message text="productname:"/>
                </form:label>

                <form:input path="productname"/>

                <form:label path="productdescription">
                    <spring:message text="productdescription"/>
                </form:label>

                <form:input path="productdescription"/>

                <form:label path="productcondition">
                    <spring:message text="productcondition"/>
                </form:label>

                <form:input path="productcondition"/>

                <form:label path="productage">
                    <spring:message text="productage"/>
                </form:label>

                <form:input path="productage" />

                <form:label path="productean">
                    <spring:message text="productean"/>
                </form:label>

                <form:input path="productean" />

                <form:label path="productisbn">
                    <spring:message text="productisbn"/>
                </form:label>

                <form:input path="productisbn" />

                <form:label path="ordernumber">
                    <spring:message text="ordernumber"/>
                </form:label>

                <form:input path="ordernumber" />

                <form:label path="productimage">
                    <spring:message text="productimage"/>
                </form:label>

                <form:input type="file" path="productimage" />

            <c:if test="${!empty product.productname}">
                <input type="submit"
                       value="<spring:message text="Edit Product"/>" />
            </c:if>
            <c:if test="${empty product.productname}">
                <input type="submit"
                       value="<spring:message text="Add Product"/>" />
            </c:if>

</form:form>

Product List

<c:if test="${!empty listProducts}">

            Product ID
            Product image
            Product name
            Product description
            Product condition
            Product age
            Product EAN
            Product ISBN
            Product ordernumber
            Product owners id

            Edit
            Delete

        <c:forEach items="${listProducts}" var="product">

                ${product.productid}
                ${product.productimage}
                ${product.productname}
                ${product.productdescription}
                ${product.productcondition}
                ${product.productage}
                ${product.productean}
                ${product.productisbn}
                ${product.ordernumber}
                ${product.user1id}
           //image not found
                <a href="<c:url value='/editproduct/${product.productid}' />" >Edit Product
                <a href="<c:url value='/removeproduct/${product.productid}' />" >Delete Product

        </c:forEach>

</c:if>

Controller :
     @RequestMapping(value="/product/show",method= RequestMethod.GET)
     public String listProducts(@ModelAttribute("product") ProductBasic productBasic,Model model)   {
     User user = userService.getCurrentlyAuthenticatedUser();
     model.addAttribute("product", new ProductBasic());
     model.addAttribute("listProducts",this.productBasicService.listProduct(user));
     BASE64Encoder base64Encoder = new BASE64Encoder();
     StringBuilder stringBuilder = new StringBuilder();
     stringBuilder.append("data:image/png;base64,");
     stringBuilder.append(base64Encoder.encode(productBasic.getProductimage()));
     String image = stringBuilder.toString();
     model.addAttribute("saveimage",image);
     return "product";
 }

@RequestMapping(value="/product/add")
public String addProduct(@ModelAttribute("product") ProductBasic productBasic,Model model){
    User user = userService.getCurrentlyAuthenticatedUser();
    model.addAttribute("product", new ProductBasic());
    productBasicService.addProduct(user,productBasic);
    return "redirect:/product/show";
}
  @RequestMapping("/removeproduct/{id}")
    public String removeProduct(@PathVariable("id") int productid,Model model) {
        User user = userService.getCurrentlyAuthenticatedUser();
        model.addAttribute("listProducts",this.productBasicService.listProduct(user));
        this.productBasicService.removeProduct(productid,user);
        return "redirect:/product/show";
    }

    @RequestMapping("/editproduct/{id}")
    public String updateProduct(@ModelAttribute("product") ProductBasic productBasic,@PathVariable("id") Integer id,Model model){
        User user = userService.getCurrentlyAuthenticatedUser();
        model.addAttribute("product", this.productBasicService.getProductById(id));
        model.addAttribute("listProducts",this.productBasicService.listProduct(user));
        return "product";
    }

NullPointerException:
java.lang.NullPointerException
    java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:106)
    sun.misc.CharacterEncoder.encode(CharacterEncoder.java:188)
    com.WirTauschen.UserController.listProducts(UserController.java:67)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

What am I doing wrong? Kindly let me know.

A: In your Controller or method add below code for image
    BASE64Encoder base64Encoder = new BASE64Encoder();
    StringBuilder imageString = new StringBuilder();
    imageString.append("data:image/png;base64,");
    imageString.append(base64Encoder.encode(bytes)); //bytes will be image byte[] come from DB
    String image = imageString.toString();
    modelView.put("imagetoDisplay",image);// put in your model object for using in your JSP

And in your JSP


text:
Q: How to plot categorical variables with a pie chart I am concerned with a single column (fruit) from my df:
| fruit               |
| --------------------|
| apple, orange       |
| banana              |
| grapefruit, orange  |
| apple, banana, kiwi |

I want to plot the values from fruit to a pie chart to get a visual representation of the distribution of each individual fruit
I run: df.plot(kind='pie', y='fruit')
But this gives a TypeError: '<' not supported between instances of 'str' and 'int'
I have read: How can I read inputs as numbers?
But I can't see how it helps solve my problem
Any help much appreciated!

A: You can split and explode:
(df['fruit']
 .str.split(',\s*')
 .explode()
 .value_counts()
 .plot(kind='pie')
)

Output:


text:
Q: Hibernate with Hikari CP Could not extract result set on Multi-tenant DB I have configured hibernate for multi-tenancy support, however whenever I am querying this data it throws an exception. I've already double checked the column does exist in all of my tenants.
However I keep getting this exception
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
    at org.hibernate.loader.Loader.doQuery(Loader.java:909)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
    at org.hibernate.loader.Loader.doList(Loader.java:2553)
    at org.hibernate.loader.Loader.doList(Loader.java:2539)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
    at org.hibernate.loader.Loader.list(Loader.java:2364)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:495)
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:360)
    at com.sun.proxy.$Proxy52.getSingleResult(Unknown Source)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:197)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:97)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:88)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:421)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy40.findByUsername(Unknown Source)
    at org.brightworks.genesis.commons.service.account.impl.AccountServiceImpl.findByUsername(AccountServiceImpl.java:27)
    at com.brightworks.genesis.client.webapp.controller.ProductController.addProductForm(ProductController.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:769)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:144)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at com.googlecode.webutilities.filters.CompressionFilter.doFilter(CompressionFilter.java:131)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:497)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:610)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:539)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "user_account" does not exist
  Position: 270
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
    at com.zaxxer.hikari.proxy.PreparedStatementProxy.executeQuery(PreparedStatementProxy.java:52)
    at com.zaxxer.hikari.proxy.PreparedStatementJavassistProxy.executeQuery(PreparedStatementJavassistProxy.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
    ... 114 more

Here's my model
@Table(name="USER_ACCOUNT")
@Entity
public class UserAccount extends BaseAccountModel {

    @Column(name = "TENANT_CODE")
    private String tenantCode;

    @Column(name = "ROLE")
    private String role;

    public String getTenantCode() {
        return tenantCode;
    }

    public void setTenantCode(String tenantCode) {
        this.tenantCode = tenantCode;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}

My multi-tenant connection provider
public class MultitenantConnectionProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService {

    private static final long serialVersionUID = 4368575201221677384L;

    private org.slf4j.Logger logger = LoggerFactory.getLogger(MultitenantConnectionProvider.class);

    private DataSource lazyDatasource = null;

    @Override
    public boolean supportsAggressiveRelease() {
        return false;
    }

    /**
     * The DataSource/ConnectionPool we are using is the one configured by the environment
     * Which by default, in our case, is configured at client-persistence-cfg.xml
     * (named Client Data Source)
     */
    @Override
    public void injectServices(ServiceRegistryImplementor serviceRegistry) {
        Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
        lazyDatasource = (DataSource) lSettings.get(Environment.DATASOURCE);
    }

    @Override
    public boolean isUnwrappableAs(Class clazz) {
        return false;
    }

    @Override
    public <T> T unwrap(Class<T> clazz) {
        return null;
    }

    /**
     * Retrieve any connection from the Connection Pool
     */
    @Override
    public Connection getAnyConnection() throws SQLException {
        return lazyDatasource.getConnection();
    }

    @Override
    public Connection getConnection(String tenantIdentifier) throws SQLException {
        final Connection connection = getAnyConnection();
        try {
            connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
        }
        catch (SQLException e) {
            throw new HibernateException("Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e);
        }
        return connection;
    }

    @Override
    public void releaseAnyConnection(Connection connection) throws SQLException {
        try {
            connection.createStatement().execute("SET SCHEMA 'public'");
        }
        catch (SQLException e) {
            throw new HibernateException("Could not alter JDBC connection to specified schema [public]", e);
        }
        connection.close();
    }

    @Override
    public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
        releaseAnyConnection(connection);
    }
}

public class SchemaResolver implements CurrentTenantIdentifierResolver {

    /**
     *
     * If the current principal is not a TenantUserDetails Object
     * classify him as anonymous user and only give him access to the
     * public database.
     */
    @Override
    public String resolveCurrentTenantIdentifier() {
        if(SecurityContextHolder.getContext().getAuthentication() != null
                && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null){
            Object userDetails = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if(userDetails instanceof TenantUserDetails){
                TenantUserDetails details =(TenantUserDetails)
                        SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                return details.getTenantCode();
            }else{
                return "public";
            }
        }
        return "public";
    }

    @Override
    public boolean validateExistingCurrentSessions() {
        return false;
    }
}

and my configuration of the connection pool
  <bean id="clientDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver.className}"/>
        <property name="jdbcUrl" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <property name="maximumPoolSize" value="30" />
        <property name="connectionTestQuery" value="SELECT 1" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="clientDataSource"/>
        <property name="packagesToScan"  value = "org.brightworks.genesis.commons.model"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform" value="${hibernate.sql.dialect}" />
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.multiTenancy">SCHEMA</prop>
                <prop key="hibernate.tenant_identifier_resolver">com.brightworks.genesis.client.config.hibernate.SchemaResolver</prop>
                <prop key="hibernate.multi_tenant_connection_provider">com.brightworks.genesis.client.config.hibernate.MultitenantConnectionProvider</prop>
            </props>
        </property>
    </bean>


text:
Q: tcpprobe does't exist in /proc/net/ when I used SSH I am new in world of network. I made a simple SDN that contains 3 hosts, one switch and a controller. I would like to monitor the traffic using tcpprobe. I opened a terminal using xterm h1 and ran the shell there. I also made iperf server in h2. But the tcpprobe was not existed in /proc/net/ directory when I use a SSH terminal!
enter image description here
However I installed it on my VM and it is exist in /proc/net/ of my VM.
enter image description here
sudo apt-get install transcode

Here is my shell code:
#!/bin/bash

#used variables
eth=h1-eth0
port_to_probe=5001
#we will probe the iperf port
server_addr=10.0.0.2

#LOAD TCP CONGESTION CONTROL MODULES
modprobe tcp_probe port=$port_to_probe full=1 bufsize=50

for time_test in 10 20 30 60 10 20
do

echo "Traffic transmission time set to " $time_test "s randomly.\n"

#start logging data
sudo cat /proc/net/tcpprobe > tcprobe.dat &

#get the cat process ID to later kill it
pid=$!
#kill the logger
kill $pid

done

Can anybody help me?

A: The problem was that, each SSH use a port to connect to VM and this cause a change on the address of /proc/net/. To solve this problem it is enough to change the mentioned address to /proc/6337/net/. By reading this address in fact you read the real VM directory. So the final code will change to:
cat /proc/6337/net/tcpprobe


text:
Q: Calling a procedure in Delphi I have a procedure with Sender: TObject paramater
procedure TForm1.FormCreate(Sender: TObject);

How can I call this procedure again?
This version does not work:
TForm1.FormCreate(Sender: TObject);

Thanks in advance.

A: I assume that you wish to call the procedure FormCreate of an instance of a TForm1.
You can do FormCreate(Self) or FormCreate(nil) (or you can pass any TObject instance as the parameter) if you are inside the TForm1 class. Otherwise, you have to write Form1.FormCreate(Self) or Form1.FormCreate(nil) or similarly, where Form1 is the appropriate instance of the TForm1.
At any rate, it is not particularly 'elegant' to call the FormCreate procedure at later times. Indeed, the name clearly suggests that the procedure is called when the form is created.
If a particular piece of logic of your FormCreate method is needed at other stages and you simply do not want to duplicate code, you should probably implement that piece in the form of a separate method (procedure or function) and call it in FormCreate as well as in other parts of your program, as necessary.
But then, you might be better off moving that part of your business logic from FormCreate at all. What we typically do in FormCreate is create/initialise objects that are later uninitialised/destroyed in FormDestroy (if needed). So, think carefully what you are doing in FormCreate, maybe there's a better, logically more appropriate place for some or all of the actions you've implemented in this method.


text:
Q: How to count number of success of a binomial sample in R? I'm not used to R but what I want to do is this in pseudo code
T = 0
F = 0
for (i in 1:1000) {
  successCount <- count(rbinom(1,100,0.6)==1)
  if(successCount >= 59)
      T = T + 1
  else
      F = F + 1
}

Trying to run a simulation without rerun / map.
successCount <- count(rbinom(1,100,0.6)==1)

This part I've been searching but cant seem to find how to do this. Rest I think work

A: Something like this?
table(replicate(1000,ifelse(sum(rbinom(100,1,0.6)==1)>=59,1,0)))
  0   1
374 626

where 0 represents F and 1 represents T.