text:
Q: Can you use C# Kubernetes inClusterConfig for a remote Cluster? I am having trouble authenticating my C# service for a remote cluster. Trying to use my svc gets Forbidden, so I am hoping to work around with this. I know that inClusterConfig does work properly when this service is in the Cluster, but I am trying to run local and host jobs in my remote cluster.
This is what I am trying:
Environment.SetEnvironmentVariable("KUBERNETES_SERVICE_HOST", "Value1");
Environment.SetEnvironmentVariable("KUBERNETES_SERVICE_PORT", "Value1");

KubernetesClientConfiguration config = new KubernetesClientConfiguration();
config.Host = "https://xx";

config = KubernetesClientConfiguration.InClusterConfig();

Not sure if this is possible. Currently getting error

Unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined

Thanks

A: In addition to the environment variables, KubernetesClientConfiguration.IsInCluster also requires a token and certificate:
if (!FileUtils.FileSystem().File.Exists(tokenPath))
{
 return false;
}

// ...
return FileUtils.FileSystem().File.Exists(certPath);

The details of authentication are explained in this answer:

When accessing the API from a Pod, the client certificate is located
on /var/run/secrets/kubernetes.io/serviceaccount/ca.crt and in
addition, you need to authenticate using the token located on
/var/run/secrets/kubernetes.io/serviceaccount/token

Once a connection is being attempted, per this answer:

InClusterConfig uses the default service account of the namespace
where you are deploying the pod. By default that service account will
not have any RBAC which leads to Forbidden error.


text:
Q: How can I remove JSON brackets and double quotes? I'm doing a log file for a clicks-counter in PHP. The data (date, time, etc.) everytime the user clicks the button are directed in a data.json file. I want to put those data in a logfile.txt but when I use file_get_contents , the brackets and the quotations are also transferred making the logfile harder to understand. Is there a way to not include the brackets and quotations?
$txtlog = '../Logfile-'.date('mdY').'.txt';
$mytxt = fopen($txtlog, "a") or die("<br/>Unable to open file!");
fwrite($mytxt, file_get_contents("DATA.json"));
fclose($mytxt);

A: Have a look at json_decode().
Using it on what you've got from the file, it will return an array with index "date" and "time". Just iterate on it and you will be able to manage your logs

A: use this json_decode("DATA.json")

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery: Select data attributes that aren't empty? I'm trying to select all elements that have a data-go-to attribute that is not empty.
I've tried $('[data-go-to!=""]') but oddly enough it seems to be selecting every single element on the page if I do that.

A: Has 'data-attributename' and its value is not empty:
$('[data-attributename]:not([data-attributename=""])')

Has 'data-attributename' empty or not:
$('[data-attributename]')

JS Fiddle example

A: try
$(':not([data-go-to=""])')

UPDATE:
For the sake of not leading anyone astray, this answer will work in older versions of jQuery but is not future-proof.  Since @gmo and @siva's answers both seem to be working with later versions I defer to (and encourage you to upvote) their answers....and of course hope you have a fantastic day.

A: I'm not sure about a simple selector, but you could use filter():
$('[data-go-to]').filter(
    function(){
        return ($(this).attr('data-go-to').length > 0);
    });

JS Fiddle demo.
References:

*

*filter().

A: According to the documentation
this should do it
:not([attr="value"])
DEMO
Hope this helps

A: $('[data-go-to]:not([data-go-to=""])')

JSBIN

A: Just as further reference, and an up-to-date (may'14) (aug'15) (sep'16) (apr'17) (mar'18) (mar'19) (may'20) (jan'22)...
Answer that works with:

###Empty strings:
If the attr must exist & could have any value (or none at all)

    jQuery("[href]");

###Missing attributes:
If attr could exist & if exist, must have some value

    jQuery("[href!='']");

###Or both:
If attr must exist & has to have some value...

    jQuery("[href!=''][href]");

PS: more combinations are possible...

###Check this test in jsFiddle for examples:

*

*jQuery v1.9.1         -> jsFiddle online test

*jQuery v1.11.0        -> jsFiddle online test

*jQuery v2.1.0         -> jsFiddle online test

*jQuery v2.1.3         -> jsFiddle online test

*jQuery v2.2.4         -> jsFiddle online test

*jQuery v3.2.1         -> jsFiddle online test

*jQuery v3.3.1         -> jsFiddle online test

*jQuery v3.4.1         -> jsFiddle online test Last jQuery version available in jsFiddle at jan 10'22

*jQuery Edge           -> jsFiddle online test jQuery edge version (use with caution)

*jQuery v3.0.0-alpha1  -> jsFiddle online test

*jQuery v3.1.1 Slim    -> jsFiddle online test

*jQuery v3.2.1 Slim    -> jsFiddle online test

*jQuery v3.3.1 Slim    -> jsFiddle online test

*jQuery v3.4.1 Slim    -> jsFiddle online test Last jQuery Slim version available in jsFiddle at jan 10'22

###Or here in SO with this Code Snippet.
* Snippet is running jQuery v2.1.1

jQuery('div.test_1 > a[href]').addClass('match');
jQuery('div.test_2 > a[href!=""]').addClass('match');
jQuery('div.test_3 > a[href!=""][href]').addClass('match');
div,a {
    display: block;
    color: #333;
    margin: 5px;
    padding: 5px;
    border: 1px solid #333;
}
h4 {
    margin: 0;
}
a {
    width: 200px;
    background: #ccc;
    border-radius: 2px;
    text-decoration: none;
}
a.match {
    background-color: #16BB2A;
    position: relative;
}
a.match:after {
    content: 'Match!';
    position: absolute;
    left: 105%;
}

Test 1: jQuery('a[href]')

    href: test
    href: #
    href: empty
    href: not present

Test 2: jQuery('a[href!=""]')

    href: test
    href: #
    href: empty
    href: not present

Test 3: jQuery('a[href!=""][href]')

    href: test
    href: #
    href: empty
    href: not present

A: $('[data-go-to]').filter(function() {
    return $(this).data('go-to')!="";
});

Using :not, .not(), :empty etc will only check if the element itself is empty, not the data attribute. For that you will have to filter based on the data attributes value.
FIDDLE

A: $('[data-go-to!=""]:[data-go-to]').each(function() {
    // Do Your Stuff
});

A: This works for me
$('[attributename]').filter('[attributename!=""]')

A: Try this :
$('[data-go-to:not(:empty)]')

A: This works for me:
$('.data .title td[data-field!=""]')


text:
Q: Check two QSharedPointer have equal data I have two QSharedPointer, can I check are they pointed to the same object using operator== like this
QSharedPointer1 == QSharedPointer2

or I must write
QSharedPointer1.data() == QSharedPointer2.data()

Object that are stored in pointers have overloaded operator==.

A: You should use operator==:

bool operator== ( const QSharedPointer & ptr1, const QSharedPointer & ptr2 )
Returns true if the pointer referenced by
  ptr1 is the same pointer as that referenced by ptr2. If ptr2's
  template parameter is different from ptr1's, QSharedPointer will
  attempt to perform an automatic static_cast to ensure that the
  pointers being compared are equal. If ptr2's template parameter is not
  a base or a derived type from ptr1's, you will get a compiler error.

So, there is no need to fetch the pointers via data() method, + it will try to do static_cast to match the template arguments.
Also, note that it doesn't matter if objects stored in the pointer have overloaded operator== - you are just comparing pointers here, and operator== is defined for pointer types. If you want to compare the objects which pointers are referring to, you need to dereference pointers and to compare references to the objects (which will call T::operator== method):
if(*ptr1 == *ptr2)
   // ...

A: From the QSharedPointer class reference:

bool operator==(const QSharedPointer<T>& ptr1, const QSharedPointer<X>& ptr2)
Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2.

A: first version should be OK related to here

bool operator== ( const QSharedPointer<T> & ptr1, const QSharedPointer<X> & ptr2 )
Returns true if the pointer referenced by
ptr1 is the same pointer as that referenced by ptr2.


text:
Q: leaflet button inside-marker doesn't work i have a problem in showing a modal with a button that i have placed in a marker message, here is my code, all function well but not this button,
my controller.js
 **$ionicModal.fromTemplateUrl('templates/addLocation.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function(modal) {
          $scope.modal = modal;
        });**

// Get the ouvrage geojson data from a JSON
        $http.get("js/ouvrage/ouvrage.json").success(function(data, status) {
            angular.extend($scope, {
                geojson: {
                    data: data,
                    style: {
                        weight: 2,
                        opacity: 1,
                        color: 'green',
                        dashArray: '3',
                        fillOpacity: 0
                    },

                    onEachFeature: function (feature, layer) {
                    popupOptions = {maxWidth: 350};
                    layer.bindPopup(

                   '
Informations sur l"ouvrage :
'+
                      "Groupe: " + feature.properties.groupe +
                        "
Famille   : " + feature.properties.id_famille +
                        "
Ouvrage   : " + feature.properties.nom_ouvrag +
                        "
Projet    : " + feature.properties.projet +
                        "
Nombre d'élements: " + feature.properties.nbre_element +
                        "
"+
                        '**<button class="button button-primary" ng-click="modal.show();">Confirm</button>**'

                        ,popupOptions);
                    }
            }
        });
    });


text:
Q: If a function is bounded and the variable is bounded, is the function continuous? Suppose you have a function $f:C\to \mathbb R$ where $C$ is closed and bounded interval and $f$ is bounded.  Does that mean $f$ is continuous?  I know the other way around (if $f$ is continuous, $f$ is bounded) is true, but not this way.
Thanks!

A: Nope!  Consider $f(x): [0,1] \rightarrow [0,1]$ defined by $f(x) = 0$ for $0 \leq x < 1/2$ and $f(x) = 1$ for $1/2 \leq x \leq 1$.
Then the image of $f$ is $\{0,1\}$ which is a bounded set, and the domain is bounded, but $f$ has a discontinuity at $x = 1/2$.


text:
Q: how to reconnect to IBM MQ without timer I wrote some codes to get message from remote mq but after message is not available into Queue I disconnect from MQ . Then I want to reconnect to MQ . I added timer for this . But it increases open input count . Is there any way to reconnect without timer? any clue will do fine .
CODE
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IBM.WMQ;
using System.Diagnostics;
using System.Collections;
using System.Configuration;
using System.Timers;

