text:
Q: replace string with multiple-string line using awk I have two separate files and I was hoping to search and replace a string in file1 for an entire line of multiple strings in file2. I have been working on using awk but I am not sure how to replace a string for a line of strings. Below is an example of what I was looking to do.
The string to be replaced would match the first field of the line to replace it (multiple strings to insert in place of the single string). It's a "find and replace" task.
file1:
001 111 112 113 116 117
002 221 222
003 331
004
005 551 555

file2:
113 114 115
222 223 224 225 226 227
551 552 553 554

Desired output:
001 111 112 113 114 115 116 117
002 221 222 223 224 225 226 227
003 331
004
005 551 552 553 554 555

A: Try this:
awk 'NR==FNR{a[$1]=$0;next}{for(i=1;i<=NF;i++)$i=($i in a?a[$i]:$i)}1' file2 file1
001 111 112 113 114 115 116 117
002 221 222 223 224 225 226 227
003 331
004
005 551 552 553 554 555

*

*We read file2 first and create an array indexed at column1 containing entire line as value.

*For file1 we loop through each element if it is found in our array we substitute it with the value.

A: Here you go:
awk '
  FILENAME == "file2" {
    key = $1
    map[key] = $0
    next
  }
  {
    for (i = 1; i <= NF; i++) {
      if (map[$i])
        $i = map[$i]
    }
    print
  }
' file2 file1
001 111 112 113 114 115 116 117
002 221 222 223 224 225 226 227
003 331
004
005 551 552 553 554 555

This takes lines from file2 and populates an array called map with the whole line, keyed on the first element (I'm treating awk's associative array system more like a hash).  Otherwise, loop through each element and substitute those that have map values, then print the output.  Note that this must be run with file2 provided first so that the map array can be populated.


text:
Q: PlayFramework 2.6 shutdown hook Play Framework 2.6
Mongo 3.6.2
Mongo Scala Driver 2.2.0
I want to drop MongoDB database, every time when I shutdown the application. I have the following code, implementing lifecycle stop hook, but when SIGTERM is send to the applicatin it's do not drop the database. What am I doing wrong ?
@Singleton
class Repo  @Inject() (lifecycle: ApplicationLifecycle) {

  val codecRegistry: CodecRegistry = fromRegistries(fromProviders(classOf[MyCollection]), DEFAULT_CODEC_REGISTRY )
  val mongoClient: MongoClient = MongoClient()
  val database: MongoDatabase =   mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry)

 .......

 lifecycle.addStopHook { () => {
     database.drop().toFuture()
       }
     }
   }

A: Wait for the database drop Future to complete (and close the MongoClient):
import java.util.concurrent.TimeUnit

import scala.concurrent.Await
import scala.concurrent.duration.Duration

...

lifecycle.addStopHook { () =>
  val result = Await.result(database.drop().toFuture(), Duration(10, TimeUnit.SECONDS))
  Future.successful(mongoClient.close())
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Identify the state of variables in a Java program This was homework and the task was to state which variables were visible at the points in the code marked *a*, ..., *e* and what value each one had. Can someone tell me if my solutions were right?
public class Zustand {
  public static void main(String[] args) {
    final int DIV = 24;
    int variable;
    int counter = 1;
    {
      // *a*
      variable = counter++;
      int y = 12;
      variable += y;
      counter++;
      // *b*
    }
    final double d;
    {
      counter = 4;
      double a = 10.0;
      {
        d = a + ++counter;
        // c
      }
      counter = 3;
      while (counter > 0) {
        counter--;
        a -= counter;
        // *d*
      }
    }
    variable = variable / DIV;
    // *e*
  }
}

First  what variables are there? My answer to this is:

*

*final int DIV

*int variable

*int counter

*int y

*final double d

*double a
There are 6 variables for each *a*, ..., *e*. I will assign to the 6-tuple (DIV, variable, counter, y, d, a) another 6-tuple  where the component of the tuple is either a number, the character w, or the symbol -. - means it is not visible. If it is a number it means that it is visible and the number is the value which is assigned to the variable. If it is the character w it means no value is assigned to the variable but it is visible.
So, this is my solution (is it right?). If something is wrong please give me a hint where my mistake could be.

*

**a* = (24,w,1,-,-,-)

**b* = (24,14,2,12,-,-)

**c* = (24,14,4,12,15,10.0)

**d* = (24,14,0,12,15,4.0)

**e* = (24,0,0,12,15,4.0)

A: if you use System.out.println, it will help you solve it!
public static void main(String[] args) {
    final int DIV = 24;
    int variable;
    int counter = 1;
    {
      // *a*
      variable = counter++;
      int y = 12;
      variable += y;
      counter++;
      // *b*
      System.out.println("y: " + y);            //  just an example

    }
    final double d;
    {
      counter = 4;
      double a = 10.0;
      {
        d = a + ++counter;
        // c
        System.out.println("d: " + d);             //  just an example

      }
      counter = 3;
      while (counter > 0) {
        counter--;
        a -= counter;
        // *d*
        System.out.println("a: " + a);                   //  just an example
      }
    }
    variable = variable / DIV;
    // *e*

    System.out.println("variable: " + variable);            //  just an example
    System.out.println("DIV: " + DIV);
    System.out.println("d: " + d);
    System.out.println("counter : " + counter);
}

In your console, you will see something like this.

y: 12
  d: 15.0
  a: 8.0
  a: 7.0
  a: 7.0
  variable: 0
  DIV: 24
  d: 15.0
  counter : 0

A: You seem to conflate "scope" and "lifetime" with "visibility".
the y and a variables are declared inside a { } block, and that means that outside of that block in which they are declared, they do not even exist.  It is wrong, strictly speaking, to say they are not "visible" because being "visible" or not is said of things that exist.  Their scope (existence) is just the block inside which they are declared, and their lifetime "ends when that block is exited".
This must not be taken to mean that the compiler will generate calls for memory allocation upon each entry of the block of code involved, but the language behaves as if the compiler effectively does this.
Furthermore, variables are typically referenceable only after the point where they are declared.  Other languages might be more relaxed in this, and allow, say, the y variable to be referenced already at point a (I don't know by heart how this is with java specifically and don't have a compiler here right now, but I suspect it will be no - at any rate, referencing before declaring is considered poor practice anyway).
Finally, variables are "visible" throughout their scope and lifetime, except in the case when they are hidden by new declarations.  Some languages allow you to do this :
{
 int y = 0;  /* 1st variable */
 {
  long y = 5;  /* 2nd variable, DISTINCT from the first (note the different type), and "hiding" the first */
               /* (so at this point, TWO variables EXIST but only ONE is VISIBLE) */
               /* references to y here will be to the SECOND variable */
 }
}

Once again, I don't know by heart how this is with java, but I suspect it might be even disallowed altogether.  Once again, it's relatively poor practice anyway.

A: Don't forget to start with: 'what is it that is asked here?'
Because if the question is: which variables were visible at the points in the code?
Then you can't just sum up all the variables you see. But only sum up the variables that are visible at that point in the execution of the 'main' method.
Don't forget to check if variables are already initialized at that point in time.
Don't forget to check the variable type, before writing down, what you think will be the value of a variable.
And look out for shortcuts in code.
Try to think, if this part of the code wasn't written as short as this, but was written in multiple lines of code, what would the output be? And then see if your first thought is still correct.
that should help you.


text:
Q: Separate header files for concrete classes - C++ Background
I have an abstract class, something like
class IConverter{
    public:
    virtual void DoConvertion() = 0;
};

There will be many concrete classes which just implements DoConvertion method.
class TextConverter : public IConverter{
    public:
    virtual void DoConvertion(){
         // my code goes here
     }
};

class ImageConverter : public IConverter{
    public:
    virtual void DoConvertion(){
         // my code goes here
     }
};

There will be many concrete implementation like this. I have created a header file say, CharacterConverter.h which has the abstract class IConverter.
Question
Since my concrete classes just implement the DoConvertion method, is it required to create separate header files for each concrete class? I mean is it required to create ImageConverter.h, TextConverter.h and so on for all concrete classes? All these header files is going to contain the same code like IConverter abstract class.
Any thoughts?

A: It is not required.  It's basically a judgment call.
If the implementation is simple for each class you can put them all in one .h and one .cpp
If the implementations are a bit longer, then it's probably cleaner to use a separate .h and .cpp file for each.
Some advantages of using a different .h/.cpp for each class:

*

*It will keep the code organized and clean

*Reduced compiling work: A change in one of the implementations won't need to recompile all others

*Faster compiling time: Several compilers can compile multiple files at once such as Visual Studio's /MP switch.  With several files you'll have a faster compile time.

*Other files can include only what they need instead of everything

*Faster link time: Linking time will be reduced due to incremental linking

*Using version control you can look back on only the changes to a particular derived class, instead of having to go through all changes made to the massive 1 .h/.cpp file to find that one change in a particular derived class.

A: One of the main points of creating an interface class is so that clients can be depend on the abstract interface rather than the concrete implementation, and you are then free to change the implementation without impacting clients.
Putting the concrete declarations in the same header files as the interface declarations defeats this, so now if you change an implementation detail of a concrete class, your clients would need to re-compile.

A: You'll probably get answers both ways.
I'd say, for any trivial converters, having all of them in a single .h/.cpp pair is sufficient and that it's overkill to split every one into a single pair.  I think the tradeoff of maintenance of lots of files vs. maintenance of a bunch of methods within a single file is worth it in this case.
Complex conversions probably deserve their own file pairs.

A: You will need definitions of the concrete classes to create objects, so you'll need to put those definitions into a .h file somewhere.  Which file you put them in is up to you.

A: The best answer to this is what's easier to read.  One long source file is going to be difficult for you and other programmers to follow.  On the other hand, many tiny (half screen-full) source files is just as bad.

A: Something you might consider, depending on the rest of your design, is a factory, where your abstract class has a static method (or multiple static methods, depending on how you implement it) that constructs the appropriate subclass and returns it as an IConverter*.  With this, you can expose only the abstract definition in the header file, and have all the concrete class definitions and implementations in a single .cpp file along with the super class implementation.  This gets a bit unwieldy if your subclass are large, but with smaller classes it reduces the number of files you have to manage.
But, as others have pointed out, it's ultimately a judgment call.  The only performance issues would be related to compiling; more cpp files might take (slightly) longer to compile and more header files might increase dependency analysis.  But there's no requirement that every header file have a matching cpp and vice verse.
Based on the comments, I'd recommend a structure like this:
IConverter.h ==> definition of IConverter
Converters.h ==> definitions of all subclasses
IConverter.cpp ==> include IConverter.h and Converters.h, contain implementation of IConverter abstract functionality (static factory method and any inheritable functionality)
TextConvter.cpp, ImagerConverter.cpp, etc. ==> seperate cpp files for each subclass, each containing IConverter.h and Converters.h
This allows you to only include the IConverter.h in any clients that use the factory and generic functionality.  Putting all the other definitions in a single header allows you to consolidate if they're all basically the same.  Separate cpp files allow you to take advantage of the compiler benefits mentioned by Brian.  You could inline the subclass definitions in header files as mentioned, but that doesn't really buy you anything.  Your compiler is usually smarter than you are when it comes to optimizations like inline.

A: You'd probably be better off using factories or function pointers.
However, one particularly nasty way that springs to mind is using a macro to declare your concrete classes. For example:
At the bottom of IConverter.h include the following macro
#define DECLARE_CONVERTER_CLASS(CLASS_NAME) \
class CLASS_NAME : public IConverter\
{ \
    public: \
    CLASS_NAME() {} \
    virtual void DoConversion(); \
}; \

Then in MyConverter1.cpp
DECLARE_CONVERTER_CLASS(MyConverter1)

virtual void MyConverter1::DoConversion()
{
    ...
}

Yuck :-)


