text:
Q: Java Rename Problem with normale Files. With i want to rename given name to a new filename I use this jave code to rename the one file
from
"C:\Users\mkretsch\OneDrive - Sopra Steria\_Business\2019\Schulung\Java\Oracle\test11.csv
to
"C:\Users\mkretsch\OneDrive - Sopra Steria\_Business\2019\Schulung\Java\Oracle\test12.csv
hello_Muenchen mu = new hello_Muenchen();
     mu.RenameFile("C:\\Users\\mkretsch\\OneDrive - Sopra Steria\\_Business\\2019\\Schulung\\Java\\Oracle\\test11.csv,"
                 , "C:\\Users\\mkretsch\\OneDrive - Sopra Steria\\_Business\\2019\\Schulung\\Java\\Oracle\\test12.csv");

With this Java code i want to rename file_name to new_filename
static void RenameFile( String file_name, String new_filename ){
    try
    {
        File f= new File(file_name);           //file to be renamed
        File f_new= new File(new_filename);           //file to be delete

        if(f.renameTo(f_new))                      //returns Boolean value
        {
            System.out.println(f_new.getName() + " renamed");   //getting and printing the file name
        }
        else
        {
            System.out.println("failed for " + file_name + new_filename );
        }
    }
        catch(Exception e)
    {
    e.printStackTrace();
    }

}

But my code fails. I always get the
message failed for
C:\Users\mkretsch\OneDrive - Sopra Steria_Business\2019\Schulung\Java\Oracle\test11.csv,C:\Users\mkretsch\OneDrive - Sopra Steria_Business\2019\Schulung\Java\Oracle\test12.csv

A: You should have a look at java.nio because it is a more modern way to perform operations on the file system.
The following example renames the given file (as java.nio.Path) or throws an Exception (e.g. if the source file does not exist or is write protected):
public static void main(String[] args) {
    Path source = Paths.get(
            "C:\\Users\\mkretsch\\OneDrive - Sopra Steria_Business\\2019\\Schulung\\Java\\Oracle\\test11.csv");
    Path target = Paths.get(
            "C:\\Users\\mkretsch\\OneDrive - Sopra Steria_Business\\2019\\Schulung\\Java\\Oracle\\test12.csv");

    try {
        Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        System.err.println("Didn't work...");
        e.printStackTrace();
    }
}

The reason for your code not working is the trailing comma in the source file, most likely...

A: Your code seems okay, but From the file names:
 mu.RenameFile("C:\\Users\\mkretsch\\OneDrive - Sopra Steria\\_Business\\2019\\Schulung\\Java\\Oracle\\test11.csv,"
                 , "C:\\Users\\mkretsch\\OneDrive - Sopra Steria\\_Business\\2019\\Schulung\\Java\\Oracle\\test12.csv");

"C:\...\test11.csv," look there is an extra comma in the file name. That's why that file was not renaming.
Also check if the user has the write permission on that folder.


text:
Q: Schedule a price increase All our prices are managed through an external integration so price increases have to be scheduled.
Example:
In January you have an original price of £30 and receive a price increase request that has to start from February (£40). All logic must be build in advance.
How would you approach it?
A possible solution would be to create 2 attributes: increased_price and increased_price_date could be an option but this will require a process to run every day and check if there are product like this with that particular date and then update the current price.
Any other options?
Thanks

A: It depends a lot on how your getting the pricing from your integration supplier and the number of products which you have.
However I recently completed a project which under some circimstances had a price change going on every other minute so it was quite resource intensive. The approach I took there, and which might be sutible for you is to extend the Product Model's getPrice() and connect to redis where you will cache pricing in an simple key value approach.
Example:
    [100 => [
              '01' => 30.00, // January
              '02' => 40.00 // February
            ]
    ]

Now you can make a connection to this, and return the month for the current price that month.
Extending upon this logic, you can directly query the API provider of your service and return the current price in run time this gives the benefit that your code always returns the price in the suppliers database without ever needing to worry about updating your local price.
public function getPrice()
    {
        if ($this->_redisHelper->isRedisPriceReady($this->getId())) {
            return $this->_redisHelper->getPrice($this->getId());
        }

        $parentPrice = parent::getPrice();

        return $parentPrice;
    }

Above is an example of what I'm doing - checking to see if I have a redis price available (in my case we generate this at run time rather than externally hence the getPrice on the helper - this simply connects and retrieves the relevant price from the structure in redis.) That section you would replace with either an API call to the supplier, or a middle man query depending on your needs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Example applications of overloading the assignment operator I hope this isn't seen "primarily opinion based" or "too broad". It's fairly straight forward question:
What are some example problems to which overloading the assignment operator offers a solution?
I don't think I've yet seen a situation in which it would be useful, especially considering the negative implications of having a program full of surprise implicit behaviours and "smoke and mirrors".

A: Example:
struct X
{
    int *p;
    X(): p{new int[42]}
    ~X() { delete p; }
};

What will happen if you do
X x, y;
x = y;

? The default assignment operator will copy the raw pointer, and you'll end up delete-ing the same pointer twice by the destructors of x and y. In fact, you'd better declare a copy constructor here too (or, even better, use smart pointers). Note that in
X x = some_obj;

the copy constructor is invoked (or elided if the rhs is a prvalue). The assignment operator is invoked only after construction, when you say
x = some_other_obj; // x is already constructed here

If you ask whether the operator= should exist at all (in contrast to e.g. Java), then it's probably a matter of personal preference.


text:
Q: I am tried to prestashop database error my site url is :- http://www.latinwaymusic.it/prestashop/
check errors :-
(1) Db->executeS() must be used only with select, show, explain or describe queries
at line 498 in file classes/db/Db.php
(2)DbCore->executeS - [line 330 - classes/shop/Shop.php] - [1 Arguments]
(3)ShopCore::initialize - [line 100 - config/config.inc.php]
(4)require - [line 27 - index.php] - [1 Arguments]

A: For some reason your shop domain/url are empty, you should check your database for eg. in phpMyAdmin, serach for the ps_shop_url table and in domain and domain_ssl type www.latinwaymusic.it in physical_uri type /prestashop/ and save the row.

A: The query you are building is problematic. Have you updated the code yourself?
The query looks like this:
SELECT s.id_shop, CONCAT(su.physical_uri, su.virtual_uri) AS uri, su.domain, su.main
FROM ps_shop_url su
LEFT JOIN ps_shop s ON (s.id_shop = su.id_shop)
WHERE (su.domain = "". pSQL($HOST)."" OR su.domain_ssl = "". pSQL($HOST)."")
    AND s.active = 1
    AND s.deleted = 0
ORDER BY LENGTH(CONCAT(su.physical_uri, su.virtual_uri)) DESC

In the code at line 325 in file classes/shop/Shop.php, the
WHERE (su.domain = "". pSQL($host)."" OR su.domain_ssl = "". pSQL($host)."")