namespace MQMessageSender
    {
    public class MQTest
    {
        private static MQQueueManager queueManager;
        private static MQMessage queueMessage;
        private static MQGetMessageOptions queueGetMessageOptions;
        private static MQQueue queue;
        static string strReturn = "";
        static string QueueName;
        static string QueueManagerName;
        static string ChannelInfo;
        static string channelName;
        static string PortNumber;
        static string transportType;
        static string connectionName;
        static bool running = true;

        public static void Main(string[] args)
        {
            getMessage();
        }

        public static void connectMQ()
        {
            QueueManagerName = ConfigurationManager.AppSettings["QueueManager"];
            QueueName = ConfigurationManager.AppSettings["Queuename"];
            ChannelInfo = ConfigurationManager.AppSettings["ChannelInformation"];
            PortNumber = ConfigurationManager.AppSettings["Port"];
            char[] separator = { '/' };
            string[] ChannelParams;
            ChannelParams = ChannelInfo.Split(separator);
            channelName = ConfigurationManager.AppSettings["Channel"];
            transportType = ConfigurationManager.AppSettings["TransportType"];
            connectionName = ConfigurationManager.AppSettings["ConnectionName"];
            queueManager = new MQQueueManager(QueueManagerName,
            channelName, connectionName);
            strReturn = "Connected Successfully";

            // return strReturn;
        }

        public static  void getMessage()
            {
            connectMQ();
            queue = queueManager.AccessQueue(QueueName,
            MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);

            while (running)
            {
                try
                {
                    queueMessage = new MQMessage();
                    queueMessage.Format = MQC.MQFMT_STRING;
                    queueGetMessageOptions = new MQGetMessageOptions();
                    queue.Get(queueMessage, queueGetMessageOptions);
                    strReturn = queueMessage.ReadString     (queueMessage.MessageLength);
                    //messageavailable = MQC.MQRC_NO_MSG_AVAILABLE;
                    // strReturn1 = strReturn + "@@@@@@@" + messageavailable;
                }
                catch (MQException exp)
                {
                    strReturn = "Exception: " + exp.Message;
                }

                if (strReturn != "Exception: MQRC_NO_MSG_AVAILABLE")
                {
                    string path = ConfigurationManager.AppSettings["xmlFilePath"];
                    string fileName = path + "MQMessage" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xml";
                    System.IO.File.WriteAllText(fileName, strReturn);
                }
                else if (strReturn == "Exception: MQRC_NO_MSG_AVAILABLE")
                {
                    queueManager.Disconnect();
                    string path = ConfigurationManager.AppSettings["logFilePath"];
                    string fileName = path + "MQLog" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
                    System.IO.File.WriteAllText(fileName, strReturn);
                    System.Timers.Timer aTimer = new System.Timers.Timer();
                    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                    aTimer.Interval = 30000;
                    aTimer.Enabled = true;
                }
                else
                {
                    queueManager.Disconnect();
                    string path = ConfigurationManager.AppSettings["logFilePath"];
                    string fileName = path + "MQLog" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
                    System.IO.File.WriteAllText(fileName, strReturn);
                    System.Timers.Timer aTimer = new System.Timers.Timer();
                    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                    aTimer.Interval = 30000;
                    aTimer.Enabled = true;
                }
            }
        }

        public static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            getMessage();
        }
    }
}

So here I used timer to reconnect but it increases open input count . Please help

A:
So here I used timer to reconnect but it increases open input count

That's because you are not closing the queue before opening it again.
queueManager = new MQQueueManager(QueueManagerName, channelName, connectionName);

Using MQQueueManager class this way means that there is no security i.e. SSL/TLS or security exit.  Bad idea.  You should set the connection information in a Hashtable and pass the Hashtable to the MQQueueManager class.
Also, you should be using "MQGet with wait" rather than polling using a timer.
Here is a sample C# program that uses a Hashtable for connection information and performs an "MQGet with wait":
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;

///  Program Name
/// MQTest62
///
/// Description
/// This C# class will connect to a remote queue manager
/// and get messages from a queue using a managed .NET environment.
///
/// Sample Command Line Parameters
/// -h 127.0.0.1 -p 1415 -c TEST.CHL -m MQWT1 -q TEST.Q1 -u tester -x mypwd
///
/// <author>  Roger Lacroix
/// </author>
namespace MQTest62
{
   public class MQTest62
   {
      private Hashtable inParms = null;
      private Hashtable qMgrProp = null;
      private System.String qManager;
      private System.String inputQName;

      /*
      * The constructor
      */
      public MQTest62()
          : base()
      {
      }

      ///  Make sure the required parameters are present.
      /// <returns> true/false
      /// </returns>
      private bool allParamsPresent()
      {
         bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
                  inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
                  inParms.ContainsKey("-q");
         if (b)
         {
            try
            {
               System.Int32.Parse((System.String)inParms["-p"]);
            }
            catch (System.FormatException e)
            {
               b = false;
            }
         }

         return b;
      }

      ///  Extract the command-line parameters and initialize the MQ variables.
      /// <param name="args">
      /// </param>
      /// <throws>  IllegalArgumentException </throws>
      private void init(System.String[] args)
      {
         inParms = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(14));
         if (args.Length > 0 && (args.Length % 2) == 0)
         {
            for (int i = 0; i < args.Length; i += 2)
            {
               inParms[args[i]] = args[i + 1];
            }
         }
         else
         {
            throw new System.ArgumentException();
         }

         if (allParamsPresent())
         {
            qManager = ((System.String)inParms["-m"]);
            inputQName = ((System.String)inParms["-q"]);

            qMgrProp = new Hashtable();
            qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);

            qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
            qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));

            try
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
            }
            catch (System.FormatException e)
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
            }

            if (inParms.ContainsKey("-u"))
               qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));

            if (inParms.ContainsKey("-x"))
               qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));

            System.Console.Out.WriteLine("MQTest62:");
            Console.WriteLine("  QMgrName ='{0}'", qManager);
            Console.WriteLine("  Output QName ='{0}'", inputQName);

            System.Console.Out.WriteLine("QMgr Property values:");
            foreach (DictionaryEntry de in qMgrProp)
            {
               Console.WriteLine("  {0} = '{1}'", de.Key, de.Value);
            }
         }
         else
         {
            throw new System.ArgumentException();
         }
      }

      ///  Connect, open queue, read (browse) a message, close queue and disconnect.
      ///
      private void testReceive()
      {
         MQQueueManager qMgr = null;
         MQQueue inQ = null;
         int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING;

         try
         {
            qMgr = new MQQueueManager(qManager, qMgrProp);
            System.Console.Out.WriteLine("MQTest62 successfully connected to " + qManager);

            inQ = qMgr.AccessQueue(inputQName, openOptions);
            System.Console.Out.WriteLine("MQTest62 successfully opened " + inputQName);

            testLoop(inQ);

         }
         catch (MQException mqex)
         {
            System.Console.Out.WriteLine("MQTest62 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
         }
         catch (System.IO.IOException ioex)
         {
            System.Console.Out.WriteLine("MQTest62 ioex=" + ioex);
         }
         finally
         {
            try
            {
               if (inQ != null)
                  inQ.Close();
               System.Console.Out.WriteLine("MQTest62 closed: " + inputQName);
            }
            catch (MQException mqex)
            {
               System.Console.Out.WriteLine("MQTest62 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
            }

            try
            {
               if (qMgr != null)
                  qMgr.Disconnect();
               System.Console.Out.WriteLine("MQTest62 disconnected from " + qManager);
            }
            catch (MQException mqex)
            {
               System.Console.Out.WriteLine("MQTest62 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
            }
         }
      }

      private void testLoop(MQQueue inQ)
      {
         bool flag = true;
         MQGetMessageOptions gmo = new MQGetMessageOptions();
         gmo.Options |= MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING;
         gmo.WaitInterval = 2500;  // 2.5 seconds wait time or use MQC.MQEI_UNLIMITED to wait forever
         MQMessage msg = null;

         while (flag)
         {
            try
            {
               msg = new MQMessage();
               inQ.Get(msg, gmo);
               System.Console.Out.WriteLine("Message Data: " + msg.ReadString(msg.MessageLength));
            }
            catch (MQException mqex)
            {
               System.Console.Out.WriteLine("MQTest62 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
               if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE)
               {
                  // no meesage - life is good - loop again
               }
               else
               {
                  flag = false;  // severe error - time to exit
               }
            }
            catch (System.IO.IOException ioex)
            {
               System.Console.Out.WriteLine("MQTest62 ioex=" + ioex);
            }
         }
      }

      ///  main line
      /// <param name="args">
      /// </param>
      //        [STAThread]
      public static void Main(System.String[] args)
      {
         MQTest62 write = new MQTest62();

         try
         {
            write.init(args);
            write.testReceive();
         }
         catch (System.ArgumentException e)
         {
            System.Console.Out.WriteLine("Usage: MQTest62 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
            System.Environment.Exit(1);
         }
         catch (MQException e)
         {
            System.Console.Out.WriteLine(e);
            System.Environment.Exit(1);
         }

         System.Environment.Exit(0);
      }
   }
}


text:
Q: Distinct SUM with many-to-many relationships this is a followup question os this. Since the other answers an important part(how to SUM by partition) i keep it accepted. But another part worries me.
How to SUM in a many-to-many relationship if the "left" side should counted just once.
Consider following sample data which hopefully explains my problem:
declare @t1 table (ID int,Price money, Name varchar(10))
declare @t2 table (ID int,Orders int,  Name varchar(10))
declare @relation  table (t1ID int,t2ID int)
insert into @t1 values(1, 200, 'AAA');
insert into @t1 values(2, 150, 'BBB');
insert into @t1 values(3, 100, 'CCC');
insert into @t2 values(1,25,'aaa');
insert into @t2 values(2,35,'bbb');
insert into @relation values(1,1);
insert into @relation values(2,1);
insert into @relation values(3,2);
-- following record will cause the "wrong" sum
insert into @relation values(2,2);

select
 T2.Name as T2Name
,T2.Orders As T2Orders
,T1Sum.Price As T1SumPrice
,T1.Price As T1HighestPrice
,T1.Name As T1HighestPrice_Name
FROM @t2 T2
INNER JOIN (
    SELECT Rel.t2ID
        ,Rel.t1ID
        ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
        ,SUM(Price)OVER(PARTITION BY Rel.t2ID) AS Price
        FROM @t1 T1
        INNER JOIN @relation Rel ON Rel.t1ID=T1.ID
)AS T1Sum ON  T1Sum.t2ID = T2.ID AND t1Sum.PriceList = 1
INNER JOIN @t1 T1 ON T1Sum.t1ID=T1.ID

Actual result:
T2Name  T2Orders    T1SumPrice  T1HighestPrice  T1HighestPrice_Name
aaa         25          350,00          200,00          AAA
bbb         35          250,00          150,00          BBB

Desired result:
T2Name  T2Orders    T1SumPrice  T1HighestPrice  T1HighestPrice_Name
aaa         25          350,00          200,00          AAA
bbb         35          100,00          150,00          BBB

Notice the difference in T1SumPrice. The last entry in the relation-table inserts a T1 to bbb that was already assigned to another T2(aaa), hence it's already part of T1SumPrice for T2-group with Name=aaa.
So how can i prevent counting values twice when they are already part of another group?
Edit:
This is the resulting query from Nikola's answer(which is actually part of a table-valued-function). Note that i need to use the scalar-valued-functions to retrieve the values:
select T2.idSparePart As T2_ID
,T2.PartNumber as T2_PartNumber
,Gambio.getGoodsIn(T2.idSparePart,@FromDate,@ToDate) AS GoodsIn
,Gambio.getOrdered(T2.idSparePart,@FromDate,@ToDate) AS Ordered
,T1Sum.ClaimedReused As T1SumPrice_ClaimedReused
,T1Sum.Costsaving As T1SumPrice_Costsaving
,T1.Price As T1HighestPrice
,T1.idSparePart AS T1HighestPrice_ID
,T1.SparePartName As T1HighestPrice_Number
,T1.SparePartDescription As T1HighestPrice_Name
,Cat.SparePartCategoryName As T1HighestPrice_Category
FROM Gambio.SparePart T2
INNER JOIN (
    SELECT Rel.fiSparePart
        ,Rel.fiTabSparePart
        ,ROW_NUMBER()OVER(Partition By Rel.fiSparePart Order By Price DESC)As PriceList
        ,SUM(Gambio.getMaterialQuantity(Rel.fiTabSparePart,NULL,NULL,@idClaimStatus,1))OVER(PARTITION BY Rel.fiSparePart) AS ClaimedReused
        ,SUM(Gambio.getCostSaving(Rel.fiTabSparePart,NULL,NULL,@idClaimStatus))OVER(PARTITION BY Rel.fiSparePart) AS Costsaving
        FROM tabSparePart T1
        INNER JOIN
          (select fiTabSparePart
            , fiSparePart
            from Gambio.trelSparePartClaimGroup relation
            where not exists (
                select null
                from Gambio.trelSparePartClaimGroup rel
                where rel.fiTabSparePart = relation.fiTabSparePart
                and rel.fiSparePart < relation.fiSparePart
            )
        )
        Rel ON Rel.fiTabSparePart=T1.idSparePart
)AS T1Sum ON  T1Sum.fiSparePart = T2.idSparePart AND t1Sum.PriceList = 1
INNER JOIN tabSparePart T1 ON T1Sum.fiTabSparePart=T1.idSparePart
INNER JOIN tabSparePartCategory AS Cat
    ON Cat.idSparePartCategory=T1.fiSparePartCategory

Unfortunately it seems to skip some T1-records so that i get a wrong result

A: The way to do that is to filter relations so that all but first one get omitted. And if I read your example correctly, T1SumPrice should be 100,00 for bbb row because from relation you see that where t2id=1 you sum 200+150, and for t2id=2 100+150 but 150 is already spent in previous row.
select
 T2.Name as T2Name
,T2.Orders As T2Orders
,T1Sum.Price As T1SumPrice
,T1.Price As T1HighestPrice
,T1.Name As T1HighestPrice_Name
FROM t2 T2
INNER JOIN (
    SELECT Rel.t2ID
        ,Rel.t1ID
        ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
        ,SUM(Price)OVER(PARTITION BY Rel.t2ID) AS Price
        FROM t1 T1
        INNER JOIN
          (select t1id, t2id
             from Relation
            where not exists (select null from relation test where test.t1id = relation.t1id
                              and test.t2id < relation.t2id)
        )
        Rel ON Rel.t1ID=T1.ID
)AS T1Sum ON  T1Sum.t2ID = T2.ID AND t1Sum.PriceList = 1
INNER JOIN t1 T1 ON T1Sum.t1ID=T1.ID

P.S. I was using  Sql Fiddle and had to get rid of @.
EDIT: attempt at explanation.
It works because only one of t2 relationships is permitted by subquery rel. I choose first id, but this depends on your use-case. As others have said, there are other options, equal or proportional distribution.

A: To pro-rata the T1 price across the SUM column but not the MAX column, try the following:
select
 MAX(T2.Name) as T2Name
,MAX(T2.Orders) As T2Orders
,SUM(T1Sum.ProRataPrice) As T1SumPrice
,MAX(T1Sum.Price) As T1HighestPrice
,MAX(CASE WHEN PriceList=1 THEN T1Sum.Name END) As T1HighestPrice_Name
FROM @t2 T2
INNER JOIN (
  SELECT Rel.t2ID
        ,Rel.t1ID
        ,Name
        ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
        ,Price
        ,Price / COUNT(*)OVER(PARTITION BY Rel.t1ID) AS ProRataPrice
        FROM @t1 T1
        INNER JOIN @relation Rel ON Rel.t1ID=T1.ID
)AS T1Sum ON  T1Sum.t2ID = T2.ID
GROUP BY T2.ID

A: As the question isn't clear exactly what rules to implement to elimate duplicates I offer the following approach:
;WITH T1Sum AS
(   SELECT  Rel.t2ID,
            Rel.t1ID,
            ROW_NUMBER() OVER(PARTITION BY Rel.t2ID ORDER BY Price / Relations DESC) As PriceList,
            SUM(Price / Relations) OVER (PARTITION BY t2ID) [Price]
    FROM    @t1 T1
            INNER JOIN
            (   SELECT  *,COUNT(*) OVER(PARTITION BY t1ID) [Relations]
                FROM    @Relation
            ) rel
                ON Rel.t1ID = T1.ID
)
SELECT  T2.Name as T2Name,
        T2.Orders As T2Orders,
        T1Sum.Price As T1SumPrice,
        T1.Price As T1HighestPrice,
        T1.Name As T1HighestPrice_Name
FROM    @t2 T2
        INNER JOIN T1Sum
            ON T1Sum.t2ID = T2.ID
            AND t1Sum.PriceList = 1
        INNER JOIN @t1 T1
            ON T1Sum.t1ID = T1.ID

This will distribute the price evenly through duplicate relations so for the example it will return:
T2Name  T2Orders    T1SumPrice  T1HighestPrice  T1HighestPrice_Name
aaa         25          275,00          200,00          AAA
bbb         35          175,00          150,00          BBB


text:
Q: css3 columns without cutting paragraphs Im trying to set a series of  in a column layout. Ive been trying with CSS3 but it cuts the elemens in half. Heres an example:
http://jsfiddle.net/zh9zq/
Is it possible to have the columns not cut certain elements in half? Thanks

A: Solution found:
-webkit-column-break-inside:avoid;
-moz-column-break-inside:avoid;
-o-column-break-inside:avoid;
-ms-column-break-inside:avoid;
column-break-inside:avoid;


text:
Q: Google Play Promo Videos not getting displayed in Mobile but visible via Laptop Browser Since Nov 2019, Google Play Promo Videos not getting displayed in Mobile but visible via Laptop Browser.
I checked a few other apps and in there the promo video is visible.
What could be the reason?

A: I figured it out. Its cause Google Play is preventing promo videos from being displayed if Ads are enabled on the video.
Remove ads for that specific video and wait for 3 days it will get enabled again in Google Play via Android Phones.


text:
Q: add click event to Jquery UI accordian Header When you create a Jquery UI accordian you get a bunch of headers, that when you click them a div opens. However, I would like to preform an additional action upon clicking the header.
How do i do this?
Any ideas?
Thanks!

A: You need to wrap your code in ready handler:
$(function(){
  $("#CreateNewUserHeader").click(function() {
    alert("test");
  });
});

Also make sure that you do not assign same id to more than one elements.

A: What I've done when I needed to do this in the past was something like this:
$('#accordion h3 a').bind('click', function (e) {
  // bind to the the header / anchor clicks
  if (!condition) {
    e.preventDefault();
    e.stopPropagation();
  }
});

A: You guys should read the documentation, there is an event handler that will do it all for you.
https://api.jqueryui.com/accordion/#event-activate
$( ".selector" ).accordion({
  activate: function( event, ui ) {}
});

A: Javascript
$("#CreateNewUserHeader").click(function() {
    alert("test");
});

html

Create New User

some stuff


text:
Q: are refs overriden or inherited in extjs? i had this parent class : assume its on correct syntax (views aliases, stores and xtypes):
    Ext.define('myParent' {
       extend : 'Ext.app.Controller',

refs : [{
        ref : 'formwindow',
        selector : 'forms-formwindow'
    }, {
        ref : 'mainForm',
        selector : '#mainForm'
    }],

    });

    i had this subclass :

    Ext.define('myChild' {
       extend : 'myParent',

    });

whenever i put this code in my subclass:
refs : [{
        ref : 'myReference',
        selector : 'myProduct'

    }],

i got this error during runtime :
Uncaught TypeError: Object [object Object] has no method 'getMainForm'

i wonder if refs from the parent class were overriden by my child class....
what happened ? does it really overrides myParent's refs?

A: As you've found out yourself, there's no special treatment of the refs property so, yes, it does get overridden.
To augment it instead of replacing, you'll have to do it in the child classes constructor, like in this example:
Ext.define('myChild', {
    extend: 'myParent'
    ,constructor: function() {
        this.refs = (this.refs || []).concat([{
            ref: 'myReference',
            selector: 'myProduct'
        }]);
        this.callParent(arguments);
    }
});

A: This really bugs me about Ext Controllers so today I had a go a fixing it, rixo solution works great but here is an alternative to extending every child class. Extend Ext.app.Controller instead using "onClassExtended" method
    /**
 * Extends Ext.app.Controller with the ability to have refs defined in
 * Controllers and any of subclasses.
 * Duplicate refs overwrite each other, last one in class hierarchy wins.
 */
Ext.define('App.Controller', {
    extend: 'Ext.app.Controller',
    //private make refs extensible by any subclasses
    onClassExtended : function(cls, data, hooks) {
        var onBeforeClassCreated = hooks.onBeforeCreated;
        hooks.onBeforeCreated = function(cls, data) {
            var me = this,
                name = Ext.getClassName(cls),
                prototype = cls.prototype,
                superCls = cls.prototype.superclass,
                thisRefs = data.refs || [],
                superRefs = superCls.refs || [],
                newRefs = [],
                i = 0;
            if (thisRefs.length > 0) {
                for (i=0; i < thisRefs.length; i++) {
                    if (typeof thisRefs[i] !== 'undefined') {
                        newRefs.push(thisRefs[i]);
                    }
                }
            }
            if (superRefs.length > 0) {
                for (i=0; i < superRefs.length; i++) {
                    if (typeof superRefs[i] !== 'undefined') {
                        newRefs.push(superRefs[i]);
                    }
                }
            }
            data.refs = newRefs;
            onBeforeClassCreated.call(me, cls, data, hooks);
        };
    }
});


text:
Q: How to past Check 50 for Bleep.py in Pset 6? The number of "*" printed fluctuates according to the length of string entered
def main():
    # check command line argument
    if len(argv) != 2:
        print("Usage: python bleep.py dictionary")
        exit(1)

    else:
        ban = set()

        # Load txt file
        with open(argv[1], "r") as f:
            for line in f:
                # strip the space and add to set
                ban.add(line.strip())

        # prompt user input
        input = get_string("What message would you like to censor?\n")

        # Split input into word tokens
        token = input.split()
        censored_msg = ""

        for i in token:
            if i.lower() in ban:
                censored_msg = (censored_msg + "*"*(len(token)+1) + " ")
            else:
                censored_msg += i + " "

        # print censored message
        print(censored_msg.strip())

if __name__ == "__main__":
    main()

It prints fine for some cases, such as
Input: heck my gosh
Output: **** my ****
But not so in others (should be **** ****)
Input: heck gosh
Output: * * (just 6 * for 8 letters)

A: Is it a typo? Check this line very carefully
censored_msg = (censored_msg + "*"*(len(token)+1) + " ")
and remember which is what here for i in token:


text:
Q: Sending an array or list to asp.net mvc controller using jquery I have a project to find a place with Asp.Net MVC. The purpose of my project is to find latitude and longitude collectively according to the address column in the excel file. I use axios to find latitude and longitude by address. When I select the excel file I want, it is saved in the database. I want to find the latitude and longitude of the addresses in excel and save them in the database. I used the series in Console.log to see the data I wanted and I was successful, but there is a continuous recording going to the controller. I want to go to the controller as a list or as a series. Where am I doing wrong? Is there anyone who can help me?
This is my javascript code:
$('input[type="file"]').change(function (e) {
        handleFileSelect(e);
    });

    function handleFileSelect(evt) {

        var files = evt.target.files; // FileList object
        var xl2json = new ExcelToJSON();
        xl2json.parseExcel(files[0]);
    }

    function getLatLng(address, fn) {
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: address,
                key: 'apiKey'
            }
        }).then(function (response) {
            fn(response.data.results[0].geometry.location.lat, response.data.results[0].geometry.location.lng);
        })
        //axios.get({ 'address': address }, function (results, status) {
        //    fn(results[0].geometry.location.lat(), results[0].geometry.location.lng());
        //});
    }

    var ExcelToJSON = function () {

        this.parseExcel = function (file) {
            var reader = new FileReader();

            reader.onload = function (e) {
                var data = e.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    var d = JSON.parse(json_object);
                    console.log(d);

                    for (var i = 0; i <= d.length; i++) {

                        $.each(d[i + 1], function (IndexNo, Deger) {
                            console.log(Deger);

                            getLatLng(d[i + 1].Adres, function (lat, lng) {
                                if (lat != '' && lng != '') {
                                    console.log(lat);
                                    console.log(lng);
                                }

                                var maps = [
                                    { lat:lat },
                                    { lng: lng }
                                ];

                                maps = JSON.stringify({ 'maps': maps });

                                console.log(maps);

                                var maplist = new Array();

                                maplist[0] = lat;
                                maplist[1] = lng;

                                var postData = { value: maplist };

                                  var maplst = new Array();
                                var map;
                                $.each(maplist,function () {
                                    map = {};
                                    map.Latitude = maplist[0];
                                    map.Longitude = maplist[1];
                                    maplst.push(map);
                                    console.log(map);
                                    document.getElementById('items').value = map;
                                });
                            });

                        });

                    }

                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);
        };
    };