text:
Q: Showing Base64String Image with Thymeleaf I am storing jpg images in a database (as byte array). I want to avoid dropping onto filesystem before showing on a web page.
Unit Tests show that database storage and retrieval are working without corruption. Fies can be extracted from database and converted back to jpg file
The image was converted to bytearray and stored in database with the following code:
public static byte[] getImageAsBytes(BufferedImage buffer) throws IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(buffer, "jpg", baos);
    baos.flush();
    byte[] imageInByte = baos.toByteArray();
    baos.close();
    return imageInByte;

}

I have a class ViewWrapperMediaImage that contains the byte array retrieved from the database. This class also has a method that converts the bytearray to base64 String.
package jake.prototype2.controller.viewwrapper;

import org.apache.commons.codec.binary.Base64;

import jake.prototype2.model.assessment.MediaImage;
import jake.prototype2.model.assessment.TestStructureException;
import jake.prototype2.model.structure.InterfacePersistenceBean;

public class ViewWrapperMediaImageCreate extends ViewWrapperTestContentElementCreate
{

private byte[] image;

protected String mediaFileName;

private static final long serialVersionUID = 4181515305837289526L;

public ViewWrapperMediaImageCreate(InterfacePersistenceBean persistenceBean) throws TestStructureException
{
    ....
    }
}

public byte[] getImage()
{
    return image;
}

public String generateBase64Image()
{
    return Base64.encodeBase64URLSafeString(this.getImage());
}

public void setImage(byte[] image)
{
    this.image = image;
}

public String getMediaFileName()
{
    return mediaFileName;
}

public void setMediaFileName(String mediaFileName)
{
    this.mediaFileName = mediaFileName;
}
}

My Thymeleaf tile then calls the conversion method generateBase64Image():

<img  th:src="@{'data:image/jpeg;base64,'+${vwNewTestContentElement.generateBase64Image()}}" />

It doesn't work.
The generated html source is as follows:
 < img src="data:image/jpeg;base64,_9j_4AAQSkZJRgABAgAAAQABAAD_2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL_2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL_wAARCADhASwDASIAAhEBAxEB_8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL_8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4-Tl5ufo6erx8vP09fb3-....

Any hints would be deeply appreciated

A: OK, it turns out this is dead easy, I solved within 2 mins of asking the question, but I bet others will have the same question.
The answer is don't use URLSafe
It works with encodeBase64String()


text:
Q: select multiple tables with MySql php I have 4 tables and I want to display the results for all of them. However, I am having the problem in retrieving the data from these tables. For all tables, they are having the same key which is called applicantId and I want to join all tables with this key.
Also, this is the account base website that I am building on. So there will be a unique accountId for these data. This means that a person can only view their own data within their account.
The problem I am having now is that I not able to get the data from MySql.
These are my tables below:
account table:

applicantpersonaldetails table:

employementdetails table:

existingbankproducts table:

This is my code in php:

                        <?php

                        $stmt = $DB_con->prepare("SELECT * FROM applicantpersonaldetails,employementdetails,existingbankproducts "
                                . "WHERE applicantpersonaldetails.ApplicantID = employementdetails.ApplicantID "
                                . "= existingbankproducts.applicantID "
                                . "and applicantpersonaldetails.AccountID ='{$accountId}'");
                        $stmt->execute();

                        if ($stmt->rowCount() > 0) {
                            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                extract($row);
                                ?>
<?php
                            }
                        } else {
                            ?>

                                       No Data Found ...

                            <?php
                        }
                        ?>

The $accountId is get it after I login.

A: u should join the tables together while selecting them, this means that while the tables still remain different u select them as a unique table using the "id" field as primary key. here is some documentation about the join rule
https://www.w3schools.com/sql/sql_join.asp

A: You are missing an AND.
This should work.
$stmt = $DB_con->prepare("SELECT * FROM applicantpersonaldetails,employementdetails,existingbankproducts "
    . "WHERE applicantpersonaldetails.ApplicantID = employementdetails.ApplicantID "
    . "and applicantpersonaldetails.ApplicantID = existingbankproducts.applicantID "
    . "and applicantpersonaldetails.AccountID ='{$accountId}'");

By the way I suggest you to use JOIN since selecting from multiple tables makes the statement very unclear. Furthermore using aliases would be a good idea since your table names are pretty long.
$stmt = $DB_con->prepare("SELECT * FROM applicantpersonaldetails apd "
    . "JOIN employementdetails ed ON apd.ApplicantID = ed.ApplicantID "
    . "JOIN existingbankproducts ebp ON apb.ApplicantID = ebp.ApplicantID "
    . "WHERE apd.AccountID ='{$accountId}'");


text:
Q: Html elements not registering when updates uploaded to cPanel I am using cPanel on BlueHost to make a website for a client. I have uploaded my files to the public.html folder and everything is live and looks good. But when I make changes and upload the files again.. some of the new html elements that I have added dont show up on mobile. They show up on desktop so I know its working and registering but idk why it wont show up on my phone. Any ideas? Im not sure if its a cPanel problem. I dont think its a Sass problem either. Do mobile devices take longer to recognize changes on a hosted site? Any help would be great. Thanks.

A: Thanks for joining the community. I'll be glad to help you or find a solution.
If you are just copying and pasting the files from your computer to the cpannel keep in mind that you need to change the path of some files in order for them to grab the style or any external sheet, I had a similar problem when uploading my website


text:
Q: Javascript: Connecting html and js files I'm tring to understand how to connected my html with another file js, but the issues is with this software call topsytle4 it a trail basic,but for some reason it show the file but no feature can be us that could be use.

A: Add this line between <head> and </head>:
<script src="your_js_path_here"></script>


text:
Q: Store Stored Procedure return value using JPA I'm trying to use JPA (and Spring Boot 2) for executing a SQL Server stored procedure. Here is the procedure:
CREATE Procedure [dbo].[GetStatus]
@statusId   char(32),
@bar    int
AS
BEGIN TRY
    SELECT IIF(COUNT(1)>0 , 1, 0)   FROM Status WITH (NOLOCK)
    WHERE statusId = @statusId AND bar = @bar
END TRY
BEGIN CATCH
    EXEC EventLog @@PROCID
END CATCH
GO

I'm trying to capture the return value but can't find a way to do so. My entity is:
@Entity
@Table(name = "status")
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(name = "getStatusByStatusId",
                procedureName = "GetStatus",
                parameters = {
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "statusId", type = String.class),
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "bar", type = Integer.class)                    })
})
public class Status implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    private Integer bar;
    private String statusId;
    private Date createDate;
}

And my repository is:
@Repository
public interface StatusRepository extends JpaRepository<Status, Long> {
    @Procedure("GetStatus")
    int getStatusByStatusId(@Param("statusId") String statusId, @Param("bar") Integer bar);
}

When I run this method from the service layer, I get an error:

"Parameter out was not defined for stored procedure..."

I tried to add out parameter (by naming it count and type as Integer). I tried List, Object[] but nothing worked.
Only thing that worked is if I change the repository method to return void. But in that case I can't get the return value.
So, my question is how can I get that SELECT value? Any help is appreciated. My app.yml has:
  datasource:
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    url: jdbc:sqlserver://dev.lsd.com:1433;databaseName=Qrex;integratedSecurity=true;MultiSubnetFailover=true;authenticationScheme=JavaKerberos
    username:
    password:
  jpa:
    hibernate:
      ddl-auto: none
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    show-sql: true
    database-platform: org.hibernate.dialect.SQLServerDialect
    database: sql_server

and my gradle dependency is:
compile "com.microsoft.sqlserver:mssql-jdbc:6.4.0.jre8"

A: I'm not convinced that JPA can handle stored procedures returning an arbitrary number of result sets and/or update counts and/or error messages. All the examples I've seen are rather simplistic. Your procedure returns either:

*

*A result set containing a projection (not an entity!)

*Whatever the EventLog procedure returns. Could be anything

Here's how to do it with JDBC directly (there are no OUT parameters, so an ordinary PreparedStatement will do.
Here's how to fetch only one result set with JDBC:
try (PreparedStatement stmt = connection.prepareStatement(
    "EXEC [GetStatus] ?, ?"
)) {
    stmt.setString(1, statusId);
    stmt.setInt(2, bar);

    if (stmt.execute()) {
        try (ResultSet rs = stmt.getResultSet()) {
            // Do your thing
        }
    }
}

Here's how to fetch an arbitrary number of result sets
In case you want to retrieve whatever EventLog produces as well, you might prefer calling this instead:
try (PreparedStatement stmt = connection.prepareStatement(
    "EXEC [GetStatus] ?, ?"
)) {
    stmt.setString(1, statusId);
    stmt.setInt(2, bar);

    fetchLoop:
    for (int i = 0, updateCount = 0; i < 256; i++) {
        boolean result = (i == 0)
            ? s.execute()
            : s.getMoreResults();

        if (result)
            try (ResultSet rs = s.getResultSet()) {
                System.out.println("Result      :");

                while (rs.next())
                    System.out.println("  " + rs.getString(1));
            }
        else if ((updateCount = s.getUpdateCount()) != -1)
            System.out.println("Update Count: " + updateCount);
        else
            break fetchLoop;
    }
}