should be
WHERE (su.domain = \''.pSQL($host).'\' OR su.domain_ssl = \''.pSQL($host).'\')

Your code has "" (two-times double quote) which seems to be coming from MS SQLServer SQL syntax, which will never work in PHP.


text:
Q: No sln file in MVC project. Any way to generate? I am supposed to take over a project which is MVC based. in the source code folder, I see all the required files except the sln file. Is there a way to generate the sln file for MVC project? Will it work as expected?

A: If your project has the .csproj file, then open the .csproj file with Visual Studio, then when you close VS it will ask you to save a .sln file.


text:
Q: Security vulnerabilities involved with Base64 encoded url I have an API when trying to access it through a web application, I am making ajax get and post requests.
As I am new to this, I am wondering what the security concerns are with respect to the content type.
Right now I know of two content types I can POST the data as:

*

*Base64enoded URL.

*JSON
If I am passing the data as encoded URL, the data will appear in the query string.
Even if Base64encoded wouldn't it be a bad way of passing sensitive information?
I read several articles and most of them said JSON or URL encoded wouldn't matter much in terms of security.
What are the security breaches that I must be concerned with when looking at the content type used to pass data between the application and the API?

A: Base64Encode/Decode is not developed to encrypt or transfer data securely. Can use Base64 to transfer string contains special characters without interrupt the protocol or function as mentioned here
In your case, you should use SSL to make a secure & encrypted connection between server & client.
And also you can use the RSA Encryption method to encrypt your data, Before sending it. (SSL uses this algorithm)
When you come to API, There is another point (Sniffing Security). You should provide a security layer to protect your data from being modified in the middle way. You can use HMAC to verify the data.
These are very common security tips. You can find more by googling the following keywords.
HMAC, Hash, RSA Encryption, SSL Certificate


text:
Q: Searching a File in a folder with number pattern I have given below find command to find and list all the files in a folder, The files are listed in alphabetical order but I want to list all the files in number pattern. when i used "-number" in place of "-name" it is not working.
find . -type f -name '*'
I100001093
I200001093
I300001093
XB00001093
I100001094
I200001094
I300001094
XB00001094
I100001095
I200001095
I300001095
XB00001095

can anyone please suggest me the right command to list in numerical order.

A: Depending how you want the I and X and so forth parts to be handled, you might be able to just use the sort command like:
find . -type f | sort -n

if that isn't the sort order you want, you'll have to give us more detail (and ideally show us the desired output from your example).
Given that you want to group the start of the names together, we can specify the key field to sort.  Since the output from find will start with ./{id} with the next two characters (seemingly) being related in a batch together, we can start sorting from the 5th character on line specifying the sort key:
find . -type f | sort -n -k 1.5

-k for sort lets you specify the key on which to sort, here we're sorting on the first field, but starting at the 5th character then using -n to sort numerically
If you want only the current directory, you can use -maxdepth as in:
find . -maxdepth 1 -type f | sort -n -k 1.5

if you want it to be portable:
find . -path '*/*/*' -prune -o -type f | sort -n -k 1.5


text:
Q: Netbeans Jlabel visibility when switching tabs I'm working on a jframe program where I have 2 tabs (Home & About) .. now I would like to display a jlabel in the about tab only when a button is clicked , I managed to do that by using jLabel5.setVisible(true); ... it works fine , but when I go back to the home tab and go back
again to the about tab , the jlabel is gone so I have to press again so it can appear ... is there a way that I can make it stay there without it resetting everytime i switch tabs? thanks ... this is a gif showing what exactly my problem is http://imgur.com/LEaYQxL

A: Perhaps you could share the code, however there might be a work around, you could try to create a "flag" which is only a variable that is going to be true or false, create a variable flag that will change to true once you click in your button and then, when you pass to the About tab you will check if flag is true then jLabel5.setVisible(true) else jLabel5.setVisible(false), remember to initialize the flag variable as false.
Hope this work around works for you

A: You could try to make this: when you click the button you set the setVisible(true) and also set "true" a false boolean. So you click, the boolean wasClicked, that was false became true, and before you write if wasClicked is true: setVisible(true). A code example:
boolean wasClicked = false;

if(wasClicked == true) {
jLabel5.setVisible(true);
}

When button is clicked (actionlistener):
wasClicked = true;
jLabel5.setVisible(true);


text:
Q: Checking out repository on work group computers I have created a local repository and its URL is file:///F:/subversion/MyProject
And I checked out MyProject to my local machine....it works fine..
But when I try to CheckOut on a WorkGroup Computer using
URL: file:///Server_Name/F:/subversion/MyProject .. it gives an error like
Error: Unable to open an ra_local session to url.
Error: Unable to open repository file:///Server_Name/F:/subversion/MyProject
I also tried Server_Name/file:///F:/subversion/MyProject
Any help would be highly apprecialble..
Thanks

A: Please do not access a repository which is not on your local harddrive via the file:/// mechanism.
It's a bad idea and you will get into troubles in the future. The only question is how long it will take until your repository is corrupt, not whether it will happen.

A: This
file:///Server_Name/F:/subversion/MyProject

Is not the right way to address the F: drive on a remote machine. You need to set up a share on the machine and then address it using
\\servername\sharename\......

If you encounter problems with this specifically, you're better off asking on Stack Overflow's sister site, superuser.com.
This method is perfectly fine for a small number of clients in a local network. You could, however, also consider setting up a proper SVN Server like VisualSVN.


text:
Q: SQL Server 2008 Audit trigger based on sub string I would like to create a trigger based on a column but only for those records that end in _ess.  How can I set up an audit trigger to do this?
Here is the current trigger but it just checks for all changes to username, whereas I just want it to check when username is updated to or from a username ending in _ess.
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[AUDIT_UPD_HRPERSONS_USERNAME] ON [dbo].[HRPersons] FOR UPDATE NOT FOR REPLICATION As
BEGIN
DECLARE
@OperationNum   int,
@DBMSTransaction VARCHAR(255),
@OSUSER VARCHAR(50),
@DBMSUSER VARCHAR(50),
@HostPhysicalAddress VARCHAR(17),
@contexto varchar(128),
@ApplicationModifierUser varchar(50),
@SessionInfo_OSUser varchar(50),
@HostLogicalAddress varchar(30)

Set NOCOUNT On

IF @@trancount>0
BEGIN
EXECUTE sp_getbindtoken @DBMSTransaction OUTPUT
END
ELSE BEGIN
SET @DBMSTransaction = NULL
END

IF PatIndex( '%\%',SUSER_SNAME()) > 0
BEGIN
set @OSUSER = SUSER_SNAME()
set @DBMSUSER = NULL
END
ELSE BEGIN
SET @OSUSER = NULL
SET @DBMSUSER = SUSER_SNAME()
END

set @HostPhysicalAddress = (SELECT net_address FROM master..sysprocesses where spid=@@spid )
set @HostPhysicalAddress = substring (@HostPhysicalAddress,1,2) + '-' + substring (@HostPhysicalAddress,3,2) + '-' + substring (@HostPhysicalAddress,5,2) + '-' + substring (@HostPhysicalAddress,7,2) + '-' + substring (@HostPhysicalAddress,9,2) + '-' + substring (@HostPhysicalAddress,11,2)

SELECT @contexto=CAST(context_info AS varchar(128)) FROM master..sysprocesses WHERE spid=@@SPID
IF (PatIndex( '%APPLICATION_USER=%',@contexto) is not null) and (PatIndex( '%APPLICATION_USER=%',@contexto) > 0)
set @ApplicationModifierUser=substring(ltrim(substring(@contexto,PatIndex( '%APPLICATION_USER=%',@contexto)+17,128)),1, charIndex( '///',ltrim(substring(@contexto,PatIndex( '%APPLICATION_USER=%',@contexto)+17,128) ) ) - 1 )
ELSE
set @ApplicationModifierUser=NULL
IF (PatIndex( '%OS_USER=%',@contexto) is not null)  and ( PatIndex( '%OS_USER=%',@contexto)>0 )
set @SessionInfo_OSUser=substring(ltrim(substring(@contexto,PatIndex( '%OS_USER=%',@contexto)+8,128)),1, charIndex( '///',ltrim(substring(@contexto,PatIndex( '%OS_USER=%',@contexto)+8,128) ) ) - 1 )
ELSE
set @SessionInfo_OSUser=NULL
IF (PatIndex( '%LOGICAL_ADDRESS=%',@contexto) is not null) and (PatIndex( '%LOGICAL_ADDRESS=%',@contexto)>0)
set @HostLogicalAddress=substring(ltrim(substring(@contexto,PatIndex( '%LOGICAL_ADDRESS=%',@contexto)+16,128)),1, charIndex( '///',ltrim(substring(@contexto,PatIndex( '%LOGICAL_ADDRESS=%',@contexto)+16,128) ) ) - 1 )
ELSE
set @HostLogicalAddress=NULL

INSERT INTO AuditedOperations ( Application, Object, OperationType, ModifiedDate, ApplicationModifierUser, OSModifierUser, DBMSModifierUser, Host, HostLogicalAddress, HostPhysicalAddress, DBMSTransaction)
VALUES (APP_NAME(), 'HRPERSONS', 'U', GETDATE(), @ApplicationModifierUser, @OSUSER, @DBMSUSER, HOST_NAME(), @HostLogicalAddress, @HostPhysicalAddress, @DBMSTransaction)

Set @OperationNum = @@IDENTITY

INSERT INTO AuditedRows (OperationNum, RowPK)
SELECT @OperationNum, ISNULL(CAST(INSERTED.ID as nvarchar),CAST(DELETED.ID as nvarchar))
FROM INSERTED FULL OUTER JOIN DELETED ON INSERTED.ID=DELETED.ID

INSERT INTO AuditedRowsColumns (OperationNum, RowPK, ColumnName, ColumnAudReg, OldValue, NewValue)
SELECT @OperationNum, ISNULL(CAST(INSERTED.ID as nvarchar),CAST(DELETED.ID as nvarchar)), 'USERNAME','A', CONVERT( VARCHAR(3500),DELETED.USERNAME), CONVERT( VARCHAR(3500),INSERTED.USERNAME)
FROM INSERTED FULL OUTER JOIN DELETED ON INSERTED.ID=DELETED.ID

END

GO

A: Just add this:
INSERT INTO AuditedRows (OperationNum, RowPK)
SELECT @OperationNum, ISNULL(CAST(INSERTED.ID as nvarchar),CAST(DELETED.ID as nvarchar))
FROM INSERTED FULL OUTER JOIN DELETED ON INSERTED.ID=DELETED.ID
-- Restrict it to only those where the username is changing from or to %_ess
WHERE (deleted.username like '%_ess' or inserted.username like '%_ess')

INSERT INTO AuditedRowsColumns (OperationNum, RowPK, ColumnName, ColumnAudReg, OldValue, NewValue)
SELECT @OperationNum, ISNULL(CAST(INSERTED.ID as nvarchar),CAST(DELETED.ID as nvarchar)), 'USERNAME','A', CONVERT( VARCHAR(3500),DELETED.USERNAME), CONVERT( VARCHAR(3500),INSERTED.USERNAME)
FROM INSERTED FULL OUTER JOIN DELETED ON INSERTED.ID=DELETED.ID
-- Restrict it to only those where the username is changing from or to %_ess
WHERE (deleted.username like '%_ess' or inserted.username like '%_ess')


text:
Q: How do I see the actual HTTP response going out from Express? I'm experiencing intermittent Proxy errors for an Express app behind an Apache proxy. These only happen when making the request through the proxy, and only when the browser does the request. The proxy says that it can't understand the response from Express.
I'd like to see the actual HTTP response sent by Express, so how could I get it's content to log it somewhere? Note that this must include headers as they are sent.


text:
Q: jQuery how to translate livequery to on? I have this code which works however it is using a old legacy function "livequery" which should really be switched to using "on".  However for the life of me I can't get this to work.
Here is my code snippet.
jQuery('.box').livequery(function(){
     jQuery('a', this).click(function() {
          return false;
     });
     jQuery(this).draggable({
        appendTo: "body",
        helper: 'clone',
        opacity: 0.5,
        zIndex: 900,
        stop: function(event, ui) {
        return true;
        }
     });
});

And I tried this...
jQuery('.box').on('draggable', function(){
     jQuery('a', this).click(function() {
          return false;
     });
     jQuery(this).draggable({
        appendTo: "body",
        helper: 'clone',
        opacity: 0.5,
        zIndex: 900,
        stop: function(event, ui) {
        return true;
        }
     });
});

That didn't work as I am guessing "draggable" isn't the event name...
Thanks..

A: This answer over there New Inserted dom node may help you to convert your code into on functionality instead of live function


text:
Q: Remove part of an email address I have emails like sales@joebloggs.com.
I am looking to select out everything after the @ and before the ..
Result should be joebloggs.

A: Here is a solution using substring and position:
substring(col from (position('@' in col)+1)
              for (
                  position('.' in substring(col from (position('@' in col)+1))) - 1
              )
          )

A: Simple regex pattern should do the job.
SELECT regexp_matches('sales@joebloggs.subdomain.com', '@([^.]+)\.');

SQL Fiddle
Edit: fixed to support subdomains. I assume you want to get the part before first dot.

A: Solution using substring and instr
SELECT
substring('sales@joebloggs.com', instr('sales@joebloggs.com', '@') + 1, instr('sales@joebloggs.com', '.') - (instr('sales@joebloggs.com', '@') + 1))
FROM dual;


text:
Q: My username and password dont work on SHH Trixbox I have a Trixbox Linux instaled (based on Asterisk distribution). I can acces the console normally with my root account.
Its very simple, restart my machine, type login: root and password ************* and finish.
But, I can access SSH of this machine with the same account.
I connect in my server using port 22, the server request my credential, I type root and password ****************. This return "Password Invalid".
Can anybody help me associate my root account with the SSH account?


text:
Q: SQL Query, incorrect syntax near "keyword" could you help me, in finding the error in my query, i'm taking hours in solving this error, thanks in advance
sqlquery = "SELECT dbo.trans_queue.que_no, dbo.trans_step.step_remarks," _
                & " dbo.office.office_name, dbo.transaction.trans_name," _
                & " dbo.trans_queue.date_arrive, dbo.trans_queue.time_arrive" _
                & " FROM dbo.trans_queue" _
                & " INNER JOIN dbo.trans_step ON dbo.trans_queue.trans_step_Id = dbo.trans_step.trans_step_Id" _
                & " INNER JOIN dbo.office ON dbo.trans_queue.office_Id = dbo.office.office_Id" _
                & " INNER JOIN dbo.transaction ON dbo.trans_queue.trans_Id = dbo.transaction.trans_Id" _
                & " WHERE dbo.office.office_Id = '" & Now_Office_ID & "'" _
                & " ORDER BY dbo.trans_queue.time_arrive AND dbo.trans_queue.date_arrive"

the error always telling me that
"incorrect syntax near 'transaction'"

A: Most probably the problem comes from the fact that your table name TRANSACTION is a reserved word in Transact SQL. Replace all the occurrences of transaction in your query by the word between square brackets:
sqlquery = "SELECT dbo.trans_queue.que_no, dbo.trans_step.step_remarks," _
            & " dbo.office.office_name, dbo.[transaction].trans_name," _
            & " dbo.trans_queue.date_arrive, dbo.trans_queue.time_arrive" _
            & " FROM dbo.trans_queue" _
            & " INNER JOIN dbo.trans_step ON dbo.trans_queue.trans_step_Id = dbo.trans_step.trans_step_Id" _
            & " INNER JOIN dbo.office ON dbo.trans_queue.office_Id = dbo.office.office_Id" _
            & " INNER JOIN dbo.[transaction] ON dbo.trans_queue.trans_Id = dbo.[transaction].trans_Id" _
            & " WHERE dbo.office.office_Id = '" & Now_Office_ID & "'" _
            & " ORDER BY dbo.trans_queue.time_arrive AND dbo.trans_queue.date_arrive"

A: Your error should be using the researved word "transaction" you dont specify your Database, in Microsoft SQL SERVER you should use :
dbo.[transaction].trans_name,


text:
Q: Replace variable num in double quotes - SED I have a line like this:
"abc/x-y-z": "^1.4"

I need to replace ^1.4with * in the same file such that the output is "abc/x-y-z": "*"
The num inside the double quotes could be any variable number.
I tried this but it is highly specific to ^1.4 number:
sed -i '21s/^1.4/*/' abc.json

A: With your shown samples, please try following. You need to escape ^ here to make it literal character and you need to escape . dot as well to make it treat as literal character.
sed 's/\^1\.4/*/' Input_file

OR as per OP's comment to make it dynamic try:
sed 's/\^[0-9]+\.[0-9]+/*/' Input_file

Also if you are performing it on 21st line of your file then use 21s like you tried in your attempt. This code will substitute only very 1st occurrence of ^1.4 here in case you want to substitute all occurrences then use g(globally substitution) option for above code.
I have not used -i option(to do inplace update into Input_file itself) once you are happy with results then use sed -i option in above code.

A: When making changes to files, I prefer the file editor ed to the stream editor  sed (ed is standard, sed -i isn't, and different versions have different quirks that bite people here on a regular basis).
ed -s input.txt <<EOF
21s/"^[[:digit:]]\{1,\}\(\.[[:digit:]]\{1,\}\)\{0,1\}"/"*"/
w
EOF

On line 21, matches a quote followed by a carat followed by 1 or more digits, optionally followed by a period and another sequence of 1 or more digits and finally the trailing quote character. All that is replaced by "*", and finally the changed file is written back to disk.
Posix BREs are a pain, no? GNU ed 1.17 and newer, and NetBSD ed can take EREs instead:
ed -Es input.txt <<EOF
21s/"\^[[:digit:]]+(\.[[:digit:]]+)?"/"*"/
w
EOF

which is a lot easier to read.


text:
Q: Sql Server: How to Deny users access to linked servers I'd like to deny access to query linked servers to a group of users. I've put them in a role and assigned certain permissions to object level permissions to the that group. I'm at a loss after searching BOL and 'net how to DENY access to linked servers.
EDIT:
I decided to break out profiler to verify exactly what SSMS is calling when displaying linked servers and ensure that a DENY was issued on that system view/SP. Turns out it calls sys.servers, but Sql Server doesn't honor the ACL on this system view -- It's does to other system views (ex: sys.dm_db_index_physical_stats).

A: Here is a workaround I just thought of:
On Linked Server Properties dialog box, Properties tab; add users that you don't want to access the linked server. Then, assign them some dummy user/pass combination that will be rejected on target server.

A: Afaik referencing a linked server is not controlled by access control lists (ACLs). In other words, you cannot GRANT/DENY/REVOKE permission to use a linked server. You can certainly control the permission to change a linked server via ALTER ANY LINKED SERVER permission.
This apparent lack of permission is because the linked servers are forwarding specific credentials to the remote server, controlled via the impersonation or the remote_logins settings associated with the linked server. The actual access control happens on the remote server, using the credentials associated with the linked server. So in order to deny a group of users access to the linked server, you need to deny that group access to the remote server on the remote server itself.

A: The type of authentication is of importance.  When you link the servers they have to be linked using Kerberos and then you can control the access on the linked server.  Otherwise your group will always be authenticated on the credentials specified in the link.

A: AFACS, linked servers are missing proper access control.  I would like to do the following:

*

*Create a credential for connecting to the remote server

*Create a new linked server:
a. Specify a server role or AD group or security as the local user
b. Specify the credential as the remote user

*Add logins to the server role or AD group to control access.

A: Take your transact statement, put it into a SSIS package 'Execute SQL Task'
In the link server security properties, add the userid (on your server) you want to access the link server to the top section along with the uid and pw for the linked server and click the radio button 'not be made'
when you schedule your job in sql server agent, select your ssis package and use your proxy (db/security/credentials) on the run as line in the job step.

A: DENY SELECT ON [sys].[sysservers] on <..>


text:
Q: Нет подключения в клиенте к серверу через Socket.io, хотя сервер говорит обратно. Постоянное подключение и дисконнект Уже который час бьюсь с недопонимаем, надеюсь, сможете помочь(
Версии socket.io:
на клиенте - 3.1.2
на сервере - 1.3.7
Сервер:
io.on('connection', (socket) => {
    console.log(`connected ${socket.id}`);

    socket.on('STREAM_STARTED', ioResponse);
    socket.on('MESSAGE_ADD', ioAddMessage);

    socket.on('disconnect', () => {
        console.log(`disconnect ${socket.id}`);
        if(state.connection){
            bot.telegram.sendMessage(state.chatId, ' Соединение закрыто!' + '\n' + 'Оператор вне сети!');
        }
    })
});

Клиент:
const socket = io(RN_APP_API_URL, {
        autoConnect: false,
        transports: ['websocket'],
        upgrade: false,
        forceNew: false,
        timeout: 10000
    })

    socket.on('connection', (data) => console.log(1))

    React.useEffect(() => socket.connect(), []);

    socket.on('connect', () => console.log(socket.id))

    console.log(socket.connected);

При подключении с клиента по сокетам, сервер говорит что подключение есть и пишет об этом в консоль,
но клиент говорит, что подключения нет и ни на какие события не реагирует.
Также, постоянно идет подключение к серверу:
disconnect WpGmWMILxDs8FxoZAAAh
disconnect WpGmWMILxDs8FxoZAAAh
disconnect fFtdvAxPYMpJVdq2AAAi
disconnect fFtdvAxPYMpJVdq2AAAi
connected riQ5lraHl9Pf4u8NAAAo
connected riQ5lraHl9Pf4u8NAAAo
disconnect hRjatYCXqkwGOkqrAAAj
disconnect hRjatYCXqkwGOkqrAAAj
connected ltn1DI0iWSCm72HvAAAp
connected FTWsnzIFY7Wc0INPAAAq
connected ltn1DI0iWSCm72HvAAAp
connected FTWsnzIFY7Wc0INPAAAq
disconnect 7ugnRPGL0LOqta44AAAk
disconnect 7ugnRPGL0LOqta44AAAk
connected Uyq_WTNzpidPX8OmAAAr
connected Uyq_WTNzpidPX8OmAAAr
connected Iwx4XZafqc_XZwU4AAAs
connected Iwx4XZafqc_XZwU4AAAs
disconnect rFF6fYN7SX3AHWzSAAAl
disconnect rFF6fYN7SX3AHWzSAAAl
connected N4nRZajVofIIjjpiAAAt
connected N4nRZajVofIIjjpiAAAt
disconnect pLdKHP_6Hi6Kui7KAAAm
disconnect pLdKHP_6Hi6Kui7KAAAm
connected pWzWCuU-vP0Huo8wAAAu
connected pWzWCuU-vP0Huo8wAAAu

Тоже не понимаю почему так происходит

A: https://socket.io/docs/v4/client-installation/#Version-compatibility
У вас несовместимые версии на сервере и клиенте.


text:
Q: Limit Post Creation Count by Author or Role I need to limit the number of posts that can be created.
I'd like any variation of total posts, posts per time period (month), by author (ID) or by role.
off-the-shelf plugins found so far in the repository are no longer supported.
is there a functions.php snippet or other approach that works consistently?
any suggestions?
thanks

A: I have a site that offers non-paying members up to 5 posts using this:
function author_post_count($user_id, $post_type = array('YOUR_CUSTOM_POST_TYPE_NAME_HERE')) {
    $args = array(
        'post_type'         => $post_type,
        'author'            => $user_id,
        'posts_per_page'    => -1
    );

    $query = new WP_Query($args);
    return $query->found_posts;
}

Then I use:
if ( author_post_count(get_current_user_id()) >5) {
SHOW RESTRICTION NOTICE CODE HERE FOR USERS WITH MORE THAN 5 POSTS
}

So you could use those two together and then the save_post hook.
If you're not familiar, read up on it and in particular this part about avoiding a loop: https://developer.wordpress.org/reference/hooks/save_post/#avoiding-infinite-loops
Then you could change the query to use Date Parameters

A: There is a function in WordPress name count_user_posts which accept two parameters, first is $userid and second is $post_type. So, providing this function the user ID and post type you can check if the user has more than 5 posts or not.
In code this would look a more like below-
// Assuming user ID is 5 and the post type is 'post'
if ( count_user_posts( 23 , 'post' ) > 5 ) {
    // Do what you prefer if the post count is more than 5.
}


text:
Q: How to make labels only appear above certain bars I would like to add a custom label above certain bars within this chart.  How would I add labels to only bar 4 and bar 8 in this example:
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
            ha='center', va='bottom')

With this code I get a label above each bar.  But I only want labels (with value 34 and 55, for example) above the fourth and eighth bar.
What is the best way to accomplish this?
Here is where I found this example: Adding value labels on a matplotlib bar chart

A: That code was written for Python 2 and a much earlier version of pandas; I have touched it up a little to work for Python 3.
There are other ways to do this, but without changing the structure of the code too much, what you can do is specify indices of the bar labels you want to plot, shown below as which, and plot them only if they correspond:
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
fig, ax = plt.subplots(figsize=(12, 8))
freq_series.plot(kind='bar', ax=ax)
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = [f'label{i}' for i in range(len(rects))]

which = [3, 7]

for index, rect in enumerate(rects):
    if index in which:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2, height + 5, height,
                ha='center', va='bottom')


text:
Q: Как добавить строку по нажатию на кнопку в html есть страница с окном входа, нужно по нажатию на кнопку регистрация, появлялось еще одно поле, например (1 номер, 2 пароль, 3 повторить пароль). Да и как сделать так чтобы кнопки еще поменяли название свое, у меня изначально кнопка sign in, после нажатия кнопки register нужно поменять название на "register", а сверху поменять текст у "sign in " и "register"
На первой фотке так как сейчас, а на второй так как надо сделать, надеюсь там все понятно что нужно.
(ссылка на index.html и css файл) --> https://yadi.sk/d/lNa9LS7Aa0YFxA

A: Для начала добавьте все элементы которые нужны для регистрации. Затем, тем элементам, которые нужно скрыть на странице входа, добавьте класс, например, "class". Далее создайте еще класс, например, "hide". В hide пропишите display: none. В js (jquerry) нужно прописать такую логику:
if ([нажатие на кнопку осуществляется]) {
      $(".class").addClass("hide");
    } else {
      $(".class").removeClass("hide");
    }

2 вариант. Просто создать еще один отдельный html для регистрации и при нажатии на кнопку переходить на него.
P.S. Подретактируйте мой ответ, пожалуйста.


text:
Q: How do I assign variables when prompting user for an expression? I'm trying to write a program that asks a user to input an expression (ex: '2 + 2') and assign variables to each string ('x = 2', 'y = +', 'z = 2') and have it output a float with sig figs at the tenths place ('4.0').
My thought process was to change the variable str values to int, output the answer to the expression based on whatever operator is assigned for y ('+', '-', '*', or '/'), and then change this to a float with the proper number of decimals.
The issue is, any code I try to write with the "y" assigned variable (the assigned operator) gives me an indicator of invalid syntax.
By doing 'x + y + z' I'm told TypeError: unsupported operand type(s) for +: 'int' and 'str'. I'm not sure why if y is being assigned as an operator. I'm guessing the '+' value it's being read as a str, but I don't know what to assign it as to convert it to be useable in an equation.
# Prompt user input
expression = input("Expression: ")

#Assign str to a list of variables at once
x, y, z = expression.split(" ")

# Convert string to integer, string to operator

# Convert X to int
x = int(x)
# Convert Y to...?
y = '-' or '+' or '*' '/'
# Convert Z to int
z = int(z)

# Convert expression to float
answer = float(x + y + z)

# Format answer to output to the tenths place
format_answer = "{:.1f}".format(answer)
print(format_answer)


text:
Q: How does document.cookie affect XMLHttpRequest? Unlike other headers, I can't set the Cookie header using XMLHttpRequest.prototype.setRequestHeader.
Instead, cookies must be manipulated via document.cookie.
Unfortunately, it seems inconstent.
document.cookie = 'name=foo';
var xhr = new XMLHttpRequest;
xhr.open('GET', url1);
xhr.send();

document.cookie = 'name=bar';
var xhr = new XMLHttpRequest;
xhr.open('GET', url2);
xhr.send();

In Chrome 47 and IE 10, both requests have name=bar. In Firefox 43, the first request has name=foo and the second has name=bar.
Which of these behaviors complies with HTML5 standards? How can I control the Cookie header for a a request?

(Since I know I will be asked about this: AWS Cloudfront won't look at any headers except Cookie for serving private content. And hundreds of combined resources don't fit in a policy cookie, so I have to set a different policy cookie for each request. A sad API, but that's why.)


text:
Q: Dual Role USB device on AVR Is it possible to run both USB Host and USB Device controllers on top of an AVR (ATMega64)?
Specifically, what I'm looking for is to receive data from a usb keyboard, and simultaneously sending keystrokes to a PC.
From what I've seen, both VUSB & LUFA stacks support USB host modes, but they work with a single usb port only.
Any help is appreciated!
Thanks!

A: You might consider using a PS/2 keyboard, they are simple to interface with, it's basically just a serial protocol. Then you can still use USB in Device mode to connect to the host PC.

A: *

*I don't think that V-USB supports host (OTG) mode and LUFA host mode will require at least an AT90USB646 which is quite expensive.

*I don't know about a cheap micro that has 2 USB port but you may try using two. Just connect them via an UART and exchange the needed information.
That said, davr is probably right that using a PS/2 keyboard would be simpler.


text:
Q: RecyclerView with enlarged first visible item I want to find solution for RecyclerView with enlarged first visible item like here.
I started with adding ScrollListener to RecyclerView and catching IDLE_STATE, but of course item is enlarging when we stop scrolling, but I want to changing size of item like example above. How can I start with that?

A: It looks to me like they have a scroll listener that as it offsets in the X direction it grows by an equal number of pixels in the Y position. Then Set a minHeight and maxHeight on your image view so it never shrinks or grows passed the sizes you are looking for.


text:
Q: Unable to build entity manager factory on Jelastic Enviroment I have an webapp that work like a charm at localhost, but when I deploy in on a Tomcat 8 + Java 8 + Postgres 9.3 Jelastic Enviroment I get the following exception when trying to access the database:
  2015-01-28 18:06:11 HibernatePersistence [WARN] HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
  2015-01-28 18:06:11 HibernatePersistence [WARN] HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
  2015-01-28 18:06:11 HibernatePersistence [WARN] HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
  2015-01-28 18:06:12 LogHelper [INFO] HHH000204: Processing PersistenceUnitInfo [
    name: pu
    ...]
  2015-01-28 18:06:12 Version [INFO] HHH000412: Hibernate Core {4.3.6.Final}
  2015-01-28 18:06:12 Environment [INFO] HHH000206: hibernate.properties not found
  2015-01-28 18:06:12 Environment [INFO] HHH000021: Bytecode provider name : javassist
  28-Jan-2015 18:06:13.062 WARNING [http-nio-8080-exec-2] null.null javax.servlet.ServletException: Filter execution threw an exception
   javax.el.ELException: javax.servlet.ServletException: Filter execution threw an exception
    at org.apache.el.parser.AstValue.invoke(AstValue.java:258)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:72)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
  Caused by: javax.servlet.ServletException: Filter execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:255)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
    at br.com.logtec.controller.LoginController.requestDispatcher(LoginController.java:92)
    at br.com.logtec.controller.LoginController.login(LoginController.java:55)
    at br.com.logtec.controller.LoginController$Proxy$_$$_WeldClientProxy.login(LoginController$Proxy$_$$_WeldClientProxy.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    ... 44 more
  Caused by: java.lang.ExceptionInInitializerError
    at br.com.logtec.security.AppUserDetailsService.buscaUsuarioPorLogin(AppUserDetailsService.java:68)
    at br.com.logtec.security.AppUserDetailsService.loadUserByUsername(AppUserDetailsService.java:28)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:101)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:195)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    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.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:166)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    ... 57 more
  Caused by: javax.persistence.PersistenceException: Unable to build entity manager factory
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:83)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at br.com.logtec.util.PersistenceUtil.<clinit>(PersistenceUtil.java:14)
    ... 75 more
  Caused by: org.hibernate.jpa.boot.archive.spi.ArchiveException: Could not build ClassFile
    at org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.toClassFile(ClassFileArchiveEntryHandler.java:88)
    at org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:65)
    at org.hibernate.jpa.boot.archive.internal.ExplodedArchiveDescriptor.processDirectory(ExplodedArchiveDescriptor.java:167)
    at org.hibernate.jpa.boot.archive.internal.ExplodedArchiveDescriptor.processDirectory(ExplodedArchiveDescriptor.java:142)
    at org.hibernate.jpa.boot.archive.internal.ExplodedArchiveDescriptor.processDirectory(ExplodedArchiveDescriptor.java:142)
    at org.hibernate.jpa.boot.archive.internal.ExplodedArchiveDescriptor.processDirectory(ExplodedArchiveDescriptor.java:142)
    at org.hibernate.jpa.boot.archive.internal.ExplodedArchiveDescriptor.processDirectory(ExplodedArchiveDescriptor.java:142)
    at org.hibernate.jpa.boot.archive.internal.ExplodedArchiveDescriptor.visitArchive(ExplodedArchiveDescriptor.java:78)
    at org.hibernate.jpa.boot.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:72)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.scan(EntityManagerFactoryBuilderImpl.java:723)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:219)
    at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:51)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:182)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:131)
    at org.hibernate.ejb.HibernatePersistence.getEntityManagerFactoryBuilderOrNull(HibernatePersistence.java:93)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:88)
    at org.hibernate.ejb.HibernatePersistence.getEntityManagerFactoryBuilderOrNull(HibernatePersistence.java:101)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:69)
    ... 79 more