This is my controller:
[HttpPost]
    public ActionResult Index(FormCollection formCollection, string[] items)
    {
        LocationDBEntities db = new LocationDBEntities();
        List<AWSServerless_Google_Geocoding_Mvc.Models.Map> mapList = new List<AWSServerless_Google_Geocoding_Mvc.Models.Map>();
        mapList = new List<AWSServerless_Google_Geocoding_Mvc.Models.Map>();
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["FileUpload"];
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                string fileName = file.FileName;
                string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
                var path = Path.Combine(Server.MapPath("~/Content/FileUpload"), file.FileName);
                file.SaveAs(path);
                var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                if (db.Map.Where(x => x.FileName == fileName).Any())
                {
                    TempData["Message"] = "Aynı isimden dosya mevcut.";
                    ViewBag.Path = path;
                    return View();
                }
                else
                {
                    using (var package = new ExcelPackage(file.InputStream))
                    {
                        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                        var currentSheet = package.Workbook.Worksheets;
                        var workSheet = currentSheet.First();
                        var noOfCol = workSheet.Dimension.End.Column;
                        var noOfRow = workSheet.Dimension.End.Row;
                        for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                        {
                            var map = new Map();
                            map.UserID = Convert.ToInt32(Session["UserID"]);
                            for (int i = 0; i < items.Length; i++)
                            {
                                map.Latitude = items[0];
                                map.Longitude = items[1];
                            }
                            map.Address = workSheet.Cells[rowIterator, 3].Value.ToString();
                            map.ExcelPath = path;
                            map.FileName = fileName;
                            map.LastFileName = Request.Cookies["sonYuklenenDosya"].Value;
                            map.PrevFileName = Request.Cookies["oncekiYuklenenDosya"].Value;
                            map.BeforeFileName = Request.Cookies["dahaOncekiYuklenenDosya"].Value;
                            map.ModifyUserId = Convert.ToInt32(Session["UserID"]);
                            map.ModifyUser = Session["FirstName"].ToString();
                            map.ModifyDate = DateTime.Now;
                            map.CreateUserId = Convert.ToInt32(Session["UserID"]);
                            map.CreateHost = Session["FirstName"].ToString();
                            map.CreateDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                            mapList.Add(map);
                            map.FileCount = mapList.Count;
                        }
                    }
                }

            }
        }
        foreach (var item in mapList)
        {
            db.Map.Add(item);
        }
        db.SaveChanges();
        return View(mapList);

enter image description here
Please help me.

A: Javascript:
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };

$.ajax({
    type: "POST",
    url: "/Home/SaveList",
    data: postData,
    success: function(data){
        alert(data.Result);
    },
    dataType: "json",
    traditional: true
});

Controller:
public JsonResult SaveList(List<String> values)
{
  //code...
}


text:
Q: is it possible to detect if a element has validate attributes like ng-maxwidth? I have a central angular directive to watch validation rules like ng-maxlength, ... - That works fine, but in my current solution I have a lot of watchers and I try to reduce them by looking if the attribute is really set in der HTML Element.
form.element*.required*  works easy, but the others?
Regards klaus


text:
Q: How to download folder from putty using ssh client how to download folder(contains folder inside folder and files) from putty using  ssh client
i want download entire Dump to local Drive...
can any one guide me ...

A: You need to use some kind of file-transfer protocol (ftp, scp, etc), putty can't send remote files back to your computer.  I use Win-SCP, which has a straightforward gui.  Select SCP and you should be able to log in with the same ssh credentials and on the same port (probably 22) that you use with putty.

A: You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.
Please see the following link on how to download a file/folder:
https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

A: If you need to download a folder via a Linux command try this out:
$ scp your_username@remotehost.edu:foobar.txt -r /some/local/directory
Sources:

*

*http://www.linuxquestions.org/questions/linux-general-1/useing-scp-to-copy-entire-directories-with-sub-folders-362842/

*http://www.hypexr.org/linux_scp_help.php
Related Post:
How to download a file from server using SSH?
8)

A: I use both PuTTY and Bitvise SSH Client.  PuTTY handles screen sessions better, but Bitvise automatically opens up a SFTP window so you can transfer files just like you would with an FTP client.


text:
Q: iPad Ad hoc version not run on the device I'm facing a problem when running the AdHoc distribution app, I've developed an application and test it using development certificate on real device, running successfully, but when produce the adHoc and send it to my client to test it, the application installed successfully but does not run, where is the problem in this case?
the application using large image file (about 3-5 MB each image, but the number of the image is small, about 5-6 image) how can it run on the development certificate ?
Solution:
It seems that the tested ad hoc device was using a 3.4 ios version, and the app was developed for ios 5 and was contain some feature of the ios 5, so it was crashing every time the app run.
thx in advance.

A: It seems that the tested ad hoc device was using a 3.4 ios version, and the app was developed for ios 5 and was contain some feature of the ios 5, so it was crashing every time the app run.


