text:
Q: Ajax call throwing off anchor tags I current have a page that displays from top to bottom: a responsive table containing a list of classes my company offers, a map showing the location of each class, and an agenda for the class. My employer would like me to add an anchor link in another page that links directly to the agenda portion of the page.
The issue that is that when the anchor is clicked, the user is redirected to the agenda (the desired result), but then the ajax call to the server finishes and the table above expands and pushes the agenda down.
I have tried to wrap the table in a div with a calculated height based on the contents of the table, but the min-height seems to be applied after the fact.
Here is the url for the anchored link: http://www.grastontechnique.com/clinicians/M1_Trainings#m1-training-agenda
I will also include the code snippets pertaining to the table and ajax calls.
Here is the call to the server
$scope.loadData = function () {
        $.ajax({
            url: '@Url.Action("getTrainings", "Clinicians")',
            data: { "trainingType": "M1" },
            success: function (data) {
                newData = JSON.parse(data)
                index = 0;
                tableHeight = 77;
                trainingsTable = document.getElementById("m1-trainings-table-container");
                newData["records"].forEach(function (object) {
                    if (newData["records"][index]["Early_Bird_Discount_Amount__c"] > 0)
                    {
                        tableHeight += 141;
                    }
                    else
                    {
                        tableHeight += 125;
                    }

                    newData["records"][index].firstDayStartTime = BuildTimeString(new Date((newData["records"][index]["First_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')));
                    newData["records"][index].firstDayEndTime = BuildTimeString(new Date((newData["records"][index]["First_Day_End__c"].slice(0, -9) + "Z").replace('+', '.')));
                    newData["records"][index].lastDayStartTime = BuildTimeString(new Date((newData["records"][index]["Final_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')));
                    newData["records"][index].lastDayEndTime = BuildTimeString(new Date((newData["records"][index]["Final_Day_End__c"].slice(0, -9) + "Z").replace('+', '.')));

                    newData["records"][index]["First_Day_Start__c"] = new Date((newData["records"][index]["First_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')).toDateString();
                    newData["records"][index]["Final_Day_Start__c"] = new Date((newData["records"][index]["Final_Day_Start__c"].slice(0, -9) + "Z").replace('+', '.')).toDateString();

                    index += 1;
                });
                trainingsTable.style.minHeight = tableHeight + "px";
                $scope.trainingsList = newData['records'];
                $scope.$apply();
            }
        });
    };

And here is the table container

M1-Basic Training Schedule

To qualify for the Early Bird Special (Save $50) your registration must be paid for anytime 30-days prior to your training date.

        <input type="text" id="zip-input" class="locate-a-provider-input" style="margin: 25px auto; padding-left: 5px;" ng-model="searchQuery" placeholder="Search Trainings">

State

Location

Time & Date

Register

                            State:

{{training.Venue_State__c}}

                                Venue:

                                {{training.Venue_Name__c}}

                                {{training.Venue_Street_Address_1__c}}

                                {{training.Venue_City__c}}, {{training.Venue_State__c}} {{training.Venue_Postal_Code__c}}

                                Dates:

                                 80 && training.Capacity_Full__c < 99.99">Closing Soon

                                = 100">Wait List

                                 0 && training.Capacity_Full__c < 100">Early Bird Special: Save ${{training.Early_Bird_Discount_Amount__c}}!

                                {{training.First_Day_Start__c}}

                                {{training.firstDayStartTime}} - {{training.firstDayEndTime}}

                                {{training.Final_Day_Start__c}}

                                {{training.lastDayStartTime}} - {{training.lastDayEndTime}}

                            <button class="rounded-button button-sign-up" ng-click="toTraining(training.Id)">Sign Up</button>

Any help would be greatly appreciated.
Danny D.


text:
Q: WCF method that updates object passed in Am I correct in thinking that if I have a WCF OperationContract takes in an object and needs to set a property on that object so the client gets the update, I need to declare it to return the object.
e.g. given a datacontract:
[DataContract]
public class CompositeType
{
    [DataMember]
    public int Key { get; set; }

    [DataMember]
    public string Something { get; set; }
}

this will not work with WCF:
public void GetDataUsingDataContract(CompositeType composite)
{
  composite.Key = 42;
}

this will work:
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
  composite.Key = 42;

  return new CompositeType
  {
    Key = composite.Key,
    Something = composite.Something
  };
}

A: If you use 'out of the box' WCF, you are actually using a form of webservices, that uses serialized versions of the objects that are sent from client to server.
This is the reason you cannot 'by reference' change properties on objects. You will always have to use a request / response pattern.

A: IMO, authoring methods that produce output via side-effects is a "bad" thing. Having said that however, are there circumstances that necessitate this model? Yes.
Certainly C# programming model permits this, is WCF broken? No. At a certain point, one must realise they are consuming WCF, and as a framework it attempts to satisfy a majority of use-cases [for instance, replicating all input parameters on all round trips to preserve implicit side effect semantics is, in a word, silly].
Of course, there are ways to work around this - C# also provides for explicit declaration of these scenarios and WCF supports these as well!
For instance
// use of "ref" indicates argument should be returned to
// caller, black-eye and all!
public void GetDataUsingDataContract (ref CompositeType composite)
{
    composite.Key = 42;
}

Give it a go!
Hope this helps :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I plot lines in the future in pine script? I have been trying to plot take profit and stop loss lines for a script I wrote, but I am struggling with plotting lines in the future.
I have tried using the plot and line.new functions but with no success.
An example of what I would like to see

A: You can calculate the values you want to plot on the graph then set offset. Something like this,
plot(close, offset = 1, color = color.black, linewidth=2)

here offset will be number bars in the future. i.e 1 is calculated bar in future.

A: I wrote something that does exactly what you seek. I plot the Daily Pivot lines to the right of the bars, so they don't get in the way. The trick is to use a trendline instead of a "plot" line, and have the trendline offset by a certain amount of time rather than using the "offset" feature.
You can see I calculate the time value of one bar using labeldt, then define the x1 and x2 options using (time + (labeldt * 20)), which means to begin the trendline at the current bar and plot it 20 bars into the future. The y1 and y2 options define what price level it will be plotted on.
Good luck
/////////////////////
// F L O O R   P I V O T S
//
/////////////////////

labeldt = time - time[1]

/////////////////
//LINE PRICE CALCULATIONS
/////////////////////////
PPFunc() =>
    xHighPP = high[1]
    xLowPP = low[1]
    xClosePP = close[1]
    [xHighPP, xLowPP, xClosePP]

[xHigh, xLow, xClose] = security(syminfo.tickerid, 'D', PPFunc())

//xHigh  = security(tickerid,1440, high[1])
//xLow   = security(tickerid,1440, low[1])
//xClose = security(tickerid,1440, close[1])

vPP = (xHigh+xLow+xClose) / 3

/////////////////////////

//LINE PLOT

PlothlineDayPivotPoint = line.new(x1=time, y1=vPP, x2=time + (labeldt * 20), y2=vPP, extend=extend.none, color= #0000ff, xloc=xloc.bar_time)

//LINE STYLE

line.set_width(PlothlineDayPivotPoint, 1)

//LINE DELETER

line.delete(PlothlineDayPivotPoint[1])

/////////////////////

For your purposes you can ignore the "Line Price Calculations" section - that is just me calculating the price level.


text:
Q: Paste Cell Reference from another worksheet I am trying to get this script to work but cannot work it out.
So i would like the result on Sheet 1 from Sheet 4.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
ss.getRange('AM2').activate();
ss.getCurrentCell().setFormula('=[4] AL3');

I hope i am close ?

A: Explanation:

*

*Firstly, define the sheets you want to work with:
var sheet1 = ss.getSheetByName('Sheet1');
var sheet4 = ss.getSheetByName('Sheet4');

*Get the value of cell AL3 in Sheet4:
var value = sheet4.getRange('AL3').getValue();

*Set it to cell AM2 in Sheet1:
sheet1.getRange('AM2').setValue(value);

If you want to use the formula instead, then just do that:
var sheet1 = ss.getSheetByName('Sheet1');
sheet1.getRange('AM2').setFormula('Sheet4!AL3');

Solution:
I think you are looking for this:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Sheet1');
var sheet4 = ss.getSheetByName('Sheet4');
var value = sheet4.getRange('AL3').getValue();
// sheet1.getRange('AM2').setValue(value); // if you want the value use this
sheet1.getRange('AM2').setFormula('Sheet4!AL3'); // if you want the formula use this
}

If the name of the sheets have a space between the word and the number, for example Sheet 1 instead of Sheet1 and Sheet 4 instead of Sheet4, then use this solution:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Sheet 1');
var sheet4 = ss.getSheetByName('Sheet 4');
var value = sheet4.getRange('AL3').getValue();
//sheet1.getRange('AM2').setValue(value); // if you want the value use this
sheet1.getRange('AM2').setFormula("'Sheet 4'!AL3") // if you want the formula use this
}


text:
Q: activity Unfortunately closed error main activity : getting error at the line:
final TextView registerpage = (TextView) findViewById(R.id.register);
    registerpage.setOnClickListener(new OnClickListener(){

package com.example.indianrecipe;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends  Activity {

    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);

    setContentView(R.layout.loginpage);

    final TextView txt_username = (TextView) findViewById(R.id.name);

    final TextView txt_psw = (TextView) findViewById(R.id.pass);

    Button btn_signin=(Button) findViewById(R.id.signinb);

    btn_signin.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {

    RegisterHandler db= new RegisterHandler(getBaseContext());
    db.onOpen(null);
    Log.v("LoginDetails", txt_username.getText().toString()+"../.."+txt_psw.getText().toString());
    Cursor cur = db.get_info( txt_username.getText().toString() , txt_psw.getText().toString());
    if(cur.getCount()!=0)
    {
        Log.v("Login",cur.getString(3));
        String password=cur.getString(0);

        Intent i = new Intent(Login.this, FullscreenActivity.class);
        i.putExtra("USERNAME", txt_username.getText().toString());
        i.putExtra("PASSWORD", txt_psw.getText().toString());
        startActivity(i);

        db.close();
        }
        else
        Toast.makeText(getBaseContext(), "Please enter Valid User name and password", Toast.LENGTH_LONG).show();
        }});

    final TextView registerpage = (TextView) findViewById(R.id.register);
    registerpage.setOnClickListener(new OnClickListener(){

        public void onClick(View v) {
            System.out.println("error here==" + registerpage);

        setContentView(R.layout.register_user);

    }
    });

    Button reg_btn=(Button) findViewById(R.id.regbtn);
    reg_btn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {

    RegisterHandler db= new RegisterHandler(getBaseContext());
        final EditText cuisine= (EditText) findViewById(R.id.fav_cuisine);
        final EditText email= (EditText) findViewById(R.id.email_id);
        final EditText name= (EditText) findViewById(R.id.person_name);
        final EditText password= (EditText) findViewById(R.id.pass_reg);

    db.addUser(cuisine.toString(),email.toString(),name.toString(),password.toString());

    }
    });

    }

}

Snapshot Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.indianrecipe"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.indianrecipe.Login"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

            <activity
            android:name="com.example.indianrecipe.FullscreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name">
            </activity>
    </application>

</manifest>

heres the logcat:
here's the logcat
ComponentInfo{com.example.indianrecipe/com.example.indianrecipe.Login}: java.lang.NullPointerException
01-22 08:08:12.650: E/AndroidRuntime(1051):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
01-22 08:08:12.650: E/AndroidRuntime(1051):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
01-22 08:08:12.650: E/AndroidRuntime(1051):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
01-22 08:08:12.650: E/AndroidRuntime(1051):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
01-22 08:08:12.650: E/AndroidRuntime(1051):     at android.os.Handler.dispatchMessage(Handler.java:102)
 E/AndroidRuntime(1051):    at android.os.Looper.loop(Looper.java:137)
01-22 08:08:12.650: E/AndroidRuntime(1051):     at android.app.ActivityThread.main(ActivityThread.java:4998)
 E/AndroidRuntime(1051):    at java.lang.reflect.Method.invokeNative(Native Method)
 E/AndroidRuntime(1051):    at java.lang.reflect.Method.invoke(Method.java:515)
01-22 08:08:12.650: E/AndroidRuntime(1051):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777) E/AndroidRuntime(1051):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
 E/AndroidRuntime(1051):    at dalvik.system.NativeStart.main(Native Method)
 E/AndroidRuntime(1051): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1051):     at com.example.indianrecipe.Login.onCreate(Login.java:71)

the register id in xml file:
<TextView
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/nomem"
        android:layout_alignBottom="@+id/nomem"
        android:layout_toRightOf="@+id/nomem"
        android:clickable="true"
        android:text="@string/register" />


text:
Q: django-paypal empty order summary/price wanted to integrate paypal payment into my paypal application but hit a snag. I installed dcramer's version of django-paypal and followed the instructions given for WPP (payment pro).
In my view, I followed the same item details in the examples:
def buy_my_item(request):
  item = {"amt": "10.00",             # amount to charge for item
          "inv": "inventory",         # unique tracking variable paypal
          "custom": "tracking",       # custom tracking variable for you
          "cancelurl": "http://myapp/url",  # Express checkout cancel url
          "returnurl": "http://myapp/url"}  # Express checkout return url

  kw = {"item": item,                            # what you're selling
        "payment_template": "payment.html",      # template name for payment
        "confirm_template": "confirmation.html", # template name for confirmation
        "success_url": "/success/"}              # redirect location after success

  ppp = PayPalPro(**kw)
  return ppp(request)

I am able to make a call to paypal sandbox and got redirected to the buyer payment page. There I noticed the buyer's order summary is empty when I did include the amount as shown above.
Any steps I missed here?
the debug messages:
PayPal Request:
    {'amt': '10.00',
     'cancelurl': 'http://bar.com',
     'custom': 'tracking',
     'inv': 'inventory',
     'method': 'SetExpressCheckout',
     'noshipping': 1,
     'returnurl': 'http://foo.com'}

PayPal Response:
{'ack': 'Success',
 'build': '2571254',
 'correlationid': '2f119c4489c1b',
 'timestamp': '2012-02-23T11:00:43Z',
 'token': 'EC-13C49181MF5610640',
 'version': '54.0'}


text:
Q: what is a commit log? in google's bigtable context, what does a commit log mean? and what is the use of a commit log?

A: In any database context, a "commit" is the application of a single transaction to the DB. A commit log is a record of transactions. It's used to keep track of what's happening, and help with e.g. disaster recovery - generally, all commits are written to the log before being applied, so transactions that were in flight when the server went down can be recovered and re-applied by checking the log.


text:
Q: How to pass environment variables to Apache Superset docker container on Azure Container Instances I'm able to create a working container group of Apache Superset using the Azure CLI like this:
az container create --resource-group myrg --name superset-test --image apache/superset:1.5.1 --dns-name-label superset-test --ports 80 8088 --cpu 2 --memory 8

Now I want to pass some environment vars to customize the deployment, e.g., I want the database backend to be my Azure Postgres Flexible Server, not the default Postgres docker container superset_db.  But I can't figure out how to pass that info via environment variables.
I've tried like this, with --environment-variables:
az container create --resource-group myrg --name superset-test --image apache/superset:1.5.1
 --dns-name-label superset-test --ports 80 8088 --cpu 2 --memory 8 --environment-variables DATABASE_DIALECT="postgresql"
"DATABASE_USER"="superset" "DATABASE_PASSWORD"="superset" "DATABASE_HOST"="azpostgresql1.mydomain.com"
"DATABASE_PORT"="5432" "DATABASE_DB"="superset"

But they seem to be ignored - the Superset container starts up the same way and no data is populated into my db.  Can I do this via the CLI?  Or is there another way I should execute this deployment?
Update: I'm now focused on the SECRET_KEY variable since, if one is not passed, the default is used and a message appears in the container once I connect to it via the Azure web portal and run superset init:

A Default SECRET_KEY was detected, please use superset_config.py to override it.

That's a clean way to verify that the problem is in my env variables.  Once the container starts up, I can verify the connection to the same Postgres DB I want to use as the application backend by listing it as a database source and testing the connection.

A: Have you tried running this container via the Azure web portal as per this example? This would ensure all variables are present and parsed correctly.
Azure documentation suggests using single quotes ' rather than double " for env var specification. As per this docs example. Though I realise it shouldn't really make much difference.
If you won't have any luck with the above, you may want to explore another option - have you seen the Superset database connection UI? It may prove useful in checking the connectivity.
Other than that, it's difficult to explore other options. A bit more context would help:

*

*have you seen any traffic arrive at the target database?

*is there any traffic in the local Postgres instead?

*any chance you can confirm in the web portal that the variables were set correctly via the cli?

A: Instead of using CLI use PgAdmin. In PgAdmin, we can connect our application to Postgres to local or on azure platform. The environment variables which were shown in the question, directly mentioned in the PgAdmin credentials and it will allow access to the application to database.
Follow the steps:

*

*Open PgAdmin

*On the Left click on Servers

*Click on Dropdown

*Right Click on Open Clusters and select properties

*Click on Open Connection tab and give all the environment variables which were created.

*Check the working of the application again after setting up all the variables.


text:
Q: Status 400 The request sent by the client was syntactically incorrect. Angularjs http I have spring controller on the server:
@RequestMapping(value = "/lab/getAlgo", method = RequestMethod.POST)
    public @ResponseBody Algo14web  getPicksByLeague(@RequestBody AlgoRequest request) {
    ...

Class AlgoRequest:
class AlgoRequest{
        public int id;
        public int limit; // I tried change to double and float too
    }

And AngularJS :
$http.post(urlSer.url+"lab/getAlgo",{id:1,limit:2.5});

And when client sent request to server get Status 400 The request sent by the client was syntactically incorrect

A: It's because 2.5 isn't an integer.
Your AlgoRequest class requires the limit field to be an integer, but you've tried to pass 2.5 in. It's syntactically incorrect because you haven't supplied a value that fits the syntax of an integer.


text:
Q: Probability of even sum in submatrices There is a fixed integer $m\times n$ matrix $M$. The question is what is the probability that a random $m\times k$ submatrix summed over rows produce a column with all even numbers.
Without loss of generality assume that even numbers all equal 0, and odd numbers are ones. For a given $m\times k$ submatrix, for a given row, the probability that the sum is even equals the probability that the sum is odd. Then the probability that all $m$ rows are even equals $2^{-m}$ and does not depend on $k$.
I am puzzled with the fact that $m\times n$ matrix contains $n \choose k$ submatrices of shape $m\times k$. If I simply multiply $2^{-m}$ and $n \choose k$, for large enough $k$ it exceeds 1. As Mike Earnest pointed out, different $m\times k$ submatrices do not have to be independent. I don't clearly see a way to account for this. And the question now becomes, how many submatrices of shape $m\times k$ sum to column of zeros mod 2? Any hints and/or tips very much welcome.
The matrix $M$ is fixed. So we can extract any sort of information from it, $e.g.$ number of ones for the whole matrix, or for individual columns.
-edited for clarification, as requested in comments


text:
Q: Error Correction for wrong Output My Programme requests two variables: one integer and one float. Both must be greater than 0 and less than 2000. But testing an input of 45 and 0 it is accepting the value and showing the output of 0.00 although the conditions require (cash > 0) && (balance > 0).
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int cash;
    float balance ;
    cin >> cash >> balance;
    if((cash%5==0) && (cash <= balance) && (cash > 0) && (balance > 0) && (cash <= 2000) && (balance <= 2000))
    {
        balance = (balance - cash) - 0.50;
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    else if (cash%5 != 0)
    {
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    else if (cash > balance)
    {
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    return 0;
}

A: Condition is false in expression (cash <= balance) , so it will not check other condition and jump to else part and cash > balance is satisfied so it will execute expression inside cash > balance part.
For example
 int a=1,b=2,c=3;
 if((cout<<"first ") && ( a==2 ) && (cout<<" second\n"))
 {
    cout<<"condition true\n";
 }
 else
 {
    cout<<"condition false\n";
 }

Here first will print and when a==2 expression occur which is false so it will move to else part.


text:
Q: Same text but nonzero diff I have two files, the contents of which are exactly same as it appears to my eyes, however, the diff of both shows all lines being different, the reason i suspect has something to do with character format/encoding but i am not sure.
The output of "file --mime" on both is same.
Can someone enlighten me on whats going on? and how could i possibly change one form to another, some command/tool.

A: Maybe line endings? Try dos2unix and unix2dos.

A: It's probably line endings. Is one from a Unix machine and the other from a Windows machine, by any chance?
http://en.wikipedia.org/wiki/Newline#Common_problems


text:
Q: Which is better bigint or nvarchar in case of primary key I need primary key for table bus which stores info like bus no , bus type , registration no etc. As we know bus no is itself unique and can be primary key but its of datatype string which slow down searching in table, So another possible solution is adding auto increment field of type int, but this will increase network data as every time I need to select both bus no and bus id(auto incremented) for user selection on winform. I need to know which approach is better or is there other better approach.
Table Schema Approach 1
bus no - nvarchar(10) (primary key)
bus registartion no - nvarchar(10)

Approach 2
Bus id - int (autoincremnted) (primary key)
Bus no - nvarchar(10)
bus registartion no - nvarchar(10)

A: *

*Numeric - not null - columns are always the best option for primary keys on database tables. The database engine can store, index and look them up in the most efficient way.

*Do not mind network traffic overhead. Simply do not query columns you do not need in your result set. Avoid SELECT * statements.

*If necessary, type conversions (e.g. Integer to String) can easily be done in your SELECT's or in your client program.

When modeling your database, it is a best practice to add a primary key column to every table in advance, even if you feel you do not need it. Give your primary key column a standardized name (tablename + 'id' is a common naming convention) and type (integer, uniqueidentifier) and stick with it. Do not mix integer, long, short and other data types, because it can only complicate joining of tables.
E.g. for your entity Bus:

*

*table name is Bus

*primary key name is BusId

*primary key type is Int


text:
Q: возврат вложенного словаря из функции Возможно ли вернуть написать функцию, которая будет возвращать вложенный словарь исходя из аргументов?
Например:
def foo(key):
    d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    return d[key]

foo(['c']['d'])

Я ожидаю получить:
3
Я получаю:
TypeError: list indices must be integers or slices, not str

Я понимаю, что можно возвращать весь словарь, или захардкодить возврать конкретной части словаря, но это все крайне не гибко

A: само ['c']['d'] синтаксическая ошибка. поэтому придётся передавать список ['c','d'] и в цикле или рекурсивно решать задачу. Например так:
def foo(key,d):
    while len(key):
        d = d[key[0]]
        key = key[1:]

    return d

d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
print(foo(['c','d'],d))

A: В данном случае проще возвращать весь словарь, и к возвращенному значению уже обращаться по индексам: foo()['c']['d'] - это очень даже гибко.
Другой вариант - передавать в функцию другую функцию, которая будет брать нужное значение (или вообще выполнять какие-то произвольные вычисления от исходной структуры данных):
def foo(key):
    d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    return key(d)

print(foo(lambda x: x['c']['d']))

Так например работают функции сортировки по произвольному ключу:
d = [dict(a=5), dict(a=3), dict(a=10)]
d.sort(key=lambda x: x['a'])
print(d)  # [{'a': 3}, {'a': 5}, {'a': 10}]


text:
Q: Why Nationalism and Patriotism seem like it swap meaning? When I try to distinguish these two words I found many people link something like intolerance and illogical with Nationalism while Patriotism seem more progressive. But from etymology the word Patriot felt more militaristic and require obedient than Nation
What happen to these words and why we have these mismatch meaning?

A: Webster's 1913 Dictionary has this as one of its definitions for nationalism:

*The policy of advocating the interests of one's own country exclusively, regardless of effects of a country's actions on other countries.

This sense of the word carries a more negative connotation than patriotism. Often in political discourse, the word nationalism is used in this negative sense, while people tend to use patriotism to talk about the more positive aspects of dedication to one's country.


text:
Q: Help me calculating chromatic polynomial of this subgraph
This is the subgraph. I just wanted to do a couple of exercises with chromatic polynomials, but around the web are pretty standard ones, so i came up with this one myself. I thought it's pretty straightforward.
It is: i color $A$ with $x$ colors, automatically $B$ and $C$ are both different, so $B$ is colored with $x-1$ colors and $C$ with $x-2$ colors and $E$ with $x-1$ colors.
This gives us that $F$ must be colored with $x-3$ colors and D with $x-2$ colors.
And it gives me polynomial equal to $$x(x-1)^2(x-2)^2(x-3)$$
But according to wikipedia, coefficient next to $[x^{n-1}]$ is equal to minus number of edges. Wolfram says that $$[x^{n-1}]x(x-1)^2(x-2)^2(x-3) = -9$$
but we have clearly 8 edges here. Seems like i counted something wrong (too much?), so i'd love to hear some hints or solutions to my problem. Thank you in advance!

A: The problem here is that you haven't accounted for the fact that $E$ and $B$ might have the same color, and $E$ and $C$ might have the same color.
There are cases here that need considering:
Case 1: $E$ has the same color as $B$.
In this case, there are $x$ choices for $A$; $x-1$ for $B$ and $E$; $x-2$ for $C$; $x-1$ for $D$; and $x-2$ for $F$. So, the contribution by this case is $x(x-1)^2(x-2)^2$.
Case 2: $E$ has the same color as $C$.
In this case, there are $x$ choices for $A$; $x-1$ choices for $C$ and $E$; $x-2$ for $B$; $x-2$ for $d$; and $x-1$ for $F$. So, the contribution by this case is $x(x-1)^2(x-2)^2$ as well.
Case 3: $E$, $B$, and $C$ all have different colors.
In this case, there are $x$ choices for $A$, $x-1$ for $B$, $x-2$ for $C$, and $x-3$ for $E$; given these choices, there are $x-2$ choices for $D$ and $x-2$ choices for $F$. So, the contribution by this case is $x(x-1)(x-2)^3(x-3)$.
So, all told, the chromatic polynomial for $G$ is
$$
\begin{align*}
P_G(x)&=2x(x-1)^2(x-2)^2+x(x-1)(x-2)^3(x-3)\\
&=x(x-1)(x-2)^2(x^2-3x+4)\\
&=x^6-8x^5+27x^4-48x^3+44x^2-16x.
\end{align*}
$$

A: Alternatively you can use Deletion-Contraction on your graph; the edge AE works well.
You can then use Complete Intersection and other standard methods (see pages 24 and 25 of my coursenotes) to get:
 $$P(G,x) = P(G-AE,x) - P(G/AE,x) \\
 = \frac{P(C_3,x)P(C_5,x)}{P(K_2,x)} - x(x-1)(x-2)^3 \\
 = (x-2)((x-1)^5 + 1 - x) - x(x-1)(x-2)^3 \\
 = x(x-1)(x-2)^2 ( x^2 - 2x + 2 - (x-2) ) \\
 = x(x-1)(x-2)^2 ( x^2 - 3x + 4 )\\
 = x^6 - 8x^5 +27x^4 -48x^3 +44x^2 -16x $$
For $P(G/AE,x)$ we can break it into 3 triangles using Complete Intersection twice:
$$P(G/AE,x) = \frac{P(ABD,x)P(ABCF,x)}{P(K_2,x)} \\
  = \frac{P(ABD,x)}{P(K_2,x)} \frac{P(ABC,x)P(ACF,x)}{P(K_2,x)} \\
  = \frac{ [ x(x-1)(x-2) ]^3 } { [ x(x-1) ]^2 }\\
  = x(x-1)(x-2)^3$$
However, it is easier to use the method outlined by Nicholas for such graphs made of triangles.


text:
Q: Anchor tag not jumping to id This is usually a basic thing to do, however suprisingly im having difficulties with it.
I got a link:
t.b.a.

That i want click to jump to the map section at the bottom of my page

 ....

Ive added 678 to make sure its unique. I tried changing the 'section' to 'div' but none of it works. What could be preventing it from working?

A: spell mistake maps678 to #map678 you forget 's'
t.b.a.

A: Your anchor and your ID are differents.
maps678
This will work:
t.b.a.


text:
Q: Cocoapods giving error on after updating Mac OS catalina I have updated the Mac OS to Catalina 10.15.6. Now, when I try to install pods in Xcode project it gives following errors. I searched a lot over but could not find any working solution.
Here is log:
 pod install
Traceback (most recent call last):
    18: from /usr/local/bin/pod:23:in `<main>'
    17: from /usr/local/bin/pod:23:in `load'
    16: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/bin/pod:55:in `<top (required)>'
    15: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command.rb:52:in `run'
    14: from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
    13: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command/install.rb:46:in `run'
    12: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/command.rb:150:in `verify_podfile_exists!'
    11: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/config.rb:200:in `podfile'
    10: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/config.rb:221:in `podfile_path'
     9: from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.9.3/lib/cocoapods/config.rb:161:in `installation_root'
     8: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:274:in `normalize'
     7: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:136:in `decompose'
     6: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:136:in `inject'
     5: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:136:in `each'
     4: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:147:in `block in decompose'
     3: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:326:in `codepoints'
     2: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:336:in `load'
     1: from /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:336:in `open'
/Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/multibyte/unicode.rb:336:in `initialize': No such file or directory @ rb_sysopen - /Library/Ruby/Gems/2.6.0/gems/activesupport-4.2.11.1/lib/active_support/values/unicode_tables.dat (Errno::ENOENT)


text:
Q: Spring boot mvc validate enum by value In my spring boot application I want to validate enum by custom value:
I have my DTO like following :
@Data
public class PayOrderDTO {
    @NotNull
    @EnumValidator(enumClass = TransactionMethod.class)
    private TransactionMethod method;
}

And my enum validator annotation defined like bellow:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Constraint(validatedBy = EnumValidatorImpl.class)
public @interface EnumValidator {
    String message() default "is invalid";

    /**
     * @return Specify group
     */
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * @return Specifies the enumeration type. The parameter value must be a value in this enumeration type
     */
    Class<? extends EnumBase> enumClass();

    /**
     * @return Can it be null
     */
    boolean nullable() default false;

    /**
     * @return Values to exclude
     */
    int[] exclusion() default {};

}

This is the implementation of my enum validator annotation
public class EnumValidatorImpl implements ConstraintValidator<EnumValidator, EnumBase> {
    private boolean nullable;

    private Set<String> values;

    @Override
    public void initialize(EnumValidator constraintAnnotation) {
        this.nullable = constraintAnnotation.nullable();
        Class<? extends EnumBase> enumClass = constraintAnnotation.enumClass();
        int[] exclusion = constraintAnnotation.exclusion();

        values = new HashSet<>();
        EnumBase[] enumConstants = enumClass.getEnumConstants();
        for (EnumBase iEnum : enumConstants) {
            values.add(iEnum.getValue());
        }
        if (exclusion.length > 0)
            for (int i : exclusion) {
                values.remove(i);
            }
    }

    @Override
    public boolean isValid(EnumBase param, ConstraintValidatorContext constraintValidatorContext) {
        if (nullable && param == null) {
            return true;
        }
        else if(param == null)
            return false;
        return values.contains(param.getValue());
    }
}

this is my enum:
public enum TransactionMethod implements EnumBase {
    CREDIT_CARD("creditcard"),
    DEBIT_CARD("debitcard");
    public String label;

    TransactionMethod(String label) {
        this.label = label;
    }

    @Override
    public String getValue() {
        return this.label;
    }

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public static TransactionMethod fromString(String value) {
        return TransactionMethod.valueOf(value);
//        return Arrays.stream(TransactionMethod.values())
//                .filter(el -> el.getValue().equals(value))
//                .findFirst()
//                .orElseThrow(() -> {
//                    throw new IllegalArgumentException("Not valid method");
//                });
    }
}

when I'm sending my http request to that rest controller :
@RequiredArgsConstructor
@RestController
@RequestMapping("/orders")
@Validated
public class PaymentRestController {

    public ResponseEntity<?> createPayment(
            @Valid @RequestBody PayOrderDTO payOrderDTO
    ) {
        return ResponseEntity.ok("Worked");
    }
}

request example:
POST /orders/ HTTP/1.1
Host: store.test
Content-Type: application/json
Content-Length: 152

{
    "method":"creditcard",
}

I'm expecting to get invalidation exception or error message defined in my enum validator, instead I get an exception in the console that contains :
JSON parse error: Cannot construct instance of `x.TransactionMethod`, problem: No enum constant x.TransactionMethod.creditcard

But if I sent this request :
POST /orders/ HTTP/1.1
Host: store.test
Content-Type: application/json
Content-Length: 152

{
    "method":"CREDIT_CARD",
}

the application works normal
I want to validate enum using label instead of constant value of the enum, if it doesn't exists, a validation error will be thrown like :
HTTP 422 : field 'method' is not valid, expected values are ['creditcard','debitcard']

I tried some solutions as well like the convertor
public class TransactionMethodStringEnumConverter implements Converter<String, TransactionMethod> {
    @Override
    public TransactionMethod convert(String source) {
        Optional<TransactionMethod> first = Arrays.stream(TransactionMethod.values()).filter(e -> e.label.equals(source)).findFirst();
        return first.orElseThrow(() -> {
            throw new IllegalArgumentException();
        });
    }

}

but seems like I does nothing.
I would really appreciate is someone has a good solution for this, Thank you

A: To deserialize an enum by label value you can use @JsonValue annotation on a getter:
public enum TransactionMethod implements EnumBase {

    CREDIT_CARD("creditcard"),
    DEBIT_CARD("debitcard");

    public String label;

    TransactionMethod(String label) {
        this.label = label;
    }

    @Override
    @JsonValue
    public String getValue() {
        return this.label;
    }
}

How To Serialize and Deserialize Enums with Jackson
Also, pay attention to the facts:

*

*You have values.remove(i) in the initialize() method of EnumValidatorImpl, although elements of Set are not indexed and Set<String> values has generic type String.

*In your EnumValidator you can set nullable=true using boolean nullable(), but in PayOrderDTO you still check the method field for null using @NotNull, which can lead to an undesirable result.

EDIT:
You can define locale-specific messages with MessageSource, look at this article.
In your message.properties: invalid.transaction.method=is not valid, expected values are ['creditcard','debitcard']
Then add message to annotation:
@EnumValidator(enumClass = TransactionMethod.class, message = "{invalid.transaction.method}")

By failed validation catchMethodArgumentNotValidException in @ExceptionHandler method in @RestController or @RestControllerAdvice and format message as you want, e.g.:
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public void handleException(MethodArgumentNotValidException e) {

    String errorMessage = e.getBindingResult().getFieldErrors().stream()
            .map(fieldError -> fieldError.getField() + " " + fieldError.getDefaultMessage())
            .collect(Collectors.joining(";"));

    LOG.error(e.getMessage()); // method is not valid, expected values are ['creditcard','debitcard']
}


text:
Q: C# How to measure function time execution I have a C# function that I want to measure execution time:
// save audit log using XML approach
if (records > 0) {

    using(SQLRepository repo = new SQLRepository()) {

        // this is one approach that I want to meassure
        repo.SaveChangeLog(tw.ToString());

        // this is second approach that I want to meassure
        repo.SaveChangeLogApproach2(tw.ToString());
    }
}

Is there something already in Visual Studio that I can use to get those executions times?

A: You should be using the System.Diagnostics.Stopwatch class.

A: Note that if you time both method calls within the same using statement, the first call may be slower due to instantiation of the repo class.


text:
Q: Reset Windows user profile settings to default values After I upgraded Windows 7 to Windows 10, the user account I use seems to be corrupted. For example, after I enabled Spotlight on that account, it doesn't let me disable it, and after I upgraded to 1511, after I log in it shuts down the PC. When I managed to log in, I noticed that the accent color was changed as well, and setting it to "Automatically pick an accent color from my background" didn't fix it.
I created a new account after the Windows 10 upgrade, and it doesn't have these problems, so my guess is that somehow the settings from Windows 7 have messed up my profile.
Microsoft's solution is to delete the account and start from scratch. I'm trying to avoid that, since I want to keep my application settings, and if I have to start from scratch, I might as well do a clean Windows 10 installation instead.

A: So, after messing up my profile thoroughly by using a tool designed for windows XP, I went ahead and followed Microsoft's advice and just created a new local account. I'm my case, it was painless enough, but I had to reinstall a few apps that I installed for just the other account instead of fire all users.
Marking this as the accepted answer, but if someone suggests a better solution in the future, I'll be interested in trying it out and accepting it.


text:
Q: Async issue in discord bot code; Unexpected Token ( I wanted to start my bot but the console is giving me the SyntaxError : Unexpected token (.
A few months ago the code worked just fine, now it keeps giving me this error:
    bot.on("ready", async () => {
                          ^
SyntaxError: Unexpected token (

I tried removing the async keywords completely in my code but now I get another error:
console.log(` `);
SyntaxError: Unexpected token .

bot.on("ready", async () => {
    console.log(` `);
    console.log(` `);
    console.log(`============================================`);
    console.log(` `);
    console.log('     The bot is now fully opertational!')
    console.log(` `);
    console.log(`============================================`);
});

I expect the ouput to be "The bot is now fully operational".

A: try this code:
bot.on('ready', () =>{
    console.log(` `);
    console.log(` `);
    console.log(`============================================`);
    console.log(` `);
    console.log('     The bot is now fully opertational!')
    console.log(` `);
    console.log(`============================================`);
})

This should work :)


text:
Q: Combinations between elements in two tuples in Python I have two tuples:
t1 = ('A', 'B')
t2 = ('C', 'D', 'E')

I wonder how to create combinations between tuples, so the result should be:
AC, AD, AE, BC, BD, BE

EDIT
Using
list(itertools.combinations('abcd',2))

I could generate list of combinations for a given string:
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

If I insert tuple instead of string the following error occurs:
TypeError: sequence item 0: expected string, tuple found

Any suggestion how to proceed?

A: for value_one in t1:
    for value_two in t2:
        result = (str(value_one), str(value_two))
        print result

This uses no external libraries. Literally just two for loops and string concatenation. Format the output however you'd like.
This seems like you either did not put any effort into finding this answer, or I am misinterpreting the question.
Edit: I see that you are coming from an R background, so you may not understand Python syntax. Please refer to guides for Python basics; I believe they will help greatly. To save the values from the loop, as @Naman mentioned, you will want to make an empty list and [list_name].append([value]) the desired values, then print the values in the list using other constructs.

A: itertools.product does exactly what you are looking for:
>>> import itertools
>>> t1 = ('A', 'B')
>>> t2 = ('C', 'D', 'E')
>>> list(itertools.product(t1, t2))
[('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E')]
>>> [''.join(x) for x in itertools.product(t1, t2)]
['AC', 'AD', 'AE', 'BC', 'BD', 'BE']

A: All possible combinations:
import itertools

t1 = ('A', 'B')
t2 = ('C', 'D', 'E')

print(tuple(itertools.combinations(t1 + t2, 2)))

Output: (('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E'))

A: Here is my simple method:
for i in t1:
    for j in t2:
        print(i+j,end="")

This three line of input  gives the above combinations.

A: You can print what you want by iterating over both the tuples(or make an empty list and store your output in that list)
l = []
for c1 in t1:
    for c2 in t2:
        print c1 + c2 + ',',
        l.append(c1 + c2)

Finally list l will contain the output elements. You can process its elements or make a tuple of it by
t = tuple(l)

A: t = []
for x in t1:
    for y in t2:
        t.append(x+y)

t = tuple(t)

So iterate over both tuples, append every combination to a list and then convert the list back to a tuple.


text:
Q: formating lines in the paragraphs I'm writing report in latex .But my document appear with not good style all lines in paragraphs not in same length >How to get that ?
edit:
\documentclass{book}
\begin{document}

\pagestyle{empty} %No headings for the first pages.

\tableofcontents
\pagestyle{plain}

\flushleft
\clearpage
 \chapter*{Dedication}
 \addcontentsline{toc}{chapter}{Dedication}
%\begin{Dedication}

First,we  thank God for His blessings and to reconcile and repaid during these years that have passed us to get to this stage of science, knowledge and culture.

We thank our parents on a continuous effort and giving and  permanent support to reach  Achievements.
 \clearpage
\end{document}

A: Hard to guess what output you want, three alternatives:

\documentclass{article}

\begin{document}

\begin{description}
  \item[In nature,] clustering is a mechanism for solving  diversity and
complexity things from simple and basic elements.
    In IT field: is a good concept and technique to use existing component
hardware or software to accomplish specific goal with special  characteristics
 (cost, time, performance at all).
 \item[The history] of the cluster usage begin in largest computers in the
 world , But clusters are also playing important roles in technical and commerce
 computing, taking advantage of low cost, complex market PC-based computer
technology. These
    Beowulf-cluster systems have Become too popular, play the best role in
 reducing cost, area needed for the environment, time for
    execution, on the other side it increased the performance and extended
   the scope for most of the net based application, Flexibility
    Configuration and promotion, and the ability to provide new and powerful
 tool, and open new opportunities for the whole computing applications.
\end{description}

\bigskip

  \textbf{In nature,} clustering is a mechanism for solving  diversity and
complexity things from simple and basic elements.
    In IT field: is a good concept and technique to use existing component
hardware or software to accomplish specific goal with special  characteristics
 (cost, time, performance at all).

\textbf{The history} of the cluster usage begin in largest computers in the
 world , But clusters are also playing important roles in technical and commerce
 computing, taking advantage of low cost, complex market PC-based computer
technology. These
    Beowulf-cluster systems have Become too popular, play the best role in
 reducing cost, area needed for the environment, time for
    execution, on the other side it increased the performance and extended
   the scope for most of the net based application, Flexibility
    Configuration and promotion, and the ability to provide new and powerful
 tool, and open new opportunities for the whole computing applications.

\bigskip

  \paragraph{In nature,} clustering is a mechanism for solving  diversity and
complexity things from simple and basic elements.
    In IT field: is a good concept and technique to use existing component
hardware or software to accomplish specific goal with special  characteristics
 (cost, time, performance at all).

\paragraph{The history} of the cluster usage begin in largest computers in the
 world , But clusters are also playing important roles in technical and commerce
 computing, taking advantage of low cost, complex market PC-based computer
technology. These
    Beowulf-cluster systems have Become too popular, play the best role in
 reducing cost, area needed for the environment, time for
    execution, on the other side it increased the performance and extended
   the scope for most of the net based application, Flexibility
    Configuration and promotion, and the ability to provide new and powerful
 tool, and open new opportunities for the whole computing applications.

\end{document}

A: You have added \flushleft that disables justification. Hence remove it.
\documentclass{book}
\usepackage{ragged2e}
\begin{document}

\pagestyle{empty} %No headings for the first pages.

\tableofcontents
\pagestyle{plain}

%\flushleft   %%<- remove
\clearpage
 \chapter*{Dedication}
 \addcontentsline{toc}{chapter}{Dedication}
%\begin{Dedication}
\Centering
First,we  thank God for His blessings and to reconcile and repaid during these years that have passed us to get to this stage of science, knowledge and culture.

We thank our parents on a continuous effort and giving and  permanent support to reach  Achievements.
 \clearpage
\end{document}


text:
Q: Need help understanding java linked list putAfter() method An element in the chain that comprises a LinkedList.
Note: the operations of this class manage the relationship between a Link and its neighbors.
The LinkedList is responsible for keeping tract of the head and tail of the list.
public class Link<Item> {
    private final Item item;
    private Link<Item> next;
    private Link<Item> prev;

Insert this Link into a list after a given Link.
@param before is the given Link.
public final void putAfter (Link<Item> before) {
    prev = before;
    if (null == before) return;
    next = before.next;
    before.next = this;
    if (null != next)
        next.prev = this;
}

A: You have made a basic mistake in the coding of the method1.
You can find it by:

*

*reading your code and "executing" it in your head ... or with a pencil and paper, or

*running it in a debugger and single-stepping the method to see what each statement is actually doing.

We could tell you what your mistake is, but you will learn to program better if you try to find the problem yourself.  That will make you a better programmer in the long run ... and that's what we want2.

1 - Based on the nature of the method you are writing, I am assuming that this is some kind of learning exercise.  If that was not the case, my answer would have been different ...
2 - And to be clear, I do not condone doing other peoples' homework for them.  It is in nobody's interest in the long term.


text:
Q: Code breaks syntax highlighting in Atom / Nuclide This Javascript / React Native code, which works just fine, breaks the syntax highlighting in Atom  / Nuclide for anything that comes after it. Is there anything wrong with the code or is it the syntax highlighting engine?
static navigationOptions = {
    headerTitle: "TFN Top Headlines",
    headerTitleStyle: { fontFamily: "Iowan Old Style" },
    headerLeft: (
      <Icon
        size={35}
        onPress={() => {
          _this.toggleMenu();
        }}
        style={{
          marginLeft: 10
        }}
        name="navicon"
      />
    )
  };

A: You will need to install a Plug-in to support JSX formatting.
You could try https://atom.io/packages/language-babel


text:
Q: Create LINQ request I have some collections:
Dictionary<InvoceHeader, List<InvoiceHierarchy>> where
public class InvoceHeader
{
    public int InvoiceId { get; set; }
    public string DocumentNumber { get; set; }
    public string DocumentDate { get; set; }
    public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Certificate { get; set; }
    public string Description { get; set; }
}

I need to write a LINQ request to get such a collection from the original collection --> Dictionary<string, List<string>>, where key --> InvoceHeader.DocumentNumber, value --> List two elements from InvoiceHierarchi such as the SerialNumber and Certificate.

A: Dictionary<string, List<string>> converted = original
    .ToDictionary(
        kvp => kvp.Key.DocumentNumber,
        kvp => kvp.Value.Select(ih => ih.SerialNumber + ih.Certificate).ToList());

A: Try following :
   class Program
    {
        static void Main(string[] args)
        {
            List<InvoceHeader> headers = new List<InvoceHeader>();
            List<InvoiceHierarchi> hierarchi = new List<InvoiceHierarchi>();

            var query = (from header in headers
                         join hierarch in hierarchi on header.DocumentNumber equals hierarch.Certificate
                         select new { header = header, hierarch = hierarch }
                         ).ToList();

            Dictionary<string, object> dict = query
                .GroupBy(x => x.header.DocumentNumber, y => new { header = y.header, hierachi = y.hierarch })
                .ToDictionary(x => x.Key, y => (object)y.ToList());

        }

    }
    public class InvoceHeader
    {
        public int InvoiceId { get; set; }
        public string DocumentNumber { get; set; }
        public string DocumentDate { get; set; }
        public string DocumentReference { get; set; }
    }

    public class InvoiceHierarchi
    {
        public string SerialNumber { get; set; }
        public string ProductCode { get; set; }
        public string Certificate { get; set; }
        public string Description { get; set; }
    }

A: That should be the query that you are looking for, only that you can replace the anonymous types that I am using in the query with a custom type that you created.
var newCollection = originalCollection.Select(x => new
                {
                    Key = x.Key.DocumentNumber,
                    Value = x.Value.Select(y => new
                    {
                        y.SerialNumber,
                        y.Certificate
                    }).ToList()
                });

If you want again to convert it to Dictionary, you can also add that line:
 var newDictionary = newCollection.ToDictionary(x => x.Key, y => y.Value);


text:
Q: Nested Loop in JavaScript : Can anyone please explain to why I get this result in this code? I'm  learning Nested Loop in Javascript and I just still don't understand why I get this result.
Original Code:

    const list = [['A' , 'B' , 'C', 'D'],
                 ['E' , 'F' , 'G', 'H'],
                 ['I' , 'J' , 'K', 'L'] ];

    for (let i = 0; i < list.length ; i++){
       const row = list[i];
       console.log(`LIST #${i + 1}`);

          for (let j = 0; j < row.length ; j++){
           console.log(row[i]);
         }
       }

Result:
LIST #1
-------
A
LIST #1
-------
F
LIST #1
-------
K

Can anyone explain to me ? thanks!
Edit:
This is not a typo question, I just don't understand why i got A, F  K (4x in a row) when i tried to use console.log(row[i]);

A: You printed row[i]. But You must print row[j]

const list = [['A' , 'B' , 'C', 'D'],
             ['E' , 'F' , 'G', 'H'],
             ['I' , 'J' , 'K', 'L'] ];

for (let i = 0; i < list.length ; i++){
   const row = list[i];
   console.log(`LIST #${i + 1}`);

      for (let j = 0; j < row.length ; j++){
       console.log(row[j]);       // here you must print row[ j ] for right answer
     }
   }

A: It's because you're using row[i] instead of row[j]. (For the moment, you're using the index of the first loop)

const list = [['A' , 'B' , 'C', 'D'],
             ['E' , 'F' , 'G', 'H'],
             ['I' , 'J' , 'K', 'L'] ];

for (let i = 0; i < list.length ; i++){
  const row = list[i];
  console.log(`LIST #${i + 1}`);
  for (let j = 0; j < row.length ; j++){
    console.log(row[j]); /* row[j] instead of row[i] */
  }
}

Moreover, if you want, you can use .map for your array list insead of for loops.

const list = [['A' , 'B' , 'C', 'D'],
             ['E' , 'F' , 'G', 'H'],
             ['I' , 'J' , 'K', 'L'] ];

list.map((list, listIndex) => {
  console.log(`LIST #${listIndex+1}`);
  console.log(list.join(' '));
});


text:
Q: LAN speeds and firewall/switch connections I have a small network with about ten users. All workstations flow into a Dell PowerConnect 3424 which then has a single link to a SonicWALL firewall and from there to a cable modem. More important than internet connectivity is speed between machines (specifically a Windows Server box on the LAN which everyone uses simultaneously). I believe the 3424 has gigabit connections, but they look like they're for stacking.
Is there a way to test the speeds on the LAN to see where the speeds are at?
Is there any low-hanging fruit insofar as increasing speeds?

A: The easiest way to test speed is to simply copy a file from one machine to another on the lan.
What are you using the windows server for? If you're all using it as a file server, I'd say no problem. If it's running some intensive terminal services stuff, might be an issue, but more likely a resource issue on the server, than on your lan.
10 people on a lan shouldn't saturate anything, even at a mere 100Mb. You'd have to be doing something really intense.

A: Iperf is a pretty easy way to test this and see what parameters make the biggest difference.

A: Most modern PC's will have a Gigabit capable Network adapter in them, and it'll be set to Auto Negotiate by default, meaning they'll connect automagically to a 10Mb, 100Mb, or 1000Mb Switch.
One easy way might be to find such a PC and check the speed that it connects to the LAN at, which will tell you the speed (and duplex) of the port you're connecting from.  You'll need to check that it's set to Autonegotiate first of course.
One common issue with speeds is the common speed/duplex mismatch issue.  This will manifest itself particularly under fairly heavy load, and for this reason I'd strongly suggest manually setting the speed and duplex of any Server or Router connecting to the fastest supported speed and duplex combination, which would be in order of fastest to slowest 1000/Full, 1000/Half, 100/Full, 100/Half, 10/Full, 10/Half.
Just because the Switch is capable of Gigabit operation, it doesn't mean that the cabling is!  If you're using old Cat3 or Cat5 cabling that a chair has been running over for years, don't expect to get 1000Mbit performance from it!
Hope you find something useful in my ramblings above!

A: You can plug your server NIC into one of the gigabit ports and the workstations into the 100mb ports; that way each workstation will still be limited to a maximum of 100mb/s to and from the server, but the server will have a greater aggregate throughput.
To check what speed your network connection is at, go to the Local Area Network device in the control panel. Windows will tell you what speed you are connected at (i.e., 100 mbps, 1 Gbps).
You will probably find that your disk i/o on the server is the bottleneck in transferring files, rather than the network bandwidth. You can run perfmon on the server and view statistics such as disk queue - if this plateaus, then you probably have reached the maximum speed at which your disks can transfer data.
Task Manager on the server will show you what your network throughput is. Some servers or network drives have more informative information. The HP Teaming adapter has loads of useful statistics to look at, if you have an HP server.


text:
Q: Angular :: Enviroment file fetch propery error Im new to Angular2, I have added some API configurations in environment file,its not giving any exception during compile time but getting exception at run time.
import { environment as defaultEnvironment } from './environment.defaults'

export const environment = {
  ...defaultEnvironment,
  production: false,
  apiService: {
    serviceUrl: defaultEnvironment.baseURL + "TestService/",
    getCompanies: this.serviceUrl + "GetCompanies",
  }
};

At run time when its fetching value of serviceUrl in getCompanies, im getting exception "Uncaught TypeError: Cannot read property 'serviceUrl' of undefined"
Can anyone help to know why this is happening ? Thanks

A: Usually the this has as type typeof globalThis globalThis. Which I believe has as type any in a typescript environment. So that's why the compiler is not complaining (as long as you don't use strict: true in typescript.
I suppose angular does things a bit differently in the environment files. These are specially parsed to be able to get replacement values in your codebase.
Nevertheless, what you are trying to do there will not work. this will never be the object you are currently constructing. You will need to split that up:
import { environment as defaultEnvironment } from './environment.defaults'

const serviceUrl = defaultEnvironment.baseURL + "TestService/";

export const environment = {
  ...defaultEnvironment,
  production: false,
  apiService: {
    serviceUrl,
    getCompanies: serviceUrl + "GetCompanies",
  }
};


text:
Q: Manipular String em JAVA? Tenho uma consulta de SQL que o conteúdo me traz assim:
fulano@mail.com;ciclano@mail.com

Eu preciso somente do primeiro endereço, tenho que desconsiderar tudo que esta a partir do ;?

A: Se for diretamente na SQL utilize um junção de funções, SUBSTRING e CHARINDEX:
SELECT SUBSTRING(email, 1,CHARINDEX(';', email)-1) from emails;

onde email é o campo que guarda os endereços eletrônicos separados por virgula e emails o nome da tabela.
Resposta retirada: SoEn - How to split a comma-separated value to columns

Uma adequação para pegar os e-mail que não possuem items separados por ;, ou seja, apenas um e-mail contido no campo sem ;:
select CASE WHEN Charindex(';', email)>0
   THEN Substring(email, 1,Charindex(';', email)-1) ELSE
   email END
from emails

Referencias:

*

*SUBSTRING (Transact-SQL)

*CHARINDEX (Transact-SQL)

*CASE (Transact-SQL)

A: Existem algumas maneiras:
com indexOf
String result = "fulano@mail.com;ciclano@mail.com";
int index = result.indexOf(";");
if (index > 0) {
    result = result.substring(0, index);
}
System.out.println(result);

com split
String result = "fulano@mail.com;ciclano@mail.com";
String[] emails = result.split(";");
result = emails[0];
System.out.println(result);

A: Pode usar a função split do Java para fazer isso.
String email = "fulano@mail.com;ciclano@mail.com.br";
String[] emails = email.split(";");
System.out.println(emails[0]);

A função split divide uma String em várias Strings usando o delimitador dado e retorna as partes em um vetor de String. Como vc precisa apenas o primeiro, é só usar:
emails[0]

Veja funcionando no ideone.


text:
Q: Tests fail when creating community user When our unit tests create a new user with the community license, the test fails with the following exception: System.DmlException:
Insert failed. First exception on row 0; first error: LIMIT_EXCEEDED, limit exceeded: [].
Test class
@isTest
private class UsersSetTest {
  @isTest(SeeAllData=true)
  static void setCompanyNameForCommunityUsers() {
    UserRole portalRole = [SELECT Id FROM UserRole WHERE PortalType = 'None' Limit 1];
    ProfilesData profileData = new ProfilesData();
    Profile communityProfile = profileData.selectProfileByName(CommunitiesExt.PROFILE_CUSTOMER_ACCESS);
    Profile adminProfile = profileData.selectProfileByName('System Administrator');

    User portalAccountOwner1 = new User(
      UserRoleId = portalRole.Id,
      ProfileId = adminProfile.Id,
      Username = System.now().millisecond()+'test2@test.com',
      Alias = 'batman',
      Email='ab@abc.com',
      EmailEncodingKey='UTF-8',
      Firstname='a',
      Lastname='b',
      LanguageLocaleKey='en_US',
      LocaleSidKey='en_US',
      TimeZoneSidKey='America/Chicago'
    );
    insert portalAccountOwner1;

    Contact contact1;
    User user1;
    System.runAs(portalAccountOwner1) {
      //Create account
      Account portalAccount1 = new Account(Name='TestAccount',OwnerId=portalAccountOwner1.Id);
      insert portalAccount1;

      //Create contact
      contact1 = new Contact(FirstName='Test',Lastname='Testy',AccountId=portalAccount1.Id,Email=System.now().millisecond()+'test@test.com');
      insert contact1;

      user1 = SObjectFactory.buildTestUserForProfile(System.now().getTime()+'test@test.com', communityProfile.Id);
      user1.CompanyName = null;
      user1.ContactId = contact1.Id;
      user1.PortalRole = 'Manager';

      insert user1;
    }

    user1 = [SELECT CompanyName FROM User WHERE Id = :user1.Id];
    System.assertEquals(CommunitiesExt.COMPANY_NAME_MEMBER, user1.CompanyName);
  }
}


text:
Q: USB3.0 controller with VIA chip does not see external drive I've installed an "ORICO Superspeed 5-Port PCI-E to USB 3.0 PCI Expansion Card, Mini PCI-E USB 3.0 Hub Controller Adapter with Internal USB 3.0 20-PIN Connector [ VL800 and VL812 USB 3.0 Controller]" that is supposed to work with Linux on my HP GL380 server which does not have any 4 pin Molex or SATA power connectors. (everything is directly connected to the motherboard and risers)
I'm hoping I won't need to plug in the secondary power as this "should" just be for powering an external USB device that needs power. As my external drives already have power supplies, they should theoretically not need power from the port.
After much searching I found a "Sangoma ST1 PCI-E Riser with Power Adapter +12 V Molex Y Connector" that will plug into an unused PCI-E slot and provide power, but it is rather expensive, so I'm hoping I won't need it...
From the command line:
Using lspci -v the entry for this card is:
 0e:00.0 USB controller: VIA Technologies, Inc. VL805 USB 3.0 Host Controller   (rev 01) (prog-if 30 [XHCI])
    Subsystem: VIA Technologies, Inc. VL805 USB 3.0 Host Controller
    Physical Slot: 3
    Flags: bus master, fast devsel, latency 0, IRQ 26
    Memory at fdef0000 (64-bit, non-prefetchable) [size=4K]
    Capabilities: [80] Power Management version 3
    Capabilities: [90] MSI: Enable+ Count=1/4 Maskable- 64bit+
    Capabilities: [c4] Express Endpoint, MSI 00
    Capabilities: [100] Advanced Error Reporting
    Kernel driver in use: xhci_hcd

The controller card is seen by lsusb as:
 /:  Bus 08.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 5000M
    |__ Port 2: Dev 2, If 0, Class=Hub, Driver=hub/4p, 5000M

But when I plug in an external drive (that works fine on one of the server's built-in USB ports) nothing happens.
Am I missing something in the setup or should I try to power the USB 3.0 ports and see if it works?

A: it's bug, already report here:
https://bugzilla.redhat.com/show_bug.cgi?id=1409098


text:
Q: how to change runtime errors into english I am seeing run-time errors in local language of windows which is annoying (pic below). I have changed regional settings to English from Windows settings, and also international language from Visual Studio environments settings also added globalization uiCulture="en-US" into web.config but still no success, is there something I am missing?

A: Just in case you encounter a localized messaged and are looking for the original error message: You can use the service on unlocalize.com to translate back:

http://www.unlocalize.com/SearchResults.aspx?search=Uygulamas%C4%B1nda+Sunucu+Hatas%C4%B1

A: ok found out the solution just added lines below into application_error in global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

A: I think the problem is from IIS configuration, it was not installed in an English Windows and the Error Page is not in English due to this.
See you

A: Could it be that your browser is asking for a non English page by default? What happens if you  change the default accepted language in, say, IE? You could find the settings in Options->General->Languages.


text:
Q: How to open recently modified or recently created file using command prompt bat file How to open recently modified or recently created file using command prompt bat file. I have a folder in my C: drive named "test plans" in which reports get save automatically (with name 'Summary141013 113403.csv'; "Summary" is a constant but date and time keep change). I want my .bat file to open recently created file.

A: openLastFile.cmd
@echo off
setlocal enableextensions
set _dir=c:\test plans
set _lastFile=
for /F "tokens=*" %%f in ('dir /od /b "%_dir%\*.csv"') do set _lastFile=%%f
if not "%_lastFile%"=="" (
    notepad "%_dir%\%_lastFile%"
)
endlocal

A: for /f %%a in ('dir /b /a-d /od "c:\test plans\*.csv"') do set "RecentFile=%%~a"
"c:\test plans\%RecentFile%"

This opens the file with the associated program.

A: This will open files modified today in the Current Working Directory by NotePad:
FORFILES /M *.csv /D 0 /C "cmd /c notepad.exe @file"

Or open it with default associated open handler, MS Excel, eg:
FORFILES /M *.csv /D 0 /C "cmd /c @file"


text:
Q: Installing router - failed to verify router settings I'm trying to install a TP-Link wireless router. I am using a modem an have a PPPoE connection. I connected the router to the computer and the modem, but in the last step of the Easy Setup it says " Failed to verify router settings. 1. Please check the WAN connection type and parameters. 2. Please check your connectivity and retry."
The internet works fine if i connect the modem directly to the computer.
When I connect the computer to the router, the wireless network is detected by other devices, but cannot be accessed.
I accessed the router settings, and everything seems normal, except that it just says "Connecting...". It never manages to connect to the internet. I tried restarting the router and several walkthroughs on the web, but I couldn't get it to work.

A: I had the same error.. the mistake I was making was that I was selecting PPPoE settings whereas I should have selected Dynamic IP because I havent been given a user id or password by my service provider. In dynamic IP option it automatically detects the given IP by the provider. My router is now connected flawlessly :) no more error of "failed to verify router settings"


text:
Q: Can i inject a Singleton-DependencyInjected object in multiples areas in a Blazor client application? I have a Blazor application where i am injecting a class (NotificationClass) to the MainLayout.razor.
The NotificationClass has a Errors string property. My goal is to using this class to bind to some component so i can show an errors that occur in any area of the client application. The ultimate idea is to show a Toast notification when an error occurs.
But so far this doesnt appear to be working.
Question
Is it possible to inject a singleton instance to different areas of the application?
If so, i think i need to implement a Changed event so i can invoke StateHasChanged in the MainLayout.razor.
Resolved

I was able to resolve this myself by doing exactly what i suspected. I
  raised an event which is handled by MainLayout. On that

event handled, i invoke this.StateHasChanged().


text:
Q: Remove multiple words from String in one statement I wish to purge the http:// and www. parts of an URL String using one statement.
I am not after wizardly regex-solutions, I simply want to know if there is a way to replace (read: remove) both words in one single replace statement.
Dream scenario:
String url = "http://www.superfect.com";
String[] purge = {"http://", "www."};
url = url.replace(purge, "");

This does not run, however. How is this usually done in Java?

A: In a single line, with a single replacement action:
url = url.replaceAll("http://|www\\.", "");

A: Do this in a simple loop:
String purge[] = {"www.", "http://", "https://", "ftp://"};
String result = url;
for (int i = 0; i < purge.length; ++i)
{
    result = result.replace(purge[i], "");
}

Now, the result String is the one you want. As codesalsa pointed out and given the context of URL's, you might want to do it this way:
String purge[] = {"http://", "https://", "ftp://", "www."}; //order is important!
String result = url;
for (int i = 0; i < purge.length; ++i)
{
    if (result.startsWith(purge[i])
    {
        result = result.substring(purge[i].length);
    }
}

A: Java doesn't offer a method for replacing more than one literal character sequence at a time.  Regular expressions could be used, to match both intended replacement targets in the same call.
Without regular expressions, you need to call replace once for each target.
url = url.replace("http://", "").replace("www.", "");

A: You could do
url = url.replaceAll("http://(?:www\\.)?", "");

A: You've got already plenty of nice & working solutions written right here. I'm, however, kinda a fan of clean, easily-understandable code. There's nothing more wonderful than elegant one-command solution. Here you go. You're welcome!
public class Test {
        public static String parseDomainName(String url) {
            return (
                url.startsWith("http://www.") ? url.replaceFirst("http://www\\.", "") :
                    url.startsWith("http://") ? url.replaceFirst("http://", "") :
                        url.startsWith("www.") ? url.replaceFirst("www\\.", "") :
                            url
            );
    }

    public static void main(String[] args) {
        System.out.println(parseDomainName("http://www.google.com"));
        System.out.println(parseDomainName("http://google.com"));
        System.out.println(parseDomainName("www.google.com"));
        System.out.println(parseDomainName("google.com"));
        System.out.println(parseDomainName("http://misleading.www.com"));
    }
}

Alright, I'm just joking! But it's the single solution right here, which works in one command and doesn't use regular expressions (well, method replaceFirst() actually accepts only a regular expressions, but it'd be working on the same logic even with different method, which accepts only plain text string).
Use this solution as it's the best compromise if you really want to avoid using regular expressions. This solution I've made is really just a joke and it'd be horrible to see it used somewhere. :-)

A: How about this?
url = url.replace("http://www.", "");

Wouldn't that work?


text:
Q: Reading text file containing adjacent matrix then outputs BFS and DFS (JAVA) public class BFS
{

    private Queue<Integer> queue;

    public BFS()
    {
        queue = new LinkedList<Integer>();
    }

    public void bfs(int adjacency_matrix[][], int source)
    {
        int number_of_nodes = adjacency_matrix[source].length - 1;

        int[] visited = new int[number_of_nodes + 1];
        int i, element;

        visited[source] = 1;
        queue.add(source);

        while (!queue.isEmpty())
        {
            element = queue.remove();
            i = element;
            System.out.print(i + "\t");
            while (i <= number_of_nodes)
            {
                if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
                {
                    queue.add(i);
                    visited[i] = 1;
                }
                i++;
            }
        }
    }

    public static void main(String... arg)
    {
        int number_no_nodes, source;
        Scanner scanner = null;

        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_no_nodes = scanner.nextInt();

            int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_no_nodes; i++)
                for (int j = 1; j <= number_no_nodes; j++)
                    adjacency_matrix[i][j] = scanner.nextInt();

            System.out.println("Enter the source for the graph");
            source = scanner.nextInt();

            System.out.println("The BFS traversal of the graph is ");
            BFS bfs = new BFS();
            bfs.bfs(adjacency_matrix, source);

        } catch (InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input Format");
        }
        scanner.close();
    }
}

above is the code. I just want to use a text file containing the adjacent matrix instead of asking the user for input for adjacent matrix.  Can someone help me with this one? Appreciate any help :)

A: //For files which is included in your project follow the below line :

InputStream is= ClassLoader.getSystemResourceAsStream(filename);

//Otherwise create the file obj(File file = new File("Location/of/yourfile"))
//and pass onto FileReader which in turn passed onto InputStream

BufferedReader br= new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
  String[] inputArr= line.trim().split(" ");
  //Put in the matrix using loop
}


text:
Q: Django1.8: UnicodeEncodeError 'gbk' codec can't encode character '\xbb' I'm using django 1.8, developing in windows7.
The system codec is 'gbk'.
When I call:
print(request.POST)

In my view function, I got this error:
UnicodeEncodeError at /mrp/list/item/purchase/0/
'gbk' codec can't encode character '\xbb' in position 206: illegal multibyte sequence

I notice that the debug information shows META['PYTHONIOENCODING'] = 'GBK'
But when I try to print the python encoding before the error code:
import sys
print(sys.getdefaultencoding())

I shows utf8!
So why it is using 'GBK'? Where should I change that setting? I've been searching for the documents but with no luck.
Please help!

META:
Variable    Value
SYSTEMROOT
'C:\\Windows'
PATH_INFO
'/mrp/list/item/purchase/0/'
HOMEPATH
'\\Users\\Alfred'
WINDOWS_TRACING_LOGFILE
'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log'
HTTP_ACCEPT_LANGUAGE
'zh-CN,zh;q=0.8,en;q=0.6,ru;q=0.4,zh-TW;q=0.2'
DJANGO_SETTINGS_MODULE
'ecerp.settings'
SHIM_MCCOMPAT
'0x810000001'
USERDOMAIN
'Alfred-PC'
SERVER_NAME
'activate.adobe.com'
PROCESSOR_IDENTIFIER
'Intel64 Family 6 Model 58 Stepping 9, GenuineIntel'
WINDOWS_TRACING_FLAGS
'3'
FP_NO_HOST_CHECK
'NO'
wsgi.file_wrapper
''
QUERY_STRING
''
CLASSPATH
'.;C:\\Program Files\\Java\\jdk1.8.0_31\\lib;C:\\Program '
'Files\\Java\\jdk1.8.0_31\\lib\\tools.jar;d:\\java\\lib'
SERVER_PROTOCOL
'HTTP/1.1'
PYTHONIOENCODING
'GBK'
ALLUSERSPROFILE
'C:\\ProgramData'
USERNAME
'Alfred'
NUMBER_OF_PROCESSORS
'4'
PROGRAMFILES(X86)
'C:\\Program Files (x86)'
HTTP_PRAGMA
'no-cache'
PSMODULEPATH
'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\'
TMP
'C:\\Users\\Alfred\\AppData\\Local\\Temp'
COMPUTERNAME
'ALFRED-PC'
SESSIONNAME
'Console'
USERPROFILE
'C:\\Users\\Alfred'
SERVER_PORT
'8000'
PROCESSOR_ARCHITECTURE
'AMD64'
REMOTE_HOST
''
HTTP_COOKIE
'verify_code=eW91Y2h1YW5n; sessionid=pncf4qix2xxjvkig3ek9v9oyvgb7aouc; '
'csrftoken=daIMsNDpBbireeQsbVGRJ6tMYijwxAu8'
wsgi.multithread
True
wsgi.input
<_io.BufferedReader name=908>
PATHEXT
'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY'
PROGRAMW6432
'C:\\Program Files'
PYCHARM_HOSTED
'1'
COMMONPROGRAMW6432
'C:\\Program Files\\Common Files'
HTTP_ORIGIN
'http://localhost:8000'
WINDIR
'C:\\Windows'
GATEWAY_INTERFACE
'CGI/1.1'
PROGRAMDATA
'C:\\ProgramData'
wsgi.multiprocess
False
REQUEST_METHOD
'POST'
OS
'Windows_NT'
SERVER_SOFTWARE
'WSGIServer/0.2'
HTTP_CONNECTION
'keep-alive'
SYSTEMDRIVE
'C:'
PYTHONPATH
'D:\\app\\ecerp'
GRANDE
'C:\\Program Files (x86)\\Fuji Xerox\\DocuPrint SSW2\\SimpleMonitor for AP'
JAVA_HOME
'C:\\Program Files\\Java\\jdk1.8.0_31'
wsgi.run_once
False
HTTP_REFERER
'http://localhost:8000/mrp/list/item/purchase/0/'
COMMONPROGRAMFILES
'C:\\Program Files\\Common Files'
LOGONSERVER
'\\\\ALFRED-PC'
PUBLIC
'C:\\Users\\Public'
COMSPEC
'C:\\Windows\\system32\\cmd.exe'
HTTP_HOST
'localhost:8000'
TEMP
'C:\\Users\\Alfred\\AppData\\Local\\Temp'
wsgi.errors
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='GBK'>
PROCESSOR_REVISION
'3a09'
COMMONPROGRAMFILES(X86)
'C:\\Program Files (x86)\\Common Files'
HTTP_CACHE_CONTROL
'no-cache'
REMOTE_ADDR
'127.0.0.1'
HTTP_ACCEPT
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
PROGRAMFILES
'C:\\Program Files'
HTTP_ACCEPT_ENCODING
'gzip, deflate'
CONTENT_LENGTH
'1266'
wsgi.url_scheme
'http'
HOMEDRIVE
'C:'
PROCESSOR_LEVEL
'6'
HTTP_USER_AGENT
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/41.0.2272.118 Safari/537.36'
RUN_MAIN
'true'
LOCALAPPDATA
'C:\\Users\\Alfred\\AppData\\Local'
#ENVTSLOGSSS2364
'3014800'
PYTHONUNBUFFERED
'1'
CSRF_COOKIE
'daIMsNDpBbireeQsbVGRJ6tMYijwxAu8'
CONTENT_TYPE
'application/x-www-form-urlencoded'
PATH
'C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Program Files (x86)\\Intel\\iCLS '
'Client\\;C:\\Program Files\\Intel\\iCLS '
'Client\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program '
'Files (x86)\\Intel\\OpenCL SDK\\2.0\\bin\\x86;C:\\Program Files '
'(x86)\\Intel\\OpenCL SDK\\2.0\\bin\\x64;C:\\Program Files\\Intel\\Intel(R) '
'Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) '
'Management Engine Components\\IPT;C:\\Program Files (x86)\\Intel\\Intel(R) '
'Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\Intel(R) '
'Management Engine Components\\IPT;C:\\Program Files (x86)\\Bitvise SSH '
'Client;C:\\Python34;C:\\Python34\\Scripts;C:\\Dev-Cpp\\bin;C:\\Program Files '
'(x86)\\QuickTime\\QTSystem\\;C:\\Program '
'Files\\TortoiseGit\\bin;C:\\Python34\\Scripts;C:\\Program '
'Files\\nodejs;D:\\upupw\\MySQL\\bin;C:\\Users\\Alfred\\AppData\\Roaming\\npm;C:\\Program '
'Files\\Java\\jdk1.8.0_31\\bin;C:\\Development\\android-sdk\\platform-tools;C:\\Development\\android-sdk\\tools'
SCRIPT_NAME
''
wsgi.version
(1, 0)
APPDATA
'C:\\Users\\Alfred\\AppData\\Roaming'

A: Finally I found that was because of the wrong file encoding.
The newly updated Pycharm IDE Under Windows changed the default encoding.
So my new code files encoding is turned to be GBK, which should be utf8.
And I changed the IDE setting, change the file encoding, everything is well.


text:
Q: Multiple Calculations VB.NET I'm sorry if this question has been asked so many times.
But on all the posts..i could not find a clear solution.
I asked my question before and it helped me very good...Still this problem remaining.
Make multiple calculations without pressing the '=' sign
if
'5+3 ='

then
'8'

WORKS!
But if
'5+5/10='

then
NOT WORKS
It's NOT the intention to build a difficult calcutor like (5*5)+(2+3)
It should just keep doing the calculation on the previous result
Made a sloppy solution that if the user tries to make multiple calculations
he gets an messagebox("error") and everything resets
SUB FOR THE OPERATORS
button.text becomes an operator:
Private Sub Operators_Buttons_Click(sender As Object, e As EventArgs) Handles AdditionButton.Click, SubtractionButton.Click, _
                                                                           MultiplicationButton.Click, DivisionButton.Click
    Dim x As Button = CType(sender, Button)
    Dim button As String = x.Text

    _Operator = button

if there is no value in the textbox this sub fix it
If ThereIsAnValue() = False Then
            MessageBox.Show("Give in a value before u use an operator")

            ResultTextbox.Text = "0"

'if ThereIsAnValue is true it will check if there is an first number stored somewhere
    'If _IsThereAnFirstNumber is always false in the formload
Else
        If _IsThereAnFirstNumber = False Then

'the input will go in _value1
 _Value1 = Convert.ToDecimal(ResultTextbox.Text)
                ResultTextbox.Text = "0"

'now there is an value in Value1
                _IsThereAnFirstNumber = True

if _IsThereAnFirstNumber is true when we press an operator
ElseIf _IsThereAnFirstNumber = True Then

I made this garbage code...
                MessageBox.Show("Please press the '=' sign after every single calculation")
                MessageBox.Show("System reset")
                _IsThereAnFirstNumber = False
                _Value1 = Nothing
                _Value2 = Nothing
                ResultTextbox.Text = "0"

            End If

SUB FOR THE EQUAL SIGN
Private Sub EqualsButton_Click(sender As Object, e As EventArgs) Handles EqualsButton.Click
        If _IsThereAnFirstNumber = True Then

            _Value2 = Convert.ToDecimal(ResultTextbox.Text)
            ResultTextbox.Text = "0"
        End If

        Select Case _Operator
            Case "+"
                _Result = _Value1 + _Value2
            Case "-"
                _Result = _Value1 - _Value2
            Case "*"
                _Result = _Value1 * _Value2
            Case "/"
                _Result = _Value1 / _Value2

        End Select
        ResultTextbox.Text = Convert.ToString(_Result)

        _IsThereAnFirstNumber = False
    End Sub

So in other words, my program only enters the "garbage code" if ThereIsAnFirstNumber is true.
Cause if I press the equal sign it will become false.
But what code should I write that if get in that "garbage code" ?
To keep the calculating going on?
when I say '5+5/10=' it will go 'the garbage sub'at the '/'sign..What I want is that if press that '/' sign that the calculator stores the 5+5 and divides it by the /10 if then i would say +3 it would have to be 4 after i press the '=' sign
thanx

A: If you want to build a simple calculator, your approach is not right. You should proceed as the Windows calculator works, that is, calculating the result as the operations are pressed. Its quite complicated to explain and I won't write the whole code for you, just to guide you how it can be done, you should proceed as follows;
 Private _result as decimal
 Private _value as decimal

 Private Sub PlusButton_Click(sender As Object, e As EventArgs) Handles PlusButton.Click

  If _result <> cdec(0) then
     _result = _result + _value
  EndIf

  // Then you can add your other logics, such as writting the calculation in a Textbox
End Sub

You can do the same for the other signs also.
If ever you wish to use 1 handle for all signs, then you amy use a case-else block as you did.


text:
Q: Is there a good algorithm for this graph problem? There's an undirected graph with weights on edges (weights are non-negative integers and their sum isn't big, most are 0). I need to divide it into some number of subgraphs (let's say graph of 20 nodes to 4 subgraphs of 5 nodes each) in a way that minimizes sum of weights of edges between different subgraphs.
This sounds vaguely like the minimum cut problem, but not quite close enough.
In alternative formulation - there's a bunch of buckets, all items belong to exactly two buckets, and I need to partition buckets into bucket groups in a way that minimizes number of items in more than one bucket group. (nodes map to buckets, edge weights map to duplicate item counts)

A: This is the minimum k-cut problem, and is NP hard. Here's a greedy heuristic that will guarantee you a 2-1/k approximation:
While the graph has fewer than k components:
  1) Find a min-cut in each component
  2) Split the component with the smallest weight min-cut.
The problem is studied in this paper: http://www.cc.gatech.edu/~vazirani/k-cut.ps


text:
Q: Convert matlab statement to python I should convert the following matlab statement in python:
lam = find(abs(b)>tol,1,'first')-1;

Thanks in advance

A: NumPy doesn't have the capability to get the first matching one, not yet anyway.
So, we need to get all matching ones with np.where to replace find and numpy.abs would be the replacement for abs. Thus, it would be -
import numpy as np

lam = np.where(np.abs(a)>tol)[0][0]-1

Thus, we are getting all matching indices with np.where(np.abs(a)>tol)[0], then getting the first index by indexing into its first element with np.where(np.abs(a)>tol)[0][0] and finally subtracting 1 from it, just like we did on MATLAB.
Sample run -
On MATLAB :
>> b = [-4,6,-7,-2,8];
>> tol = 6;
>> find(abs(b)>tol,1,'first')-1
ans =
     2

On NumPy :
In [23]: a = np.array([-4,6,-7,-2,8])

In [24]: tol = 6

In [25]: np.where(np.abs(a)>tol)[0][0]-1
Out[25]: 1 # 1 lesser than MATLAB vesion because of 0-based indexing

For performance, I would suggest using np.argmax to give us the index of the first matching one, rather than computing all matching indices with np.where(np.abs(a)>tol)[0], like so -
In [40]: np.argmax(np.abs(a)>tol)-1
Out[40]: 1


text:
Q: SQL Server select on aggregate function I have a challenge regarding the use of an aggregate function in a where statement.
    SELECT [tb_users].[id_user]
      ,[name]
      ,[Title]
      ,[FirstName]
      ,[LastName]
      ,[type]
      ,sum ([tb_LockAuditTrail].[price]) as SumPrice
  FROM [SALTO_SPACE].[dbo].[tb_Users]
  join [tb_LockAuditTrail]
  on [tb_Users].[Cardcode] = [tb_LockAuditTrail].[Cardcode]

  where [type] = 1
   group by [tb_users].[id_user]
      ,[name]
      ,[Title]
      ,[FirstName]
      ,[LastName]
      ,[type]
  order by [SumPrice] desc

This is running fine. From this dataset I want to select only the records above a certain SumPrice level. How do I do this?
I cannot use the alias SumPrice in the where statement because aliases are not allowed in where statements.
I also cannot use the aggregate SUM function in a where statement. So for now I don't see a solution other than filtering the result afterwards in an Excel sheet.

A: After the group by block and before the orderby block you write
HAVING sum ([tb_LockAuditTrail].[price]) > 100

Change the 100 accordingly
Even if HAVING weren't a thing, you don't have to use excel. Every SELECT creates a block of data that can be used like a table so you could wrap it all in brackets, give it an alias, and select from the query as if it were a table:
SELECT *
FROM
(
  SELECT productcategory, sum(price) as sumprice
  FROM products
  GROUP BY productcategory
) summed
WHERE
  summed.sumprice > 100

Get down with the notion that tables are only one kind of "block of data" that queries can use; you'll considerably increase your SQL querying ability if you keep in mind the fact FROM can use blocks of data from other sources such as queries and table valued functions. Here's another example:
  SELECT *
  FROM

    products p

    INNER JOIN
    (
      SELECT productcategory, sum(price) as sumprice
      FROM products
      GROUP BY productcategory
    ) sumcat
    ON p.productcategory = sumcat.productcategory

    INNER JOIN
    (
      SELECT warehouse, count(*) as sumprice
      FROM products
      GROUP BY warehouse
    ) countwh
    ON p.warehouse = countwh.warehouse

  WHERE
    ...

You can also use the WITH command, to alias a query so you can then use it like a table:
  WITH
    sumcat AS (
      SELECT productcategory, sum(price) as sumprice
      FROM products
      GROUP BY productcategory
    ),
    countwh as (
      SELECT warehouse, count(*) as sumprice
      FROM products
      GROUP BY warehouse
    )

  --now use them like tables
  SELECT *
  FROM

    products p
    INNER JOIN sumcat s ON p.productcategory = s.productcategory
    INNER JOIN countwh c ON p.warehouse = c.warehouse

This is one way how we can get every product detail but also the sum of all the prices in the category and the count of all the products in the various warehouses - perhaps pointless data but I'm demonstrating how you can use subqueries to generate blocks of data that can be joined to tables, and also each detail line can have a summary aspect too. Ordinarily you have to lose detail to generate summaries so the learning notions here are:

*

*subqueries are blocks of data just like tables and can be joined just like tables

*give everything an alias and use it

*to get detail and summary together generate the summary and join it to the detail

*a table can appear multiple times in a query and can be joined to itself even, so long as the two occurrences of the table have different aliases


text:
Q: rewrite pretty urls with php and htaccess, mapping 404 for subpages In .htaccess I have following rules for having page/subpage rewrite.
#Permalinks
RewriteEngine on
<IfModule mod_rewrite.c>
RewriteEngine On
#catch potential subpages first
RewriteRule ^([a-z\-]+)/([a-z\-]+)/?$ index.php?page=$1&subpage=$2 [L]
#
RewriteRule ^([a-z\-]+)$ index.php?page=$1 [L]
</IfModule>

In php I do this:
if (!$_GET) {
    //
    $page = "home";
    $page_title = "General Site Title";
    include ("template/index.php");
    //
} else if ($_GET['page'] == "words") {
    //
    $page = "words";
    $page_title = "Words Page";
    include ("template/words.php");
    //
} else if ($_GET['page'] == "about") {
    //
    $page = "about";
    $page_title = "About Page";
    include ("template/about.php");
    //
} else {
    //
    header("HTTP/1.0 404 Not Found");
    //
        include ("template/404.php");
    //
    exit();
    //
}

This works great, for showing 404.php when page doesn't exist.
But what if I want to have 404.php also when page/subpage doesn't exist?
For example I'm planning to have /members page. If someone goes to non existing /members/user1, I need to check DB for existing user, if doesn't exist I should show 404.php but is this correct logic to use in this situation?
p.s. how do I add rewrite /about/ to show same page? currently /about returns 200, but /about/ returns apache page not found.

A: First of correction in rules to make trailing slash optional in both rules:
RewriteEngine On

RewriteRule ^([a-z-]+)/([a-z-]+)/?$ index.php?page=$1&subpage=$2 [L,NC,QSA]
RewriteRule ^([a-z-]+)/?$ index.php?page=$1 [L,NC,QSA]

Now about checking /members/user1 yes you can check DB for existence of member record and if not found you can return 404 status/page.


text:
Q: I need help finding wildcard to use in mysql funcion JSON_SEARCH I'm tring to get the right wildcard (trying [0-9]%) using:
JSON_SEARCH(packages, 'one', 'openstack-neutron-[0-9]%', null, '$.packages[*]')

I just need to get "openstack-neutron-12.1.0-2-el7ost.noarch"
but not all the
"openstack-neutron-blabla1-14.5.5-el7ost.noarch"
"openstack-neutron-blabla2-12.1.0-2-el7ost.noarch"
...
What I'm I doing wrong?
Thanks

A: So your seachstring must start with  openstack-neutron- and end with -12.1.0-2-el7ost.noarch
USE
WHERE JSON_SEARCH(packages, 'one', 'openstack-neutron-%', null, '$.packages[*]') IS NOT NULL
    AND JSON_SEARCH(packages, 'one', '%-12.1.0-2-el7ost.noarch', null, '$.packages[*]') IS NOT NULL