And this is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
         xmlns="http://xmlns.jcp.org/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name="pu">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>br.com.logtec.converter.LocalDatePersistenceConverter</class>
    <class>br.com.logtec.converter.LocalTimePersistenceConverter</class>
    <class>br.com.logtec.converter.LocalDateTimePersistenceConverter</class>

    <properties>
        <property name="hibernate.archive.autodetection" value="class, hbm, jar" />

        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://postgres13461-homolog.jelastic.hostdime.com/logtec-db" />
        <property name="javax.persistence.jdbc.user" value="webadmin" />
        <property name="javax.persistence.jdbc.password" value="KEc6X4BhYO" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
        <property name="hibernate.format_sql" value="true" />

    </properties>
</persistence-unit>

Any help is welcome, I am really stucked here


text:
Q: cocoa NSArrayController show custom wizard on add action I have the NSArrayController and NSTableView, also linked "add" button with add method of NSArrayController. When I clicked the add button - it just create new row at NSTableView.
I wish to show my custom wizard, where user can input all necessary information.
What is the best way to do it?

A: As you need to do some custom action you need to do it programatically.
Create an outlet for the NSArrayController.
Create an IBAction for the Add button. Show your wizard here.
Then call the add method for NSArrayController.


text:
Q: How to navigate string based method names in MVC? I don't know how best to describe this but here we go.
For the most part, Visual Studio is great at helping you navigate through code.
Eg, if I see an unfamiliar line like this CRM.UpdateAdminAccounts(model.Email) I can hover over the object/method names to discover what they actually are, or right click and choose Go To Definition to jump straight to the code that makes the class, property, or whatever.
This is possible because the code is strongly typed and behind the scenes the compiler assigns symbols to everything making it easy for VS to know exactly what the text refers to and jump to it when required or find out where else it is referenced.
The same is not true of many lines of code in MVC where method names are referred to as a string literal.
Eg  return RedirectToAction("Index", "Home")    or in a view: @Url.Action("Delete", new { id = item.ID })
If I want to jump straight to the Index or Delete action code I can't do it without lots of intermediate steps. Worse still, the action may not exist or there might be a typo not spotted until runtime.
Am I the only one to feel this is a huge step backward and could easily be improved with the use of reflection?
My question is simply, are there any tools or tricks I should be using to make this kind of thing possible and easier to use?