text:
Q: The page isn't redirecting properly in asp.net I am trying to publish my website to the server .So i published that and i got a lot of errors,i fixed them ,i get another error The page isn't redirecting properly in asp.net when i call the url .
When i call a picture from my website for example 127.0.0.1/i.png it works and the ie shows me the picture but when i call 127.0.0.1/fa/default.aspx i get this error :

Here is my web.config
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>

  <connectionStrings>
    <add name="BaHamayeshban" connectionString="Data Source=(local);Initial Catalog= hamayeshban.ir_conf.qums;integrate security=true;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824"/>
      </requestFiltering>
    </security>
  </system.webServer>

  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime maxRequestLength="1048576"/>
    <pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID"/>
  </system.web>

</configuration>

actually the IIS doesn't show me the resource of the error ,and i couldn't find the error  resource.
Here is the iis folder

Best regards

A: where is your webconfig? in order to make it work you have to put at least one weconfig file at project level
put webconfig file here
C:\inetpub\wwwroot\Fa\ Web.config


text:
Q: Symfony private messages I want to make private messages in my site. I want that user can delete  received or sent messages. For it I need two tables one for send message and one for receive....Is it to possible that when user send messages, it automatically add fro two tables? or it is better to make some relations with tables? or  maybe exist better solution?

A: I think you need just one table:
Message:
  columns:
    from: integer
    to: integer
    header:  string(100)
    body:    blob
    show_in_outcoming:
      type: boolean
      default: true
    show_in_incoming:
      type: boolean
      default: true
    is_read:
      type: boolean
      default: false
  UserFrom:
    class: sfGuardUser
    local: from
    foreign: id
    foreignType: one
    type: one
  UserTo:
    class: sfGuardUser
    local: to
    foreign: id
    foreignType: one
    type: one

where

*

*is_read indicates whether or not the message been read (false - unread, true - read - for incoming messages only)

If the user who sends the message want to delete it, we simply hide it (not delete from the DB) - set show_in_outcoming to false.
If the user who received the message want to delete it, we hide it too - set show_in_incoming to false. This approach allows us to recover the "hidden" messages (or remove them altogether)

A: Maybe, you should create a message table, with tow relation to user table:
message:
  columns:
    user_emitter_id: ...
    user_reciever_id: ...
    body: ...
  relations:
    userEmitter:
      class: user
      local: user_emitter_id
      foreign: id
    userReciever:
      class: user
      local: user_reciever_id
      foreign: id

A: There is a symfony plugin that allows you to do this. Check sfSocialPlugin.

A: Message:
  columns:
    from: integer
    to: integer
    header:  string(100)
    body:    blob
    show_in_outcoming:
      type: boolean
      default: true
    show_in_incoming:
      type: boolean
      default: true
    is_read:
      type: boolean
      default: false

  relations:
    UserFrom:
      class: sfGuardUser
      local: from
      foreign: id
      foreignType: one
      type: one
    UserTo:
      class: sfGuardUser
      local: to
      foreign: id
      foreignType: one
      type: one


text:
Q: Summation of power inequalities some idea for solve (?):
$x\in \mathbb{R}$
$\sum_{n=2}^{\infty } x^{n}\le 6$
I am at a loss :/
Thx

A: Let's pretend that our sum starts from $n=0$. Then we have $S=1+x+x^2+\ldots+x^{n-1}+x^n$. Let us then notice how $(1-x)S=1-x^{n+1}\iff S=\dfrac{1-x^{n+1}}{1-x\quad\ }$ . Now, as n tends towards $\infty$, if x were greater than $1$ in absolute value, then $S\to\pm\infty$. So $|x|<1$, in which case, $S=\dfrac1{1-x}$ . But our sum starts at $n=2$, so its value is $S'=S-(1+x)\le6$ . Can you take it from here ? :-) We have $\dfrac1{1-x}-(1+x)\le6$. Since $|x|<1$, it follows that $1-x>0$, so that multiplying both sides with it won't change the comparison sign. Thus, $1-(1-x^2)\le6(1-x)\to x^2+6x-6$ $\le0$. Now, we know from theory that $ax^2+bx+c$ has the same sign as a outside of the interval $(x_1,x_2)$, and the sign opposite to it inside the same interval, where $x_1$ and $x_2$ are the two roots of the function. In our case, $a=1$, and its roots are $-3\pm\sqrt{15}$ , so $x\in(-3-\sqrt{15},-3+\sqrt{15})$. But, at the same time, $x\in(-1,1)$. Intersecting the two intervals, we have $x\in(-1,-3+\sqrt{15})$, since, obviously, $0<\sqrt{15}<\sqrt{16}=4$.


text:
Q: Laravel 403 Invalid Signature only on Nginx Web Server Problem
I am creating a signed URL through laravels 'temporarySignedRoute' function copied and pasted from laravels signed routes documentation, on my web server the url comes out to a 403 invalid signature. The signed URL's work on my local machine but upon uploading it to my test server it gives the error shown below.

What I've tried
I have been searching for a solution for awhile now and have tried many that have been posted on stack overflow but nothing seems to solve my problem.
I have tried all of the following:

*

*Forcing all routes to https through the AppServiceProvider, this forced all of the url's to be https but gave the same result.

*I tried changing Nginx's configuration as described here.

*I also tried adding the TrustProxies middleware with the proxies configured to '*' or all, like described in laravel's documentation on Trust Proxies, same result.

*Stopped the web server from forcing the domain to https to test if it was just https causing it, same result.

-- UPDATE --
I went into vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php while trying to search around for any clues in the project. I decided to datadump (dd) out the tokens it was comparing on my local and hosted projects and this was the result. Code shown below as well.
public function hasValidSignature(Request $request, $absolute = true)
{
    $url = $absolute ? $request->url() : '/'.$request->path();

    $original = rtrim($url.'?'.Arr::query(
        Arr::except($request->query(), 'signature')
    ), '?');

    $expires = $request->query('expires');

    $signature = hash_hmac('sha256', $original, call_user_func($this->keyResolver));
    dd($signature . " :: " . $request->query('signature', ''));
    return  hash_equals($signature, (string) $request->query('signature', '')) &&
           ! ($expires && Carbon::now()->getTimestamp() > $expires);
}

Local Project

Hosted Project

So the Token is not being passed through on my web server but is on my local. Also another thing I noticed is that the web servers token is always the same and never changes no matter what.
My current Nginx configuration can be viewed here.
My current virtual hosts configuration is here.

A: I think this might be the issue.
Try to change your location block in the config file to
try_files $uri $uri/ /index.php?$query_string;
I think you have missed the ? between index and query string.
Update this and make sure to reload your Nginx server.
sudo service nginx reload
Let me know if this works.

A: The post from Prince Kumar Barnwal fixed my issue back then, I recently rediscovered another version of this issue while attempting to use docker in the same setup and I thought I would post it here in case anyone has the same issue.
We are using a Proxy Server and certifying our docker laravel projects on that, all projects have the TrustProxies setup, then we forceHTTPS in the AppServiceProvider.php which makes AJAX calls work. This causes issues as the project itself is not encrypted but all urls it generates thinks it is since we are forcing it. When the proxy passes the URL in the request it is http, when the project expects HTTPS.
I found a solution to this, its not the most clean and theirs probably a better fix out there but I made a middleware that goes on all of the projects signed routes, basically it just changes the url in the request to be secure if the project is in production. This is not insecure as the proxy handles the security and this is ONLY on the signed routes.
Below is the middleware that goes ONLY on the signed routes.
<?php

namespace App\Http\Middleware;

use Closure;

class SecureSignedURL
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(config('app.env') === 'production' || config('app.env') === 'staging') {
            $request->server->set('HTTPS', 'ON');
        }
        return $next($request);
    }
}

My web.php with the middleware, its defined as secure_signed_url in my Kernel.php
Route::group(['middleware' => ['secure_signed_Url', 'signed']], function () {
        route::get('/exampleurl1', 'TestController@route_exampleurl1_signed')->name('exampleurl1.signed');
        route::get('/exampleurl2', 'Template\TemplateController@route_exampleurl2_signed')->name('exampleurl2.signed');
});

Again I don't know if this is the best fix, this is a very obscure bug in Laravel. If you have any suggestions for a better way of fixing this I'm open to suggestions.
My Old Github Issue that may help: https://github.com/laravel/framework/pull/31434

A: This is not a Nginx error. That's how laravel handles invalid signed urls if you check the Illuminate\Routing\Middleware\ValidateSignature it throws an Illuminate\Routing\Exceptions\InvalidSignatureException which aborts the request with a 403 status. What I did,
Created a custom signed middleware which extends the actual ValidateSignature
<?php

namespace App\Http\Middleware;

use App\Exceptions\InvalidEmailVerificationException;
use Closure;
use Illuminate\Routing\Middleware\ValidateSignature as MiddleWare;

class ValidateSignature extends Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->hasValidSignature()) {
            return $next($request);
        }

        throw new InvalidEmailVerificationException;
    }
}

which throws a custom App\Exceptions\InvalidEmailVerificationException
<?php

namespace App\Exceptions;

use Symfony\Component\HttpKernel\Exception\HttpException;;