I've described this approach of fetching arbitrary result sets and update counts more in detail here, specifically also how to fetch exceptions and warnings correctly.
If you use that approach, you might want to wrap that logic in some library code.
Using jOOQ
There's also the possibility to use jOOQ for these things (disclaimer: I work for the vendor), in case of which you could call:
Results results = ctx.fetchMany("EXEC [GetStatus] ?, ?", statusId, bar);

To get an org.jooq.Results type, which wraps interleaved result sets, update counts, exceptions, and warnings


text: Q: Is there any defects for using same database prefix in WordPress for multiple sites? I have now two sites using the same database prefix i.e., not other than wp_ Now, the argument arises that if there are some known issues or defects for them being same. As if I install WordPress from Softaculous from cPanel then it doesn't generate the same prefix until we do it.


text:
Q: JOIN query with multiple databases In MSSQL with JOIN, it is possible to cross tables from different databases. For example:
select
        PM_ID,
        PR_Name,
        OTD_Name
        from SomeTable
        inner join PRD_Det on PM_ID = PR_Id
        inner join DataBase2.dbo.PRI_Desc on PM_Oper = O_Id
        where PM_Id = @PM_Id

I'm trying to make something similar with EntityFramework:
        Entities1 _Context1 = new Entities1 ();
        Entities2 _Context2 = new Entities2 ();

        var data = (from w in _Context1 .SomeTable
                    join s in _Context2.PRI_Desc on w.PRD_Det.Single().PM_Oper equals s.O_Id
                    where w.PRD_Det.Single().PM_Id == PM_ID
                    select new SomeDetails()
                        {
                            PM_ID = w.PRD_Det.Single().PM_Id,
                            PR_Name = w.PR_Name,
                            OTD_Name = s.OTD_Name
                        }).ToList();

I'm getting the following error

The specified LINQ expression contains references to queries that are
  associated with different contexts

How can I solve this issue?

A: That is not supported in  Entity Framework (as the exception also indicates). You can use Joins only on Entities within the same Context.


text:
Q: Stop SIP SUBSCRIBEs from endpoint I am working with SIP protocol, and I have an issue with an endpoint (ZTE). The endpoint sends a lot of SUBSCRIBE method messages and I want to stop that because i don't whant to implement it.
I already tried to respond with 403 (Method Forbibben) and 405 (Method Not Allowed), but the endpoint is still sending SUBSCRIBE.
What is the propper way to stop an endpoint to send that method?
Thanks!

A: Sending a 405 (Method not allowed) response is correct. You should also add an Allow header with the methods you DO support.
Omit the SUBSCRIBE method from the Allow headers in (all) your requests and responses to the endpoint. This indicates that you don't support the SUBSCRIBE method.
Of course, you can't control whether the endpoint complies. If it's poorly implemented it could still send SUBSCRIBEs despite you indicating not to send them.

A: A well-behaved UAC should inspect the Allow-Event header in any response and only subscribe to those event packages listed in the header. If there is no Allow-Event header, or an empty value, the assumption should be that the UAS does not support any event package.
Try to include an empty Allow-Event header in the preceding response.


text:
Q: Publish Web.Release.config to IIS from VS, web deploy, one-click publish I have a few appSetting entries in my web.config.
I have some different entries in web.Release.config that I would like to push to IIS(7) when
I publish. (I am publishing using the one-click publish in VS2010 using the web deploy method).
When I publish to IIS and run the app, the app is getting the values from web.config and not web.release.config.
(I am in the Release configuration when I publish).
What am I missing ?
[EDIT]
The app settings section of the web.release.config:
<appSettings>
    <add key="StylesheetPath" value="http://mySite/Stylesheet/"/>
    <add key="ImagePath" value="http://mySite/Stylesheet/images/"/>
  </appSettings>

Thanks

A: In your web.release.config's appSettings node, add a transform attribute
<appSettings xdt:Transform="Replace">
<add key="StylesheetPath" value="http://mySite/Stylesheet/"/>
<add key="ImagePath" value="http://mySite/Stylesheet/images/"/>
</appSettings>

This xdt:Transform tells the config builder to take the appSettings node in your web.config and replace it with this one. When you deploy it, the web.config should be updated.


text:
Q: Embedded Components and Divisors I'm trying to understand a comment in the introduction to chapter 18 of Eisenbud's Commutative algebra with a View Toward Algebraic Geometry:
'..is the unimxedness theorem which explains, for example, why hyperplane sections of smooth varieties do not have embedded components. This is the reason we can treat divisors as codimension 1 subvarieties. It is thus a pillar of algebraic geometry.'
I don't see the pillar =(
What's wrong with embedded components? Is this comment referring to how Cartier divisors correspond to Weil divisors (In regular schemes)? It seems like all you need for this is the codimension 1 local rings to be DVRs. What's the relation between this and primary decomposition of an ideal $(f)$ having embedded primes?
My question is not coherent but maybe someone can just elaborate the quoted text?
Thanks!


text:
Q: How to map a JSON file from an API on React, selecting values to be added on a selector on product details I'm trying to add a couple of selectors on a product details page from a JSON file and I was able to do it properly from an array , the problem is that I am not able to do it from an array of objects. I'll try to show it as clear a possible:

*

*For product size - (extracted from Json api) - "size":["30","32"]
and from product details page, it works -
<FilterSize onChange={(e) => setSize(e.target.value)}>
{product.size?.map((s) => (
{s}
))}

*However I'm not able to get the values using the same structure with an array of objects. Although I guess it shouldn't be so difficult , I've been already hours))