A: Your best bet is to have simple names for your methods that match the action names, and then redirect using nameof() in the string parameter.
public class CustomerController : Controller
{
    public ActionResult Details(int? id)
    {
        if (!id.HasValue)
            return RedirectToAction(nameof(Index));

        return View();
    }

    public ActionResult Index()
    {
        return View();
    }
}

Code sourced from ASP.NET MVC Controller Overview (C#) and modified slightly.
In this way, you can hover/click/follow reference on the Index part of nameof(Index) and VS will jump your cursor over to the Index() method.
This doesn't work perfectly if you are forced to disambiguate method names by making them more complex (e.g. if you had IndexOne() and IndexTwo()) for some reason.
The only other alternative, really, is to try and find a VS extension that can parse the code and jump you to a reference.


text:
Q: Error using Hashtable for windows phone application I want to use this expression parser.
I import this code that is on the site:
using System;
using System.Collections;
using info.lundin.Math;
// some other imports

public class Test
{
  public static void Main( String[] args )
  {
    // Instantiate the parser
    ExpressionParser parser = new ExpressionParser();
    // Create a hashtable to hold values
    Hashtable h = new Hashtable();
    // Add variables and values to hashtable
    h.Add( "x", 1.ToString() );
    h.Add( "y", 2.ToString() );
    // Parse and write the result
    double result = parser.Parse( "xcos(y)", h );
  }
}

but it says that the namespace Hashtable could not be found.
i google it and i found out that Hashtables are not included in Silverlight and  i should use a dictionary.
But when i use dictionary it gives my an error that says:
cannot convert from System.Collections.Generic.Dictionary<string,string> to System.Collections.Hashtable
Any suggestions?

A: I would modify the source code in the parser program so that it also is compatible with Silverlight(i.e. change any hashtable implementations into dictionary implementations)

A: Hashtables and ArrayLists are not included in the silverlight. So you cant use it.
You can use generic collections—List and Dictionary instead of HashTables and ArrayLists.


text:
Q: Add ids of Favorite products to localstrorage (array) I have a Product class in React and Star icon to add the product to Favorites. I store favorite products ids in localstorage. But when I click on new product the previouos id is replaced with new product id. How can I store ids of fav products in an array?
This is my code:
 class Product extends React.Component {
  state = {
    favIconActive: false,
    iconColor: "black",
  };

  addToCart = () => {
    this.props.onClick();
    localStorage.setItem("Cart", this.props.card.sku);
  };

  addToFavourites = () => {
    if (this.state.favIconActive) {
      this.setState({ favIconActive: false });
      localStorage.removeItem("Favorites", this.props.card.sku);
    } else {
      this.setState({
        favIconActive: true,
      });
      localStorage.setItem("Favorites", this.props.card.sku)
    }
  };

  render() {
    const {
      card: { name, price, imgUrl, sku, color },
    } = this.props;
    return (

{name}

        Color: {color}
        Price: {price} $

          <FontAwesomeIcon
            icon={faStar}
            color={localStorage.getItem(JSON.parse(sku)) ? "orange" : "black"}
          />

        SKU: {sku}
        <Button text="Add to cart" color={"black"} onClick={this.addToCart} />

    );
  }
}

A: You favorite products ids must be stored in an array.
 addToFavourites = (id) => {
    if (this.state.favIconActive) {
      this.setState({ favIconActive: false });
      let favorites = JSON.parse(localStorage.getItem("Favorites"));
      let index = favorites.findIndex(productId => productId === id);
      favorites.splice(index, 1);
      localStorage.setItem("Favorites", JSON.stringify(favorites));
    } else {
      this.setState({
        favIconActive: true,
      });
      let favorites = JSON.parse(localStorage.getItem("Favorites"));
      favorites.push(id);
      localStorage.setItem("Favorites", JSON.stringify(favorites));
    }
  };

A: Instead of storing true or false for a particular state you can create a state to store index of element for which favorite icon is clicked.
Check out this blog for reference


text:
Q: Two elements $x,y$ not nilpotent implies $\exists a$ in ring and $n, m > 0$ such that $a^n=x$, $a^m=y$? I'm trying to prove that $\bigcap\limits_{P\in \mathcal{P}}P\subseteq Nil(R)$, where $R$ is a commutative unital ring and $\mathcal{P}$ is a collection of prime ideals of $R$.
Suppose $a\not\in Nil(R)$ and let $\mathcal{S}=\{I: I \text{ is an ideal of $R$, such that } I\ne R, a^n\not\in I  \text{ for all $n>0$}  \}$. Then $\mathcal{S}$ is non-empty because $0\in Nil(R)$, so $0\in I$ for some $I\in \mathcal{S}$, thus $\langle 0\rangle\in \mathcal{S}$. Also, by Zorn's Lemma, since $R$ is an upper bound for any chain in the poset $(\mathcal{S}, \subseteq)$, there exists a maximal set $M\in \mathcal{S}$ (which, I think, must be an ideal, since $\mathcal{S}$ is a collection of ideals).
Now the part I don't get. I need to prove in this part that $x,y\not\in M$ implies that $\exists n,m>0$ such that $a^n\in M\cup\{x\}$ and $a^m\in M\cup\{y\}$. We know that, since $x,y\not\in M$ and $\mathcal{S}$ contains only sets with nilpotent elements, and $M$ is maximal (and it is related to all other sets in $\mathcal{S}$ by inclusion), then $a^n$ must be equal to $x$ and $a^m$ must be equal to $y$, and that $x,y$ must be non-nilpotent. But here's the part I don't understand:

*

*How can it possibly be the case that for two arbitrary $x$ and $y$, there must necessarily exist some element $a$ such that $a^n=x$ and $a^m=y$? What is the mystery here?

A: You can prove $\bigcap_{P\in\mathcal{P}}P\subseteq\operatorname{Nil}(R)$ if $\mathcal{P}$ is the collection of all prime ideals of $R$.
The union of a chain of ideals is an ideal: given two elements in the union, they belong to one and the same element of the chain, so their sum too; the other condition is easy. Thus Zorn's lemma applies to the set $\mathcal{S}$ consisting of the ideals that contain no power of $a$, where $a\notin\operatorname{Nil}(R)$. This set is not empty, because $(0)\in\mathcal{S}$.
It's clear that the union of a chain in $\mathcal{S}$ is an element of $\mathcal{S}$, so the family contains a maximal element $M$.
We want to show that $M$ is prime, that is,

for all $x,y\in R$, if $x\notin M$ and $y\notin M$, then $xy\notin M$.

Suppose $x\notin M$ and $y\notin M$.
Note: we have to consider $M+(x)$ and $M+(y)$, not $M\cup\{x\}$ and $M\cup\{y\}$ (which are not ideals).
Since $x\notin M$, we have that $M+(x)$ properly contains $M$. By maximality of $M$ in $\mathcal{S}$, we conclude $M+(x)\notin\mathcal{S}$, so $M+(x)$ must contain $a^m$, for some $m$. Similarly, $a^n\in M+(y)$ for some $n$. Thus $a^m=r+xs$ and $a^n=t+yu$, for $r,t\in M$ and $s,u\in R$. Consequently
$$
a^{m+n}=rt+xst+yru+xysu
$$
If $xy\in M$, then we conclude that $a^{m+n}\in M$, because $rt,xst,yru\in M$. Contradiction. Therefore $xy\notin M$.

A simpler approach. We want to show that if $a$ is not nilpotent, then there exists a prime ideal that contains no power of $a$. Consider the multiplicative set $S=\{a^n:n\in\mathbb{N}\}$. Then the ring $S^{-1}R$ is nonzero, so it contains a maximal ideal $M$. The inverse image of $M$ under the canonical ring homomorphism $R\to S^{-1}R$ is the required prime ideal.


text:
Q: How to make Twitter API requests to statuses/user_timeline I have created a Twitter Developer account and would like to use it to monitor tweets. As such, I will be using GET statuses/user_timeline. I have created an app on https://developer.twitter.com/en/apps, and I can view consumer API keys as well as access token / access token secret. However, after reading through the Twitter docs for quite some time I just can't figure out how to authenticate myself. I figured I needed to pass some HTTP headers or something, but I'm not sure. Here is my code at the moment:
import requests

def main():
    request_url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
    parameters = {
        "screen_name": "jack",
        "count": 3,
        "exclude_replies": True,
        "include_rts": False
    }
    r = requests.get(request_url, params=parameters)
    print(r.text)


text:
Q: Appropriate treatment in logistic regression of a variable whose interpretation varies above and below 1 - use of splines? I am working with a healthcare dataset with a binary outcome (discharged yes/no). One of the explanatory variables I would like to include in the model is a resource intensity score whose interpretation varies above and below 1. 1 implies expected resource use. Below 1 implies less than expected resource use. Above 1 implies greater than expected resource use. The variable is continuous with an approximate range in the dataset from 0.5 to 10. It is scaled so that a score of 2 implies double the resource use of a score of 1. There is a long tail as some patients use 5 or even 10 times the resources of a typical patient.
Currently, I have used R's rcs package to use a linear spline with a knot set at 1 to incorporate this variable. With this implementation, I get improved model performance and fit using a variety of diagnostics. I want to be sure that I am interpreting the results correctly, however. While the variable is identified as significant, the reported odds ratio is 0.99 (0.93-1.07). If I fit a cubic spline to the variable with 4 knots, I get an odds ratio of 0.73 (0.65 - 0.81) for the transformed variable. The odds ratios of the remaining predictors are essentially unchanged between the two models.
Do either of the above approaches make sense? Should I be pursuing another approach/transformation of the variable?
How do I interpret and report the odds ratio with respect to resource intensity? For example, currently with my linear spline the odds ratio is 1, which I understand to mean that the linear spline-transformed resource intensity score has no effect on probability of discharge. Is that correct?
Edit: I have attempted a log transformation as suggested below, which is a good thought. However plotting the partial residuals of this transformation shows a clear U-shaped distribution:

For comparison, here are the residuals with the untransformed variable:

My understanding from Harrell's Regression Modeling Strategies is that this appearance suggests that this variable would be amenable to modeling either with a transformation (which I have tried unsuccessfully) or splines.
If I were to use splines, should I simply not report an odds ratio for this variable? Report it on a quartile basis, etc.? I understand from the summary.rcs help that I can report an odds ratio for any data range.


text:
Q: Delete eth0 avahi from the ifconfig list Hello this is the response I get from ifconfig. Now I have two eth0 things being showed up. I need to delete the second one which says eth0:avahi. I posted my ifconfig's response on a site as I has problem using wired internet, and they suggested to remove the eth0 avahi, to get internet.
But I am a newbie to linux networking and have no idea how to delete this.
response for ifconfig
eth0 Link encap:Ethernet HWaddr 18:a9:05:22:cd:f9
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:28 Base address:0x4000

eth0:avahi Link encap:Ethernet HWaddr 18:a9:05:22:cd:f9
inet addr:169.254.10.43 Bcast:169.254.255.255 Mask:255.255.0.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
Interrupt:28 Base address:0x4000

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:796 errors:0 dropped:0 overruns:0 frame:0
TX packets:796 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:64016 (64.0 KB) TX bytes:64016 (64.0 KB)

wlan0 Link encap:Ethernet HWaddr 00:26:82:3c:ac:27
inet6 addr: fe80::226:82ff:fe3c:ac27/64 Scope:Link
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:52142 errors:0 dropped:0 overruns:0 frame:0
TX packets:30404 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:60816983 (60.8 MB) TX bytes:4160159 (4.1 MB)

A: The ethX:avahi (or whatever your interface's name is) will disappear as soon as you get either a fixed or dynamic IP from e.g. a router.
In case you're using the command line you can use this:
sudo ifdown eth0 && sudo ifup eth0
or
sudo /etc/init.d/networking restart
Although the avahi interface can be annoying, it should only show up when you didn't get any IP.
Like Elias said you can also try to disable to daemon by editing /etc/default/avahi-daemon to have it look like this:
AVAHI_DAEMON_DETECT_LOCAL=0
To sum up I suggest you simply restart your networking and if there is a router willing to give you an IP then your avahi interface should be gone.
This is my interfaces file just in case:
auto lo
iface lo inet loopback
auto wlan0
iface wlan0 inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

ps: as you can see I'm using wpasupplicant and got rid of network-manager but that's unrelated to the avahi issue.

A: Avahi is a daemon (a service) which is responsible for several things, including attributing you an IP address when DHCP (automatic IP address from a DHCP server on the network) fails.
The fact that eth0:avahi appears means that the system failed to get an IP on the eth0 interface (your wired network interface).
Normally, NetworkManager should take care of attributing an IP automatically to eth0. However, you could try to force it. Your /etc/network/interfaces doesn't list eth0, so what you can try is the following.
First, edit /etc/network/interfaces (with sudo gedit /etc/network/interfaces for example) so it reads this:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

This will tell the computer to consider getting an IP automatically for eth0.
Then, restart the network with:
$ sudo /etc/init.d/networking restart

If it still doesn't work, there might be other issues:

*

*are you sure there is a DHCP server on your network? If there isn't, you'll have to setup the IP address manually;

*if you have a DHCP server, it probably means that your problem is a hardware issue. Check that the cable is well plugged and lights are on on both sides of it.

A: Hello I am new at ubuntu as well.
I had a similar problem to the one described above and I caused it myself.
My linux version is Ubuntu 10.04.1 LTS and I use eth0 to connect to a dsl modem/router which also is a dhcp server for the pc in eth0.
I was reading a book about linux and tried to use the "ifdown eth0" and "ifup eth0" command but I was getting the following results.
sudo ifdown eth0
Ignoring unknown interface eth0=eth0.
ifdown: interface eth0 not configured

sudo ifup eth0
Ignoring unknown interface eth0=eth0.

I look it up in the internet and it found that in the /etc/network/interfaces file there should have the record I show bellow for the eth0 in order for these commands to work.
#The loopback network interface
auto lo
iface lo inet loopback

#The primary network interface
auto eth0
iface eth0 inet dhcp

I only had only the lo record in my file and although I connected to the internet without a problem from the time I installed ubuntu I added the eth0 record as well.
As it is mentioned above I restarted the network and everything seemed to work just fine.
And I could use the ifdown and ifup commands.
Until I opened my pc again after a pc shutdown and a CPE restart.
I couldn't not browse in the web and if remember correctly I couldn't even ping my router. From what I understand the eth0 was not getting an IP address from the dhcp of the router.
Also I had the exact same ifconfig result that is shown above in the threads beginning.
In my case I could solve my problem by doing "sudo ifdown eth0" and then "sudo ifup eth0". The eth0 got an IP address and everything worked just fine. Of course every time I had a shutdown I had to repeat the process.
Today I looked the avah that is mentioned in the ifconfig response and I checked to see if it was turned on my pc.
$ cat /etc/default/avahi-daemon
# 1 = Try to detect unicast dns servers that serve .local and disable avahi in
# that case, 0 = Don't try to detect .local unicast dns servers, can cause
# troubles on misconfigured networks
AVAHI_DAEMON_DETECT_LOCAL=1

I guess it is turned on although it doesn't mention anything about the dhcp.
In my case i remove the eth0 entries from the /etc/network/interfaces and I got back in the situation I was before.
I cannot use the ifup and ifdown command but after a shutdown eth0 got it's IP from my routers dhcp without a problem.
What I haven't done is set my avahi setting to 0 and then add the eth0 in the /etc/network/interfaces file to see what happens.
I hope my writtings help and not confuse.
Regards
Elias

A: Check if avahi is listed in your /etc/network/interfaces file. If it is, delete it from there.

A: for ubuntu20, ifconfig has
enp0s31f6:avahi: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 169.254.4.163  netmask 255.255.0.0  broadcast 169.254.255.255
        ether f8:75:**:**:**:**  txqueuelen 1000  (Ethernet)
        device interrupt 16  memory 0xea200000-ea220000

Settings > Network:
 select 169.xxx.xxx.xxx connection, click ⚙ icon:
  click remove connection profile

then, enp0s31f6:avahi will gone


text:
Q: Why does Apache Redirect with relative URL work in OSX but not CentOS? Trying to do something simple here, but having a great deal of difficulty
.htaccess
Redirect 301 /foo-bar /foobar

This works on OSX but CentOS complains that I'm not using a full URL.
CentOS wants
Redirect 301 /foo-bar http://example.com/foobar

I don't want to specify the the full host name for each URL.
Both OSX and CentOS are running Apache 2.2.x
Is there some way to accomplish this?

Update:
I've tried RewriteRule and it doesn't even seem to work
RewriteEngine On
RewriteRule ^/foo-bar$ /foobar [R=301,L]

The match isn't even made and now I'm getting a 404 error

A: Apparently apache doesn't support relative urls in the target of a Redirect until 2.2.6
My CentOS is running 2.2.3 so that's was the problem there

My attempt at using RewriteRule was also incorrect. The following will work as intended
RewriteEngine On
RewriteRule ^foo-bar$ /foobar [R=301,L]

Note the leading / is removed from my original question

Long story short, you can use Redirect with relative urls if your apache is >= 2.2.6
Redirect 301 /foo-bar /foobar

Or use RewriteRule if you are stuck on an older version
RewriteEngine On
RewriteRule ^foo-bar$ /foobar [R=301,L]


text:
Q: Encoding Error with Topo To Raster I'm relativley new to python and I already found a ton of questions and answers about encoding and the UnicodeEncodeError, but I can't figure it out for my specific problem and keep getting this error: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 7: ordinal not in range(128)". I am using IDLE Python 2.7.12
I want to use the arcGis tool TopoToRaster for a set of ca. 200 lakes. I have one folder containing 200 folders(one for each lake), in each lake-folder there are three shapefiles with names lakename_P.shp for points, lakename_B.shp for polygon/boundary and lakename_L.shp for polyline. The lakes are danish lakes and therefore almost all contain ø, æ and/or å in the folder names and shp names.
I am iterating through the single folders with a for loop and run the tool for every lake taking the right feature classes as an input.
I found this code, which actually works with my code, but I can't print anything with it and i am also aware of the disatvantages so I want to avoid it.
import sys
reload(sys)
sys.setdefaultencoding('utf8')

other solutions used the .encoding when reading and writing files, which I don't really do.
Can anyone recomend a solution other than reload(sys). Maybe I just have to put the .encoding somewhere, but I really don't know where and how to. I am thankfull for every help but want to mention that I already read all the Python Unicode HOWTO and other blog posts.
-*- coding: iso-8859-15 -*-
import arcpy
from arcpy import env
from arcpy.sa import *
path = "//projects/soer"
arcpy.env.workspace = path
arcpy.env.overwriteOutput = True

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

wss = arcpy.ListWorkspaces("*", "Folder")
wss.sort()

for ws in wss:
   arcpy.env.workspace = ws
   for polygon in arcpy.ListFeatureClasses(feature_type = "Polygon"):
       myBoundary = polygon
   for point in arcpy.ListFeatureClasses(feature_type = "Point"):
       myPoint = point
   for polyline in arcpy.ListFeatureClasses(feature_type = "Polyline"):
       myContour = polyline

   output = ws + '/' + 'ttr'
   outTTR = TopoToRaster([TopoPointElevation([[myPoint, 'z']]),
                          TopoContour([[myContour, 'z']]),
                          TopoBoundary([myBoundary])], 2,
                          "#", "#", "#", "#", "NO_ENFORCE")
   outTTR.save(output)

A: I finally managed to solve it myself and it was as easy as that:
for polygon in arcpy.ListFeatureClasses(feature_type = "Polygon"):
    myBoundary = polygon.encode('utf-8')
for point in arcpy.ListFeatureClasses(feature_type = "Point"):
    myPoint = point.encode('utf-8')
for polyline in arcpy.ListFeatureClasses(feature_type = "Polyline"):
    myContour = polyline.encode('utf-8')


text:
Q: Swift AppDelegate crashed Whenever I import Firebase and do FIRApp.configure() in AppDelegate, it crashes my app. Moreover, it crashes class AppDelegate: UIResponder, UIApplicationDelegate (Thread 1: signal SIGABRT) and it reports like this:

libc++abi.dylib: terminating with uncaught exception of type
  NSException (lldb).

I haven't worked even with storyboards.
Could you please help me to fix this crash?

A: *

*Check whether you have copied GoogleService-Info.plist to the project.

*Also try enabling keychain sharing under capabilities in Xcode.

A: When you select GoogleService-Info.plist in the Project Navigator, make sure that Target Membership is checked for your target.


text:
Q: Tab Key on Android Hard Keyboard How can I disable a tab key on a form so that it goes to the next button when press.
This is a hardware Tab key on a qwerty hardware keyboard.

A: You should implement the protected boolean onKeyDown(int keyCode, KeyEvent event) {}, check for the keyCode and if the key is tab, then consume the event.
Hope this helps!


text:
Q: Android arrrayOutOfBoundException I get a ArrayIndexOutOfBoundsException from the Arraylist I use.Whenever I try to click back button when i am at 1st item of arraylist or the next button when i am at the last item of arraylist my app crash.And for the rest of the items it works perfectly on next and previous button click.I don't know exactly how to check when the index is out of reach.
1.Here is my : Activity Class
public class SecondActivity extends AppCompatActivity {
 int position=0;
ImageButton buttonNext;
ImageButton buttonPrevious;
ImageButton buttonPlay;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
   final TextView nameEnglish =(TextView)findViewById(R.id.engNames);
   final TextView arabicTxt = (TextView) findViewById(R.id.araName);
   final TextView txtMeaning =(TextView)findViewById(R.id.textMeaning);

    Bundle bundle = getIntent().getExtras();
    final List<Names> namesList= bundle.getParcelableArrayList("LIST");
     position = bundle.getInt("Position");
  final   Names mk = namesList.get(position);

    if (bundle != null) {

        nameEnglish.setText(mk.getName());
        arabicTxt.setText(mk.getArabicName());
        txtMeaning.setText(mk.getMeaning());
    }
    buttonNext=(ImageButton) findViewById(R.id.nextbutton);
    buttonPrevious = (ImageButton)findViewById(R.id.previousbutton);
    buttonPlay = (ImageButton)findViewById(R.id.playbutton);

    buttonNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (position==namesList.size()-1)
            {

                buttonNext.setEnabled(false);
            }
            position++;
            Names names1 = namesList.get(position);

            if (position < namesList.size() ){

                nameEnglish.setText(names1.getName());
                arabicTxt.setText(names1.getArabicName());
                txtMeaning.setText(names1.getMeaning());

            }

        }
    });

    buttonPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (position == 0) {

                buttonPrevious.setEnabled(false);
            }

            position--;
            Names names2 = namesList.get(position);

            if (position > 0 ) {

                nameEnglish.setText(names2.getName());
                arabicTxt.setText(names2.getArabicName());
                txtMeaning.setText(names2.getMeaning());

            }

        }
    });

}

}
3.Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.islamiclearn.namesofallah, PID: 18205
                                                                           java.lang.ArrayIndexOutOfBoundsException: length=99; index=-1
                                                                               at java.util.ArrayList.get(ArrayList.java:413)
                                                                               at com.islamiclearn.namesofallah.activity.SecondActivity$2.onClick(SecondActivity.java:85)
                                                                               at android.view.View.performClick(View.java:5637)
                                                                               at android.view.View$PerformClick.run(View.java:22429)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Thanks for yours advise in advance.