class InvalidEmailVerificationException extends HttpException
{
    /**
     * Create a new exception instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct(403, 'Your email verification token seems to be invalid.');
    }
}

then change the signed middleware in your App\Http\Kernel.php $routeMiddleware to 'signed' => \App\Http\Middleware\ValidateSignature::class,
in your 403.blade.php view, you can display the message as
@if ($exception instanceof \App\Exceptions\InvalidEmailVerificationException)

Snap!

Verification token expired.

                            @if (session('resent'))

                                    {{ __('A fresh verification link has been sent to your email address.') }}

                            @endif

{{ $exception->getMessage() }}

                            Email me a new link
@endif


text:
Q: Como usar Herança de templates, para herdar Folhas de Estilo (css) no meu projeto Django? Tenho uma template base.html e outra template library.html que esta herdando base!
Consegui herdar a maior parte de base.html, só que quando tento adicionar mais uma tag link no bloco de Estilo O Django acusa erro de TemplateSyntaxError, quando eu retiro o bloco com a nova tag link a mais ele renderiza a template normalmente!
Base.html:
<!DOCTYPE html>
{% load staticfiles %}

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="">

<title>{% block title %}{% endblock %}</title>

<link href="{% static 'css/bootstrap.min.css ' %}" rel="stylesheet">
<link href="{% static 'css/starter-template.css ' %}" rel="stylesheet">
<link href="{% static 'css/navbar-static-top.css ' %}" rel="stylesheet">

{% block Estilo %}
{% endblock %}

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>
      Library Chameleon

Home

Emprestimo

Relatórios

          Serviços

Cadastrar Livros

Cadastrar Usuarios

Cadastrar Funcionarios

Pesquisa

Livro

Usuario

Funcionario

{% block Corpo %}
{% endblock %}

{% block JScript %}
{% endblock %}

Library.html:
{% extends 'base.html' %}

{% block title %}Chameleon | Cadastro de Livro{% endblock %}

{% block Estilo %}
<link href="{% static 'css/cadastros.css' %}" rel="stylesheet">
{% endblock %}

{% block Corpo %}

  <form class="form-signin" role="form">

Cadastro

    <input type="text" class="form-control" id="codigo" name= "codigo" placeholder="Codigo" required autofocus>
    <input type="text" class="form-control" id="titulo" name= "titulo" placeholder="Titulo" required>
    <input type="text" class="form-control" id="autor" name= "autor" placeholder="Autor" required>
    <input type="text" class="form-control" id="editora" name= "editora" placeholder="Editora" required>
    <input type="text" class="form-control" id="genero" name= "genero" placeholder="Genero" required>
    <input type="text" class="form-control" id="publicacao" name= "publicacao" placeholder="Ano: 0000" required>

    <textarea id="sinopse" name="sinopse" placeholder="Sinopse" rows = 10 cols = 63 required></textarea>

<button class="btn btn-lg btn-primary btn-block" type="submit">Salvar</button>
  </form>

{% endblock %}

{% block JScript %}
{% endblock %}

Erro retornado do Django:
TemplateSyntaxError at /cadLivro/
Invalid block tag: 'static', expected 'endblock'
Request Method: GET
Request URL:    http://localhost:8000/cadLivro/
Django Version: 1.6.2
Exception Type: TemplateSyntaxError
Exception Value:
Invalid block tag: 'static', expected 'endblock'
Exception Location: C:\Python27\lib\site-packages\django\template\base.py in invalid_block_tag, line 331
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.6

A: Adicione o {% load staticfiles %} no library.html também.
No Django é obrigatório adicionar os cabeçalhos necessários em cada arquivo de template, mesmo que eles já estejam declarados no  template-base. Você está usando o static dentro do bloco de estilo, mas o template ainda não sabe o que isso significa, devido a ausência do {% load staticfiles %}.


text:
Q: Append and element to an  if it has an specific anchor with jQuery or JS I am working with bootstrap using tabs. I am doing a nested tab which now supports many levels of tabs, but I want to append and icon  to all the nav list corresponding to the tab-pane how has a tab-group inside it. Following I explain better.
Here is a basic example of what I have, the solution should work for many levels as possible:

link 1

link 2

link 3

Nothing

Nothing

link 1

link 2

Nothing

Nothing

The idea
As you can see in the first .tab-group .tab-content > .tab-pane you can find that id="003" has an other .tab-group inside.
Now in the first .tab-group .nl-nav I have to find which
 element has the link a with the anchor #003 and append a  to that link:
Example:

link 1

link 2

link 3

I have to repeat or do the same to all the .nl-nav > .li that can be found inside the tab-groups of the nested tabs corresponding to their own .tab-content .tab-pane contents

A: You can use filter():

$('.nl-nav a').filter(function() {
  return $(this.hash).find('.tab-group').length;
}).append('')
.icon-class:after {
  content: '... ICON';
  color: red;
}
.tab-content{
   padding-left:80px
}
.tab-pane .tab-group{
  margin-left:50px
}

link 1

link 2

link 3

Nothing

Nothing

      Nested tabs

link 1

link 2

Nothing

            Nested tabs

A: If I understand you correctly, you can select each ul and loop through them.
It could look like this:
var nlnavs = $("ul[class=nl-nav]");
for(var i = 0; i < nlnavs.length; i++){
  var childs = $(nlnavs[i]).children();
  for (var j = 0; j < childs.length; j++){
   $(childs[j]).append("YOUR ICON");
  }
}

Here is a working JSFiddle


text:
Q: Unity Lighting 2DDL InvalidCastException i am just new to unity and c# scripting language... i was just trying to make something in unity and was using 2DDL for lighting the problem i am getting is whenever i hit to play and test the game the light is following the gameobject correctly but after a while it's getting stuck at any random point... you can check the screenshot for the full error detail.

2DLight Script
void Update(){

        getAllMeshes();
        setLight ();
        renderLightMesh ();
        resetBounds ();

    }

    void getAllMeshes(){
        //allMeshes = FindObjectsOfType(typeof(PolygonCollider2D)) as PolygonCollider2D[];

        Collider2D [] allColl2D = Physics2D.OverlapCircleAll(transform.position, lightRadius, layer);
        allMeshes = new PolygonCollider2D[allColl2D.Length];

        for (int i=0; i<allColl2D.Length; i++) {
            allMeshes[i] = (PolygonCollider2D)allColl2D[i];
        }

    }

    void resetBounds(){
        Bounds b = lightMesh.bounds;
        b.center = Vector3.zero;
        lightMesh.bounds = b;
    }


text:
Q: Set Button text vertical align to center/middle? Hey I want to display the text of my button in the center of my button.
So is there a attribute I can change so that it's appears in the center?
Right now it's at the top border of my button.
I tried to use the padding-top attribute, but it looks different when using different browser like Firefox, IE, etc.
Is there a general solution to display the text in the center of a button?
Thank you for any hints!

A: As you have not shared the code i am assuming 30px height of your button. Use this css in your button.
button{
   height:30px;
   line-height:30px;
}

and remove padding if any.
This will center align your text.
EDIT : Sometimes the text is little bottom aligned from center for that you can also use this
button{
   height:30px;
   display: inline-flex;
   align-items: center;
}

Thanks


text:
Q: how to convert .mobi and epub to html and text in php I have a bunch of EPUB books that I have to convert to MOBI if I get a Kindle.
I would like to know whether there will necessarily be any loss of detail (e.g. meta-data, layout info) during a conversion from EPUB to MOBI and vice versa, analogous to a conversion between MP3 and WMA? What happens when multiple conversions are applied consecutively, e.g. EPUB->MOBI->EPUB->MOBI->EPUB.
How bad will the information lose get?


text:
Q: Object doesn't recognized, how to solve? I have a simple code to work with getters and setters. I have created a object from book class in another class. But this object doesn't recognize by the class. Why is that? I get this error

An object reference is required for the nonstatic field, method, or property 'member'

class Book
{
    private int num;

    public void setNum(int no)
    {
        this.num = no;
    }
    public int getNum()
    {
        return this.num;
    }

}

class Program
{
    Book bb = new Book();
    public static void Main()
    {
        bb.setNum(10);
        Console.WriteLine("Insert value" + bb.getNum);
    }
}

A: GetNum is a function, you have to add () to it to get the value.
If you don't do this, C# is looking for a property with this name and this does not exist.


text:
Q: Put trigger in MySQL database to update Oracle database? I want to create an insert trigger on MySQL which will automatically insert the record into an Oracle database. I would like to know if there are people that have experience to share on this topic.
Cheers

A: Invoke a script as is done in this example that calls the Oracle code.
Note: you lose support for transactions (there will be no built-in rollback for the Oracle database) when you perform this type of cascading, and you also will take a likely very large performance hit in doing so. The script could turn around and simply call Java code or some other executable that invokes your some generic code to insert into Oracle, or it could be a raw query that gets passed arguments from the script.
This is almost certainly a bad idea because of the odd side-effect behavior, but it's one that can be implemented. I think that you would be much better off having the code to do this against two different DataSources (in Java/.NET speak) rather than have a hidden script in a MySQL trigger that screams unmaintainable, as well as hidden failure for future developers.


text:
Q: Insert one element in a matrix cell I write that code:
final_results = {};
for eva = 1:N
        final_results{eva,1} = .....;
        final_results{eva,2} = .....;
        final_results{eva,3} = .....;
        if eva == N
           final_results{1,4} = ....;
        end
end

But output is a cell of dimension Nx4 in which the fourth column contain the number I put in final_results{1,4} and the other are []. How I can put only final_results{1,4} without obtain []?


text:
Q: ActionBarCompat - how to use it I'm trying to use ActionBarCompat on my own project.
I've already opened the sample project (http://developer.android.com/resources/samples/ActionBarCompat/index.html), But I don't know how to implement it on my own.
I can't find any tutorial of some kind.
Should I make this project as a library?
Can someone give me some directions, please.

A: This answer describes how to use the new ActionBarCompat library (July 2013).
In Android Studio, open build.gradle and add this:
dependencies {
    compile 'com.android.support:appcompat-v7:18.0.+'
}

In Eclipse, create a library project based on the code in sdk\extras\android\support\v7\appcompat and add it to your project.
Activities have to extend ActionBarActivity.
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    ActionBar ab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ab = getSupportActionBar();
        ab.setTitle("Test");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView =
                    (SearchView) MenuItemCompat.getActionView(searchItem);

        return super.onCreateOptionsMenu(menu);
    }
}

Themes have to be (or extend) one of the Theme.AppCompat themes, for example:
<activity android:theme="@style/Theme.AppCompat.Light" ... />

Source: How to add ActionBarCompat to your project, blog post by Gabriele Mariotti

A: As for implementation, just stick to the sample code provided under the MainActivity.java class. You can find it here or under <your local android-sdks folder>/samples/android-15/ActionBarCompat/src/com/example/android/actionbarcompat/MainActivity.java. In general, all you need to do is the following:

*

*Code a menu resource where you declare the items for the action bar (See http://developer.android.com/resources/samples/ActionBarCompat/res/menu/main.html)

*Code an Activity that extends ActionBarActivity

*Override onCreateOptionsMenu() so that it inflates the menu you coded in step #1

*Override onOptionsItemSelected() so that you handle the event when the user taps any of the ActionBar items you defined in step #1.

I think it makes sense to build an Android Library project out of the ActionBarCompat code; then you can just reference it from your custom Android project. Remember it's licensed under the Apache License, Version 2.0.


text:
Q: How to write a truly secure user profile with zero identifying information, that they can do password resets to? Does anyone have any thoughts on how to build a user profile system on a site that is so secure that there's absolutely no way to figure out that person's identity; while also allowing them to reset their password?

*

*Don't want their email

*Don't want a phone number for SMS

*Don't want to use the social media platforms to authenticate

*Cannot use secret questions because they forget their own answers

*Cannot use a TOTP app on a cell phone because people lose/break their phones (and some still don't have a cellphone)

*Cannot use a cookie on their device because it isn't universal across phone/laptop/tablet, and they break their devices

*Cannot fingerprint their browser agent, ip, etc, because the users access the site from multiple systems, from multiple different IP's.  There are also multiple users logging in from the same home computer.

*Cannot issue them a physical token because cost, and, they'd lose them

Has anyone figured out an identity broker system that isn't associated with big social media?  The user could register their identity stuff with the 3rd-party broker, and the broker just gives me a key to identify them?  That is free for everyone to use?  Kind of like the GPG key ecosystem...
Looking for ideas.  How can I register an account for you, but no matter how hard I try, I never have any data that I could use to Google you?


text:
Q: Deleting SSIS folder in the SSISDB catalog using Powershell I'm trying to write a Powershell script to redeploy a project to SSIS and without trashing the catalog I simply want to delete the folder that contains the project.

Below is the code that calls Drop() on FolderToDrop:
$integrationServices = New-Object $Namespace".IntegrationServices" $sqlConnection
$catalog = $integrationServices.Catalogs["SSISDB"]
if ($catalog.Folders.Contains("FolderToDrop")) {
  $catalog.Folders["FolderToDrop"].Drop()
}

The exception that is thrown:
Exception calling "Drop" with "0" argument(s): "Operation 'Drop' on object 'CatalogFolder[@Name='FolderToDrop']' failed during execution."
At C:\Projects\Scripts\Deploy.ps1:36 char:29
+     $catalog.Folders["FolderToDrop"].Drop <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Any ideas as to what I'm missing trying to delete this folder?

A: It would seem that you need to delete the Environments and Projects from the folder before dropping it.
$folder = $catalog.Folders[$FolderName]

if($folder.Environments.Contains($EnvironmentName)) {
    $folder.Environments[$EnvironmentName].Drop()
}

if($folder.Projects.Contains($ProjectName)) {
    $folder.Projects[$ProjectName].Drop()
}

$folder.Drop()

A: If you want to delete all folders whitout specify the environment/project name, you could use:
function CatalogFolderDrop($catalog, $folderName)
{
    while ($catalog.Folders[$folderName].Environments.Count -ne "0")
    {
        $env = $catalog.Folders[$folderName].Environments | Select-Object -First 1
        $catalog.Folders[$folderName].Environments[$env.Name].Drop();
    }
    while ($catalog.Folders[$folderName].Projects.Count -ne "0")
    {
        $prj = $catalog.Folders[$folderName].Projects | Select-Object -First 1
        $catalog.Folders[$folderName].Projects[$prj.Name].Drop();
    }
    $catalog.Folders[$folderName].Drop();
}

A:     private void CatalogFolderDrop(String fdr)
    {
        while (mtIntegrationServices.Catalogs["SSISDB"].Folders[fdr].Environments.Count > 0)
        {
            mtIntegrationServices.Catalogs["SSISDB"].Folders[fdr].Environments.ElementAt(0).Drop();
        }
        while (mtIntegrationServices.Catalogs["SSISDB"].Folders[fdr].Projects.Count > 0)
        {
            mtIntegrationServices.Catalogs["SSISDB"].Folders[fdr].Projects.ElementAt(0).Drop();
        }
        mtIntegrationServices.Catalogs["SSISDB"].Folders[fdr].Drop();
    }


text:
Q: postgres get left table all data then group by count right table matching data I have two table products  and summary_orders.
products table has two fields
id | name
1  | apple
2  | orange

summary_orders table has fields
id | product_id | user_id | get_count
1  | 1          | 1       | 5
2  | 1          | 1       | 4

My desire output for user_id 1 is
name   total
Apple  9
orange 0

I have tried below query
SELECT products.name,
       SUM(summary_orders.get_count) AS total
FROM
    summary_orders
LEFT JOIN
    products ON products.id = summary_orders.product_id
WHERE
    user_id = 1
GROUP BY product_id,products.id
ORDER BY product_id ASC

I am getting result
name   total
Apple  9

Orange is missing. How can I get the count also with orange ?

A: you should change the direction of your join query, there are two ways:

*

*change LEFT JOIN to RIGHT JOIN

*first query on table products then INNER/LEFT JOIN with  summary_orders
you can read more about join and direction join here.
Edit Section:
also your query grammer is wrong, you select a column that not in group by result:
SELECT products.name,
       SUM(summary_orders.get_count) AS total
FROM
    summary_orders
RIGHT JOIN
    products ON products.id = summary_orders.product_id
WHERE
    user_id = 1
GROUP BY products.id,products.name
ORDER BY products.id ASC


text:
Q: Find and replace strings in a python dictionary I have a dictionary that looks like:
d = {'alleged': ['truths', 'fiels', 'fact', 'infidelity', 'incident'],
 'greased': ['axle', 'wheel', 'wheels', 'fields', 'enGine', 'pizza'],
 'plowed': ['fields', 'field', 'field', 'incident', '', '']}

I would like to go over it and replace some items for another strings. The strings to be find and the ones to replace them are also in a dictionary, in which the key is the string to be found and the value is the string to replace it:
d_find_and_replace = {'wheels':'wheel', 'Field': 'field', 'animals':'plants'}

I tried to use a function like:
def replace_all(dic1, dic2):
    for i, j in dic.items():
        dic3 = dic1.replace(i, j)
    return(dic3)

but it won't work because obviously, it uses replace built-in function replace inside it, and it is not possible to use it for dictionaries. Any suggestions on how to do this? Thank you very much for any help.
Edited to correct spelling mistakes.

A: Try just using direct assignation:
for key in d:
    li = d[key]
    for i,item in enumerate(li):
        li[i] = d_find_and_replace.get(item, item)

A: here is a solution. I also fixed your dictionaries they were messy. Check your spelling because with those given keys I think there is only going to be one match that will be replaced. for example engine will never match enGine, unless you don't care to match lower or upper case, in that case you can use if val.lowercase()
d = {'alleged': ['truths', 'fiels', 'fact', 'infidelity', 'incident'],
     'greased': ['axle', 'wheel', 'wheels', 'fields', 'enGine', 'pizza'],
     'plowed': ['fields', 'field', 'field', 'incident', '', '']}

d_find_and_replace = {'fields': 'field', 'engine': 'engine', 'incidint':'incident'}

keys_replace = d_find_and_replace.keys()
print d
for key in d.keys():
    for i, val in enumerate(d[key], 0):
        if val in keys_replace:
            index_to_replace = keys_replace.index(val)
            d[key][i] = d_find_and_replace[keys_replace[index_to_replace]]

print d


text:
Q: 2T2R with two antennas Regarding the 2T2R, the device should have two transmitter antennas and two receiver antennas in order to double the data rate. However, as I see different devices, the 2T2R has only two antennas, and 4T4R has four antennas. As I know, most of these devices support full duplex. Why do they have half of the antennas on their board?

A: Each antenna is both a transmit and receive antenna, so you can run 2T2R with only two antennas...


text:
Q: Retrieve escaped XML and unescape using XSLT I am calling a web service that embeds the response XML as escaped XML.
I'm receiving the complete SOAP response, but am only interested in the escaped XML.
I would like to get the information recived in the escaped XML and put it in some tags.
Response from the Web Service:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
    <ns1:getListReturnsResponse xmlns:ns1="http://services.ws.zzz">
        <ns1:out>
            <?xml version="1.0" encoding="UTF-8"?>
            <returns>
                <num_returns>4</num_devoluciones>
                <list_returns>
                    <return>
                        <id_ret>111</id_ret>
                    <return>
                        <id_ret>222</id_ret>
                    </return>
                    <return>
                        <id_ret>333</id_ret>
                    </return>
                    <return>
                        <id_ret>444</id_ret>
                    </return>
                    </return>
                </list_returns>
            </returns>
        </ns1:out>
    </ns1:getListReturnsResponse>
</soap:Body>

With this response, i want to get the information in the escaped XML.
The XSLT that i'm using:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://services.ws.zzz">
<xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"/>

<xsl:template match="//ns1:out">
    <xsl:value-of select="." disable-output-escaping="yes" />
        <output-parms>
            <num-returns-out><xsl:value-of select="num_returns/text()"/></num-returns-out>
        </output-parms>
</xsl:template>

With this, I need to have the result returned in the num_returns> tag of the XML escaped in  as here:
<output-parms>
    <num-returns-out>4</num-returns-out>
</output-parms>

Help me please!! ;)
Thanks to all

A: With XSLT-1.0 you have to do this in two steps:

*

*Extract the escaped XML, for example with this template
<xsl:template match="//ns1:out">
    <xsl:value-of select="normalize-space(.)" disable-output-escaping="yes" />
</xsl:template>

Notes:

*

*You cannot use xsl:for-each on the escaped XML like you did above.

*disable-output-escaping is not implemented by all XSLT processors, because this is optional. If it didn't work at all, this could be the reason why.

*Your escaped XML is not well-formed. The last </return> is erroneous and num_returns is closed with a num_devoluciones. There are also other errors in it, so the output must be sanitized before proceeding with step 2.

*Transform the output again to extract the elements you want:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="/returns">
    <output-parms>
        <num-returns-out><xsl:value-of select="num_returns/text()"/></num-returns-out>
    </output-parms>
  </xsl:template>

</xsl:stylesheet>

Output is:
<output-parms>
  <num-returns-out>4</num-returns-out>
</output-parms>

If you can use an XSLT-3.0 processor, you can make use of the XPath-3.0 parse-xml function and achieve this in one step easily:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://services.ws.zzz">
<xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*" />

    <xsl:template match="//ns1:out">
        <xsl:variable name="innerXML" select="parse-xml(.)" />
        <xsl:element name="output-parms">
            <xsl:copy-of select="$innerXML/returns/num_returns" />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>


text:
Q: Websocket over MQTT by Mosquitto 1.6.10 I have problem with using Websocket on MQTT by Mosquitto.
I'm using raspberry pi as a broker, and want to publish some information, subscribe on web.
Former method (in 1.4.10 version etc.) is to add those two lines
====================
listener 9001
protocol websockets
====================
in /etc/mosquitto/mosquitto.conf or /etc/mosquitto/conf.d/(certain .conf file)
and modify allowance about Websocket in config.mk to [yes]
but in 1.6.10 version, perticularly in raspberrypi, I can't find
the config.mk file so it doesn't works.
Can anybody tell me where's config.mk or if there's any other method to use Websocket on rasp.pi?


text:
Q: BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'search' App.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="." method="post">
        Search: <input type="text" name="search">
        <input type="submit" value="Show">
   </form>
</body>
</html>

main.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/CmpPr')
def cmpP():
    return render_template('CmpPr.html')

@app.route('/CmpSpes')
def cmpS():
    return render_template('CmpSpes.html')

@app.route('/App', methods=['POST', 'GET'])
def App():
    search = request.form['search']
    return render_template('output.html', n=search)

@app.route('/Gro')
def Gro():
    return render_template('Gro.html')

if __name__ == '__main__':
   app.run(debug=True)

I have created multiple html pages
I want to print the message, request from TextBox(above code) and print to another html page
I tried using request.form.get('search') but its returning null
And if I use request.form.get('search', FALSE or TRUE) it returns FALSE or TRUE
I have also used if else loop to specify GET and POST method, still it shows the same error
Can anyone please help me on this
Thank You

A: Firstly, your form action should point to the view that handle the form data (i.e. /App):
<form action="/App" method="post">

Secondly, you should only obtain the form data when the request's method is POST, since you have set method="post" in the template. Also, you will need to render the App.html that contains the form when request method is GET:
@app.route('/App', methods=['POST', 'GET'])
def App():
    if request.method == 'POST':  # get form data when method is POST
        search = request.form['search']
        return render_template('output.html', n=search)
    return render_template('App.html')  # when the method is GET, it will render App.html

P.S. The error you got is explained clearly that there isn't a key called search in the form data.


text:
Q: Error messages when installing OSMnx and GeoPandas Hello I am trying to install OSMnx and GeoPandas using pip install osmnx and pip install geopandas (according to this link: https://geoffboeing.com/2016/11/osmnx-python-street-networks/) It says that in order to use OSMnx you have to install geopandas and rtree first, rtree was installed with no issues, but this happened when trying to install osmnx (actually I tried to install osmnx before I found out that I need to install geopandas, I am giving this error here in order to give you as much information as possible)
ERROR: Command errored out with exit status 1:
 command: 'c:\users\hodor\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Hodor\\AppData\\Local\\Temp\\pip-install-m1_7rif2\\Shapely\\setup.py'"'"'; __file__='"'"'C:\\Users\\Hodor\\AppData\\Local\\Temp\\pip-install-m1_7rif2\\Shapely\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Hodor\AppData\Local\Temp\pip-install-m1_7rif2\Shapely\pip-egg-info'
     cwd: C:\Users\Hodor\AppData\Local\Temp\pip-install-m1_7rif2\Shapely\
Complete output (9 lines):
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\Hodor\AppData\Local\Temp\pip-install-m1_7rif2\Shapely\setup.py", line 80, in <module>
    from shapely._buildcfg import geos_version_string, geos_version, \
  File "C:\Users\Hodor\AppData\Local\Temp\pip-install-m1_7rif2\Shapely\shapely\_buildcfg.py", line 200, in <module>
    lgeos = CDLL("geos_c.dll")
  File "c:\users\hodor\appdata\local\programs\python\python37\lib\ctypes\__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] Given module was not found
----------------------------------------

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
What shall I do (I do NOT want to install anaconda, so if there is a way of avoiding anaconda I would be very happy)?
Any help appreciated, thank you very much
EDIT: OK I tried the steps explained in the question mentioned as a duplicate of my question, I was able to install fiona following these steps but when I typed pip install geopandas I got this new error:
ERROR: Command errored out with exit status 1:
 command: 'c:\users\hodor\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Hodor\\AppData\\Local\\Temp\\pip-install-5yg59bp6\\shapely\\setup.py'"'"'; __file__='"'"'C:\\Users\\Hodor\\AppData\\Local\\Temp\\pip-install-5yg59bp6\\shapely\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Hodor\AppData\Local\Temp\pip-install-5yg59bp6\shapely\pip-egg-info'
     cwd: C:\Users\Hodor\AppData\Local\Temp\pip-install-5yg59bp6\shapely\
Complete output (9 lines):
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\Hodor\AppData\Local\Temp\pip-install-5yg59bp6\shapely\setup.py", line 80, in <module>
    from shapely._buildcfg import geos_version_string, geos_version, \
  File "C:\Users\Hodor\AppData\Local\Temp\pip-install-5yg59bp6\shapely\shapely\_buildcfg.py", line 200, in <module>
    lgeos = CDLL("geos_c.dll")
  File "c:\users\hodor\appdata\local\programs\python\python37\lib\ctypes\__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] Uvedený modul nebyl nalezen
----------------------------------------

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
EDIT 2: Even though the cmd wrote "succesfully installed fiona" when I tried to run simple Attempt.py
import fiona

I got this message:
Traceback (most recent call last):
  File "c:\Users\Hodor\.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\Hodor\.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 432, in main
    run()
  File "c:\Users\Hodor\.vscode\extensions\ms-python.python-2019.10.41019\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Hodor\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Hodor\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Hodor\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\Users\Hodor\Desktop\Untitled-1.py", line 1, in <module>
    import fiona
  File "C:\Users\Hodor\AppData\Local\Programs\Python\Python37\lib\site-packages\fiona\__init__.py", line 87, in <module>
    from fiona.collection import BytesCollection, Collection
  File "C:\Users\Hodor\AppData\Local\Programs\Python\Python37\lib\site-packages\fiona\collection.py", line 9, in <module>
    from fiona.ogrext import Iterator, ItemsIterator, KeysIterator
ImportError: DLL load failed: Module not found

This may also help with troubleshooting of my issue

A: It can be really difficult to install the geospatial dependencies with pip, primarily due to Fiona in my experience. If you can use conda, it's strongly recommended to follow the install instructions in the OSMnx documentation

If you have any trouble with the installation, try installing OSMnx in a new, clean conda environment using conda-forge and strict channel priority:

conda config --prepend channels conda-forge
conda create -n ox --strict-channel-priority python=3 osmnx


text:
Q: ClassCastException on reload when I edit my code and reloade the play tab on localhost:3001/@tests I always get
ClassCastExceptions when I attempt to run a test.
E.g. (just an example, but you can substitute TestClass for any class)
A java.lang.ClassCastException has been caught, Cannot cast TestClass to TestClass

This is seriously slowing down the development. Are there any solutions to that?
play version "1.2.3"
java version "1.6.0_23"
OpenJDK Runtime Environment (IcedTea6 1.11pre) (6b23~pre11-0ubuntu1.11.10.2)
OpenJDK 64-Bit Server VM (build 20.0-b11, mixed mode)

A: This seemingly bogus exception can be caused by the two objects coming from two differect packages ( com.pack0000.TestClass & com.pack1111.TestClass ) or in a single package but loaded by two different classloaders or the class existing in two different jars.  On the line before the exception, print out xxx.getClass().getCanonicalName() and xxx.getClass().getClassLoader() for both and see if that sheds any light.


text:
Q: How do stop a CSS file from rendering with jQuery? I am building a website on a Sharepoint server that has specific CSS files rendering that I cannot access or remove. Is it possible with jQuery to remove these style sheets from the DOM before rendering ? or can I specify certain elements on the page to only adhere to specific css styles without rendering others from this file ?

A: Is there a reason you want to use JQuery over plain Javascript?
You can use this Javascript to replace an external stylesheet.
function createjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 return fileref
}

function replacejscssfile(oldfilename, newfilename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
   var newelement=createjscssfile(newfilename, filetype)
   allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
  }
 }
}

replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js"
replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css"

Read more on this page.

A: This code disabled the stackoverflow stylesheet in the Firebug console.
var href = "http://sstatic.net/stackoverflow/all.css?v=84b08398d3dc";
jQuery('link[rel=stylesheet][href="' + href + '"]').get(0).disabled = true

As with all javascript, it could done without jQuery.  And I'm assuming that you have a good reason for resorting to a javascript solution when the obvious way to disable a stylesheet is to remove the reference in the HTML.
(Adapted from this post, which shows how to switch stylesheets using jQuery.)

A: You mentioned not having access to removing the CSS files from SharePoint...
Does that mean you don't have access rights to the Masterpage file? I'd recommend trying to edit the masterpage if at all possible before using a jQuery workaround.
If you can gain access to the Masterpage, you can remove references to the Sharepoint specific CSS files there.
in Sharepoint Designer

*

*_catalogs

*

*masterpage (Master Page Gallery)

*

*[YourMasterPageFile]

remove the following from <head>:
<Sharepoint:CssLink runat="server"/>


text:
Q: Appcelerator Studio Corporate Proxy I have been having trouble with the latest Appcelerator Studio behind a corporate proxy.

*

*I have tried manually entering my credentials into the studio preferences.

*I have tried using cntlm and pointing the studio to that.

I keep getting locked out of my account.
Has anyone had any luck doing this?

A: If you haven't already found a solution, I have found this to work with Appcelerator CLI:
Activate Authenticated Proxy Usage
appc config set proxyServer http://DOMAIN%5CUSERNAME:PASSWORD@PROXY_SERVER:PROXY_PORT

Deactivate Proxy Usage
appc config set proxyServer

Replace DOMAIN, USERNAME and PASSWORD with your authentication credentials.
  Replace PROXY_SERVER with the domain name or ip address of your proxy server
  Replace PROXY_PORT with the port that your proxy is listening on.