text:
Q: API returns array of objects when retrieving all records but only a single object when filtering First of all I am very new to all this. I have a simple CRUD MERN stack app that outputs an unordered list of entries from a database using .map. I am trying to implement a input box that can be used to filter the list based on a parameter. Everything works fine when all results are retrieved however when only 1 result is retrieved I am getting an error that .map is not a function.
TypeError: missions.map is not a function
MissionsList.render
src/Components/missionList.js:121
  118 |
All data is test data only

  119 |
  120 |
> 121 |

      | ^  122 |   {missions.map((mission, index) => (
  123 |
 {
> 77 |       this.setState({ missions: response.data });
     | ^  78 |       console.log(response.data);
  79 |     })
  80 |     .catch(e => {

Looking at the console I can see that the API is working and I can see when all results are retrieved I am getting back an array of objects and when I only retrieve one result I am getting back just an object. I know that this is why it is breaking because .map only works for arrays but I dont know how to fix it.
Here is the code for the input box and the functions called

      <input
        type="text"
        className="form-control"
        placeholder="Search by Msn Number"
        value={searchMsn}
        onChange={this.onChangeSearchMsnNumber}
      />

        <button
          className="btn"
          type="button"
          onClick={this.searchMsn}
        >
          Search
        </button>

  retrieveMissions() {
    MissionDataService.getAll()
      .then(response => {
        this.setState({ missions: response.data });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  searchMsn() {
    MissionDataService.get(this.state.searchMsn)
      .then(response => {
        this.setState({ missions: response.data });
        console.log(response.data);
      })
      .catch(e => {
        console.log(e);
      });
  }

  onChangeSearchMsnNumber(e) {
    const searchMsn = e.target.value;
    this.setState({
      searchMsn: searchMsn
    });
  }

Here is the http.get code
   get(msnNumber) {
      return http.get(`/missions/${msnNumber}`);
    }

Here is the API side of the code
router.get('/:msnNumber', function(req, res, next) {
  Mission.findOne({msnNumber: req.params.msnNumber}, function(err, foundMission){
    if (foundMission) {
      res.send(foundMission);
    } else {
      res.send("No missions matching that mission number were found");
    }
  });
});

Any help would be greatly appreciated.

A: I was able to fix this by using Mission.find instead of findOne. It seems that find returns an array of objects even if there is only one result while findOne always just returns an object.


text:
Q: Losing variable. Element is undefined in VARIABLES We are getting this error in both ColdFusion 9 and ColdFusion 11 servers in production. I originally thought is related to ColdFusion 9 and JavaHeap space or not enough memory. We moved this process to run on a brand new server (ColdFusion 11) where nothing else is running and has a lot of memory and we still get the error. Here is some of the code for this cfm page:
<cfset variables.email_count = 0>

<cfoutput query="getOrdersForNotification" group="order_id">

    <cfset variables.inv = "">
    <cfset variables.usePdf = false>
    <cfif isDefined("application.feature_list_using_pdf_attachment")
            and listFindNoCase(application.feature_list_using_pdf_attachment, "injection scheduler", ",")
        >
        <cfset variables.usePdf = true>
    </cfif>

    <cfthread name="InjectionSchdEmail#dateFormat(now(), 'mmdd')#_#timeFormat(now(), 'HHmmss')#_#getOrdersForNotification.order_id#"
        threadOrderId="#getOrdersForNotification.order_id#"
        threadMemberId="#getOrdersForNotification.member_id#"
        threadNotificationEmail="#getOrdersForNotification.notification_email#"
        threadDateReq="#getOrdersForNotification.date_req#"
        threadStoreCode="#getOrdersForNotification.store_code#"
        threadStoreName="#getOrdersForNotification.store_name#"
        threadToGoLabel="#application.togo_label#"
        threadOrderTotal="#getOrdersForNotification.order_total#"
        threadDelTimeValueFront="#getOrdersForNotification.del_time_value_front#"
        threadSubject="#variables.subjectAndBodyTemplates.subject#"
        threadBody="#variables.subjectAndBodyTemplates.body#"
        threadFromEmail="#variables.fromEmail#"
        threadLocalNow="#variables.localNow#"
        threadLocalNowInt="#variables.localNowInt#"
        threadDs="#ds#"
        threadUsePdf="#variables.usePdf#"
        >
        <cftry>
            <cfset url.order_id = threadOrderId>
            <cfset url.member_id = threadMemberId>
            <cfsavecontent variable="variables.inv">
                <cfinclude template="invoicedeska.cfm">
            </cfsavecontent>

            <cfset variables.order_day=dateFormat(application.UdfService.toSlashDate(threadDateReq), 'mmm dd')>

            <cfset local.subject = threadSubject>
            <cfset local.subject = ReplaceNoCase(local.subject, "[Store Code]", threadStoreCode, "all")>
            <cfset local.subject = ReplaceNoCase(local.subject, "[Takeout Label]", threadToGoLabel, "all")>
            <cfset local.subject = ReplaceNoCase(local.subject, "[Order ID]", threadOrderId, "all")>
            <cfset local.subject = ReplaceNoCase(local.subject, "[Order Total]", NumberFormat(threadOrderTotal,"9,999.99"), "all")>
            <cfset local.subject = ReplaceNoCase(local.subject, "[Required Time]", threadDelTimeValueFront, "all")>
            <cfset local.subject = ReplaceNoCase(local.subject, "[Required Date]", variables.order_day, "all")>

            <cfset local.body = threadBody>
            <cfset local.body = ReplaceNoCase(local.body, "[Store Code]", threadStoreCode, "all")>
            <cfset local.body = ReplaceNoCase(local.body, "[Store Name]", threadStoreName, "all")>
            <cfset local.body = ReplaceNoCase(local.body, "[Order ID]", threadOrderId, "all")>
            <cfset local.body = ReplaceNoCase(local.body, "[Order Total]", NumberFormat(threadOrderTotal,"9,999.99"), "all")>
            <cfset local.body = ReplaceNoCase(local.body, "[Required Time]", threadDelTimeValueFront, "all")>
            <cfset local.body = ReplaceNoCase(local.body, "[Required Date]", variables.order_day, "all")>
            <cfset local.body = "#application.UdfService.multiLiner(local.body)#">

            <cfif threadUsePdf>

                <cfdocument
                    format="PDF"
                    name="variables.attachment"
                    localURL="#application.pdf_localURL#"
                    orientation="#application.pdf_orientation#"
                    marginleft="#application.pdf_marginleft#"
                    marginright="#application.pdf_marginright#"
                    margintop="#application.pdf_margintop#"
                    marginbottom="#application.pdf_marginbottom#"
                    unit="#application.pdf_unit#"
                    scale="#application.pdf_scale#"
                >
                    #variables.inv#
                </cfdocument>
            <cfelse>

                <cfset variables.attachment = variables.inv>
            </cfif>

            <cfmail to="#threadNotificationEmail#" from="#threadFromEmail#" subject="#local.subject#" type="html">
                #local.body#
                <cfif isDefined("variables.attachment") and threadUsePdf eq false>
                    <cfmailparam
                        file="invoice_#threadOrderId#_#threadLocalNowInt#.html"
                        type="application/html"
                        content="#variables.attachment#"
                        />
                <cfelseif isDefined("variables.attachment") and threadUsePdf>
                    <cfmailparam
                        file="invoice_#threadOrderId#_#threadLocalNowInt#.pdf"
                        type="application/pdf"
                        content="#variables.attachment#"
                        />
                </cfif>
            </cfmail>

            <cfset invoice_emailed = application.MessageService.setEmailedInvoice(orderId = threadOrderId, localNow = threadLocalNow, emailAddress = threadNotificationEmail, datasource = threadDs)>

            <cfcatch type="any">
                <cfset variables.attachment = "">
                <cfmail from="erroralerts@monkeymediasoftware.com" to="erroralerts@monkeymediasoftware.com" type="html" subject="POS injection notification email faliure">
                    <cfif isDefined("cgi.server_name")>
                        Server: #cgi.server_name#
                    </cfif>
                    <cfdump var="#cfcatch#" label="cfcatch">

                    <cfdump var="#threadOrderId#" label="threadOrderId">

                    <cfdump var="#threadMemberId#" label="threadMemberId">

                    <cfdump var="#threadNotificationEmail#" label="threadNotificationEmail">

                    <cfdump var="#threadDateReq#" label="threadDateReq">

                    <cfdump var="#threadStoreCode#" label="threadStoreCode">

                    <cfdump var="#threadStoreName#" label="threadStoreName">

                    <cfdump var="#threadToGoLabel#" label="threadToGoLabel">

                    <cfdump var="#threadOrderTotal#" label="threadOrderTotal">

                    <cfdump var="#threadDelTimeValueFront#" label="threadDelTimeValueFront">

                    <cfdump var="#local.subject#" label="local.subject">

                    <cfdump var="#local.body#" label="local.body">

                    <cfdump var="#threadFromEmail#" label="threadFromEmail">

                    <cfdump var="#threadLocalNow#" label="threadLocalNow">

                    <cfdump var="#threadLocalNowInt#" label="threadLocalNowInt">

                    <cfdump var="#threadDs#" label="threadDs">

                    <cfdump var="#threadUsePdf#" label="threadUsePdf">

                    <cfdump var="#variables.inv#" label="variables.inv">

                </cfmail>
                <cfrethrow />
            </cfcatch>
        </cftry>
    </cfthread>

    <cfset variables.email_count = variables.email_count + 1>
</cfoutput>

<cfoutput>#variables.email_count# emails sent @ #local_now()#</cfoutput>

Error:

Element EMAIL_COUNT is undefined in VARIABLES.
  The error occurred on line

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I nest a linear layout inside a relative layout to achieve the desired UI experience? I am trying to get the following look (screenshot from my iOS app) on the Android version of my app.

I have defined my layout file as follows in Android:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/postTextTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/shareLILayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:gravity="top|left|start"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:id="@+id/shareLILayout"
        android:layout_alignParentBottom="true"
        android:background="#999999"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal" >

        <ImageButton
            android:contentDescription="@string/li_btn_desc"
            android:id="@+id/postToLIButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="5dp"
            android:background="@android:color/transparent"
            android:src="@drawable/linkedin_switch_off" />

        <TextView
            android:id="@+id/postToLITextView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/share_on_linkedin"
            android:layout_gravity="center_vertical"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="14sp" />

    </LinearLayout>
</RelativeLayout>

If I swap my ImageButton and TextView above, my app just crashed with a RuntimeException! Also I am not able to center the text so that its aligned to the center of the button. What am I doing wrong?

A: Simply swap the ImageButton and TextView order. Your runtime error is either unrelated or is caused by the need to clean your project before you need to redeploy it (sometimes resource IDs get funky). Also use android:gravity="center_vertical" for you TextView to center it properly


text:
Q: Can there be multiple font-sizes within one 's value Is there a way to do something like this?
<input value="small text
       BIG TEXT"
       type="text" />

This code doesn't work. But can I mimic this?

A: Mixing styles within a textbox is not possible with pure HTML and CSS. What you'll need to look for is a third-party control for richtextbox.  Just Google your platform (PHP or ASP.NET) to find one to your liking.


text:
Q: Bootstrap HTTPS and IE8 I am currently working on payment system and we are using bootstrap framework to develop the front end. All the testing is done on local environment and we moved our new project to staging environment and now facing issue on IE8. Layout is not rendering correctly on IE8. there is only 1 different I found between local and staging is the HTTP and HTTPS protocol. Below is my Header section and I am quite sure we have this issue because of the Secure environment. Has anyone had a similar issue ?

<!--[if (gte IE 6)&(lte IE 8)]>
<script src="https://www.example.com/javascript/selectivizr.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
<script src="https://www.example.com/javascript/html5shiv.min.js"></script>
<script src="https://www.example.com/javascript/respond.min.js"></script>
<![endif]-->

<!--[if IE 8]>
<link  href="https://www.example.com/css/bootstrap.css"  rel="stylesheet" type="text/css" media="screen"/>
<![endif]-->

<link href="https://cdn.example.com/css/index.min.css" type="text/css" rel="stylesheet" />

<!--[if IE 8]>
<link rel="stylesheet" type="text/css" media="screen" href="https://www.example.com/css/index_ie8.css"/>
<![endif]-->

https://cdn.example.com/css/index.min.css includes Bootstrap CSS + Main CSS


text:
Q: Filter a spark dataframe based on column datatypes I have a dataframe with col_a and col_b and both are written as "String" in the parquet file I receive. col_b could be an int or a string and I want to filter out all rows where col_b is not an int.
Input:
col_A   col_b
1       "abc"
2       "3"
3       "xyz"

Output:
col_a   col_b
2       3

I understand I need to typecast, but not sure how to proceed beyond that

A: UDF is really not required here. You can cast the column as int and it will return null wherever it fails and then filter the non-null rows.
val df = Seq((1, "abc"),
             (2, "3"),
             (3, "xyz")).toDF("col_a", "col_b")

df.filter( $"col_b".cast("int").isNotNull ).show

//+-----+-----+
//|col_a|col_b|
//+-----+-----+
//|    2|    3|
//+-----+-----+

A: You can use filter operation on your dataframe for filtering the non Integer values. Create a UDF that will accept the column value and returns true if the value can be converted to Int else it returns false.
//your original DF
val df = Seq((1, "abc"),
  (2, "3"),
  (3, "xyz")).toDF("col_a", "col_b")

//create a udf for filter function
val isValueInt = udf((value: String) => Try(value.toInt).isSuccess)

//apply the filter on DF
df.filter(isValueInt($"col_b")).show(false)

//    output
//    +-----+-----+
//    |col_a|col_b|
//    +-----+-----+
//    |1    |3    |
//    +-----+-----+


text:
Q: Iterate through updating F# Map vs a C# Dictionary I have a collection of key/value pairs contained inside an F# Map
type node = {myFloat:float, data1:int; data2:int;}
type nodesCollection = {metaData:int nodes:Map<float,node>}

let results = processData (nodes:Map<float,node>)

The function processData returns a list of tuples  with the following signature
val results : (node * int * int * int * int) List

I would like to:

*

*Only work with the first item of the tuple (i.e. node)

*Iterate through either the key/value pairs in the Map or the list of nodes

*Replace the node values in the Map with those if the list in the key exist in both

*If the key doesn't exist in the Map added the node from the list to the Map

*Return the updated Map

Ignoring the fact that the returned tuple needs to be parsed, I would do something like this in C# if I was using a Dictionary<float,node>
foreach newNode in nodesInList
{
  if (nodesCollection.nodes.Contains(newNode.myfloat))
     nodesCollection.nodes[newNode.myfloat] = node
  else
     nodesCollection.nodes.Add(newNode.myfloat, node);
}

return nodesCollection.nodes

How would I approach this using a Map and functional style?

A: Fold is a general technique to manipulate state in an immutable iterative/recursive way. If you want to experiment with it in C# it's the Aggregate LINQ extension method.
In F# Map.add is actually add/replace, so you don't need to branch based on whether the key is contained.
type node = {myFloat:float; data1:int; data2:int;}
type nodesCollection = {metaData:int; nodes:Map<float,node>}

let nodeColl = { metaData = 5; nodes = Map.empty }
let results : (node * int * int * int * int) List = []

let nodes = List.map (fun (n, _, _, _, _) -> n) results

let res = List.fold (fun map e -> Map.add e.myFloat e map) nodeColl.nodes nodes


text:
Q: Magento 1.9 : How to cache custom module or extension I never worked to cache Magento modules before. Now going to do for the first time so i have three questions regarding cache.

*

*What are the complete steps to cache a module?

*Any caching types are there?

*What are the pros & cons for this?

Can anyone help on this please.

A: *

*Not sure what you mean by caching a module. You don't cache a module, you cache a module's data - which can be anything from text, to json, html, objects, etc.

Usually, blocks & collection data should be cached, but you can cache anything else using Mage::app()->saveCache() and Mage::app()->loadCache(). Check the methods for the required parameters.
Blocks can be easily cached by extending Mage_Core_Block_Abstract and implementing the getCacheKeyInfo method - check the abstract class for more caching options.
Same for collections, see Mage_Core_Model_Mysql4_Collection_Abstract for more details - look for _canUseCache()

*Not sure what you mean by this. Magento uses various cache tags, but you're not bound to those, you can add any tag you like. Also, cache backends vary from files to memcached and redis, it's up to you which one you use.

*Pro's and con's for using caching? You should always cache operations that might take a long time to process, mostly those that are executed often and produce the same result. This is not really a magento question, it's more about application architecture, performance optimization and the desire to create a solid extension. try searching for "when should i cache data" on google.
Ultimately, look at the magento core code and see when they cache things and try to figure out why.


text:
Q: Initiate lazyload on button click I'm trying to get this to work when a button is clicked. The purpose of this is a simple lightweight lazyload which works when a filter button is clicked.
At the moment I'm unable to get this to work with a button.

Default

Most Popular (1 - 10)

Most Popular (10 - 1)

Name Ascending (a - z)

Name Descending (z - a)

Random


text:
Q: get inputStream from zipFile then add to another zipFile getting null pointer exception I'm trying to get input stream from zip file then add it to another zip file but it throws null pointer exception.
here is my code.
       ZipParameters parameters = new ZipParameters();
       ZipFile newZipFile = new ZipFile(new File(CacheDir, "temp.card"));
       File temp = new File(CacheDir, "tempFile");
        if (!temp.exists()) {
                temp.createNewFile();
        }
       newZipFile.createZipFile(temp, parameters);
       if(newZipFile.getFile().exist()){
       if (string != null) {
            inputStream = zipFile.getInputStream(zipFile.getFileHeader(string));
       }
       if (inputStream != null) {
            newZipFile.addStream(inputStream,parameters);
       }
       }

non of objects in this scope are null.
but I'm getting exception here:
newZipFile.addStream(inputStream,parameters);

Log:
12-14 06:27:43.891: W/System.err(2197): net.lingala.zip4j.exception.ZipException: input file is null
12-14 06:27:43.891: W/System.err(2197):     at net.lingala.zip4j.io.CipherOutputStream.putNextEntry(CipherOutputStream.java:71)
12-14 06:27:43.895: W/System.err(2197):     at net.lingala.zip4j.io.DeflaterOutputStream.putNextEntry(DeflaterOutputStream.java:45)
12-14 06:27:43.895: W/System.err(2197):     at net.lingala.zip4j.zip.ZipEngine.addStreamToZip(ZipEngine.java:230)
12-14 06:27:43.895: W/System.err(2197):     at net.lingala.zip4j.core.ZipFile.addStream(ZipFile.java:395)

A: Tracing that exception to its origin, I found in the source code of zip4j that
if (!zipParameters.isSourceExternalStream() && file == null) {
    throw new ZipException("input file is null");
}

So the quick fix is to bypass that check by
parameters.setSourceExternalStream(true);

P.S.: I have no idea what externalStream means, but it worked


text:
Q: Choosing MongoDB collections structure for similar data structures What is the better way to store similar structures in MongoDB? Choose one collections for all or one for each structure? Any benefits of having one/few?
For example, I have to store some logs, for further analytics. There is a common part for each structure and some data specific for some stat type, like:
{
  timestamp: ...,
  client: { ... },
  type: 'stats_for_item1',
  data: {
     id: ObjectId('xxx'),
     field1: 1,
     field2: 2
  }
},
{
  timestamp: ...,
  client: { ... },
  type: 'stats_for_item2',
  data: {
     id: ObjectId('zzz'),
     field3: 3,
     field4: {
        field5: [5, 1]
     }
  }
}

As you see we have common part, and data field, with few different fields for item1 and item2.
Seems that only timestamp and type fields will be indexed (and _id of course). And there is limited number of such items, say 3 item types in total. There will be a lot of writes, and small amount of reads
So, my question, how to organize such structures? Use one big collection stats and store everything there? ot create few collections stats_item1, stats_item2 and stats_item3. What is optimal? Any benefits? From mongo perspective, for sharding/indexing/querying/locking/etc?

A: I would probably keep one collection. In the case you do get another stat-type later, you don't have to re-architect your code around the new collection that you then have to be adding.  You can search specifically on items where you have a specific type by creating an index on "type", but you can also search through all items because you have them all in a collection with an index on "timestamp". (Please note that MongoDB also adds an _id field to every document, and to that one it will add an index too).
For sharding, you will need to pick a key per collection. I don't know what your write/read ratios are and how you intent to read data, but I suspect you're doing some sort of logging with some analysis later. In that case, perhaps a shard key on "client" makes most sense. timestamp is probably going to be a poor choice as it'd force all writes unto one shard.
The difference between one or three collections for locking doesn't make a lot of difference, as right now mongoDB doesn't do locking per collection (just per server instance with lock yielding in 2.0, and per-DB with lock yielding in the upcoming 2.2).
cheers,
Derick


text:
Q: SmalltalkHub versus SqueakSource3 With the next closing of SqueakSource repository, I wonder what is the advantage of SmalltalkHub over SqueakSource3. Is there some feature missing in SqueakSource3?
I have noticed that basic functionality like explore projects seems broken in SmalltalkHub, which is understandable because it is still in beta, but why to move or register projects to SmalltalkHub then?

A: Pharo's core development happens completely on SmalltalkHub.
It is much faster than SqueakSource3, which is the main point in favor of it. SmalltalkHub is still being extended and new features are on the way. For a typical use case from the image side there is little or no difference between the two.

A: SmalltalkHub is faster than SS3. It has a new look. You can manage team and collaborators with a modern interface. Nicolas Petton uses it daily for work and in addition it will continue to enhance it. All the Pharo core packages are hosted there. Finally, you can also easily install and use SmalltalkHub in your company if you need it. The software stack behind SmalltalkHub is really robust and nice. Several companies uses it for other projects.

A: From a risk-avoidance POV, there is something to be said for storing them in both. Their software stacks and feature sets are sufficiently different. Just make sure you identify one as primary. Copying the monticello files from one repository to the other is easily automated. Stef provided some scripts to copy whole projects from squeaksource to smalltalkhub recently, they would equally well work for canary or ss3.


text:
Q: Design Problem - Is Inheritance the right way to simplify this code? I have a design problem I'd like to solve.
I have an interface, lets call it IProtocol, which is implemented by two separate classes. We're looking at over 600 lines of code here. The vast majority of the stuff they do is the same, except for some specific areas, like DiffStuff();
Current structure is something like this:
public class Protocol1 : IProtocol
{
  MyInterfaceMethod1()
  {
     Same1();
     DiffStuff();
     Same2();
  }
}

And

public class Protocol2 : IProtocol
{
  MyInterfaceMethod1()
  {
     Same1();
     Same2();
  }
}

I'm concerned with having copy-paste errors and the classic problem of code duplication if I keep the two protocols separate. We're talking about a full 600 lines of code each, not some simple methods.
I'm considering changing the implementation of Protocol1 to inherit from protocol2, like this (Protocol2 would mostly stay the same, except I'd have to wrap Same1() and Same2() into private methods.)
public class Protocol1 : Protocol2
{
  void Same1()
  {
     base.Same1();
  }

  void Same2()
  {
     base.Same2();
  }

  MyInterfaceMethod1()
  {
     Same1();
     DiffStuff();
     Same2();
  }
}

Is this the right way to go about dealing with this problem?
Edit:
Many people helped me with this question, thanks for the clear understanding. In my case, the two objects are not of the same type, even though much of their implementation is shared, so I went with Bobby's suggestion to use abstract base class, creating small methods to encapsulate changes between the classes.  Additional Thanks to:

*

*jloubert

*Hans Passant

*Jeff Sternal

A:     /// <summary>
    /// IProtocol interface
    /// </summary>
    public interface IProtocol
    {
        void MyInterfaceMethod1();
        void Same1();
        void Same2();
    }

then...
public abstract class ProtocolBase : IProtocol
{
    #region IProtocol Members

    public void MyInterfaceMethod1()
    {
        // Implementation elided...
    }

    public void Same1()
    {
        // Implementation elided...
    }

    public void Same2()
    {
        // Implementation elided...
    }

    public abstract void DiffStuff();

    #endregion
}

finally...
public sealed class Protocol1 : ProtocolBase
{
    public override void DiffStuff()
    {
        // Implementation elided...
    }
}

public sealed class Protocol2 : ProtocolBase
{
    public override void DiffStuff()
    {
        // Implementation elided...
    }
}

A: Not quite.  There's no point in adding the Same1 and Same2 methods, you inherit them from ProtocolBase.  And DiffStuff() should be a virtual method so that you can override it and give it different behavior.

A: You're awfully close to describing the template method pattern, which has a long pedigree as an effective solution to problems like yours.
However, you should consider using composition instead of inheritance. The two approaches offer different advantages and disadvantages, but composition is often (usually?) better *:
 public class Protocol {

      private ISpecialHandler specialHandler;

      public Protocol() {}

      public Protocol(ISpecialHandler specialHandler) {
          this.specialHandler = specialHandler;
      }

      void Same1() {}
      void Same2() {}

      public void DoStuff() {
          this.Same1();
          if (this.specialHandler != null) {
              this.specialHandler.DoStuff();
          }
          this.Same2();
      }
 }

Callers can then pass in object instances (strategies) that provide specialized algorithms to handle whatever case is at hand:
 Protocol protocol1 = new Protocol(new DiffStuffHandler());
 protocol1.DoStuff();

*See Patterns I Hate #2: Template Method for a detailed explanation of why composition is usually better than inheritance in your case.

A: I better design (in my opinion)
public abstract class Protocol_common : IProtocol
{
  MyInterfaceMethod1()
  {
     Same1();
     DiffStuff();
     Same2();
  }

  abstract void DiffStuff();

}

public class Protocol1 : Protocol_common
{
  DiffStuff()
  {
      /// stuff here.
  }
}

public class Protocol2 : Protocol_common
{
  DiffStuff()
  {
      /// nothing here.
  }
}

(That's actually more pseudo-code than proper C#, but I hit the high points)

A: You might want to consider whether this type of pattern works:
public class ProtocolHelper
{
    public void Same1() {}
    public void Same2() {}
}

public class Protocol1 : IProtocol
{
    private readonly ProtocolHelper _helper = new ProtocolHelper();

    void MyInterfaceMethod1()
    {
        _helper.Same1();
        DiffStuff();
        _helper.Same2();
    }
}

You can tell if this makes sense by seeing if you can come up with a good name for the 'ProtocolHelper' class.  If a name naturally arises from your logic, then this is a good way to break up the class.  You might need to pass in some dependencies (such as private fields) as parameters to the methods in order to make this work.

A: I agree with MathEpic. I would use Template method pattern.


text:
Q: How to force HTTPS using .htaccess for example.com? I want to force https for a site, but it only works if i type www.example.com, and not when i use example.com. Here is my htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Can you guys help me with that?

A: Then put these lines above HTTPS condition
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ "https\:\/\/example\.com\/$1" [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


text:
Q: Compare Products link or button does not work in Magento 1.9.3.2
Compare Products link or button does not work in Magento 1.9.3.2
i have added product comparison link doesn't work. This is in Magento
  1.9.3.2 My issues are almost identicalto this post, with the exception that clearing the index did not work. Is there anything else I can
  try?
Here are the issues: When I click "Add to Compare" on a product, a
  message stating that "such-and-such product successfully added to
  compare list" appears.However the compare products sidebar shows "You
  have no items to compare."but it's not working any more.

A:
It looks like your Magento DB does not have
  report_compared_product_index table.
Import the following SQL to create this table structure in your DB.

CREATE TABLE IF NOT EXISTS `report_compared_product_index` (
`index_id` bigint(20) unsigned NOT NULL COMMENT 'Index Id',
  `visitor_id` int(10) unsigned DEFAULT NULL COMMENT 'Visitor Id',
  `customer_id` int(10) unsigned DEFAULT NULL COMMENT 'Customer Id',
  `product_id` int(10) unsigned NOT NULL COMMENT 'Product Id',
  `store_id` smallint(5) unsigned DEFAULT NULL COMMENT 'Store Id',
  `added_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Added At'
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='Reports Compared Product Index Table' AUTO_INCREMENT=1 ;

ALTER TABLE `report_compared_product_index`
 ADD PRIMARY KEY (`index_id`), ADD UNIQUE KEY `UNQ_REPORT_COMPARED_PRODUCT_INDEX_VISITOR_ID_PRODUCT_ID` (`visitor_id`,`product_id`), ADD UNIQUE KEY `UNQ_REPORT_COMPARED_PRODUCT_INDEX_CUSTOMER_ID_PRODUCT_ID` (`customer_id`,`product_id`), ADD KEY `IDX_REPORT_COMPARED_PRODUCT_INDEX_STORE_ID` (`store_id`), ADD KEY `IDX_REPORT_COMPARED_PRODUCT_INDEX_ADDED_AT` (`added_at`), ADD KEY `IDX_REPORT_COMPARED_PRODUCT_INDEX_PRODUCT_ID` (`product_id`);


text:
Q: Go SQL query inconsistency I am experiencing some really weird inconsistencies when executing queries, and was wondering if anyone knew why.
Imagine I have a struct defined as follows:
type Result struct {
    Afield string      `db:"A"`
    Bfield interface{} `db:"B"`
    Cfield string      `db:"C"`
    Dfield string      `db:"D"`
}

And a MySQL Table with the following cols:
A : VARCHAR(50)
B : INT
C : VARCHAR(50)
D : VARCHAR(50)

The query I would like to execute:

SELECT A, B, C, D FROM table WHERE A="a"

first way it can be executed:
db.Get(&result, `SELECT A, B, C, D FROM table WHERE A="a"`)

second way it can be executed:
db.Get(&result, `SELECT A, B, C, D FROM table WHERE A=?`, "a")

The inconsistencies I am experiencing are as follows: When executing the query the first way, the type of Bfield is int. However, when executing the query the second time, it is []uint8.
This outcome is occurring for example when B is 1.
Why is the type of Bfield different depending on how the query is executed?
connection declaration:
// Connection is an interface for making queries.
type Connection interface {
    Exec(query string, args ...interface{}) (sql.Result, error)
    Get(dest interface{}, query string, args ...interface{}) error
    Select(dest interface{}, query string, args ...interface{}) error
}

EDIT
This is also happening using the Go database/sql package + driver. The queries below are assigning Bfield to []uint8 and int64 respectively.

db is of type *sql.DB

query 1:
db.QueryRow(SELECT A, B, C, D FROM table WHERE A="a").Scan(&result.Afield, &result.Bfield, &result.Cfield, &result.Dfield)
-- > type of Bfield is []uint8
query 2:
db.QueryRow(SELECT A, B, C, D FROM table WHERE A=?, "a").Scan(&result.Afield, &result.Bfield, &result.Cfield, &result.Dfield)
--> type of Bfield is int64
EDIT
Something else to note, when chaining multiple WHERE clauses, as long as at least 1 is populated using ?, the query will return int. Otherwise if they are all populated in the string, it will return []uint8

A: Short answer: because the MySQL driver uses a different protocol for queries with and without parameters. Use a prepared statement to get consistent results.
The following explanation refers to the standard MySQL driver github.com/go-sql-driver/mysql, version 1.4
In the first case, the driver sends the query directly to MySQL, and interprets the result as a *textRows struct. This struct (almost) always decodes results into a byte slice, and leaves the conversion to a better type to the Go sql package. This works fine if the destination is an int, string, sql.Scanner etc, but not for interface{}.
In the second case, the driver detects that there are arguments and returns driver.ErrSkip. This causes the Go SQL package to use a PreparedStatement. And in that case, the MySQL driver uses a *binaryRows struct to interpret the results. This struct uses the declared column type (INT in this case) to decode the value, in this case to decode the value into an int64.
Fun fact: if you provide the interpolateParams=true parameter to the database DSN (e.g. "root:testing@/mysql?interpolateParams=true"), the MySQL driver will prepare the query on the client side, and not use a PreparedStatement. At this point both types of query behave the same.
A small proof of concept:
package main

import (
    "database/sql"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

type Result struct {
    Afield string
    Bfield interface{}
}

func main() {
    db, err := sql.Open("mysql", "root:testing@/mysql")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    if _, err = db.Exec(`CREATE TABLE IF NOT EXISTS mytable(A VARCHAR(50), B INT);`); err != nil {
        log.Fatal(err)
    }
    if _, err = db.Exec(`DELETE FROM mytable`); err != nil {
        log.Fatal(err)
    }
    if _, err = db.Exec(`INSERT INTO mytable(A, B) VALUES ('a', 3)`); err != nil {
        log.Fatal(err)
    }

    var (
        usingLiteral         Result
        usingParam           Result
        usingLiteralPrepared Result
    )
    row := db.QueryRow(`SELECT B FROM mytable WHERE A='a'`)
    if err := row.Scan(&usingLiteral.Bfield); err != nil {
        log.Fatal(err)
    }
    row = db.QueryRow(`SELECT B FROM mytable WHERE A=?`, "a")
    if err := row.Scan(&usingParam.Bfield); err != nil {
        log.Fatal(err)
    }
    stmt, err := db.Prepare(`SELECT B FROM mytable WHERE A='a'`)
    if err != nil {
        log.Fatal(err)
    }
    defer stmt.Close()
    row = stmt.QueryRow()
    if err := row.Scan(&usingLiteralPrepared.Bfield); err != nil {
        log.Fatal(err)
    }

    log.Printf("Type when using literal:  %T", usingLiteral.Bfield)         // []uint8
    log.Printf("Type when using param:    %T", usingParam.Bfield)           // int64
    log.Printf("Type when using prepared: %T", usingLiteralPrepared.Bfield) // int64
}

A: Your first SQL string, in MySql is ambigous and can have too meaning as explained on StackOverflow in following address
When to use single quotes, double quotes, and back ticks in MySQL
Depending on SQL-MODE, your SQL command can be interpreted as
SELECT A, B, C, D FROM table WHERE A='a'

that is what I think you are expecting.
or as
SELECT A, B, C, D FROM table WHERE A=`a`

To avoid this ambiguity, can you make a new FIRST test in replacing double quotes by single quote ?
If the same behavior continue to be there, my answer is not a good response.
If BOTH SQL select return same value, your question has been solved.
Using ` character, you pass a variable name and not a string value !


text:
Q: How to add all missing combination in a dataframe I have a dataframe of around 15000 rows, something like as below,
dataframe =
date        |  value  |  count  |  dayofWeek
01/01/2021  |  250    |   1     |    0
01/01/2021  |  235    |   2     |    0
01/01/2021  |  244    |   3     |    0
..
..
01/01/2021  |  255    |  25     |    0
02/01/2021  |  225    |   1     |    1
02/01/2021  |  230    |   2     |    1
..
..
02/01/2021  |  275    |   20    |    1
03/01/2021  |  265    |   1     |    2
..
..

The dataframe has some missing data for the count.As for each date, there should be 25 count, if the count number is not present, we want to add the data with value-0 , and dayofWeek as per the date. There will be always atleast 10 count present for a specific date.
I don't know where to start as I am new to pandas. Can someone help.

A: Create the complementary dataframe them merge it to your original dataframe
N = 5  # In your case 25

# First find the missing count for each date
cnt = df['date'].value_counts().loc[lambda x: x < N] \
               .apply(lambda x: range(x+1, N+1)).explode()

# Create the dataframe
dfc = pd.DataFrame({'date': cnt.index, 'value': 0, 'count': cnt.values,
                    'dayofWeek': pd.to_datetime(cnt.index, dayfirst=True).dayofweek})

# Concatenate them:
out = pd.concat([df, dfc]).sort_values(['date', 'count']).reset_index(drop=True)

Output:
>>> out
          date  value count  dayofWeek
0   01/01/2021    250     1          4
1   01/01/2021    235     2          4
2   01/01/2021    244     3          4
3   01/01/2021    244     4          4
4   01/01/2021    244     5          4
5   02/01/2021    225     1          5
6   02/01/2021    230     2          5
7   02/01/2021    275     3          5
8   02/01/2021      0     4          5  # <- Added
9   02/01/2021      0     5          5  # <- Added
10  03/01/2021    265     1          6
11  03/01/2021      0     2          6  # <- Added
12  03/01/2021      0     3          6  # <- Added
13  03/01/2021      0     4          6  # <- Added
14  03/01/2021      0     5          6  # <- Added

Setup MRE
data = {'date': ['01/01/2021']*5 + ['02/01/2021']*3 + ['03/01/2021'],
        'value': [250, 235, 244, 244, 244, 225, 230, 275, 265],
        'count': [1, 2, 3, 4, 5, 1, 2, 3, 1],
        'dayofWeek': [4, 4, 4, 4, 4, 5, 5, 5, 6]}
df = pd.DataFrame(data)
print(df)

# Output
         date  value  count  dayofWeek
0  01/01/2021    250      1          4
1  01/01/2021    235      2          4
2  01/01/2021    244      3          4
3  01/01/2021    244      4          4
4  01/01/2021    244      5          4  # <- Full, do nothing
5  02/01/2021    225      1          5
6  02/01/2021    230      2          5
7  02/01/2021    275      3          5  # <- Missing 4 and 5
8  03/01/2021    265      1          6  # <- Missing from 2 to 5


text:
Q: Oracle equivalent to Postgres' @> (contains) function I'm trying to write a conversion from PostgreSQL that will work in Oracle.
My problem is that I am struggling to find an Oracle SQL statement that will replace the Postgres @> (contains) operator.
The query in Postgres reads like this:
CASE
    WHEN descriptivegroup @> '{Building}' AND descriptiveterm IS NULL THEN 'Building Fill'
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm = '{"Multi Surface"}' THEN 'Multi Surface Fill'

etc., meaning that 'Building' or 'General Surface' (in the above example) should be contained within an array called descriptivegroup.
I've been trawling through Stackoverflow and other websites and I think the nearest equivalent I can find for @> in Oracle is 'member of' as in this example:
How to check if an array contains a particular string?
However, I'm struggling to work out how to work a statement like this into a CASE > WHEN type of statement so any help or suggestions that I could get from this community would be gratefully received!
Many thanks.
PS As promised, here is a truncated version of the Postgres query.  This isn't everything as it would be far too big:
CREATE TABLE osmm.topo_area_style AS SELECT
a.*,
CASE
    WHEN descriptivegroup @> '{Building}' AND descriptiveterm IS NULL THEN 'Building

Fill'
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm = '{"Multi

Surface"}' THEN 'Multi Surface Fill'
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm IS NULL AND make

= 'Natural' THEN 'Natural Fill'
    WHEN descriptivegroup @> '{"Road Or Track"}' AND descriptiveterm IS NULL AND make =

'Manmade' THEN 'Road Or Track Fill'
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm IS NULL AND make

= 'Manmade' OR make = 'Unknown' THEN 'Manmade Fill'
    WHEN descriptivegroup @> '{Roadside}' AND make = 'Natural' THEN 'Roadside Natural

Fill'
    ELSE 'Unclassified'
    END AS style_description,
CASE
    WHEN descriptivegroup @> '{Building}' AND descriptiveterm IS NULL THEN 1
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm = '{"Multi

Surface"}' THEN 2
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm IS NULL AND make

= 'Natural' THEN 3
    WHEN descriptivegroup @> '{"Road Or Track"}' AND descriptiveterm IS NULL AND make =

'Manmade' THEN 4
    WHEN descriptivegroup @> '{"General Surface"}' AND descriptiveterm IS NULL AND make

= 'Manmade' OR make = 'Unknown' THEN 5
    WHEN descriptivegroup @> '{Roadside}' AND make = 'Natural' THEN 6
    WHEN descriptivegroup @> '{Roadside}' AND make = 'Manmade' OR descriptivegroup @>

'{Roadside}' AND make = 'Unknown' THEN 7
    ELSE 99
    END AS style_code
FROM osmm.topographicarea as a;

I don't have access to the table that this SQL was written for but as you can see the table being created is a straight copy of the existing table but this code adds another 2 columns which it then populates from the descriptivegroup and descriptiveterm.


text:
Q: How to stop double click event or opening child node when clicking on parent node in jsTree? Here is the JavaScript code to prevent the double click event
$("#jstree_view").on("dblclick", 'li a', function (e) {
    e.preventDefault();
});

but it is not working.

A: set the $.jstree.defaults.core.dblclick_toggle = false
example:
$('#jstree').jstree({
    "core" : {
         "dblclick_toggle" : false
     }
});

jstree API


text:
Q: Distributed computing project to check the convergence of the Collatz problem I am about to start a distributed computing project to check the convergence of the Collatz problem.
So far, the convergence of the problem has been verified for all numbers below $87 \times 2^{60} \approx 2^{66.4}$.
See this question for details.
The algorithm which I intend to use is described here.
After some thought, I have decided to divide the problem into sub-problems, each having the size of $2^{40}$ numbers.
Now I am facing a question of how to verify that each sub-problem has been verified correctly (i.e. the worker does not cheat).
For convenience, the algorithm which verifies a particular $n = n_0$ is as follows:
\begin{align}
\text{repeat} &~ \\
n &← n + 1 \\
\alpha &← \operatorname{ctz}(n) \\
n &← n × 3^\alpha / 2^\alpha \\
n &← n − 1 \\
\beta &← \operatorname{ctz}(n) \\
n &← n / 2^{\beta} \\
\text{until } &~ n < n_0\text{,}
\end{align}
where the $\operatorname{ctz}$ is the count trailing zeros operator.
My idea so far is to sum all the $\alpha$s (or $\beta$s, or both) for all $n$ inside the specified sub-problem ($2^{40}$ numbers). This sum seems to be quite independent of the magnitude of the numbers tested. Someone else could then independently verify this checksum (i.e. double-checking). Is this a good way or do you have a better idea (to prevent cheating)?


text:
Q: Problem with calling a method using a prototype Hi I have this code written and I want the output to be "bill jones is a snowboarder of beginner skill on the slopes.". I am getting "function () { return this.firstName + " " + this.lastName; } is a snowboarder of beginner skill on the slopes." I think the problem is the way I am calling the fullName method but I am stuck.
https://codepen.io/stefan927/pen/yLPJdQG?editors=1111
(function() {
  const fullName = document.getElementById('fullName');
  const type = document.getElementById('type');
  const ability = document.getElementById('ability');

  function Person(firstname, lastname, type, ability) {
    this.firstName = firstname;
    this.lastName = lastname;
    this.type = type;
    this.ability = ability;
  }
  Person.prototype.fullName = function() {
    return this.firstName + " " + this.lastName;
  }

  var skier = new Person('Bill', 'Jones', 'snowboarder', 'beginner');

  fullName.textContent = skier.fullName;
  type.textContent = skier.type;
  ability.textContent = skier.ability;

}())

A: Like Pointy pointed ( no pun intended ) out in his comment, you are not calling the fullName function which is invoked with a pair of (). So, in your code fullName.textContent = skier.fullName should be fullName.textContent = skier.fullName(). That should resolve your issue.

A: You have added fullName to the Persons prototype, and it's a function.
So you need to call/invoke this function.
fullName.textContent = skier.fullName(); //added () to fullName


text:
Q: Determining if Parcel is Sub-Dividable? I am trying to determine which residential real estate parcels are sub-dividable but am running into issues when it comes to placement of an already existing structure on a parcel.
For example, let's assume the minimum requirements to create a new parcel is 10,000 square feet with 50' of frontage along the road. I can calculate parcels that have at least 20,000 square feet with at least 100' of frontage and know that those parcels may be sub-dividable. However, if an already existing structure is right in the center of said parcel then it is no longer sub-dividable without demolishing the structure.
How can I take into account the location of existing structures on a lot to see if the empty space between the structure and lot boundaries are sufficient to sub-divide?
Example of Sub-Dividable Lot:

A: Simplified approach:
- make sure your frontage line is single one per parcel:

*

*densify buildings (clone first) and convert vertices to points

*find coordinates of points projection on relevant front line:

lr="FRONTAGE"
def Chainage(id,shp):
    q='"PAR_ID"='+str(id)
    with arcpy.da.SearchCursor(lr, 'Shape@',q) as cursor:
        for row in cursor:
        geom=row[0]
        L=geom.measureOnLine (shp.firstPoint)
        p=geom.positionAlongLine (L)
        return str(p.firstPoint)
    return -1
#----
Chainage( !PAR_ID! , !Shape! )

Chop frontage by projected points and select longest bit per parcel:

Results can be misleading, e.g. I doubt that a couple of 'high' potential orange parcels can be subdivided into 2 equal parts, but you'll have to inspect much shorter list of candidates.
Note: it is possible to actually subdivide potential candidates, but it will take ages to complete calculations with high resolution results.


text:
Q: Only replace a string only once in the entire file I have a file that I wish to only replace a string only once in the entire file IE the first match it finds should be replaced.
sed -i 's/foo/foo1/1'

A: Try following:
sed -i '0,/foo/s//foo1/' file

Here,
/foo/ will fetch line number of the first occurrence of foo, let's say #n
Then the same word will be searched till line #n and replaced by foo1

A: awk '!f{f=sub(/foo/,"foo1")} 1' file


text:
Q: Use partial fractions to write $\frac{1}{x^2 + x – 1}$ as $\frac{A_1}{x – α_1} + \frac{A_2}{x – α_2}$ and write it as a power series Find the roots $α_1$, $α_2$ of $x^2 + x – 1$ and use partial fractions to write $\frac{1}{x^2 + x – 1}$ as $\frac{A_1}{x – α_1} + \frac{A_2}{x – α_2}$ , for suitable $A_1, A_2$. Using the power series for $\frac{1}{x – α}$ , find another power series for f(x).
First of all, this problem is for the Fibonacci sequence. I have already showed that one of the power series f(x) = $\frac{-1}{x^2+x-1}$ and now I am trying to find another one. This is what I have done so far: I know that the roots $α_1=-(\frac{1+\sqrt5}{2})$ and $α_2=-(\frac{1-\sqrt5}{2})$, so $$\frac{A_1}{x + \frac{1+\sqrt5}{2}} + \frac{A_2}{x + \frac{1-\sqrt5}{2}}$$ $$1=A_1(\frac{1-\sqrt5}{2}) + A_2(\frac{1+\sqrt5}{2})$$ $$A_1=-A_2$$ $$1=-A_2(\frac{1-\sqrt5}{2}) +A_2(\frac{1+\sqrt5}{2})$$ $$1=\sqrt5A_2$$ $$A_2=\frac{1}{\sqrt5}$$$$A_1=-\frac{1}{\sqrt5}$$ This would make the partial fraction be $$\frac{-\frac{1}{\sqrt5}}{x +\frac{1+\sqrt5}{2}} + \frac{\frac{1}{\sqrt5}}{x +\frac{1-\sqrt5}{2}}$$. I'm not sure however if this would be correct. If it isn't, where did I go wrong? If it is, how can I write this as a power series?

A: HINT: You know the standard power series
$$\frac1{1-x}=\sum_{n\ge 0}x^n\tag{1}$$
for a simple geometric series, and you have functions of the form $\frac1{x+a}$. The trick is to manipulate what you have to replace $a$ by $1$:
$$\frac1{x+a}=\frac{\frac1a}{1+\frac{x}a}=\frac1a\cdot\frac1{1-\left(-\frac{x}a\right)}\;,$$
and you can now use $(1)$.
To get the power series I find it a bit easier to use partial fractions to write
$$\frac{-1}{1-x-x^2}=\frac{A}{1-\alpha x}+\frac{B}{1-\beta x}\;,$$
so that the denominators already have the desired $1$. Since $1-x-x^2=(1-\alpha x)(1-\beta x)$, we have $\alpha\beta=-1$ and $\alpha+\beta=1$, and solving the system for $\alpha$ and $\beta$ yields
$$\alpha=\frac{1+\sqrt5}2\qquad\text{and}\qquad\beta=\frac{1-\sqrt5}2\;.$$
I'll leave it to you to solve for $A$ and $B$. Once you have them, you simply write
$$\begin{align*}
\frac1{x^2+x-1}&=\frac{-1}{1-x-x^2}\\
&=\frac{A}{1-\alpha x}+\frac{B}{1-\beta x}\\
&=A\sum_{n\ge 0}(\alpha x)^n+B\sum_{n\ge 0}(\beta x)^n\\
&=\sum_{n\ge 0}\left(A\alpha^n+B\beta^n\right)x^n\;.
\end{align*}$$


text:
Q: I want to coordinate two NSMutableDictionary(s) dictProductList =    (
        {
        "product_capacity" = "20.00";
        "product_code" = ITEM001;
        "product_description" = test;
        "product_id" = 1;
        "product_name" = "Water Bottle";
        "product_price" = "25.00";
        "product_unit" = LTR;
    }
)

and another one is
 NSMutableDictionary *firstOne = [NSMutableDictionary dictionary];
 [firstOne setObject:@"5" forKey:@"product_quantity"];

While I am try to add this two mutable dictionary I got error. Am using this below method.
[dictProductList addEntriesFromDictionary:firstOne];

The error message is
-[__NSArrayM addEntriesFromDictionary:]: unrecognized selector sent to instance 0x166d87f0

A: Show the code that creates dictProductList. It looks like it is an array with one dictionary in it.
The error: " -[__NSArrayM addEntriesFromDictionary:]: unrecognized selector sent to instance 0x166d87f0"
says that the message addEntriesFromDictionary was sent to an NSMutableArray.
It in fact dictProductList is an NSMutableArray the correct code would be:
[dictProductList addObject:firstOne];

In Objective-C the error message are usually helpful and it is worthwhile taking the time to understand them. In this case it say the message was sent to an NSMutableArray and NSMutableArray has no message addEntriesFromDictionary. So either the object is incorrect or the message is incorrect.


text:
Q: accessing shared-to-all onedrive worksheet using microsoft graph My (first) android app is working quite nicely but i am left with 1 very major issue i am trying to solve for several days now
I am trying to use Graph to access an Excel document in my OneDrive from another account. This file is declared public to all by a sharing link.
I am using the next GET to retrieve the file
https://graph.microsoft.com/v1.0/drives/MY_DRIVE/MY_EXCEL_FILE/workbook/worksheets/Data/tables/TableData/rows
The only problem is that the file must be on the user shared folder which i would like to avoid for security reasons.
I am using onedrive for business but if that is a problem, i can use a personal account, though the users of the app must use business since i grant access only to a certain organization.
[UPDATE Sep-27 2018]
With regards to the file shouldn't need to be in a shared folder, the following is the why I think this (I hope I'm wrong):

*

*while in my business onedrive account, i share the file as public and retrieve the sharing link:
https://MY_ORGANIZATION.sharepoint.com/:x:/g/personal/MY_USER/Eabkxa2md3JEsW0qQEuYRK4BKnnnHeJqNuspeZ6TEdkWsQ

*I enter Graph Explorer and run the command to retrieve same file as excel JSON:
https://graph.microsoft.com/v1.0/drives/MY_DRIVE/MY_EXCEL_FILE/workbook/worksheets/Data/tables/TableData/rows

*Graph explorer replys with an HTTP 200 and the correct JSON (as noted, also working correctly on my android app).

*I log out from Graph Explorer and OneDrive and make sure the shared link is still working.

*I connect Graph Explorer using a different account (same organization) and run the same command to retrieve excel JSON:
https://graph.microsoft.com/v1.0/drives/MY_DRIVE/MY_EXCEL_FILE/workbook/worksheets/Data/tables/TableData/rows

*This time i get "Failure - Status Code 404":
{
    "error": {
        "code": "itemNotFound",
        "message": "The resource could not be found.",
        "innerError": {
            "request-id": "6d095277-fa07-40ba-bfcb-c93e96660fdc",
            "date": "2018-09-27T15:43:28"
        }
    }
}

*If I  enter the shared link using my browser, the file is shown in the shared list (below "Recent" and above "Discover" folders on browser):
 https://MY_ORGANIZATION.sharepoint.com/:x:/g/personal/MY_USER/Eabkxa2md3JEsW0qQEuYRK4BKnnnHeJqNuspeZ6TEdkWsQ

*When I return to Graph Explorer and run the command again, I get an HTTP 200 response.
https://graph.microsoft.com/v1.0/drives/MY_DRIVE/MY_EXCEL_FILE/workbook/worksheets/Data/tables/TableData/rows

My conclusion is that file must be inthe shared folder. Please correct me if I am missing something.
ps: After file appears on the 2nd account's "shared" folder, looking at the OneDrive "Manage Access", I now see the 2nd account's inisitals. This is probably to indicate file officially accessed and shared. Deleting the file from his shared folder, keeps its initials and proper response from Graph explorer. Only canceling the share link seems to cancel the share.
[UPDATE Sep-27 2018 - 2]
Since another comment from Mr. Marc, i modified the question a bit and would like to point out i also tried the next link using the my actual sharing link. This had similar response (not sure the exact error code) + other issue in getting the actual excel.
Accessing shared DriveItems

A: You need to send the link to the user or send the invite mail to the user, both are recommended way.
If the file contains sensitive information, you need to segregate the content from the original file, so it can compliance GDPR. Currently, the sharing is for item/file level not the worksheet/excel-rows level.

You can use createLink action to share a DriveItem via a sharing link.


text:
Q: PHP Function and SQL Failing I recently converted a code block into a function so I can call it easily more than just once. My problem is that as soon as I related the block to a function it fails the SQL query every time. Here's my code block:
    function checkEvent()
{
if(!empty($_GET['e']))
    {
        $sql = mysqli_query($link, "SELECT * FROM events WHERE EventID = '" . mysqli_real_escape_string($link, $_GET['e']) . "'");

        if($sql && mysqli_num_rows($sql)==1)
            {
                if($row = mysqli_fetch_row($sql))
                    {
                        $eventid = $row[0];
                        $eventname = $row[1];
                        $desc = $row[2];
                        $time = $row[3];
                        echo $_GET['e'];
                    }
            }
        else
            {
                echo $sql;
                $failure = "Num Rows Error encountered: " . mysqli_error($link) . " / Num Rows: " . mysqli_num_rows($sqlE);
            }
    }
}

Now, I've added echos in the relevant places to check and where it currently says echo $sql; if I change that to echo "Fail."; then it will indeed do that. I have tried to get the result as a number of rows and that comes back blank. I don't understand this as my EventID is an AUTO INCREMENT and as such HAD to start at 1. I've triple checked the first entry is 1 as well.
I'm probably not seeing something really obvious, I just can't understand why this code block stopped working the instant I placed a function block around it.

A: $link doesn't exist inside your function. You either need to pass that as a parameter to the function or skip it entirely and use the "current" DB connection.
"current" in quotes because while it should work just fine while you're utilising a single database connection for the entire process, as soon as you'd start using multiple connections (to connect to multiple databases,) this approach would fail terribly.


text:
Q: Tomcat redirect problem with url pattern with sub folder I have a tomcat application with a number of servlets. Each of the general servlets checks whether the application has been setup and if not it does a redirect to contextpath/admin/setup.
This works fine when accessing the tomcat instance directly but when its behind apache using proxy pass the redirect goes to /contextpath/contextpath/admin/setup
this is my apache config

ProxyPass /mbeclectic/ http://localhost:9098/mbeclectic/

       ProxyPassReverse /
       ProxyHTMLEnable On
       ProxyHTMLURLMap http://localhost:9098/mbeclectic/ /mbeclectic/
       ProxyHTMLURLMap / /mbeclectic/

Ive tried redirecting using the complete external url but the same result.
I can access /contextpath/admin/setup directly from a browser.
I suspect its an error in the apache config, any suggestions welcome.


text:
Q: Outputting PHP variable inside HTML So the title may sound confusing, so here's a brief example.
Here's the php code (Wrapped in HTML);
echo '
<img src="<?php echo $filepath" alt="test" />';

And here's the output of that code in a source file;

As you can see, the php code is shown rather than executed. Here's the full file of which the code is located in;
<?php include('_header.php'); ?>

<?php
$username = $_SESSION['user_name'];

$filesyst = array('png', 'jpeg', 'gif', 'jpg');
foreach($filesyst as $val) {
$path = 'avatar/'.$username.'.'.$val;
if(file_exists($path)) {
$filepath = 'avatar/'.$username.".".$val;
} else {
//default image to be loaded
}
}
?>

<?php

// HERE'S THE CODE ----------
echo WORDING_YOU_ARE_LOGGED_IN_AS . $_SESSION['user_name'] . "
";
echo '
<img src="<?php echo $filepath;?>" alt="test" />';

?>

    <?php echo WORDING_LOGOUT; ?>
    <?php echo WORDING_EDIT_USER_DATA; ?>

<?php include('_footer.php'); ?>

Any ideas on what's going on here? Any help is much appreciated!

A: You are already in a php-block. Try this:
<?php

// HERE'S THE CODE ----------
echo WORDING_YOU_ARE_LOGGED_IN_AS . $_SESSION['user_name'] . "
";
echo '
';

?>

A: You have some PHP code encapsulated in the string you're echo-ing. Try this instead:
echo '
';


text:
Q: Data values not returning expected results I am having a few issues with the sensor data that is returned from the iOS SDK.  For calories, I am returning 86311 calories instead of 2708 that is displayed on my band.  Also, distance is supposed to be retuned as centimeters, but my values are inconsistent there as well.
For contact status, I do not even get results.
I'm not doing anything special other than using the "UpdatesToQueue" functions.
Has anyone else seen these issues?
Thanks,
Harry

A: The calories and distance returned by the SDK are totals since the band's last reset time. whereas the calories and distance displayed on the Band are daily values.


text:
Q: How to reload data only for supplementary view in collectionView? Is there a way to reload only header/footer data in collectionView? If I call collectionView.reloadData(), this will reloads whole collectionView so I'm trying to see if there is a way just to reload header data or footer data.
I look at this thread but it only shows how to reload section and header view not data. Thread link


text:
Q: JSF / Primefaces : How to show growl faces message when executing a method? I can show the growl message once the method is completely executed.
Is it possible to show the growl message like "Processing ...please wait a moment..." when executing a method ?
The method may take time to execute, so i may need to show a growl message to notify the user.
Or any other way to do this ?
Thank you.

A: For this purpose, there a primefaces component called BlockUI which will wait for the ajax response to complete.
Using this, you can show any image as overlay when the method is being executed and you can block the user to perform any operation in that duration.
http://www.primefaces.org/showcase/ui/blockUI.jsf


text:
Q: java.util.UnknownFormatConversionException: Conversion = 'N' This is my code:
package com.example.java;

public class PackageDataTest {

    public static void main(String[] args) {
        PackageData data1 = new PackageData("John Davids");
        System.out.printf("%Number of object created until now is : %d", PackageData.count);
    }
}

class PackageData {

    static int count = 0;
    String name;

    public PackageData(){
        this.name = "";
        ++count;
    }

    public PackageData(String name) {
        this.name = name;
        ++count;
    }

    public int getCount() { return count; }
}

I keep receiving the following error:

"Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'N'"

A: %N is not a valid conversion Format and %n is for the line break.
so if you replace the code as below:
System.out.printf("%nNumber of object created until now is : %d", PackageData.count);

output will be on new line:
Number of object created until now is : 1

check this discussion: What's up with Java's "%n" in printf?


text:
Q: SQLiteDatabase: Failed to open database My problem is when i select different lenguage from app, and again open app it app gone crash and it show Failed to open database.error is persist whenever we select different language  from app. I tried from last two days.I used some answer but they don't work for me.Please any one help me.
My error is
 E/FA: Opening the local database failed, dropping and recreating it
     E/SQLiteDatabase: Failed to open database '/data/data/<package
     name>/databases/google_app_measurement_local.db'.

A: Try to Post your code here where actual process take place, if you need to comment to clarify the question, please do so.
Anyway, the possible issue you are facing could be:

*

*You mistakenly rename the DB File, so check your file existence first

*Did you try to change the path? You can get the external path SD card programmatically with getExternalFilesDir() or getExternalStoragePublicDirectory() from your SQLiteOpenHelper Class(if you have one) Refer here.

*Or you could refer to here for DB

*Try this, but not recommended since you can copy paste everything from here.


text:
Q: C# - Move TextBox to ListBox and be able to use Add/Remove Buttons I have 3 textboxes that have certain values in them. The values are split up depending on what the strings contain using different regex.
These textboxes are in the background and the user will not see them.. However, I do want the user to see the listboxes that correspond to each textbox.  That is what the code below is:
    private void listFormatHelper()
    {
        // Splits the lines in the rich text boxes
        var listOneLines = placementOneRichTextBox.Text.Split('\n');
        var listTwoLines = placementTwoRichTextBox.Text.Split('\n');
        var listUserLines = userDefinedRichTextBox.Text.Split('\n');

        // Resest the text in the listboxes
        placementOneListBox.ResetText();
        placementTwoListBox.ResetText();
        userDefinedListBox.ResetText();

        // Set the selection mode to multiple and extended.
        placementOneListBox.SelectionMode = SelectionMode.MultiExtended;
        placementTwoListBox.SelectionMode = SelectionMode.MultiExtended;
        userDefinedListBox.SelectionMode = SelectionMode.MultiExtended;

        // Shutdown the painting of the ListBox as items are added.
        placementOneListBox.BeginUpdate();
        placementTwoListBox.BeginUpdate();
        userDefinedListBox.BeginUpdate();

        // Display the items in the listbox.
        placementOneListBox.DataSource = listOneLines;
        placementTwoListBox.DataSource = listTwoLines;
        userDefinedListBox.DataSource = listUserLines;

        // Allow the ListBox to repaint and display the new items.
        placementOneListBox.EndUpdate();
        placementTwoListBox.EndUpdate();
        userDefinedListBox.EndUpdate();
    }

HOWEVER, my problem with this is that I cannot move each item in the list... What I mean is that I want to be able to have Move up, Move down,Move left, and Move right buttons.  The Move up and Move down buttons will allow the user to move the selected item(s) up or down (to change the order of the items) in the specified list.  The Move left and Move right buttons will allow the user to move the item on the current list to the list to the "right" or "left" of the current list.
VISUAL LAYOUT OF LISTBOXES:
placementOneListBox                userDefinedListBox                placementTwoListBox
|                 |                |                 |               |                 |
|                 |                |                 |               |                 |
|                 |                |                 |               |                 |
|                 |                |                 |               |                 |
|_________________|                |_________________|               |_________________|

and I get the error:
"Items collection cannot be modified when the DataSource property is set."

Move Up Button CODE:
    private void moveUpButton_Click(object sender, EventArgs e)
    {
        if (placementOneListBox.SelectedIndex != 0 && placementOneListBox.SelectedIndex != -1)
        {
            object item = placementOneListBox.SelectedItem;
            int index = placementOneListBox.SelectedIndex;
            placementOneListBox.Items.RemoveAt(index);
            placementOneListBox.Items.Insert(index - 1, item);
        }
    }

Move Right Button CODE:
    private void moveRightButton_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < placementTwoListBox.Items.Count; i++)
        {
            userDefinedListBox.Items.Add(placementTwoListBox.Items[i].ToString());
            placementTwoListBox.Items.Remove(placementTwoListBox.SelectedItem);
        }
    }

QUESTIONS:

*

*Is there a way to go about this where I can modify the DataSource property?

*Does anyone want to take a crack at this?

*How can I change my listFormatHelper() function to do what I need it to do and allow the buttons to work without the error above?

A: You have two options:

*

*Don't use data binding; convert the data source to a sequence of objects and populate the list(s) by adding the objects in the sequence to the Items property.  Then manage the order using the Items property, as you are currently trying to do.

*Modify the data source itself to alter the order.  How you do this depends on which data source you are using.


text:
Q: Append line breaks with jQuery I want to build a string out of components (a varying number of them)
depending on the type of input. I want to insert line breaks in the resulting
. But it doesn't work. It simply does nothing.
function addToField(input) {
    problemField.append(input).append(" ");
}

function addBreak() {
    console.log('adding break');
    problemField.append("
");
}

append() doc says you can append HTML strings, so why this does not work?
(it also doesn't work with
 and \n)
With:
var problemObj = [ { value: 6, operation: '+' }, { value: 2, operation: '-' } ]

addToField(problemObj[0].value);
addBreak();
addToField(problemObj[1].operation);
addToField(problemObj[1].value);

The resulting
 is just:

6 - 2

                     ^---------
 should be here

What can i do?  I want to avoid using .html()because it can't be used so easily in a stack-push-manner to generate the string.


text:
Q: Google Places Autocomplete - modifying results I have some standard google places autocomplete code that works fine. I want to modify the result when the user selects an address from the list.
For example one of the results is
'45 Alexandra Road Holiday Flats, Alexandra Road, Southport, United Kingdom'
When the user selectes it from the list I would like the following value to appear in the text box
'45 Alexandra Road Holiday Flats, Alexandra Road, Southport, PR4 5JD'
ie, I want the post/zip code to be inserted and the United Kingdom to be removed.
I can do this in the place_changed event, the post/zip code is available and I can do some string manipulation and get the result I want.
However when I assign it to the txtBox at the end of the 'place_changed' function, something then changes it back to the original selected value without the post/zip code. This is something that has changed recently as my code used to work. The assignment/binding of the value to the txtBox happens after the place_changed event now it would seem.
var autoCompleteObject = new google.maps.places.Autocomplete(txtBox[0], GooglePlacesOptions);
// Autocomplete Listener
google.maps.event.addListener(autoCompleteObject, 'place_changed', function () {

    var place = autoCompleteObject.getPlace();

    txtBox.val('45 Alexandra Road Holiday Flats, Alexandra Road, Southport, PR4 5JD');

});

Any ideas on how to achieve this would be greatly appreciated.
Many thanks,
Mark

A: I have decided not to use the AutoComplete functionality and use the PlacesService.textSearch() instead.
Quite easy and you have more control over results and how they are displayed etc..
So the question still remains but my head is less sore :)

A: For reference, I found the answer to the following helpful as an effective workaround:
show just the street address in google.maps.event.addListener()


text:
Q: Scala wrapper API for java API I am new to Scala and I need to have a scala wrapper for my Java API
I have three Java Interfaces
public interface Client<T> {

   <T> Future<T> execute(App<T> app);

}

public interface App<T> extends Serializable{

  T process(AppContext context) throws Exception;

}

public interface AppContext {

  File getDirectory();

  void deleteDirectory();

  File createDirectory(String path);

}

Following is the Java code to create an App
public class RandomApp extends App<String> {

  @Override
  public String process(AppContext context) {

      // Inorder to access the methods in AppContext I need to access
      // it by the following way

      appContext.createDirectory("some path");
      return "random";
  }
 }

I want to have a Scala Wrapper for the Client Interface which in turn call the Java API. But I have some modifications for the new Scala API
object ScalaConverter {

  implicit class ScalaWrapper(client: Client) {

  def scalaClient = new ScalaClient(client)

  }
}

class ScalaClient(client: Client) {

  def execute[T](appContext: AppContext => T): Future[T] = {

      // I am passing appContext as closure instead of passing in
      // App because I want to take the advantage of Closures in Scala

      // I basically want to create an App with this appContext and
      // pass it to the execute method

      // For example - but this is not working

      var app = // Need to create this app with appContext

      Future {
        client.execute(app)
      }
  }

}

A: If I'm not mistaken, you just want to be able to create App objects from a function that takes a AppContext as parameter and returns a any object (let's say T).
As it's not really interesting to try to mirror the whole java API, just use it as it is, but add some extensions. And to do this you should use implicits.
To do this, I see two possibilities: either add an implicit class on the Client interface to add some functions to it, or add an implicit conversion from (AppContext => T) to App objects.
Let's got with the first solution, you have to embed the implicit class in an object (this can be a package object if you need automatic imports).
object ScalaConverter {
  class ScalaApp[T](val block: AppContext => T) extends App[T] {
    def process(context: AppContext): T = block(context)
  }

  implicit class ScalaClient(client: Client) extends AnyVal{
    def execute[T](block: AppContext => T): Future[T] = {
      client.execute(new ScalaApp(block))
    }
  }
}

Then, you just have to use your existing java Client object:
import ScalaConverter._
myJavaClient.execute { context =>
   ???
}

You should get the principle, I maybe made a mistake (did not tried to compile this)


text:
Q: How to use Visibility on Android Studio Think I have four buttons, I want to click one button which will visible some items and at the same time it will invisible/gone others three buttons data. How can I do that please send me sample code.

A: Show view
myView.setVisibility(View.VISIBLE)

hide view
myView.setVisibility(View.INVISIBLE)
or
myView.setVisibility(View.GONE)


text:
Q: Remote Desktop without NLA Let me start by saying I fully understand the purpose of Network Level Authentication, its benefits, etc...
I am trying to find a way to connect to a Windows 7 box from another Windows 7 box without using NLA. This is for a proof of concept I want to perform. The target machine is set to accept connections from all RDP versions. The problem is that the Remote Desktop Client dosen't seem to have an option for a non-NLA only connection.
Is there a way to force it to connect without NLA? Could I install an older version of the RDP Client that dosent support NLA next to my current version? Is there a third party program that would suffice?
UPDATE:
I found an old copy of mstsc 5.2 which dosent support NLA. This works for my purpose and I can keep it on hand, but I'm still curious if there is a better way to work this. Thanks.

A: I believe the key to this is that modern RDP with NLA uses the CredSSP SSPI.  So you might be able to pull this off if you can disable the CredSSP provider, perhaps just for that particular RDP session by putting something like this in an *.rdp file:
[connection-file.rdp]
enablecredsspsupport:i:0

RDP Settings for Remote Desktop Services in Windows Server 2008 R2 (technet.microsoft.com)


text:
Q: From a set of list make subsets of order 3 of those list I have the following lists:
l1 = [1,2,3]
l2 = [1,2,3]
l3 = [1,2,5]
l4 = [1,3,5]
l5 = [1,2,5]
l6 = [2,4,5]
l7 = [2,3,4]
l8 = [3,4,5]
l9 = [3,4,5]
l10 = [1,3,4]
l11 = [2,3,5]
l12 = [1,4,5]

Let s be the following set
s = {l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12}

I am willing to print subsets of order 3 of s(as a list), that is
input:  s = {l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12}, n = 3
output: [{l1,l2,l3}, {l1,l2,l4}, {l1,l2,l5},...]

Naively, I have tried the following
import itertools

def findsubsets(s, n):
    return list(itertools.combinations(s, n))

s = {l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12}
n = 3

print(findsubsets(s, n))

But got the error:
    s = {l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12}
TypeError: unhashable type: 'list'


text:
Q: legend icon width changes in google line chart I have used google chart from this location
https://developers.google.com/chart/interactive/docs/gallery/linechart#Example

Is there any possibility to change the width and height of the legend icons i.e the blue and red rectangles.

A: As seen in the documentation:
legend: {position: 'top', textStyle: {color: 'blue', fontSize: 16}}

legend.textStyle: {color: <string>, fontName: <string>, fontSize: <number>}

Is it what you was looking for ?


text:
Q: Multiple text inputs wrapped in  within
<form>

        <input name="searchInput" tabindex="0" class="form-control input-sm" id="simple-field" style="min-width: 162px; max-width: 162px;" type="text" placeholder="Enter CI" value="" label="hid">

        <input name="searchInput" tabindex="0" class="margin-5-top form-control input-sm" id="simple-field" style="min-width: 162px; max-width: 162px;" type="text" placeholder="Enter CI" value="" label="hid">

        <input name="searchInput" tabindex="0" class="margin-5-top form-control input-sm" id="simple-field" style="min-width: 162px; max-width: 162px;" type="text" placeholder="Enter CI" value="" label="hid">

</form>

which results in the following rendering in IE 11:

My question is how do I display this properly? the text forms are supposed to be stacked on top of one another, and not be arranged diagonally (red arrow) but rather horizontally.
Any assitance would be highly appreciated.
This works fine in Chrome btw.

A: Removing the pull-left classes from all these divs  should  fix your problem (if you don't have any other code causing that behaviour which you didn't post)
(You might not need these br tags either)


text:
Q: design question for transportation agency/workflow system I am designing a transportation agency/workflow system, and it including 3 types of people, customer who requests to transport some stuff, drivers who deliver the stuff, and truck manager who manages transport source/destination truck coordination and communicates/organizes drivers.
The system is expected to be a web site, and 3 kinds of people could use the web site to submit request, accept request, monitor status of specific stuff transportation, etc. The web site is more like an open agency or a workflow system.
I am wondering whether there are any existing technologies, tools or projects (better to be open source, but not a must) which I could build my application faster based on? I prefer to use .Net technologies, but not a must.
thanks in advance,
George

A: You can look at WF (Windows Workflow Foundation) for modeling workflows.
For web technologies, there is either asp.net or asp.net MVC - see http://www.asp.net for more detail.
Here is a library of free database schemas - possibly one of these can help you out.

A: Try bizagi, we were considering and i did a few prototypes with it. You may not even have to write code.


text:
Q: aviary (adobe creative SDK) doesn't work properly with angular 2 I've created simple app with angular 2:
http://plnkr.co/edit/OfjI0jCaZF5kHE45V4ur?p=preview
...
declare var Aviary: any;
...
this.featherEditor=new Aviary.Feather({
...

This working fine. But photos always flip vertically in editor when it appear. What I have to do?

A: you can use ng2-photo-editor fully customizable angular2 photo editor which you can integrate into your HTML5 app within minutes.

*

*npm install --save  ng2-photo-editor

*import { PhotoEditorComponent }     from 'ng2-photo-editor';

A: Try adding the following property to your Aviary.Feather() configuration object:
var editor = new Aviary.Feather({
    // ...
    disableWebGL: true
});

The flipping may be due to an outstanding issue related to Web GL support on Windows.


text:
Q: HTML with PHP not working I'm using Apache as a server,
my index.php code is
<?php session_start(); ?>
<html>
<my HTML code>
<?php
wait_file:{
        // Do something to receive file.
    }
    else
    {
        goto wait_file;
    }
}

detect_file:{
    if(file_exists($file))
    {
        // do something with received file.
    }
    else
    {
        goto detect_file;
    }
}
?>
</html>

but when I visit index.php ,
the webpage is always loading,
and my background picture doesn't show(it may means HTML code are not working),
I think the key point is that i used "goto",made the if-loop to wait for file,
but i don't know how to slove it .

A: *

*In this code, there is actually not much that could work. I don't
know where $file could come from, it looks like it's undefined so
your goto will result in an infinite loop.

*Then you have to have an if to use else.

*There is no output because of the infinite loop, so it is blank while loading. And I can't even see what the page should show because I don't know whats behind <my HTML code>. There is no output in the code you've posted.


text:
Q: asp.net literal control not rendered after postback I'm trying to use Google Maps in order to show some locations extracted from a database. It's al list of vending point, grouped by a set of promoters that, upon promoter selection, have to be displayed on the map.
After successfully using the Subgurim.net library, I decided to move to a Javascript implementation, with the help of https://www.codeproject.com/Articles/36151/Show-Your-Data-on-Google-Map-using-C-and-JavaScrip (the only difference is that I'm using GoogleMaps v3 calls).
The javascript insertion works very well on page load, but when I need a postback on a promoter code in order to show his vending points, I can see in the codebehing the data loaded in the literal control, but no markers are rendered on the web page. If I check with Microsoft Edge's development tools the page being generated I always find the literal control substituted with the data loaded during the very first (no postback) page load.
The aspx part of the page is very simple, and it's not contained in an UpdatePanel, although an UpdatePanel is used on the page, and I've tried also with EnableViewState true and false on the literal control, with no change.
This is the aspx relevant part :

    <asp:Literal ID="mapJs" runat="server" EnableViewState="false" />

    ....

This is the part of code that inserts the first part of the script:
StringBuilder map = new StringBuilder();
bool loadPVGiro = false;
double centerMapLat = 37.451669,
    centerMapLong = 15.05263;

map.Append(@"" + System.Environment.NewLine);
map.Append(" " + System.Environment.NewLine);

mapJs.Text = map.ToString();

This is the portion of the rendered page (from Edge's development tools):

....

Whan a postback occurs, following the selection of a promoter code, the script is fully regenerated with the list of markers, and the literal control is filled with the new script (I can see it only through a breakpoint), but the control on the page remains the first one. Obviously if I force a code during the first page load all the markers are displayed correctly.
The infoCallback function inside the script is used only to force the generation of a new InfoWindow for each marker placed on the map.
Any help would be greatly appreciated.
Rodolfo.
PS: tried also with ViewStateMode="disabled" on the literal control, without changes.
PS2> tried ClientScript.RegisterClientScriptBlock and ClientScript.RegisterStartupScript, but the script being generated are exactly the same as the literal control. Forgot to mention that the actual page is inside a MasterPage.

A: The problem seems related to the user tree inside the update panel; clicking on a user generates a postback, but the script injected in the literal control is never updated on the page, only in the codebehind. Removing the updatepanel the script is correctly updated and executed. After I'll finish the modifications needed by the project, I'll try to further investigate on this behaviour.


text:
Q: Finding limit for given function
If $f(x)=\lim\limits_{n \to \infty} \frac{x}{n} \left(\frac{1}{1+e^{-x/n}}+\frac{1}{1+e^{-2x/n}}+\dots+\frac{1}{1+e^{-x}} \right)$
  then what is  $\lim\limits_{x\to 0} \left(\frac{2f(x)-x}{x^2}\right)$?

My solution is :
$f(x)=0$ since $\lim\limits_{n \to \infty} \frac{x}{n}$ part will be zero for $n=\infty$, making entire term $0$.
then $\lim\limits_{x\to 0} \left(\frac{2f(x)-x}{x^2}\right)$ will become $\lim\limits_{x\to 0} \left(\frac{-x}{x^2}\right)$ or $\lim\limits_{x\to 0} \left(\frac{-1}{x}\right)$ = $\infty$.
This answer is not avaiable in the given options. What should be the correct answer for this questions?

A: Your answer is not correct because $f$ is not identically zero.
Note that the definition of $f$ is the limit of a Riemann sum:
$$\begin{align}f(x)&=\lim\limits_{n \to \infty} \frac{x}{n} \left(\frac{1}{1+e^{-x/n}}+\frac{1}{1+e^{-2x/n}}+\dots+\frac{1}{1+e^{-x}} \right)\\&=x\int_0^1\frac{dt}{1+e^{-tx}}=\ln\left(\frac{e^x+1}{2}\right).\end{align}$$
Therefore, as $x\to 0$,
$$\begin{align}
2f(x)-x&=2\ln\left(\frac{1+x+\frac{x^2}{2}+o(x^2)+1}{2}\right)-x\\
&=2\ln\left(1+\frac{x}{2}+\frac{x^2}{4}+o(x^2)\right)-x\\
&=2\left(\frac{x}{2}+\frac{x^2}{4}-\frac{x^2}{8}+o(x^2)\right)-x
=\frac{x^2}{4}+o(x^2)
\end{align}$$
and we may conclude that the given limit is $1/4$.


text:
Q: Stored Procedure or Bulk Statements The story is that I need to optimize my database access.
Now I need to retrieve related data from like 6 different tables. and I've summerized the people's advise in those points:

*

*Using the same connection for
different commands still pays a
visit to the db with every command
execution

*Stored procedures are a good way to
have more than select statement
(without using joins) to select from more than one table and paying only a single visit to the database

*The source of the real load on the database is the connection to it, not the quantity of the data (quantity still affects the performance but N connections is a bigger factor).
Now I want to have multiple SELECT statements and as advised and more the points above I think I should go with the Stored Procedure option. but I got the thought to use batch SELECT statements instead
Example: SELECT e FROM p; SELECT x,y,z FROM t; SELECT ....; SELECT ....;
Will this cause in a single trip to the database as the stored procedure or not ?
and what do you think about my options ?
..Thanks for your time in advance :)

A: You haven't mentioned anything about indexes. Start there because 6 tables is not a lot to include in a select statement. Exclude unnecessary columns and filter rows as needed. View the execution plan and see what is costing the most (there are a lot of other things to look for. Start Here) If the results you are returning are not related, you can run as separate queries in a stored procedure.
Run it through the Database Engine Tuning Advisor and let SQL Server earn the licensing fee.
Having a stored procedure return multiple queries may not be an ideal solution:  Any SQL Server multiple-recordset stored procedure gotchas?
Try to manage user expectations on the amount of data to pull. I have users I've been beating over the head because they absolutely must have a single dataset that has over 200 fields. They swore performance would never be an issue; times change.

A:
Will this cause in a single trip to the database as the stored procedure or not ? and what do you think about my options ?

To answer your question: the only difference is that you're transferring the whole query instead of just the stored proc name to the database server. Unless your query is a few MBs long or is executed a few thousand times per second, it shouldn't make any difference in terms of performance.

A: I looked at your other question.
It is reasonable to have both approaches.
In some applications, it is reasonable to have multiple connections, each pulling data in parallel (you can do this in ADO.NET using asyncronous methods) for display on a form or web page.
However, in your case, with your model, one has to ask what you are doing with the data?  The model is fine.  Writing a query joining all the tables is also fine.  But on a one-to-many relationship, what are you expecting?  Are you expecting to populate one parent and then a collection of children?  At this point you've left the world of rows and columns and you have an object model.  This is where things like Entity Framework or NHibernate or custom code come into play - translating your good database design into an object model which can be used well in the application.


text:
Q: Material UI searchbar - Using hooks to set state of a query I am new to React. I am trying to implement a search bar using the component:
https://www.npmjs.com/package/material-ui-search-bar
My current code is:
function Searchbar() {

  const [finalQuery, setQuery] = useState("");

    return(
        <SearchBar
            onChange={(event) => console.log(event)}
            onRequestSearch={() => setQuery(#Update the state so that it reflects the query the user wrote)}
            style={{
                marginTop: 200,
                marginLeft: 'auto',
                marginRight: 'auto',
                maxWidth: 800,
                }}
        />
    )
}

It is not clear to me how I can pass to setQuery the value of the final search (when user presses enter) so that the state finalQuery is updated.
If for example I do:
onRequestSearch={() => setQuery(console.log("trytry"))}

When I press enter, in console I get trytry so I am assuming that the state of finalQuery is correctly updated. But how can I do it dynamically?
The final query then will be sent to an API.

A: onChange is called every time the text changes so the right place to update your query is in onChange
return (
<SearchBar
    value={finalQuery}
    onChange={(newValue) => setQuery(newValue)}
    onRequestSearch={() => doSomethingWith(query)}
/>
)

A: May be you need to do this.
 <
    SearchBar
            value={finalQuery}
            onChange={(event) => setQuery(event.target.value)}
            onRequestSearch={() => doSomethingWith(finalQuery)}
        />


text:
Q: Krull dimension of a localization I'm studying some commutative algebra, and i've stepped into an exercise but i don't know if what i am doing is correct, so just wanted a proof check. The exercise is as it follows

Let $A = \mathbb{R}[X,Y,Z]$ and $p = <X-3,Y-3/7>$. Determine the Krull dimension of the localization $A_p$.

Considering that $$ 0 \subset \, <X- a_1> \,  \subset \, <X- a_1, Y-a_2> \, \subset \, <X- a_1, Y-a_2, Z-a_3>
$$ is a saturated ascending chain of prime ideals, and that the prime ideals of $A_p$ are one-to-one with prime ideal in $A$ contained in $p$, my natural guess is that $\dim A_p = \operatorname{ht} P - 1 = 1$. Is that correct?


text:
Q: Tk Filedialog giving back a tuple I am trying to take a file and put it into all directories 1 level down.
TypeError: stat: path should be string, bytes, os.PathLike or integer, not tuple

import shutil
import tkinter as tk
from tkinter import filedialog
import os

root = tk.Tk()
root.withdraw()

files = filedialog.askopenfilenames(parent=root, title='Choose file/s')
path = filedialog.askdirectory()

for dirs in path:
    shutil.copy(files, dirs)

I thought that this would be simple, what am I doing wrong?

A: Since it is "askopenfilenames", it returns the results in the form of a tuple. You can iterate over it and move the files to the directory selected:
import shutil
import tkinter as tk
from tkinter import filedialog
import os

root = tk.Tk()
root.withdraw()

files = filedialog.askopenfilenames(parent=root, title='Choose file/s')
j=filedialog.askdirectory()
path = [os.path.join(j,i) for i in os.listdir(j) if os.path.isdir(os.path.join(j,i))]

for fols,dirs in zip(path,files):
    shutil.copy(dirs, fols)

A: Thanks to everyone for your guidance and input.
The final answer, in order to select files and copy into all subdirectories inside of a folder, the answer that worked is below.
import shutil
import tkinter as tk
from tkinter import filedialog
import os

root = tk.Tk()
root.withdraw()

files = filedialog.askopenfilenames(parent=root, title='Choose file/s')
j=filedialog.askdirectory()
path = [os.path.join(j,i) for i in os.listdir(j) if os.path.isdir(os.path.join(j,i))]

for paths in path:
    for file in files:
        shutil.copy(file, paths)


text:
Q: Why does my translation matrix needs to be transposed? I'm working on a small graphics engine using OpenGL and I'm having some issues with my translation matrix. I'm using OpenGL 3.3, GLSL and C++.
The situation is this: I have defined a small cube which I want to render on screen. The cube uses it's own coordinate system, so I created a model matrix to be able to transform the cube. To make it myself a bit easier I started out with just a translation matrix as the cube's model matrix and after a bit of coding I've managed to make everything work and the cube appears on the screen. Nothing all to special, but there is one thing about my translation matrix that I find a bit odd.
Now as far as I know, a translation matrix is defined as follows:
1, 0, 0, x
0, 1, 0, y
0, 0, 1, z
0, 0, 0, 1

However, this does not work for me. When I define my translation matrix this way, nothing appears on the screen. It only works when I define my translation matrix like this:
1, 0, 0, 0
0, 1, 0, 0
0, 0, 1, 0
x, y, z, 1

Now I've been over my code several times to find out why this is the case, but I can't seem to find out why or am I just wrong and does a translation matrix needs to be defined like the transposed one here above?
My matrices are defined as a one-dimensional array going from left to right, top to bottom.
Here is some of my code that might help:
//this is called just before cube is being rendered
void DisplayObject::updateMatrices()
{
    modelMatrix = identityMatrix();
    modelMatrix = modelMatrix * translateMatrix( xPos, yPos, zPos );

    /* update modelview-projection matrix */
    mvpMatrix = modelMatrix * (*projMatrix);
}

//this creates my translation matrix which causes the cube to disappear
const Matrix4 translateMatrix( float x, float y, float z )
{
    Matrix4 tranMatrix = identityMatrix();

    tranMatrix.data[3]  = x;
    tranMatrix.data[7]  = y;
    tranMatrix.data[11] = z;

    return Matrix4(tranMatrix);
}

This is my simple test vertex shader:
#version 150 core

in vec3 vPos;

uniform mat4 mvpMatrix;

void main()
{
    gl_Position = mvpMatrix * vec4(vPos, 1.0);
}

I've also did tests to check if my matrix multiplication works and it does.
I * randomMatrix is still just randomMatrix
I hope you guys can help.
Thanks
EDIT:
This is how I send the matrix data to OpenGL:
void DisplayObject::render()
{
    updateMatrices();

    glBindVertexArray(vaoID);
    glUseProgram(progID);
    glUniformMatrix4fv( glGetUniformLocation(progID, "mvpMatrix"), 1, GL_FALSE, &mvpMatrix.data[0] );
    glDrawElements(GL_TRIANGLES, bufferSize[index], GL_UNSIGNED_INT, 0);
}

mvpMatrix.data is a std::vector:

A: For OpenGL
1, 0, 0, 0
0, 1, 0, 0
0, 0, 1, 0
x, y, z, 1

Is the correct Translation Matrix.
Why? Opengl Uses column-major matrix ordering. Which is the Transpose of the Matrix you initially presented, which is in row-major ordering. Row major is used in most math text-books and also DirectX, so it is a common point of confusion for those new to OpenGL.
See: http://www.mindcontrol.org/~hplus/graphics/matrix-layout.html

A: You cannot swap matrices in a matrix multiplication, so A*B is different from B*A. You have to transpose B before swapping the matrices.
A * B = t(B) * A

try
void DisplayObject::updateMatrices()
{
    modelMatrix = identityMatrix();
    modelMatrix = translateMatrix( xPos, yPos, zPos ) * modelMatrix;

    /* update modelview-projection matrix */
    mvpMatrix = modelMatrix * (*projMatrix);
}