A:
java.lang.ArrayIndexOutOfBoundsException: length=99; index=-1

Index -1 is invalid so you must ensure you use the correct value to get stuff from the array.

A: if (position==namesList.size()-1) {
    buttonNext.setEnabled(false);
}

Will disable the button, but only for the next time it is pressed. The code afterwards will still run, with an invalid index.
position++;
Names names1 = namesList.get(position);

if (position < namesList.size() ){
    nameEnglish.setText(names1.getName());
    arabicTxt.setText(names1.getArabicName());
    txtMeaning.setText(names1.getMeaning());
}


text:
Q: Is there a way to update/re-generate .cshtml files on Visual Studio (the ones generated when adding controller)? I updated my .edmx model file and now I want the generated edit.cshtml file and create.cshtml files updated according to it. Is there a way to get it done automatically?

A: What i'd do is:

*

*Backup related data from controllers and views.

*Delete Views and Controllers that you need to generate

*Create controllers with use of same scaffolding you used before.

*Generate views for controllers using that scaffolding

*Use your backup to update all that controller/views with logic that you had before (or skip this step if you don't need that).


text:
Q: Two columns on an uicollectionview How can I get two columns in a UICollectionView that take up the whole space without any margins or gaps much like the picture I drew below:
I tried using the following code:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(160, 160);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 1.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 1.0;
}