*Colors - (extracted from Json api) - "colors":[{"code":500,"name":"blue"},{"code":600,"name":"red}]
<FilterColor onChange={(e) => setColor(e.target.value)}>
{product.color?.map((s) => (
{s}
How to alter the formula to get the values under the key "name"?

A: Without implementation details of what is filtercolor and what you want from it, it's quite dificult to answer your question.
<FilterColor onChange={(e) => setColor(e.target.value)}
  {product.color?.map((s) => ({s.name}) }
</FilterColor>


text:
Q: Place 'selected' attribute in matching option (in directive) How do I go about placing the 'selected' attribute in the option where device.types value is equivalent to. For some weird reason, the first option gets displayed even though device.type is of some other value. Where's the best place to put the code in the directive, link, compile, or controller?
template.html
<div>

    <select ng-model="device.type">
        <option value="value1">value1</option>
        <option value="value2" selected>value2</option>
        .
        .
        .
        <option value="valueN">valueN</option>
    </select>
</div>

directive
app.directive('details', function() {
    return {
        restrict : 'E',
        scope : {
            device: '=',
            ...
        },
        templateUrl : 'template.html',
        link : function(scope, element, attrs) {
            // put 'selected' on option element where device.type is equivalent to
            // is it preferrable to put logic here? or in controller or compile
        }
    };
});

Appreciate your inputs. Thanks.

A: You don't need to create a directive to achieve that.
Just fill you select with ng-options and use track by <some field>.
Then, when your select's model changes, it will select the right option corresponding to the field you choose in track by <some field>.
Something like that :
<select
    ng-model="device"
    ng-options="device as device.type for device in devices track by device.type">
</select>

So, when you put a device object in the select's model, it will select the option with the device.type matching your model.


text:
Q: How do I prove if a sum of two specific irrational numbers is irrational? Prove that $\sqrt 2 + \sqrt 6$ is irrational. (Note that, in general, the sum of two irrational numbers could be rational.)
I tried attempting to use proof by contradiction but I'm unsure of how to go from even there. I have no clue other than that. Please help.

A: If it is rational, its square is also rational. But this would imply that $\sqrt{3}$ is rational.

A: You could try this: If $a = \sqrt 2+\sqrt 6$ is rational then so is $\frac{1}{a} = \frac{\sqrt 6 - \sqrt 2}{4} \Rightarrow \sqrt 6 - \sqrt 2 \in \mathbb{Q}$
Subtracting, we get $\sqrt 2$ is rational, which is false. Hence $a \notin \mathbb{Q}$

A: Side hint: let $\,x=\sqrt{2}+\sqrt{6}\,$, then $x^2=8+4 \sqrt{3}$ and $(x^2-8)^2=48 \iff x^4-16x^2+16=0\,$.
By the rational root theorem, any rational root of the latter polynomial would have to be an integer. But $\,1 \lt \sqrt{2} \lt 3/2\,$ and $\,2 \lt \sqrt{6} \lt 5/2\,$, so $\,3 \lt \sqrt{2}+\sqrt{6}\lt 4\,$, thus $\,x\,$ lies strictly between two consecutive integers, and therefore cannot be an integer itself.


text:
Q: Reverse Repeater Order asp.net /c# i'm working on items page where user can insert items into system and all items shown in repeater in the home page ,the latest items are displayed on the bottom of the page whilst the first items are displayed on the top ,
Is there a way to reverse the order such that the latest updates in the repeater are always displayed on top ?

A: Have you tried this?
Repeater.DataSource = data.Reverse();
Repeater.DataBind();


text:
Q: Add Flow for Boolean That Gets Updated I have a listener:
class Owner {
    private lateinit var flow: Flow<Boolean>

    init {
        flow = callbackFlow {
        val callback = object : Listener {

            override fun onExit() {
                offer(false)
            }

            override fun onEnter() {
                offer(true)
            }
        }
        MyService.register(callback)
        awaitClose {
            //service.unregister(callback)
        }
    }

    fun getFlow(): Flow<Boolean> = flow

}

So then I want that every time the callback gets called the flow gets updated and any other class observing the flow would naturally get notified. How to do this?
If I want to also set the value to true or false without the callback can I do it?

A: Here's some self-contained code that proves the basic design you have works as you expect it to. It registers two listeners, starts MyService, lets the listeners observe some events, cancels one listener, lets the other one keep going for a while, and then cancels everything and cleanly finishes.
Therefore, the question as you asked it doesn't actually point to any problem that needs to be solved.
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.concurrent.thread

fun main() = runBlocking<Unit> {
    val owner = Owner()
    val consumer1 = launch {
        owner.flow.collect {
            println("listener 1: $it")
        }
    }
    val consumer2 = launch {
        owner.flow.collect {
            println("listener 2: $it")
        }
    }
    delay(100)
    MyService.start()
    delay(600)
    println("Cancelling consumer 2")
    consumer2.cancel()
    delay(600)
    MyService.stop()
    consumer1.cancel()
}

class Owner {
    val flow = callbackFlow() {
        val callback = object : Listener {
            override fun onEnter() {
                offer(true)
            }
            override fun onExit() {
                offer(false)
            }
        }

        MyService.register(callback)
        awaitClose {
            MyService.unregister(callback)
        }
    }
}

object MyService {
    private val listeners = LinkedHashSet<Listener>()
    @Volatile
    private var keepGoing = true

    fun register(listener: Listener) {
        listeners.add(listener)
    }

    fun unregister(listener: Listener) {
        listeners.remove(listener)
    }

    fun start() = thread {
        while (keepGoing) {
            listeners.forEach {
                it.onEnter()
            }
            Thread.sleep(100)
            listeners.forEach {
                it.onExit()
            }
            Thread.sleep(200)
        }
    }

    fun stop() {
        keepGoing = false
    }
}

interface Listener {
    fun onExit()
    fun onEnter()
}

When I run it, this prints:
listener 1: true
listener 2: true
listener 1: false
listener 2: false
listener 1: true
listener 2: true
listener 1: false
listener 2: false
Cancelling consumer 2
listener 1: true
listener 1: false
listener 1: true
listener 1: false

Process finished with exit code 0


text:
Q: How to capture a list var identifying all the promotions in the main carousel and then add the index I want to add the index position of each element at the end of that element. eg: <Category>;<Action>;<Label>;<Position>
at the moment I only have <Category>;<Action>;<Label>
I dont know how to loop through them again to get the position and append that. Below is some example code. Not sure if this makes any sense. Thank you for any help.

var newArr = [];
var string = "~A~, ~B~, ~C~";
string = string.split(",");
$.each(string, function(index, element) {
  console.log("Log 1: " + element);
  element = element.replace(/\~/g, "").replace(" ", "");
  console.log("Log 2: " + element)
  newArr.push(element);
})
newArr = newArr.join(";");
console.log(newArr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: You could have a variable outside the loop
let i = 0;
then
newArr.push(i++);
newArr = bannerDataArr.join(";");

Hope this helps. The code is a little confusing.


text:
Q: pacman in Ubuntu 18.04 I am trying to install devkitPro in Ubuntu 18.04, and they are indicating that the packages are available using pacman package manager. I have installed pacman with the command sudo apt install pacman. They are indicating about using the command pacman-key --init too, but when I have attempt to use pacman-key, I get the message pacman-key: command not found.
Has someone try this before?
Thank you in advance!

A: There is a deb file here: https://github.com/devkitPro/pacman/releases/download/devkitpro-pacman-1.0.1/devkitpro-pacman.deb
Download it via:
wget https://github.com/devkitPro/pacman/releases/download/devkitpro-pacman-1.0.1/devkitpro-pacman.deb

Install it via:
dpkg -i devkitpro-pacman.deb

This particular step will take a bit to complete but hang on. It will finish in several minutes:
gpg: Generating pacman keyring master key...
After it's done,
dkp-pacman -S switch-dev

You can replace switch-dev with whatever system for which you want to develop.
Log out and back in and the directory containing the binaries will be added to you path via /etc/profile.d/devkit-env.sh.


text:
Q: exec command works in terminal not with PHP I'm writing a class who let me access to recutils through PHP.
I have a 'database' file called books.rec in ../database/ and a script who runs my Recutils.php class.
My class simply launch system application with correct parameters.
But When I try to use recins with PHP's exec function, the command doesn't work will it work in command line.
This is the command that is executed by my script :
recins -f Title -v "Moi" -f Author -v "Moche" -f Location -v "loaned" -t Books ../database/books.rec
With PHP : Nothing, the record is not inserted (no error message at all too).
In terminal : OK, the command is well done and my record is inserted.
I also have a method to do a select operation using recsel and it works very well, will it use exactly the same file (and runs from exec too).
So, could someone explain me why the command don't work will another with the same file work ?
Thanks
PS : Further informations : http://www.gnu.org/software/recutils/

A: I would double check that you are running the command as the same user from the command line and your php script. That may be the problem. exec('whoami')
You said you had a script that starts your php script it should be the same user as that.
You might also want to running a simpler exec command to see if that will work first.
Other things to try:

*

*Try checking stderr output exec('ls /tmp 2>&1', $out); This will redirect standard error to standard out so you get both.

*Try using php's shell_exec() which will invoke a shell just like when you are running from the command line(eg. bash). shell_exec('ls /tmp 2>&1 >> /tmp/log') should even put all output into a log file.

*I don't think this will help you but it is something to try if all else fails, set it as a background process and see if it completes. exec('nohup php process.php > process.out 2> process.err < /dev/null &'). The & will set the command to run in the background and let the script continue.

Good Luck

A: Is recins command accessible for PHP ? Also is path to books.rec correct ?
Try with absolute path.


text:
Q: Not able to run PMD in eclipse luna i have installed (PMD) 4.0.6 and i am using eclipse Luna and my java version is 1.8._40.Now it is installed ,its opening in editor.
Problem is when i try to check any violation of any file or any project,it won't run and it won't show the violation in editor.
Please tell me how to fix this?


text:
Q: Refresh file content in internal Midnight Commander file editor & viewer I prefer internal Midnight Commander file editor & viewer when work on remote machines.
When I read log files I expect they updates and I want to trigger re-load without losing current screen/cursor positions.
I had hard time to find out key bindings for such simple actions. At the moment I leave the viewer / editor and reenter. Obviously I lose position and mental focus.
Are there key binding to refresh file content in MC internal viewer / editor?


text:
Q: How to show $\frac{300}{v} - \frac{300}{v+20} = 1.25$ A man travels a distance of $300$ km. On his return journey his average speed increased by $20$ km/h and his journey time decreased by $1\frac{1}{4}$ hours. If $v$ is the average speed of his outward journey how can we show that:
$$\frac{300}{v} - \frac{300}{v+20} = 1.25$$
I'm very stuck.

A: By the information you have, using $\text{speed}\cdot \text{time} = \text{distance}$ you can create two equations:
$$\text{I:}\quad v\cdot t = 300\\
\text{II:}\quad (v+20)\cdot (t-1.25) = 300$$
Edit:
Express $t$ from each equation, you get
$$\text{I:}\quad t = \frac{300}{v}\\
\text{II:}\quad t = \frac{300}{v+20} + 1.25$$
Now compare substitute $t$ from the first equation into the second one.
$$\frac{300}{v} = \frac{300}{v+20} + 1.25$$
Now you only have to subtract $\frac{300}{v+20}$.


text:
Q: How to configure apache to allow rewrite rules for directories? I have some configuration in htaccess:
RewriteEngine On
RewriteRule ^(.*)$ /index.php [L,NC,QSA]

All urls redirects to /index.php
But if folder exists, it goes to folder, not to /index.php
why?
I tried this solution to make this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . index.php [QSA,L]

But this like a previously example goes to directory =(

A: Try this
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php

Or
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f
RewriteRule (.*)  index.php [QSA]

A: Use something like this:
#turn rewrite engine on
RewriteEngine On

#specify your base
RewriteBase /

#make sure, your index.php won't be rewritten
RewriteRule ^index.php - [L]

#rewrite everything else
RewriteRule ^(.*)$ index.php?para=$1 [QSA,L]

A:
But if folder exists, it goes to folder, not to /index.php

Try disabling MultiViews – it is often interfering in such cases.
Options -MultiViews

http://httpd.apache.org/docs/2.2/mod/core.html#options
http://httpd.apache.org/docs/2.2/mod/mod_negotiation.html#multiviews


text:
Q: Factorization of $112^4+1$ So I read answers like this one For which $n$ the polynomial $x^n + y^n$ will be irreducible over $\mathbb Z$?
and this one:
Factoring $x^n + y^n$ over the integers
They seem to imply (correctly) that $x^{2^k}+1$ could not be factorised. I'm just wondering how one could explain the factorization of $$112^4+1 = (2^4*7)^4+1= (112*418+1)(112*30+1)$$.
Is there a way to factorize $112^4+1$ using like a cube facor formula (which obviously cannot be used here) or something else?

A: As $x^4+1$ is irreducible over $\mathbb{Z}[x]$, this factorization doesn't generalize to all values of $x^4+1$. But it does to some:
This factorization is based on the observation that
$$3\cdot 112^2+4=194^2$$
(in other words, $3x^2+4=y^2$ has a solution at $x=112$; this is a Pell equation and as such there are infinitely many such pairs $(x,y)$ of integers.) So, we have, letting $x=112,y=194$,
$$x^4+1=(4x^4+4x^2+1)-(3x^4+4x^2)=(2x^2+1)^2-x^2(3x^2+4);$$
as $3x^2+4=y^2$ this reduces to
$$x^4+1=(2x^2+1)-(xy)^2= (x(2x-y)+1)(x(2x+y)+1),$$
which is the factorization you gave.

A: When they say expression $x^4+1$ does not factor over rational field they mean we can not find polynomials with rational coefficients to divide $x^4+1$
The story of integer factorization is a different story because an integer could be written in many different forms.  For example $ 82= 3^4+1$ and $ 82=2(41)$ so it does not factor in one form but it does in another form.
similarly $5^4 +1 = 626 = 2(313)$


text:
Q: How to detect shake level perfectly across all android devices? I want to perform a certain task when a shake is detected through an accelerometer but the problem is every device's sensitivity level is different. For example: look at this code on sensor changed `
public void onSensorChanged(SensorEvent event) {

    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];
    //formula
    float accelationSquareRoot = ((x * x + y * y + z * z)
            / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH));
    float acc = accelationSquareRoot - 1;
    String s1 = String.valueOf(acc);
    //if I used a value 10 instead of 7 below it will be fine for samsung
    phones but will not work on most nokia phones
    if (acc >= 7){//perform certain task} }

For my Nokia 6.1 the shake detection is min 1 to max 10 and if the value is above 10 nothing will be detected, for Samsung Galaxy Note7, the detection level is from min 1 to max 30, which means every manufactures hardware is a bit different from others. If I set the value to 7, I have to shake hard on my Nokia 6.1 but on Samsung phones, value 7 is considered a very low sensitivity and the code will run even on touching the phone. I want the user's having various android devices to set the sensitivity level they want like small, medium, hard. What should I do to run this on devices from nearly 1300 brands with over 24,000 distinct android devices?

A: Please Try this way,
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
   private SensorManager mSensorManager;
   private float mAccel;
   private float mAccelCurrent;
   private float mAccelLast;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
      Objects.requireNonNull(mSensorManager).registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
      SensorManager.SENSOR_DELAY_NORMAL);
      mAccel = 10f;
      mAccelCurrent = SensorManager.GRAVITY_EARTH;
      mAccelLast = SensorManager.GRAVITY_EARTH;
   }
   private final SensorEventListener mSensorListener = new SensorEventListener() {
      @Override
      public void onSensorChanged(SensorEvent event) {
         float x = event.values[0];
         float y = event.values[1];
         float z = event.values[2];
         mAccelLast = mAccelCurrent;
         mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
         float delta = mAccelCurrent - mAccelLast;
         mAccel = mAccel * 0.9f + delta;
         if (mAccel > 12) {
            Toast.makeText(getApplicationContext(), "Shake event detected", Toast.LENGTH_SHORT).show();
         }
      }
      @Override
      public void onAccuracyChanged(Sensor sensor, int accuracy) {
      }
   };
   @Override
   protected void onResume() {
      mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
      SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
   }
   @Override
   protected void onPause() {
      mSensorManager.unregisterListener(mSensorListener);
      super.onPause();
   }
}


text:
Q: Longtable - Caption too short I'm using longtable. But the caption is too short that it splits up my 12 word caption into two lines centered, only 1/3 of the table width.
I would like to show the caption in one line. Any advice?
Below is my code:
\documentclass[a4paper,12pt]{article}
\usepackage{longtable}
\usepackage{pdflscape}
\usepackage{graphicx}

\begin{document}
\begin{landscape}
\setlength\LTleft{-40pt}
\setlength\LTright{-40pt}
\begin{longtable}{@{\extracolsep{\fill}}llllllllll@{}}
\caption{Why My Caption is Squeezed Here Can I Make The Length Longer?}\\
\hline\hline
Short Name & Full Name  & Source                                     \\
\hline
\\
\hline
\end{longtable}
\end{landscape}
\end{document}

A: Add
\setlength\LTcapwidth{\linewidth}

to your code, right after (or before) setting \LTleft and \LTright.
Background: As opposite to the regular \caption the one from longtable is limited to the width \LTcapwidth. When using in portrait mode, the default value is quite reasonable, but too short in landscape mode.
Complete example document:
\documentclass[a4paper,12pt]{article}
\usepackage{longtable}
\usepackage{pdflscape}
\usepackage{graphicx}

\begin{document}
\begin{landscape}
\setlength\LTleft{-40pt}
\setlength\LTright{-40pt}
\setlength\LTcapwidth{\linewidth}
\begin{longtable}{@{\extracolsep{\fill}}llllllllll@{}}
\caption{Why My Caption is Squeezed Here Can I Make The Length Longer?}\\
\hline\hline
Short Name & Full Name  & Source                                     \\
\hline
\\
\hline
\end{longtable}
\end{landscape}
\end{document}

Shameless self-advertisement: Adding \usepackage{caption} would have solved the issue, too, since it ignores \LTcapwidth (unless set to a specific value).

A: Use \caption package and add the following line into your preamble:
\usepackage{caption}
\captionsetup[table]{labelfont=bf,textfont=normalfont,singlelinecheck=on,justification=raggedright}


text:
Q: What should be more efficient - Appending results to a new table or Inner Join with the existing table I have a Original_Table that contains an empty column called Results (which is to be populated using python code being run on other columns in Original_Table). The primary key in this Original_Table is ROWID
I also have an empty (currently) table called Results_Table  that has the same columns/data format as Original_Table
What I am doing currently:

*

*The Original_Table contains 1 million records , so I am creating
batches of 100 samples as a Temporary_Small_Table and calculating
Results column.

*Then I append the Temporary_Small_Table to the initially empty
Results_Table
As you can notice , I do not update the Original_Table with the data in my Temporary_Small_Table as I imagine a join across Temporary_Small_Table (100 records) X Original_Table(1 million records) will be very inefficient. So I simply keep on appending my Temporary_Small_Table to the Results_Table.
I wanted recommendations on what's the correct way to do this (Joining to Original_Table or Appending to Results_Table ).
One obvious consequence of  Appending to Results_Table is wasting storage space for a brand new table.
Just few additional background points:

*

*I am creating batches for running my python code in multiple threads.

*I am doing this on the Azure Databricks platform. This link tells me the database is MySQL and PostgreSQL operated as a service by Azure and AWS.

*The join I am speaking about will be done on ROWID(it's the primary
key as mentioned in the beginning)

*For point #1 , I am already splitting my batches with predetermined
row ids in the table , hence different threads picking up the same
row from the  Original_Table is not an issue at the moment for me.
How to avoid the same row from the  Original_Table from getting
picked up without predetermining row ids  for each batch is a
different topic which I would park for later


text:
Q: angular 2, karma,jasmine 404 not found issue I am trying to write a unit test for a component in angular2. The stack is angular2,karma,jasmine with Visual Studio as IDE. Find below the exception that occurred while running the unit tests through Gulp.
**16 03 2017 18:04:28.169:DEBUG [middleware:source-files]: Fetching E:/TestProject/app/component/SampleComponent

16 03 2017 18:04:28.170:WARN [web-server]: 404: /base/app/component/SampleComponent

Chrome 56.0.2924 (Windows 7 0.0.0) ERROR
  {
    "originalStack": "Error: Error: XHR error (404 Not Found) loading app/component/SampleComponent\n\tError loading app/component/SampleComponent as \"./SampleComponent\" from app/component/SampleComponent.spec.js",

    "zoneAwareStack": "Error: Error: XHR error (404 Not Found) loading app/component/SampleComponent\n\tError loading app/component/SampleComponent as \"./SampleComponent\" from app/component/SampleComponent.spec.js",

    "originalErr": {
      "originalStack": "Error: XHR error (404 Not Found) loading app/component/SampleComponent",
      "zoneAwareStack": "Error: XHR error (404 Not Found) loading app/component/SampleComponent"
    }
  }

Chrome 56.0.2924 (Windows 7 0.0.0) ERROR
  {
    "originalStack": "Error: Error: XHR error (404 Not Found) loading app/component/SampleComponent\n\tError loading app/component/SampleComponent as \"./SampleComponent\" from app/component/SampleComponent.spec.js",

    "zoneAwareStack": "Error: Error: XHR error (404 Not Found) loading app/component/SampleComponent\n\tError loading app/component/SampleComponent as \"./SampleComponent\" from app/component/SampleComponent.spec.js",

    "originalErr": {
      "originalStack": "Error: XHR error (404 Not Found) loading app/component/SampleComponent",
      "zoneAwareStack": "Error: XHR error (404 Not Found) loading app/component/SampleComponent"
    }
  }
16 03 2017 18:04:28.258:DEBUG [karma]: Run complete, exiting.
16 03 2017 18:04:28.259:DEBUG [launcher]: Disconnecting all browsers**

My folder structure is app\component
The tests are available within component folder itself. The related code in the transpiled js is as follows
const Component_1 = require("./SampleComponent");
const testing_1 = require("@angular/core/testing");

Request anyone to help on this.
Thanks
TTV

A: I resolved it by the following statement in karma.conf.js
{ pattern: './app/component/LoginComponent.js', included: true, watched: false }

Please refer the below URL for complete information.
https://psamsotha.github.io/angular/2016/12/16/angular2-testing-karma-systemjs.html
Check it


text:
Q: How to include non-key attributes in dynamodb table and assign values to it using batch_writer? Creating a table using dynamodb with hash and Range keys. Also, i have some non-key attributes and it's values to be included in it. Getting error while trying to update the table.
Code:
dynamodb = boto3.resource('dynamodb')
client = boto3.client('dynamodb')

table = dynamodb.Table('Name')
db_AccountNumber=[]  #data to be included in table is in below two lists which consists of multiple 12 digit AWS account-ID's.

db_accountalias=[]  #data contains multiple AWS account-names

# Create the DynamoDB table.
table = dynamodb.create_table(
    TableName='Name',
    KeySchema=[
        {
            'AttributeName': 'account_number',
            'KeyType': 'HASH'
        },
        {
            'AttributeName': 'account_type',
            'KeyType': 'RANGE'
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'account_number',
            'AttributeType': 'S'
        },
        {
            'AttributeName': 'account_type',
            'AttributeType': 'S'
        },
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10,
    }
)

table.meta.client.get_waiter('table_exists').wait(TableName='Name')

with table.batch_writer() as batch:
    for item in db_AccountNumber:
        for alias in db_accountalias:
            batch.put_item(
                Item={
                     'account_number' : item,
                     'account_type' : 'new',
                     'iam_alias': {'S': alias},
                     'profile': {'S': alias},
                     'cname': {'S': alias}
            }
     )

I want the non-key attributes iam_alias, profile,cname to have the same values as of now.
Executing above codes gives Error:
Traceback (most recent call last):
  File "./createdb_multiplefields.py", line 66, in <module>
    'cname': {'S': alias}
  File "/usr/lib/python2.7/site-packages/boto3/dynamodb/table.py", line 101, in put_item
    self._add_request_and_process({'PutRequest': {'Item': Item}})
  File "/usr/lib/python2.7/site-packages/boto3/dynamodb/table.py", line 110, in _add_request_and_process
    self._flush_if_needed()
  File "/usr/lib/python2.7/site-packages/boto3/dynamodb/table.py", line 131, in _flush_if_needed
    self._flush()
  File "/usr/lib/python2.7/site-packages/boto3/dynamodb/table.py", line 137, in _flush
    RequestItems={self._table_name: items_to_send})
  File "/usr/lib/python2.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/lib/python2.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the BatchWriteItem operation: Provided list of item keys contains duplicates

Clearly, the keys in my Item are not duplicate. How to fix this error and update table?

A: The error message is saying that you have duplicate keys. Your problem is in this piece of code:
with table.batch_writer() as batch:
    for item in db_AccountNumber:
        for alias in db_accountalias:
            batch.put_item(
                Item={
                     'account_number' : item,
                     'account_type' : 'new',
                     'iam_alias': {'S': alias},
                     'profile': {'S': alias},
                     'cname': {'S': alias}
            }
     )

On the first execution of the inner loop for alias in db_accountalias: your account_number is set to value of item and account_type is set to 'new'. On the second execution of the same loop, the account_number is still set to value of item (since you are still within the context of the inner loop) and similarly account_type is also still set to 'new', since it's a constant value, that is not changing as the inner loop iterates. As a result, you are getting the duplicate key value, which is what the error message indicates.

A: Figured out how to enter data to table.I replaced two for-loop statements for item in db_AccountNumber:
for alias in db_accountalias:  with just one for loop like below.
for item, alias in zip(db_AccountNumber, db_accountalias): which did the trick.


text:
Q: How to find out the valid values to use for authorized grant types in Spring Secrity I want to allow a client to use a specific grant type, but cannot find the valid values to use in the client table in the documentation.
Any ideas?

A: Very good question - I struggled to find the values for hours.
Here is how to gather the different values. Every implementation of AbstractTokenGranter carries static field grant type GRANT_TYPE:

*

*refresh_token - RefreshTokenGranter

*authorization_code - AuthorizationCodeTokenGranter

*implicit - ImplicitTokenGranter

*password - ResourceOwnerPasswordTokenGranter

*client_credentials - ClientCredentialsTokenGranter

The authorized grant types of a client can be found in the client instance via ClientDetails.getAuthorizedGrantTypes
And last but not least spring security oauth follows the specification here - so the grant types mentioned above match those mentioned in the spec.

A: Here is something I use regularly:
public enum OAuth2GrantTypes {

    AUTHORIZATION_CODE("authorization_code"),
    IMPLICIT("implicit"),
    PASSWORD("password"),
    CLIENT_CREDENTIALS("client_credentials"),
    REFRESH_TOKEN("refresh_token");

    // Currently not supported by Spring Security
    // https://tools.ietf.org/html/draft-ietf-oauth-device-flow-01
    // DEVICE_CODE("device_code")

    private final String name;

    OAuth2GrantTypes(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

This allows you to specify the grant types like this:
.authorizedGrantTypes(
    OAuth2GrantTypes.IMPLICIT.getName()
)


text:
Q: Why some keys doesnt work on my Ubuntu laptop? I'm using a Lenovo Legion S7 15ACH6 laptop with Ubuntu 22.04 LTS and I've run into an unusual issue. The 'Backspace', '[' and ']' keys only work if I press another key along with it. For example, to delete a character I need to press 'Shift' + 'Backspace' for example. Strangely if I press 'Alt' + 'Backspace' or just the 'Backspace' itself, nothing happens, as if the key is broken. Likewise with the other two keys. I tried to boot into Ubuntu from a USB flash drive, the problem remains. When booting from a USB flash drive with Windows, it offers to restore the OS settings, so i didnt meet any input field to test it out. If I connect any external keyboard, everything works correctly. Updated the Linux kernel, did not help. Please tell me, can this problem be due to physical damage or is it still at the software level? What other ways are there to test it besides a complete system reinstall? May it be because of some BIOS issues?
Changing keyboard layout doesnt affect the problem
tried to press keys with xev | grep keycode
had the same behavior: pressing one button doesnt count in utility
with two keys pressed (with any key, even 'F1' or 'Super'):
0x10, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES, state
0x11, keycode 22 (keysym 0xff08, BackSpace), same_screen YES

A: In the end, I've managed to solve the problem in the following way:

*

*boot up with Windows installing usb

*open terminal (shift + f10)

*start typing - at first nothing happened; then the keys started to work properly

*reboot back to ubuntu

*now everything is fine - all keys work properly


text:
Q: Does Kubernetes internally maintain tasks queue? We are in the development phase. We are using Kubernetes cluster consisting of master and slave EC2 instances. We are submitting tasks to Kubernetes cluster using Kubernetes_Pod_Operator of Airflow. We are looking to scale this process. So we are going to use Celeryexecutor of Airflow which is used to concurrently submit and schedule tasks on Airflow.
So the question is, should we care about number of tasks submitted to Kubernetes or irrespective of number of tasks submitted to Kubernetes, Kubernetes will service all the tasks without failure by any internal queuing ?

A: First of all, note that Kubernetes is not meant to do this kind of operations, precisely because there is no queuing idea in Kubernetes. So, you do care about the number of submitted tasks.
From the source code of "kubernetes_pod_operator.py" it seems that it just creates a pod in the right namespace, with the right image, etc.
In the end it is a pod, so it will do a job and finish (status: completed).
Taking this into consideration, it will depend on the jobs it will have to run, and your machine type. An example:
Say you are running simple pipelines that consume about 0.1CPU and few MB of memory. If your nodes are 4-CPU machines (lets assume you have enough memory), then you can run ~40 concurrent jobs per node. If you run more, you will get an error (saying your pods can't be scheduled).
So,

*

*(recommended) If you can actually determine a standard resource consumption per task (per pod), I would recommend you to set resource requests and limits per pods (As by default a pod can consume the 100% of the nodes resources), and always try to run the maximum amount of pods. You will need to keep the track of the number of pods.

*(not recommended) If you can't determine the pod consumption, you could either monitor the nodes and add tasks as long as they have enough room, or to try creating the pods with exponential back-off, if you get an error on pod creation because it can't be scheduled.

Hope it helps. Again, this is not something that I am used to see on kubernetes.


text:
Q: CPAN install GD fails I've hit a roadblock installing GD with CPAN on a new server.  The relevant
error line is

Can't load '/usr/local/lib/perl5/auto/GD/GD.so' for module GD:
  /usr/local/lib/perl5/auto/GD/GD.so: undefined symbol:
  gdImageCreateFromGd2Ptr at /usr/lib/perl5/DynaLoader.pm line 200.

While installing submodule GD::Graph
As far as I can tell, prerequisites libraries are all installed and up to date.

A: Why bother with CPAN. You are using yum. Make your life easy. This is a quick test I did on my RHEL 6.4 machine:
# uname -a
Linux ip-10-227-20-6 2.6.32-358.14.1.el6.x86_64 #1 SMP Mon Jun 17 15:54:20 EDT 2013 x86_64 x86_64 x86_64 GNU/Linux

# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.4 (Santiago)

# yum install perl-GDGraph.noarch

# perl -e 'use GD::Graph'
#

the yum install perl-GDGraph.noarch command will install below dependency packages:
(1/5): gd-2.0.35-11.el6.x86_64.rpm
(2/5): libXpm-3.5.10-2.el6.x86_64.rpm
(3/5): perl-GD-2.44-3.el6.x86_64.rpm
(4/5): perl-GDGraph-1.44-7.el6.noarch.rpm
(5/5): perl-GDTextUtil-0.86-15.el6.noarch.rpm

And it will install GD::Graph too :)


text:
Q: Is this impossible get name of class and set for variable inside class? When I create:
player huhu = new player();

I want to get "huhu" to String name inside player;
public class player{
    String name = ??? How to get "huhu" here?
    ....
}

Sorry for my poor english!

A: class Player {
    private String name;

    public Player(String s) {
        name = s;
    }
}

Player huhu = new Player("huhu");

Notice that I'm capitalizing the name of the class.
You should always capitalize your class names.

A: No, you can't access the local variables' names using standard Java.
If you really need access to the name, you'll have to pass it as a constructor parameter, as specified in some of the comments. That would require you, however, to change your code to support this for each and every variable you declare.
I'm seriously scared to ask why you need this functionality.


text:
Q: How to get a table populated with entries taken in from another screen of iOS App? I am making a app, in which i am taking the entries of the user from one screen and processing and printing them on another screen, these two screens are not consecutive screens. the problem is, the later screen dosen't get populated with the array of the details from the first
Here are the code files, that are connected for this input, processing and output
.......................pool.swift.......................

import UIKit
class Pool: NSObject
{
var name:String = ""
var route:String = ""
var date: String = ""
var capacity: Int = 4
var  car: String = ""
//var photo: UIImage
var email:String = ""

init(name:String, route:String, date: String, capacity: Int, car: String, email:String)
{
    self.name = name
    self.route = route
    self.date = date
    self.capacity = capacity
    self.car = car
    self.email = email
}

..............PoolManager.swift...........
import UIKit

class PoolManager: NSObject
{
static var pools = [Pool]()

class func AddPool(name:String, route:String, date: String, capacity: Int, car: String, email:String)
{
    let p = Pool(name: name, route:route, date:date, capacity: capacity, car:car, email:email)

    pools.append(p)
}

class func DeletePool(id: Int)
{
    pools.removeAtIndex(id)
}

class func GetPool() -> [Pool]
{
    return pools
}

}

.......UsePoolViewController.swift..............
import UIKit

class UsePoolViewController: UITableViewController
{

//let array = ["Ulhasnagar to Bandra", "Thane to Ghatkopar", "Kalyan to Thane", "Thane to Colaba"]

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return PoolManager.pools.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell =  tableView.dequeueReusableCellWithIdentifier("customcell")! as! customcell

        let pooler = PoolManager.pools[indexPath.item]

        cell.cellbox?.route = pooler.route
        // this statement doesnt work properly, cellbox gets a nil value.

        return cell

    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    if segue.identifier == "PoolingDetails"
    {
        let cell = sender as! customcell

        let PoolingDetails = segue.destinationViewController as! UsePoolDetailsViewController

        PoolingDetails.heading = cell.cellbox?.route

    }

}

override func viewDidAppear(animated: Bool) {
    tableView.reloadData()
}
}

..........UsePoolDetailsViewController.swift........
  import UIKit

class UsePoolDetailsViewController: UIViewController
{
var heading:String?

override func viewDidAppear(animated: Bool)
{
    self.title = heading
}
}

....customcell.swift......
import UIKit

class customcell: UITableViewCell
{
var cellbox:Pool?
}

A: 1st option: You can create a SharedClass which will have the data which you need throughout the app. In your case you need to update the sharedData regularly to access updated data on other screens of the applications.
2nd option: You can use the NSUserDefaults to keep the data which you can use throughout the application.


text:
Q: Couldn't match expected type in yesod blog example I am trying to get the blog example to run, but there is a problem with types in some handler functions and I don't know how to  fix it.
The example I am trying to run is posted here:
Yesod blog example
I changed a little bit of it, I added types to defaultLayout function and made it an instance of Yesod to get rid of double definitions.
defLayout :: GWidget a Blog () -> GHandler a Blog RepHtml
defLayout inside = do
  mmsg <- getMessage
  pc <- widgetToPageContent $ do
      toWidget [lucius|
body {
width: 760px;
margin: 1em auto;
font-family: sans-serif;
}
textarea {
width: 400px;
height: 200px;
}
#message {
color: #900;
}
|]
      inside
  hamletToRepHtml [hamlet|
$doctype 5

        <title>#{pageTitle pc}
        ^{pageHead pc}

        $maybe msg <- mmsg

#{msg}
        ^{pageBody pc}
|]

instance Yesod Blog where
    approot = ApprootStatic "http://localhost:3000"
    defaultLayout = defLayout

These are the functions that give me problems:
getBlogR :: Handler RepHtml
getBlogR = do
  muser <- maybeAuth
  entries <- runDB $ selectList [] [Desc EntryPosted]
  ((_, entryWidget), enctype) <- generateFormPost entryForm
  defaultLayout $ do
             setTitleI MsgBlogArchiveTitle
             [whamlet|
$if null entries

_{MsgNoEntries}
$else

        $forall Entity entryId entry <- entries

                #{entryTitle entry}
$maybe Entity _ user <- muser
    $if isAdmin user
        <form method=post enctype=#{enctype}>
              ^{entryWidget}

                  <input type=submit value=_{MsgNewEntry}>
$nothing

         _{MsgLoginToPost}
|]

getEntryR :: EntryId -> Handler RepHtml
getEntryR entryId = do
  (entry, comments) <- runDB $ do
          entry <- get404 entryId
          comments <- selectList [] [Asc CommentPosted]
          return (entry, map entityVal comments)
  muser <- maybeAuth
  ((_, commentWidget), enctype) <- generateFormPost (commentForm entryId)
  defaultLayout $ do
    setTitleI $ MsgEntryTitle $ entryTitle entry
    [whamlet|

#{entryTitle entry}

#{entryContent entry}

_{MsgCommentsHeading}
        $if null comments

_{MsgNoComments}
        $else
             $forall Comment _entry posted _user name text <- comments

                      #{name}
                      #{show posted}

#{text}

_{MsgAddCommentHeading}
            $maybe _ <- muser
                <form method=post enctype=#{enctype}>
                    ^{commentWidget}

                        <input type=submit value=_{MsgAddCommentButton}>
            $nothing

                    _{MsgLoginToComment}
|]

Here is the output I get when I try to run it:
blog.hs:147:4:
    Couldn't match expected type `GWidget Blog Blog ()'
                with actual type `(t0, t1)'
    In the pattern: (_, entryWidget)
    In the pattern: ((_, entryWidget), enctype)
    In a stmt of a 'do' block:
      ((_, entryWidget), enctype) <- generateFormPost entryForm

blog.hs:202:4:
    Couldn't match expected type `GWidget Blog Blog ()'
                with actual type `(t0, t1)'
    In the pattern: (_, commentWidget)
    In the pattern: ((_, commentWidget), enctype)
    In a stmt of a 'do' block:
      ((_, commentWidget), enctype) <- generateFormPost
                                         (commentForm entryId)

A: The type of generateFormPost has changed since the blog article, it used to be
generateFormPost :: RenderMessage master FormMessage =>
                    (Html -> MForm sub master (FormResult a, xml)) ->
                    GHandler sub master ((FormResult a, xml), Enctype)

in yesod-form-0.4.* but now it is
generateFormPost :: RenderMessage master FormMessage =>
                    (Markup -> MForm sub master (FormResult a, xml)) ->
                    GHandler sub master (xml, Enctype)

The type error should [I think, never used yesod] go away if you use yesod-form < 1, or if you replace
((_, entryWidget), enctype) <- generateFormPost entryForm

with
(entryWidget, enctype) <- generateFormPost entryForm

to reflect the change in the type of generateFormPost.


text:
Q: How do I force a shutdown even when there are other open sessions? Well, hello, this is my first time using ubuntu and I have seen that when I try to turn off the computer when other user sessiong is running it doesn't do nothing. Then I have to enter that user session and close it or turn off in it to do it work.
sorry if I use a bad english, it's because it isn't my native languaje.
thanks.

A: Assuming your account is an administrator on the computer (i.e. you have "root" or sudo privileges) this is very simple. Just open a terminal with Ctrl+Alt+T, and type:
sudo reboot

Enter your password when prompted, and the computer will shut down, regardless of what other sessions are open. Unsaved data in any applications open in the other sessions (or in yours) will be lost.
If you wish to only shutdown and not restart, the alternative is:
sudo shutdown -P now

Note: if you do not have sudo privileges, then you cannot do this. You can only shutdown when no other sessions are open; if they are, "shut down" will simply log you out.


text:
Q: struggeling with matrix and their positions I am trying to solve this program (python) where having a matrix I should show every row, every position and his value
I am trying this sentence but it is not working:
m = [
    [3, 8, 2],
    [2, 3, 1],
    [4, 2, 9]
]

for i in range(len(m)):
    print('the row number',i+1,'and the position',m[0][i],'has a value of',m[i][0])

A: You should have a nested loop to print on each raw and each col:
m = [
    [3, 8, 2],
    [2, 3, 1],
    [4, 2, 9]
]

for i in range(len(m)):
    for j in range(len(m[i])):
        print('the row number', i + 1, 'and the position', j + 1, 'has a value of', m[i][j])

which gives
the row number 1 and the position 1 has a value of 3
the row number 1 and the position 2 has a value of 8
the row number 1 and the position 3 has a value of 2
the row number 2 and the position 1 has a value of 2
the row number 2 and the position 2 has a value of 3
the row number 2 and the position 3 has a value of 1
the row number 3 and the position 1 has a value of 4
the row number 3 and the position 2 has a value of 2
the row number 3 and the position 3 has a value of 9


text:
Q: Convert a Long in a String C++?
Possible Duplicate:
C++ long to string
Easiest way to convert int to string in C++

I am use to Java where I could just use .toString() on almost anything but I am trying a few problems in C++
I can not figure out how to make a long value into a string.

A: You can either use a string stream:
#include <sstream>
#include <string>

long x;
// ...
std::ostringstream ss;
ss << x;

std::string result = ss.str();

Or you can use Boost's lexical_cast:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(x);

I think it's a common opinion that this aspect of the language isn't quite as elegant as it could be.
In the new C++11, things are a bit easier, and you can use the std::to_string() function:
#include <string>
std::string s = std::to_string(x);

A: #include <string>
#include <sstream>

std::ostringstream ss;
long i = 10;
ss << i;
std::string str = ss.str();

A: You can use a stringstream.
std::ostringstream ss;
ss << aLongNumber;
ss.str()

You use operator << like iostream cout and cin. And you use str() method to get the string.


text:
Q: PDO Connection Class using singleton pattern <?php

//db connection class using singleton pattern
class dbConn {
    //variable to hold connection object.
    protected static $db;

    //private construct – class cannot be instatiated externally.
    private function __construct()
    {

        try { // assign PDO object to db variable
            self::$db = new PDO('mysql:host=localhost;dbname=cricket', 'root', '');
            setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) { //Output error – would normally log this to error file rather than output to user.
            echo "Connection Error: " . $e->getMessage();
        }
    }

    // get connection function. Static method – accessible without instantiation
    public static function getConnection()
    {
        //Guarantees single instance, if no connection object exists then create one.
        if (!self::$db) { //new connection object.
            new dbConn();
        }
    //return connection.
    return self::$db;
    }
}
//end class

?>

please check this error if i call this parameters in index like
    $sql = "select * from user";
    $q = dbConn::getConnection()->query($sql);

   $result =  $q->fetch();
    print_r($result);
}

tutorials link : http://weebtutorials.com/2012/03/pdo-connection-class-using-singleton-pattern/

A: Your code has several issues (aside from usefulness of singleton pattern in PHP):
The idea of a singleton is that the instance is referenced by a private static variable, which isn't the case in your code, you reference an instance of a PDO object. A true singleton version of your code would have to look like this:
class TrueSingleton
{
    private static $_instance;
    private $_pdo;

    private function __construct()
    {//private constructor:
        $this->_pdo = new PDO();//<-- connect here
        //You set attributes like so:
        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //not setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<-- PHP can't know which setAttribute method to call on what object
    }
    public static function getConnection()
    {
        if (self::$_instance === null)//don't check connection, check instance
        {
            self::$_instance = new TrueSingleton();
        }
        return self::$_instance;
    }
    //to TRULY ensure there is only 1 instance, you'll have to disable object cloning
    public function __clone()
    {
        return false;
    }
    public function __wakeup()
    {
        return false;
    }
}

The rest is pretty basic, apart from, whenever you need to query the DB, you'll have to use $this->_pdo->query() inside the member functions


text:
Q: Why is visual studio 2013 loading suddenly so long, when ending debugging? Visual studio suddenly needs 10x more time to end my debugging session then last week.
I had the issue some month ago and I cleared it by re-installing VS 2013. But in my mind it´s not a proper solution to re-install it every half year.
Any ideas?


text:
Q: How can I keep track of a "like" system on android? I am currently making an android app for a friend who is a photographer where he will display his images in a RecyclerView. We would like to have sort of like a "like" feature where they can like his pictures. My question is, how would I keep track of the "likes"? What I mean is, how can I make it so that if someone already liked it, they cannot exit the app, come back and like it again? I thought about adding a +1 every time there was a like to the image properties in a database, but how can I keep them from exiting the app, coming back, and liking it again? TIA!

A: your problem is just a matter of identity. To achieve your goal, you should have a way to identify every piece of the pictures and each of the person who will give up-votes to these pictures.
If  you can identify different pictures and different users, you can achieve your goal by either of the following ways:

*

* For each of the pictures store all the users that have liked it. And every time a user want to like a picture, you should check whether he is in this collection or not. Only add the identity of the user to this collection if he is not in this set which means he did not like this picture before

*Or you can store all the pictures that are liked by the user.

Which way is better depends on your other use cases.
To identify your pictures you can just assign a distinct name for each of the picture.
So you can see the key problem it how to identify your users.
Since you do not provide a detailed use case of the like action, I will describe some general ideas.

*

*If you have a server

*
*If the user must login, you can identify your users by their login id

*If your user do not need to login, you can use some other information to identify your user for example their device id, MAC address or other device-specific indentity.

*If you do not have a server, then how can you identify all the users that use the same device? The only way I can come up with is that, you must implement a local user system and ask the user to log in before they want to like a photo.

A: If you have so signing in users my guess is that you can't. You could save on a hidden file on the device the ids of the photos the device "liked" but this can be easily deleted if the user deletes the apps cache files or uninstall/reinstall.
Not an android expert here, just mho

A: With login:
In your Database there are "User", "Image" and "User_like_image"
You just have to check if this user didnt already upvoted the image
without login:
You locally store the ID of every images he upvoted

A: A rough idea: with each item that can be liked store a list of ids that liked it on the server. Your like count is equals to the list length.
On each device generate a random device id token (UUID.randomUUID() is always a good candidate), persist it locally on the device (e.g. in SharedPreferences - wiping the app data will kill it but that can't be solved reliably) and send it to the server with each request.
The server can now

*

*tell you whether you already liked an image which is nice to see on the device and

*reject multiple likes from the same device

A simpler approach: store locally in e.g. SharedPreferences that you liked the item. Then behave nicely and don't send another like request to your server backend when you see that you already did. Can be abused because it relies no the client software to be nice but I doubt a small photographer app needs to care too much about that.
A more elaborate approach: require user accounts. That works accross devices and persists through app uninstalls. People that go far enough to create multiple accounts to vote multiple times can't be stopped anyways. The big downside is that people will most likely not want to have another account just to like some photos. Would not recommend if avoidable.

A: What I did to avoid having people like the same item twice was:
Have 2 states with the same button. If you clicked on "like" the button state changes to "Remove Like" Save the state of the button in shared prefs and check the state before a click is given.
Example:
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
    String ButtonText = button.getText().toString();
    if(ButtonText.equals("Like"){
        //code for Like

        button.setText("Remove Like");
    }
    else{
        //code for remove Like
        button.setText("Like");
    }
}

});


text:
Q: JQuery animation behave strange on fadeOut I have a div which I axpect to be closed in animated way. How whenever I try, it try to dissaper in strange way. I dont know even by which words I should google my problem.
This is my html code.
       #{ifErrors}

&{'opps'}

                    #{errors}

${error}

                   #{/errors}

        #{/ifErrors}

This the jquery event :
$('span.warning_close').click(function(){
        $(this).closest('div').animate({"width" : 0, "height" : 0, "opacity" : 0, "border" : "none", "padding" : 0}, 600);
});

A: FadeOut
demo - fadeOut
$(this).closest('div').fadeOut()

Opacity
demo - Opacity
$(this).closest('div').animate({"opacity" : 0}, 600);\


text:
Q: Javascript codes dont working in my project Hi there my javascript codes dont work.
The codes like these working perfect:
function Choice() {
    var box = document.getElementById('searchh');

    if (!count) {
        var count = 0;
    }

    box.onclick = function () {
        count++;
        if (count == 1) {
           box.style.backgroundColor = "red";
       }
        else if (count == 2) {
            box.style.backgroundColor = "green";
        }
       else if (count == 3) {
            box.style.backgroundColor = "yellow";
       }
        else {
           count = 0;
           box.style.backgroundColor = "transparent";
       }
   }

}

but like that codes : doesnt work:
$(document).ready(function () {
              $(".divsec").on("click", function () {
                  $(this).css("background", "red");
              });
          });

heres my html codes:
<%@ Page Title="" Language="C#" MasterPageFile="~/PersonelMaster.master" AutoEventWireup="true" CodeFile="temsilci.aspx.cs" Inherits="temsilci" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Hoşgeldin Temsilci</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <link href="css/fontawesome.min.css" rel="stylesheet" type="text/css" />
      <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
      <link href="css/Main.css" rel="stylesheet" type="text/css" />

<asp:Repeater ID="rp_Temsilci_isler" runat="server">
        <HeaderTemplate>

Marka

İşin Adı

Durum

Veriliş Tarihi

Teslim Tarihi

Marka Temsilcisi

Ajans Temsilcisi

Sorumlu Kişiler

        </HeaderTemplate>
        <ItemTemplate>

<%#Eval("isin_tanimi") %>

<%#Eval("isin_adi") %>

<%#Eval("is_durum") %>

<%#Eval("verildigi_tarih") %>

<%#Eval("teslim_tarihi") %>

<%#Eval("sorumlu_marka") %>

<%#Eval("sorumlu_ajans") %>

<%#Eval("revize") %>

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
        </asp:Repeater>

and this is my css:
.divsec
{
    background:white;
    height:15px;
    width:15px;
    border:1px solid #ffcb31;
}

A: Add a  before declaring code:
$(document).ready(function () {
              $(".divsec").on("click", function () {
                  $(this).css("background", "red");
              });
          });


text:
Q: A dielectric object moves past another in an electric field. How much of its movement energy is transmitted to the second object by electric force? Say the objects are cubes, or square plates, and we know their permittivity, and we know the strength of the electric field they are in, and we know the moving object's mass and speed. Can we calculate how much force the moving object will apply to the other object through the medium of the electric force?
I know you can calculate the force between charges using Coulomb's law. But I don't understand what that means if neither is moving. Is the force pushing against them the whole time and holding them in place? If one charge started to move, would all of its movement energy be transmitted to the other by the electric force? Or just some of it?

A: A dielectric object in an electric field polarizes; exactly what its charge
distribution is, depends on the field and the shape of the object, and forms
a second-order differential equation to be solved with boundary-value conditions
at the surface of the object, in three dimensions.
That's a nontrivial problem, and TWO objects, is another.   The polarization
of each object adds to the field, of course.   After doing the solution,
forces between the two objects can be calculated (because you know the charge
distribution in each object).   The solutions, in general, will NOT be
simple formulae, but will have to be approximated by finite-element methods.
Such additions as 'if one charge started to move' indicate that (in addition
to electrical forces) some other forces are present.   The only general
truth here, is that dielectric objects in an E-field will generally polarize
alike, and tend to attract each other.   That is a core principle
in the theory of gasses, and leads to van der Waals attractive terms.


text:
Q: TypeError at /cart/ 'Product' object is not subscriptable I'm creating cart model in RESTful API project. For each product in request by using for statement I want to save each product, cauz in one request may appear more than one product in cart. Below is my
serializers.py:

    from rest_framework import serializers
from main.serializers import ProductDetailsSerializer
from main.models import Cart, Product, CartProduct

# создаем сериализатор orderproduct
class CartProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = CartProduct
        fields = ('product', 'count')

class CartProductRepresentationSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='product.id')
    title = serializers.CharField(source='product.title')

    class Meta:
        model = CartProduct
        fields = ('id', 'title', 'price', 'count', 'product')

class AddProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id')

class CartSerializer(serializers.ModelSerializer):
    items = CartProductSerializer(many=True, write_only=True) # здесь мы добавляем этот продукт заказа
    class Meta:
        model = Cart
        fields = ('count', 'items') # передаем все эти поля сюда

    def get_total_cost(self, obj):
        return obj.get_total_cost()
        # здесь мы добавляем total cost (def get_total_cost(self. obj))

    def create(self, validated_data):
        request = self.context.get('request')
        items = validated_data.pop('items')
        cart = Cart.objects.create(**validated_data)
        if request.user.is_authenticated:
            cart.user = request.user
            cart.save()

        for product in items:
            product = product['product']
            # print(product)
            product_id = request.GET.get('product')
            CartProduct.objects.create(cart=cart, product_id=product_id, price=product.price, count=product['count'])
            product.save()

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['user'] = instance.user
        representation['product'] = CartProductRepresentationSerializer(instance.products.all(), many=True, context=self.context).data
        return representation

Here is the models. I create Cart and CartProduct for m2m field between Cart and Product
    models.py

from django.db import models

from account.models import User

class Category(models.Model):
    name = models.CharField(max_length=50 ,unique=True)
    slug = models.SlugField(max_length=50 ,primary_key=True)
    parent = models.ForeignKey('self', related_name='child', blank=True, null=True, on_delete=models.CASCADE)

    def __str__(self):
        if self.parent:
            return f'{self.parent} -> {self.name}'
        return self.name

class Product(models.Model):
    category = models.ManyToManyField(Category)
    title = models.CharField(max_length=250)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    author_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.title

class Comment(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    text = models.CharField(max_length=100)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return f"{self.author}: {self.text}"

class ProductImage(models.Model):
    product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products', null=True, blank=True)

class Cart(models.Model):
    date_created = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=255, blank=True, null=True, default=False)
    user = models.ForeignKey(User, related_name="carts", on_delete=models.CASCADE, blank=True, null=True)
    count = models.PositiveIntegerField(default=1)

class CartProduct(models.Model):
    product = models.ForeignKey(Product, related_name='products', on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, related_name='cart', on_delete=models.CASCADE)
    count = models.PositiveIntegerField(default=1)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True)

Here is the views.py by using ModelViewSet I want to list all products in Cart
views.py

from rest_framework import viewsets
from cart.serializers import CartSerializer
from main.models import Cart

class CartViewSet(viewsets.ModelViewSet):
    model = Cart
    serializer_class = CartSerializer

    def get_queryset(self,):
        return Cart.objects.filter(user=self.request.user)


text:
Q: Accessing WFS data through proxy in QGIS I use QGIS 2.18.4 with an Osgeo4W install, W7 x64.
The code below works fine without a proxy :
import urllib
params = {
    'service': 'WFS',
    'version': '2.0.0',
    'request': 'GetFeature',
    'typename': 'regbio',
    'srsname': 'EPSG:2154'
}
uri = 'http://ws.carmencarto.fr/WFS/119/fxx_ref?' + urllib.unquote(urllib.urlencode(params))
vlayer = QgsVectorLayer(uri, 'ma couche wfs', 'WFS')
if not vlayer.isValid():
    print u"The layer %s is not valid" %vlayer.name()
idx = vlayer.dataProvider().fieldNameIndex('NOM_DOMAIN')
uv = vlayer.dataProvider().uniqueValues(idx)
uv.sort()
for i, item in enumerate(uv):
    print i, item

The result is :
0 alpin
1 atlantique
2 continental
3 mediterraneen

The problem I'm having is that I cannot get the same result when a proxy is used.
With a proxy, I use the code of this : https://stackoverflow.com/a/37757921
However, the retrieved data are the html code.
Now, I wish to have the same result as the first code, but through a proxy.

A: From this post : https://gis.stackexchange.com/a/214915/93097, just add the following code for, according to the QgsNetworkAccessManager class instructions, setup the NetworkAccessManager according to the user's settings :
network_manager=QgsNetworkAccessManager.instance()
network_manager.setupDefaultProxyAndCache()

Working code :
import urllib

network_manager = QgsNetworkAccessManager.instance()
network_manager.setupDefaultProxyAndCache()
params = {
    "service": "WFS",
    "version": "2.0.0",
    "request": "GetFeature",
    "typename": "regbio",
    "srsname": "EPSG:2154"
}
params_unquote = urllib.unquote(urllib.urlencode(params))
uri = f"http://ws.carmencarto.fr/WFS/119/fxx_ref?{params_unquote}"
vlayer = QgsVectorLayer(uri, "my wfs layer", "WFS")
if not vlayer.isValid():
    print(f"The layer {vlayer.name()} is not valid")

idx = vlayer.dataProvider().fieldNameIndex("NOM_DOMAIN")
uv = vlayer.dataProvider().uniqueValues(idx)
uv.sort()
for i, item in enumerate(uv):
    print(i, item)

A: I ran into a similar problem to this and couldn't get the QgsNetworkAccessManager to work.
Used this instead:
from PyQt5 import QtNetwork

##Proxy Setting via QtNetwork

proxy = QtNetwork.QNetworkProxy()

proxy.setType(QtNetwork.QNetworkProxy.HttpProxy)

proxy.setHostName("proxyexample.com")#without http/https

proxy.setPort(0000)#as integer

QtNetwork.QNetworkProxy.setApplicationProxy(proxy)

Maybe it's also a hint for someone else.