but got this result:

A: By Implementing UICollectionViewDelegateFlowLayout
protocol, you can find many methods for implementing layout of UICollectionView.
collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
 collectionView:layout:minimumLineSpacingForSectionAtIndex:

should be enough to solve this.
Also you can implement,  numberOfItems and numberOfSections to specify number of row, column.    Alternatively, you can specify the size of your cells as (width of UICollectionView) / (number of columns you want) - some offset between cells
  in cellForItemAtIndexPath.     By default the cells are calculated by this and arranged accordingly. Just by decreasing the size you will see multi columns. Ref1 Ref2

A: The best way to do this I found is either in Storyboard or in the delegate methods, have an item size of 159 and a gap inbetween gap of 0.5 or even smaller if you want. Just play around with it

A: to first have set your desired indentation in viewDidLoad, for example, put the padding on 10
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
clnView.collectionViewLayout = layout

and then use this
func collectionView(collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
            //device screen size
            let width = UIScreen.mainScreen().bounds.size.width
            //calculation of cell size
            return CGSize(width: ((width / 2) - 15)   , height: 155)
    }

A: @jacobsieradzki I think you need to do some changes in the size of your cells, try first to make them smaller, I'm thinking that probably 2 cells of 160.0 width + 1.0 of interline spacing is what is causing your problem.
I've followed a Ray Wenderlich tutorial some days ago that was really easy to follow and explains very clear the concepts behind UICollectionView, also in the sample project they are doing something similar to what you're trying to achieve, here is the link in case it helps: CollectionViewTutorial


text:
Q: Calculating resistance, voltage and current in parallel circuit
I need help in solving these questions. I've tried to use Kirchhoff's law but this hasn't worked.
I have been having a lot of difficulty with the resistance and current calculations, would someone be able to help show me where I have made mistakes.

A: You're calculating total resistance incorrectly. Parallel resistance is \$ \frac{1}{R_{T}} = \frac{1}{R_{1}} + \frac{1}{R_{2}} \cdots  \$
Where you get the \$(1+1+1)/3 \$ from, I'm not entirely sure.
\${R_{1}}\$ and \${R_{2}}\$ are in series. These are in parallel with \${R_{3}}\$ and \${R_{4}}\$ which are in series.
First thing you want to do is simplify each branch into a single resistor. As \${R_{1}}\$ and \${R_{2}}\$ are in series we can simply add them. So the total resistance in our first branch is \$4\Omega\$.
If we do the same with our second branch (So \${R_{3}} + {R_{4}}\$) then we can see the total resistance in our second branch is also \$4\Omega\$.
Now we have a circuit that looks like this:

(By the way, whichever teacher drew this needs to go back to school themselves imo. Nobody would ever draw a parallel circuit like this, Google 'parallel resistor circuit to see my point')
Now that you've got this simplified circuit, finding parallel resistance is a lot simpler. Using the equation \$ \frac{1}{R_{T}} = \frac{1}{R_{1}} + \frac{1}{R_{2}} \cdots  \$ we can put our values in to get \$\frac{1}{R_{T}} = \frac{1}{4} + \frac{1}{4}\$, this comes out to be \$\frac{1}{R_{T}} = 0.5\$.
However, we don't want \$\frac{1}{R_{T}}\$ we just want \${R_{T}}\$ so we have to invert the equation like so. \$\frac{1}{R_{T}} = 0.5 \rightarrow {R_{T}}=\frac{1}{0.5}\$. This gives a value of \${R_{T}} = 2\Omega\$.
(As there is only 2 resistances you can also use \$\frac{R_{a}\times R_{b}}{R_{a}+R_{b}} \$ but it's personal choice)
You should be able to do the rest of the questions now with ease if you follow Krishn's advice in the other answer

A: Well, if look at your text book carefully, you will probably get a clear idea of solving this.
I'll give you hints to solve it:
1) As it is mentioned in the question itself parallel circuit, find the total resistance of your circuit using Parallel combination of resistors.
2) After calculating total resistance, you can easily find the total current in flowing in your circuit using Ohms law.
3) Using current division principle, you can calculate the currents flowing through different parallel branches.
and finally,
4) Using Voltage division principle, you can calculate the voltage drops across different resistors.


text:
Q: How to prevent _Excel_RangeRead() converting comma to decimal point? I read values from Excel using _Excel_RangeRead() to paste them into a program that only accepts comma as decimal separator.
I have 3,14 in Excel, but _Excel_RangeRead() converts this to 3.14. How to prevent this or convert these back?

A: If you do it this way it should work: Use parameter 3
#include <Excel.au3>
#include <MsgBoxConstants.au3>
Local $oExcel = _Excel_Open(False)
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error creating the Excel application object." & @CRLF & "@error = " & @error & ", @extended = " & @extended)
Local $oWorkbook = _Excel_BookOpen($oExcel, "c:\Autoit\ForumTests\ExcelRead.xlsx")
If @error Then
    _Excel_Close($oExcel)
    Exit
EndIf

Local $aResult = _Excel_RangeRead($oWorkbook, Default, 'A1', 3)
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example 3", "Error reading from workbook." & @CRLF & "@error = " & @error & ", @extended = " & @extended)
ConsoleWrite($aResult & @CRLF)


text:
Q: $f\circ f$ is linear implies $f$ is linear I saw a question that asked for the possible values of $f(-1)$ if $(f\circ f)(x)=4x-12$.
The solution uses the fact that if the degree of $f$ is $n$, the degree of $f\circ f$ is $n^2$, and concludes that $f$ must be linear i.e. be of the form $ax+b$. The rest is easy.
I understand that this is the case if $f$ is a polynomial, but the question doesn't state that. What if there exists a weird function with logarithms, trigonometric functions etc. that is not linear but its composition with itself is linear? In other words, maybe the composition "cancels out" the weirdness. Obviously, involutions are a trivial example since the composition is $x$.
My question is: Is there a function $f$ that is not linear, but $f\circ f$ is linear and is not the identity function?

A: For $a,b>0$, let
$$f(x)=-\frac{a+b}2x+\frac{b-a}2|x|=\begin{cases}-ax&x\ge0\\-bx&x\le 0\end{cases} $$
Then $$ f(f(x))=abx,$$
so $f\circ f$ is linear. If $a\ne b$ and $ab\ne1$, then $f$ is not linear and $f\circ f$ is not the identity.


text:
Q: Can't get lFilter to work (rpi2b) Some information: I am using a rpi2b with a cirrus logic audio card and have worked out the kernel changes to get the sound card going, I can output without problems, I can record from line in without problems (I am using pyAudio).
Now I only want to filter the signal and have found a lot of functions in the scipy library...
First thing to mention I can only use 2 channels (stereo) input the soundcard seems to doesnt allow 1 channel and I dont have a source to stream mono (iPhone, simple USB player everyone has only stereo)....
The filter line (specifications) is just an example I think it will be an other filter if it works :D
So before the code begins a little to explain. When using stereo input the samples appear to be interleaved so you get on the one channel a sample on the other... I thought this thread was helpful: Convert multi-channel PyAudio into NumPy array
Thats why I also tried to decode my stream into an array, filter and then code it again into a stream for output. If I neglect the interleaving fact I get weird noises thats why I think I should take care of it :)
Now comes the part where I fail: lFilter doesnt want to work! If I just use my unprocessed input_data it says the axis is out of range (I tried -1,0,1,2) dont know :/ and when using my reshaped etc. data I get:
return sigtools._linear_filter(b, a, x, axis, zi)
ValueError: object of too small depth for desired array

Can someone please explain why this is happening? :D Never used signals thats why I am unexperienced but I cant understand why the unprocessed data has axis problems and even though it wouldnt bother because I need the reshaped data like in the linked thread...
WIDTH = 2
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
[b,a] = signal.iirfilter(2,[50,200],rs=60,btype='band',analog=True,ftype='cheby2')
full_data = np.array([])

def callback(in_data, frame_count, time_info, status):
    global b,a,full_data
    full_data = decode (in_data, 2)
    audio_data = signal.lfilter(b,a, full_data)
    print (audio_data)
    stream_data = encode(audio_data)
    return (stream_data, pyaudio.paContinue)

I skipped the stream open part and the decode and encode since the last ones are right now exactly the same as in the thread and the first one works thats why I just posted these parts. If needed I can also provide the others.
Any help is highly appreciated!

*

*Sanj3k

This is an example of what the data looks like, at first its a 1d np array and after the reshape etc ist 2d because of the stereo....
What does lFilter need? Since I have axis errors and with 2d its to small....
screenshot from the terminal
Edit: Btw here is the documentation from scipy library for the lfilter function and it says:
x : array_like
An N-dimensional input array.

http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html

A: For one thing, you need to keep the final conditions from one chunk and feed it as initial conditions to the next chunk.  Otherwise the filter assumes rest at the start of each chunk, which will result in glitches at each chunk.
global zi
audio_data, zi = signal.lfilter(b, a, full_data, zi=zi)`

So this call will update zi and then on the next cycle it will use it as the input to lfilter, which will update it, etc.  As the docs say:
zi : array_like, optional
    Initial conditions for the filter delays.  It is a vector
    (or array of vectors for an N-dimensional input) of length
    ``max(len(a), len(b)) - 1``.  If `zi` is None or is not given then
    initial rest is assumed.

...

zf : array, optional
    If `zi` is None, this is not returned, otherwise, `zf` holds the
    final filter delay values.

To initialize zi in the first place, just create a zeros array of shape (max(len(a), len(b)) - 1, number_of_channels).


text:
Q: C6001 on using the address of uninitialized value. Why? This here is my C++ code:
void somefn(char* string){
    char *current, *next;
    current = strtok_s(string, "a", &next);  // next is unitialized -> C6001 in VS 2020
}

int main(){
    char buf[] = "foobar";
    return 0;
}

which is deemed warning-worthy by a certain compiler with certain flags (should not matter, I believe).
The only questions are:

*

*Does this lead to an undefined behavior? I currently believe that an address of an uninitialized variable is a compile-time constant.

*Can this be for any reason considered bad practice? Why?

EDIT: Promised screenshot

A: The reference documentation for strtok_s shows that the above code is perfectly valid assuming that string is not a NULL pointer. Whether "an address of an uninitialized variable is a compile-time constant" is completely irrelevant and doesn't have anything to do with the diagnostic. The compiler thinks you are using uninitialized memory.
However the 4th parameter to strtok_s, as per documentation, needs to have the pointed-to pointer initialized (by an earlier call to strtok_s) only if the first parameter is NULL.
The compiler is being rather picky, it seems. It looks like the compiler cannot prove to itself that string will never be NULL here, so it's complaining about this.
But, if you never call strtok_s here with a NULL pointer here then there's nothing wrong with this.


text:
Q: How to resize the Google noCAPTCHA reCAPTCHA How i can resize height and width for Google reCAPTCHA controls without using css attributes ?
transform
-webkit-transform ,
transform-origin ,
-webkit-transform-origin ,
Thank you All

A: I'm in the same question, the transform pack is visual and don't make the dom changes, I mean ...

This is what i need: Recaptcha and button in the bottom.

But, when i apply the transform, the recaptcha use the same space but with blank space, so, I try to make a version with the same height but minus width and works only in the Firefox Developer Tool, because the recaptcha is a iFrame, and worst than that, it's restricted, so, you can't access with js.
My solution is to back to the traditional and universal solution BUT with different positions depending the page and works.
.g-recaptcha{-webkit-transform:scale(0.77);-webkit-transform-origin:0 50%;transform:scale(0.77);transform-origin:0 50%;}
#index .g-recaptcha{-webkit-transform-origin:0 100%;transform-origin:0 100%;}

I hope this reply can resolve your problem.
Greetings,

A: you may find solution here
https://geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/
HTML:

Edit JS var reCaptchaWidth
to the size you need

<form action="" method="get">

</form>

SUBMIT