text:
Q: DOMXPath::evaluate(): Node From Wrong Document Well here's an interesting one that I can't for the life of me figure out.
I have made some classes that extend PHPs DOMNode classes, and while trying to test them, I'm getting the error in the title, and I don't understand why, as the Node is definitely from the correct Document as I understand it.
My PHPUhit test is as follows:
class XPathTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->doc = new Document();
        $this->xpath = new XPath($this->doc);
    }

    /**
     * A single node should be returned from this expression
     */
    public function testEvaluate()
    {
        $xml = '<data><test>node</test></data>';

        $this->doc->loadXML($xml);

        $result = $this->xpath->evaluate('/data/test/text()', $this->doc);

        $this->assertInstanceOf('\\DOMText', $result);
        $this->assertEquals($result->nodeValue, 'node');
    }

}

There's nothing really special about my extending classes at this point, they have the default functionality of the parent.
DOMXPath::evaluate(): Node From Wrong Document

Has anyone come across this error before?
If I don't pass $this->doc to the xpath evaluate function, I just get no result at all.

A: It turns out that the DOMXPath object must be added to the DOMDocument after the DOMDocument has XML loaded into it.
So, the following is the correct way of instantiating this test:
class XPathTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->doc = new Document();
        $xml = '<data><test>node</test></data>';
        $this->doc->loadXML($xml);

        $this->xpath = new XPath($this->doc);
    }

    /**
     * A single node should be returned from this expression
     */
    public function testEvaluate()
    {
        $result = $this->xpath->evaluate('//test/text()');

        $this->assertInstanceOf('\\Manneken\\Dom\\Text', $result);
        $this->assertEquals($result->nodeValue, 'node');
    }

}

Duh.


text:
Q: Symfony 4 API deploy to Heroku not working I've benn trying to deploy the simplest symfony 4 API to heroku.
So I did a composer req api, and updated my env and doctrine for postgres and it worked perfectly on my local (with books and reviews).
The next step was to add an app.json to provide all the env variables to heroku, I also added a Procfile which contains :
web: vendor/bin/heroku-php-apache2 public/

To go a little further, I've added a "push to heroku" button in my Readme so I can check if the env variables are all set when deploying.
The build is correct, all variables are here, the database postgres is created, the tables also. But when I check the logs or trying to access the website, or even trying some Curl, nothing is working, and I get a 404 fired back.
I don't know what I can do, I feel stuck as h.
here my files examples :
app.json
{
  "name": "Api-platform example",
  "description": "Api-platform first deploy",
  "keywords": ["api-platform", "symfony", "sample"],
  "success_url": "/",
  "env": {
    "APP_ENV": "prod",
    "APP_SECRET": "myappsecret",
    "CORS_ALLOW_ORIGIN": "*"
  },
  "addons": [
    {
      "plan": "heroku-postgresql",
      "options": {
        "version": "9.5"
      }
    }
  ],
  "buildpacks": [
    {
      "url": "heroku/php"
    }
  ],
  "scripts": {
    "postdeploy": "php bin/console doctrine:schema:create"
  }
}

[EDIT] On the heroku dashboard of my app, I can see the proper Procfile, and on the console when I try the bin/console debug:router, I see all my routes here. So I cannot understand why I see a 404 everywhere.
I thank you in advance for your help and your kindness.
Best regards,
Youyou

A: Actually there is one more package that needs to be added for this to work :
composer require symfony/apache-pack

Be sure to press Yes (it's a contributing package).
Hope I helped some people in the same case ^^.
Bye

redpajama_set_name: RedPajamaStackExchange


text:
Q: fscanf for text files in C I have a file that
1   Toy Story   1995    01-Jan-1995 http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)   Animation|Children's|Comedy
2   GoldenEye   1995    01-Jan-1995 http://us.imdb.com/M/title-exact?GoldenEye%20(1995) Action|Adventure|Thriller

and the space between columns has written with tab
here's my code but ...
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <unistd.h>

FILE *MovieF;
void addFileM();

struct Movies
{
   char MID[50];
   char MName[50];
   char MYear[50];
   char MDate[50];
   char MIMDB[100];
   char MGen[100];
}Movie[100];

int main()
{
    addFileM();
    return 0;
}

void addFileM()
{
    MovieF = fopen("d:\\movies.txt","r");
    for(int i=0;i<60;i++)
    {
        fscanf(MovieF, "%s\t%s\t%s\t%s\t%s\t%s\n",Movie[i].MID,Movie[i].MName,Movie[i].MYear,Movie[i].MDate,Movie[i].MIMDB,Movie[i].MGen);
    }
    for(int i=0;i<60;i++)
    {
        printf("%s\n%s\n%s\n%s\n%s\n%s\n\n",
                Movie[i].MID, Movie[i].MName, Movie[i].MYear,
                Movie[i].MDate, Movie[i].MIMDB, Movie[i].MGen);
    }
}

and output:
1
Toy
Story
1995
01-Jan-1995
http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)

Animation|Children's|Comedy
2
GoldenEye
1995
01-Jan-1995
http://us.imdb.com/M/title-exact?GoldenEye%20(1995)

Action|Adventure|Thriller
3
Four
Rooms
1995
01-Jan-1995

As you can see "Toy Story" is stored in two different fields, and the genre data of the first movie is printed with the second movie.
Can you tell me what's the problem?

A: The problem is that %s format specifier stops scanning whenever a whitespece char (a space, a tabulation, a newline and so on) is found.
That's why both "Toy Story" and "Four Rooms" are stored in two different fields of your struct, making your scanning literally "shift" positions (the genre field of the first movie will become the first field of the second movie and so on).
Instead of using %s you could use %[^\t].
Square brackets format specifier scans a string containing a set of characters. But in case the ^ is present the character contained is avoided. So in this case it means "store the string and stop when the first tab is found".
Even better: you can choose to store at most N characters by using the format %N[^\t]. Given the size of your destination array, just specify N as this size minus one (leaving the space for the string terminator).
Your fscanf will become something like:
fscanf(MovieF, "%49[^\t]%49[^\t]%49[^\t]%99[^\t]%99[^\t]\n",
       Movie[i].MID, Movie[i].MName, Movie[i].MYear,
       Movie[i].MDate, Movie[i].MIMDB, Movie[i].MGen);


text:
Q: Как у блока с position:fixed менять цвет при прохождении определенной границы? Нужно чтобы при прокрутке страницы на синем фоне он был красным, а на красным был синим

.block {
  width: 100%;
  height: 200px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

.fixed {
  position: fixed;
  background: blue;
  top: 100px;
  left: 100px;
  z-index: 10;
  width: 80px;
  height: 80px;
}

A:

function onScroll() {
  const back = document.elementFromPoint(10, 100);
  const className = (back.classList.contains('red')) ? 'blue' : 'red';
  const fix = document.querySelector('.fixed');
  if (!fix.classList.contains(className)) {
    fix.classList.remove('red', 'blue');
    fix.classList.add(className);
  }
}

onScroll();
window.addEventListener('scroll', onScroll);
.block {
  width: 100%;
  height: 200px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

.fixed {
  position: fixed;
  top: 100px;
  left: 100px;
  z-index: 10;
  width: 80px;
  height: 80px;
}

A: А вот решение с динамической границей

function onScroll() {
  const fix = document.querySelector('.fixed');
  const rectFix = fix.getBoundingClientRect();
  const back = document.elementFromPoint(rectFix.x - 1, rectFix.y);
  const rectBack = back.getBoundingClientRect();
  const topHeight = rectBack.bottom - rectFix.y;
  const backClass = (back.classList.contains('red')) ? 'red' : 'blue';
  const otherClass = (backClass === 'red') ? 'blue' : 'red';
  const fixTop = fix.querySelector('.top');
  fixTop.style.height = (topHeight < rectFix.height) ? (topHeight + "px") : "100%";

  if (!fixTop.classList.contains(otherClass)) {
    fixTop.classList.remove('red', 'blue');
    fixTop.classList.add(otherClass);
    const fixBottom = fix.querySelector('.bottom');
    fixBottom.classList.remove(otherClass);
    fixBottom.classList.add(backClass);
  }
}

onScroll();
window.addEventListener('scroll', onScroll);
.block {
  width: 100%;
  height: 200px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

.fixed {
  position: fixed;
  top: 100px;
  left: 100px;
  z-index: 10;
  width: 80px;
  height: 80px;
  display: flex;
  flex-direction: column;
}

.fixed .bottom {
  flex-grow: 1;
}


text:
Q: Python clean keyboard interupt I have a python script in which I'm using threading to wait for inputs on my raspberry pi. This is the first time I've ever used threading before and I'm having some difficulties handling the KeyboardInterrupt. Its not really an issue, but if the user presses control-c to early, like right as soon as the program starts, python freaks out and spews a console full of import errors. Ive tried wrapping the imports in try - excepts, but that doesn't seem to work. I have a feeling its something with the threading as I've never had this issue before.
Besides wrapping everything in try-excepts i also tried:
from threading import Thread
cond = threading.Condition(threading.Lock())
cond.acquire()
cond.wait(None)

which I hear was suppose to not allow the keyboard interrupt until its been loaded?
Is there anyway just to not have python do anything on keyboardinterrupts?
Any help would be appreciated. Thanks!
My Code:
import RPi.GPIO as GPIO
import pymysql as mysql
import time
import urllib.request
from threading import Thread

GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()

class table():
    __slots__ = ['pin','num','time']

    def __init__(self, pin, num, time=0):
        self.pin = pin
        self.num = num
        self.time = time

# Room ID
room = 6

# time (minutes)
thetime = 38

# table Setup
tableList = [ \
    table(11,6), \
    table(13,2), \
    table(15,4), \
    table(19,5), \
    table(21,3), \
    table(23,1), \
    ]

def settable(table):
    with urllib.request.urlopen("http://time.zyphox.com") as url:
        curtime = int(url.read())+(thetime*60)

    con = mysql.connect(host="345", user="435", passwd="345435", db="34534543")
    cur = con.cursor()
    cur.execute("UPDATE tables SET time='"+str(curtime)+"' WHERE number='"+str(table)+"' AND id_room='"+str(room)+"'")
    cur.close()
    con.close()
    print("Setting table " + str(table) + " to " + str(thetime) + " minutes...")

def watchtable(table):
    GPIO.setup(table.pin, GPIO.IN)
    while True:
        if(GPIO.input(table.pin)!=1 and table.time <= time.time()):
            settable(table.num)
            table.time = time.time() + 10

def main():
    print("Loading kitchen System...")
    for table in tableList:
            t = Thread(target=watchtable,args=(table,))
            t.daemon=True
            t.start()
    time.sleep(1)
    print("Successful!")

    while True:
        time.sleep(300)
        print("- Pinging MYSQL database.")

main()


text:
Q: IPhone how do display Leaderboard screen in my own game .... developed in cocos2d i want to show leaderbord in  my own game ....i am using following method for that but noting happen ... i am confuse with rootview controller as my game is developed in cocos2d so there is nothing like dat :(
// Leaderboards

-(void) showLeaderboard
{
    if (isGameCenterAvailable == NO)
        return;

    GKLeaderboardViewController* leaderboardVC = [[[GKLeaderboardViewController alloc] init] autorelease];
    if (leaderboardVC != nil)
    {
        leaderboardVC.leaderboardDelegate = self;
        [self presentViewController:leaderboardVC];
    }
}
///
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController*)viewController
{
    [self dismissModalViewController];
    [delegate onLeaderboardViewDismissed];
}

///////

-(UIViewController*) getRootViewController
{
    return [UIApplication sharedApplication].keyWindow.rootViewController;
}
///
-(void) presentViewController:(UIViewController*)vc
{
    UIViewController* rootVC = [self getRootViewController];
    [rootVC presentModalViewController:vc animated:YES];
}

////
-(void) dismissModalViewController
{
    UIViewController* rootVC = [self getRootViewController];
    [rootVC dismissModalViewControllerAnimated:YES];
}

...
regards
Haseeb

A: i dont know but it work for me.if anyone can describe the real reason for why this working in this way i will be very glad....i call it through appdelegate
[(myAppDelegate*)[[UIApplication sharedApplication] delegate]gameCenter];

and from appdelegate i call rootviewcontroller method like
-(void)gameCenter
{
    [rootViewController gameCenterLeaderboard];
}

and in rootviewcontroller there is a method
-(void)gameCenterLeaderboard
{

    GKLeaderboardViewController* leaderboardVC = [[[GKLeaderboardViewController alloc] init] autorelease];
    if (leaderboardVC != nil) {

        leaderboardVC.leaderboardDelegate = self;
        [self presentModalViewController: leaderboardVC animated: YES];

    }

}

the following method is also override in rootviewcontroller
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)leaderboardController
{

    [self dismissModalViewControllerAnimated:YES];
}

A: If you don't have a root UIViewController then I'd recommend creating a new UIViewController set it's view to your openGLView then use that view controller to present the leaderboard as a modal view controller.
UIViewController *leaderboardViewController = [[UIViewController alloc] init];
[leaderboardViewController setView:[[CCDirector sharedDirector] openGLView]];

[leaderboardViewController presentModalViewController:leaderboardVC animated:YES]; //leaderboardVC is your GKLeaderboardViewController


text:
Q: How to detect value variables prior to reshape wide to long? Consider the below df. Notice how the user Paul has two colors vs his name.
df = pd.DataFrame({'names' :['Stacey', 'John', 'Paul'],
                  'blue':['blue',np.nan, np.nan],
                  'yellow':[np.nan, 'yellow', np.nan],
                  'green': [np.nan, np.nan, 'green'],
                   'purple':[np.nan, np.nan, 'purple' ]
                 })
print(df)

 names    blue  yellow   green   purple
0  Stacey  blue     NaN    NaN     NaN
1    John   NaN  yellow    NaN     NaN
2    Paul   NaN     NaN  green  purple

If I am to reshape this df from wide to long, with pd.melt, I will expect the id 'Paul' entry to be duplicated.
df.melt(id_vars='names',
        value_vars = ['blue','yellow','green','purple'],
        value_name = 'color').dropna().drop('variable', axis=1))

      names   color
0   Stacey    blue
4     John  yellow
8     Paul   green
11    Paul  purple

How would one isolate/detect the repeated entries in the inital df so the output would be?:
    names    blue  yellow   green   purple
 2    Paul   NaN     NaN    green   purple

Thank you in advance:
pandas 0.23.4
python 3.7.1

A: You can use count for coun with exclude missing values with filtering by boolean indexing:
df = df[df[['blue','yellow','green','purple']].count(axis=1) > 1]
print (df)
  names blue yellow  green  purple
2  Paul  NaN    NaN  green  purple

Details:
print (df[['blue','yellow','green','purple']].count(axis=1))
0    1
1    1
2    2
dtype: int64


text:
Q: Trouble implementing Singleton pattern in Tomcat web application due to Class Loader I'm trying to implement a Singleton in Tomcat 6.24 on Linux with x86_64 OpenJDK 1.6.
My application is just a bunch of JSPs and some static content and the JSPs make calls to my Java code. Currently the web.xml just looks like this:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

<description>
    App Name
</description>
<display-name>App Name</display-name>

<!-- The Usual Welcome File List -->
<welcome-file-list>
    <welcome-file>pages/index.jsp</welcome-file>
 </welcome-file-list>

</web-app>

Before when I was trying to load my Singleton it was getting instantiated twice since the class was getting loaded by two different class loaders (I'm not sure why) and each loader would create an instance of the singleton which is not acceptable for my application. I finally figured out if I exported my code as a jar and put it in $CATALINA_HOME/lib then there was only one instance, but this is not an elegant solution.
I've been googling for hours, but I haven't come up with anything yet. I'm wondering if there is some other solution. Currently I'm not precompling my JSPs, could this be part of the problem? Could I write a servlet to ensure the singleton is created? If so how do I do that?

A: Ok, I finally figured out the problem.
I had made my application the default application for the server by adding a  to server.xml and setting the path to "". However, when I was accessing it through the URL http://localhost/somepage.jsp for somethings, but also the URL http://localhost/appname/anotherpage.jsp for other things.
Once I changed all the URLs to use http://localhost/ instead of http://localhost/appname the problem was fixed.

A: To ensure correct initialisation of the Singleton, you should check that you are using the default parent-first classloader, see http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html.
Then define a ServletContextListener and intialise your Singleton in the method:
contextInitialized(ServletContextEvent sce)

which is guaranteed to be called before any of your servlets or filters.

All ServletContextListeners are
  notified of context initialization
  before any filter or servlet in the
  web application is initialized.

Define your ServletContextListener in your web.xml

A: When is the singleton created first? You could force it to be created when the index.jsp is loaded by including a:
<%! MySingleton instance = MySingleton.getInstance(); %>

line.
If you precompile the jsp's and configure tomcat to never auto-reload classes or jsp's the singleton should stay single :-)

A:
Once I changed all the URLs to use http://localhost/ instead of http://localhost/appname  the problem was fixed.

This implies that you've 2 deployed webapplications and expected them to use the same classloader. This is untrue. If you want a shared library which is used by all webapplications, then you should put it in the path as denoted by "Tomcat Shared" (which is configureable by shared.loader in catalina.properties file). You only need to ensure that you do not have this library in the webapp's own library or in Tomcat/lib.


text:
Q: Custom Checkbox list control Error in asp.net. "startIndex cannot be larger than length of string" I am creating a custom checkbox control to add a div after each checkbox in a checkboxlist.
The class is below.
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports System.Globalization

Public Class MyCheckboxListCheckBox
    Inherits CheckBoxList
    Implements IRepeatInfoUser
    Protected Overrides Sub RenderItem(ByVal itemType As ListItemType, ByVal repeatIndex As Integer, ByVal repeatInfo As RepeatInfo, ByVal writer As HtmlTextWriter)

        writer.WriteBeginTag("input")
        writer.WriteAttribute("type", "checkbox")
        writer.WriteAttribute("name", UniqueID)
        writer.WriteAttribute("id", (ClientID & "_") + repeatIndex.ToString(NumberFormatInfo.InvariantInfo))
        writer.WriteAttribute("value", Items(repeatIndex).Value)
        Dim attrs As System.Web.UI.AttributeCollection = Items(repeatIndex).Attributes
        For Each key As String In attrs.Keys
            writer.WriteAttribute(key, attrs(key))
        Next
        writer.Write(">")

        writer.Write(Items(repeatIndex).Text)
        ' writer.Write("

")

    End Sub

End Class

But I get an error when i use it in a page and call the save. The error is :

startIndex cannot be larger than
  length of string. Parameter name:
  startIndex  Description: An unhandled
  exception occurred during the
  execution of the current web request.
  Please review the stack trace for more
  information about the error and where
  it originated in the code.
Exception Details:
  System.ArgumentOutOfRangeException:
  startIndex cannot be larger than
  length of string. Parameter name:
  startIndex
Source Error:
An unhandled exception was generated
  during the execution of the current
  web request. Information regarding the
  origin and location of the exception
  can be identified using the exception
  stack trace below.
Stack Trace:
[ArgumentOutOfRangeException:
  startIndex cannot be larger than
  length of string. Parameter name:
  startIndex]
  System.String.InternalSubStringWithChecks(Int32
  startIndex, Int32 length, Boolean
  fAlwaysCopy) +7492915
  System.Web.UI.WebControls.CheckBoxList.LoadPostData(String
  postDataKey, NameValueCollection
  postCollection) +60
  System.Web.UI.WebControls.CheckBoxList.System.Web.UI.IPostBackDataHandler.LoadPostData(String
  postDataKey, NameValueCollection
  postCollection) +13
  System.Web.UI.Page.ProcessPostData(NameValueCollection
  postData, Boolean fBeforeLoad) +346
  System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint) +1743

Any ideas ?

A: Place a breakpoint on your overrides renderItem function declaration.  Start your project using VS debugging mode and trace what variables are set and to what.  I have a feeling that you are using a startindex of 1 on an empty string somewhere.  Remember, arrays and such start at 0.


text:
Q: How to use jenkins to restart PM2? i'm running my node.js app on the linux server using PM2, with a config file, like this:
PM2 start mywebsite.config.js

all is good. but now i want to add jenkins to the picture.
i'm running a pipeline project in jenkins, using Jenkinsfile.
All working fine except for the last command, that should restart the app, to make the new version live:
stage('Restart PM2') {
  steps {
    sh 'pm2 restart all'  }
  }
}

and this command fails. here is the log output:
+ pm2 restart all
Use --update-env to update environment variables
[PM2][WARN] No process found
< empty pm2 log table here>
Use `pm2 show <id|name>` to get more details about an app

I understand that PM2 is working per user. means, that the user who ran the first command (start) is the one that should run the restart as well.
but how to do this?

A: To run pm2 restart all from Jenkins you need to:

*

*Configure your system to run sudo from jenkins
(https://sgoyal.net/2016/11/18/run-a-shell-from-jenkins-using-sudo-ubuntu/)

*Make a symbolic link to the .pm2/ folder, in my case(Ubuntu) it was at /root/.pm2 so i run
sudo ln -s /root/.pm2/ /var/lib/jenkins/
NOTE: /var/lib/jenkins if the default jenkins root directory, you can check yours on Jenkins configuration

*after that you can go to jenkins and setup a shell command, in my case i did:

#!/bin/sh
echo "RESTARTING ALL"
sudo pm2 restart all
echo "ALL RESTARTED"
NOTE: if you have a .pm2 folder already in your jenkins root directory rename it so you can do the symbolic link
Hope this helps

A: Instead of restarting PM2 through you jenkins code, let PM2 do it by itself, using the watch flag. in your config file, set watch to be true.
You may want to add a relatively new flag called watch-ignore. that's an array, with files to be ignored by the watch. add your log file and error file to this list. otherwise, any logged information will cause your node app to restart endlessly.
after doing these changes to the config file, run pm2 again with the config. remove the restarting code from Jenkinsfile, you don't need that anymore, pm2 will detect the new version and will reload the app!

A: BUILD_ID=dontKillMe PM2 start mywebsite.config.js

Jenkins kills the pm2 daemon to be created by the build.
You should put the keyword to prevent killing daemon by Jenkins.


text:
Q: Non-relativistic nuclear charge-current commutation relation On the second page of the paper [1], the following commutator is given for the non-relativistic nuclear charge-current operators:
$$
\left[ J^{0}(\boldsymbol{x}), \boldsymbol{J}(\boldsymbol{y}) \right] = -\dfrac{i}{m} J^{0}(\boldsymbol{y}) \nabla_{\boldsymbol{x}}\delta(\boldsymbol{x}-\boldsymbol{y}),
$$
where
$$
J^{0}(\boldsymbol{x}) = \sum_{k} \delta(\boldsymbol{x}-\boldsymbol{x}_k), \quad \boldsymbol{J}(\boldsymbol{x})=\dfrac{1}{2m} \left\{ \boldsymbol{p}_k, \sum_{k} \delta(\boldsymbol{x}-\boldsymbol{x}_k) \right\}.
$$
How is this result obtained? I am especially confused about the derivative of the $\delta$-function: how does it come out in this exact form and why is it taken with respect to $\boldsymbol{x}$?
A simplifed explanation in one dimension for just one proton would be greatly appreciated!

*

*H. Kurasawa, T. Suzuki, Commutators of the four-current and sum rules in relativistic nuclear models, https://arxiv.org/abs/1301.2644


text:
Q: parse data set in python with complex list structure I have a data set that I'm trying to parse and create a new list from. A sample is shown below:
(089964, 64509, 4890, 517, [
innerArray(a=789454, b=789454, c=56, o=1, d=66, e=63),
innerArray(a=789454, b=789454, c=56, o=1, d=66, e=63),
innerArray(a=788878, b=768910, c=112, o=2, d=66, e=63),
innerArray(a=788878, b=928718, c=2464, o=44, d=66, e=63),
innerArray(a=789454, b=789454, c=56, o=1, d=66, e=63)])
(089967, 64534, 4825, 517, [
innerArray(a=567454, b=789454, c=56, o=1, d=66, e=63),
innerArray(a=567454, b=789454, c=56, o=1, d=66, e=63),
innerArray(a=876878, b=768910, c=112, o=2, d=66, e=63),
innerArray(a=876878, b=928718, c=2464, o=44, d=66, e=63),
innerArray(a=875454, b=789454, c=56, o=1, d=66, e=63)])

I'm using a very simple code to extract what I need:
for i in tempFullList:
    print i[0],i[1],i[2],i[3],i[4]

where 089964, 64509, 4890, 517 are i[0],i[1],i[2],i[3] respectively and the entire innerArray is i[4].
What I'm really looking forward to is a list that has in each row i[0],i[1],i[2],i[3],and each element of innerarray. For example:
(089964, 64509, 4890, 517,789454,789454,56,1,66,63), ...

InnerArray is the typename of the namedtuple that was created when parsing a log file.
I'm working on a code that can iterate through all innerArray (size not fixed), and some help will be appreciated.

A: Assuming innerArray is a class and accessing elements from it works like ia.a, ia.b etc. where ia is an innerArray object, here's something you could do (xs is your entire tuple):
 result = []
 common = xs[:4] # The first 4 elements, which will be common
 xs = xs[4:]     # The list of innerArray elements
 for x in xs:
     result.append(common[:]) # Makes a copy of the common list
     result[-1].extend([x.a, x.b, x.c, x.o, x.d, x.e]) # Or however you want to get the elements out of the "innerArray"; -1 selects the last inserted list.

It is much easier for people to answer your questions if you give us as many details as you can about your code, like for example, innerArray here.
EDIT: Just noticed you have multiple tuples like xs, in which case, just iterate over the list of tuples, and for each tuple, do the above.


text:
Q: How to return an enum from a function in SwiftUI? I want to return an enum from my function. For that, I need to classify a return type.
However, what is the return type if I want to return an enum?
My code below:
class Timezone {

    func getTimeZoneFromCountry(country: String) -> ??? {
        switch country {
        case "AU":
            return Timezone.AU
        case "US":
            return Timezone.US
        default:
            return Timezone.AU
        }
    }

    enum AU: String, Identifiable, CaseIterable {
        case AEST = "AEST"
        case AWST = "AWST"
        case ACST = "ACST"

        var id: AU {self}
    }

    enum US: String, Identifiable, CaseIterable {
        case CST = "CST"
        case EST = "EST"
        case MST = "MST"
        case PST = "PST"

        var id: US {self}
    }

}

I'm trying to dynamically populate a Picker:
struct TimeZonePicker: View {
    @Binding var country: String // AU or US

    var body: some View {
        Picker("Timezone", selection: $country) {
            ForEach(*Dynamic enum here*) { i in
                Text(String(i.rawValue))
            }
        }
    }
}

Edit: New view with @Sweeper's dynamic solution:
var body: some View {
    Picker("Timezone", selection: $country) {
        ForEach(Timezone.getTimeZoneFromCountry(country: country)) { i in
            Text(String(i.rawValue))
        }
    }
}

A: Use a single enum, and have getTimeZoneFromCountry return only certain cases of the enum:
enum Timezone: String, Identifiable, CaseIterable {
    var id: Timezone { self }

    static func getTimeZoneFromCountry(country: String) -> [Timezone] {
        switch country {
        case "AU":
            return Timezone.AU
        case "US":
            return Timezone.US
        default:
            return Timezone.AU
        }
    }
    case AEST = "AEST"
    case AWST = "AWST"
    case ACST = "ACST"

    case CST = "CST"
    case EST = "EST"
    case MST = "MST"
    case PST = "PST"

    static let AU: [Timezone] = [.AEST, .AWST, .ACST]
    static let US: [Timezone] = [.CST, .EST, .MST, .PST]

}

A: The accepted answer is a good fit but for those who are care about the  quality of the code, these are extra:
First of all
You don't need to define the raw value for String based enums when the raw value and the case is exactly the same! So
case AEST = "AEST"

is exactly equal to:
case AEST

Second of all:
You can extend the Identifiable itself to have an implementation to all RawRepresentables:
extension Identifiable where Self: RawRepresentable {
    var id: Self { self }
}

Third of all:
You can use associated value in the enum for sectioning values like:
enum Timezone {
    case au([AU])
    case us([US])
,,,
}

Forth of all:
Try to avoid unknown behaviors by avoiding default assigning. You can have an optional init instead:
init?(raw: String) {
    switch raw.lowercased() {
    case "au": self = .au(AU.allCases)
    case "us": self = .us(US.allCases)
    default: return nil
    }
}

Fifth of all:
Don't forget that strings are case sensitive! Try handle the sensitivity. for  example check for lowercased.

So the full code would be something like:
enum Timezone {
    init?(raw: String) {
        switch raw.lowercased() {
        case "au": self = .au(AU.allCases)
        case "us": self = .us(US.allCases)
        default: return nil
        }
    }

    case au([AU])
    case us([US])

    enum AU: String, Identifiable, CaseIterable {
        case AEST
        case AWST
        case ACST
    }

    enum US: String, Identifiable, CaseIterable {
        case CST
        case EST
        case MST
        case PST
    }
}

extension Identifiable where Self: RawRepresentable {
    var id: Self { self }
}

A: Give return type as array of string and inside switch case return the array of strings from enum's allCase.
class Timezone {

    func getTimeZoneFromCountry(country: String) -> [String] {
    switch country {
    case "AU":
        return Timezone.AU.allCases.map({$0.rawValue})
    case "US":
    return Timezone.US.allCases.map({$0.rawValue})
    default:
    return Timezone.AU.allCases.map({$0.rawValue})
    }
    }

    enum AU: String, Identifiable, CaseIterable {
        case AEST = "AEST"
        case AWST = "AWST"
        case ACST = "ACST"

        var id: AU {self}
    }

    enum US: String, Identifiable, CaseIterable {
        case CST = "CST"
        case EST = "EST"
        case MST = "MST"
        case PST = "PST"

        var id: US {self}
    }

}


text:
Q: css margin-top is not the same in Firefox and Chrome I have a div with this css styling as below:
//Search
.input-append{
    text-align:right;
    margin-left:-35px;
    height:20px;
    margin-top:-15px!important;
    input[class*="span"]{
        margin:-2px 0 0 0;
        padding:4px;
    }
    button.btn{
    height:30px;

        margin-top:-2px!important;
            i.icon-search{

                text-shadow:none;
            }
    }
}

I dont know why it is not appearing in same position in both browser.
In Chrome it appears the div a little bit above than Firefox, How can i make an if statement if it is a Chrome browser different margin-top or vice versa!
Thanks

A: CSS Reset avoids browser inconsistencies.
So try adding the below css
* {
  margin: 0;
  padding: 0;
}

Read more about Eric Meyer's Reset CSS Tools.


text:
Q: Figure out merged commit in prepare-commit-msg hook I have tried creating a prepare-commit-msg hook that works for merge commits. The script gets passed the following arguments .git/MERGE_MSG, merge.
I need to get the hash or branch name of the merged commit (for a normal, non-octopus merge). I know I can do git rev-parse MERGE_HEAD to get the hash or name-rev --name-only MERGE_HEAD to get the branch name (if any).
However, it seems that prepare-commit-msg is called before MERGE_HEAD is created. Is there any other way of knowing which commit was merged short of parsing the auto-generated message?
I'm using git 2.4.0.

A: In a custom merge driver, the name of the
branch being merged into (destination) can be retrieved
with git symbolic-ref HEAD
and the name of the branch being merged in (source) from the
GITHEAD_<SHA> environment variable,
This is an example script fragment :
# retrieve merged branch name from an env var GITHEAD_<sha>=<branchName>
# we cannot use a sym ref of MERGE_HEAD, as it doesn't yet exist
gitHead=$(env | grep GITHEAD) # e.g. GITHEAD_<sha>=release/1.43
# cut out everything up to the last "=" sign
source="${gitHead##*=}"

# retrieve base branch name from a sym ref of HEAD
branch=$(git symbolic-ref HEAD) # e.g. refs/heads/master
# cut out "refs/heads"
destination="${branch#refs/heads/}"

echo "Merging from $source into $destination"

Source : How to retrieve branch names in a custom Git merge driver?.


text:
Q: Updating multiple columns in a single sql query with conditions I need help in building a sql query for the following criteria:
there are 3 columns in oracle database, and i need to update one of these columns checking if 1st is null then update that and don't touch other two columns, if 1st is not null then update 2nd and don't update the 3rd column else if 3rd column is null update the 3rd.
The query which i could build is:
 update temp set
    flg1 =
        case flg1
            when null then 'Y' else flg1 end,
    flg2 =
        case flg2
            when null then 'Y' else flg2 end,
    flg3 =
        case flg3
        when null then 'Y' else flg3 end,
where id = 132

i know the above query is different from what i want , need help ..

A: Try this:
 update temp set
        flg1 =
            case when flag1 is null then 'Y' else flg1 end,
        flg2 =
           case when flag1 is not null and flag2 is null then 'Y' else flg2 end,
        flg3 =
            case when flag1 is not null and flag2 is not null and flag3 is null then 'Y' else flg3 end
where id = 132

A: you should use neste case condition to achieve your requirement
Just try below code
update temp set
            flg1 =
                case when flag1 is null then 'Y' else flg1 end,
            flg2 =
               case when flag1 is not null
                   then case flag2 is null then 'Y' else flg2 end
               end,
            flg3 =
                case when flag1 is not null
                then case  flag2 is not null
                then case flag3 is null then 'Y'
                else flg3 end
                end
                end
    where id = 132

A: Maybe you want something like this?
UPDATE temp SET
    flg1 =
        CASE WHEN flg1 IS NULL THEN 'Y' ELSE flg1 END,
    flg2 =
        CASE WHEN flg1 IS NOT NULL AND flg2 IS NULL THEN 'Y' ELSE flg2 END,
    flg3 =
        CASE WHEN flg1 IS NOT NULL AND flg2 IS NOT NULL AND flg3 IS NULL THEN 'Y' ELSE flg3 END

WHERE id = 132


text:
Q: Azure Maps Fuzzy Search API (https://atlas.microsoft.com/search/fuzzy/json?) works on Postman but fails on Logic Apps I started using the Azure Maps API on a project using Logic Apps (Azure). All of a sudden the HTTP action stopped working and I am getting a 400 BadRequest Error.
"error": {
    "code": "400 BadRequest",
    "message": "Bad request: one or more parameters were incorrectly specified or are mutually exclusive."
However, when I call the same API using Postman or my browser, it works fine.
API: https://atlas.microsoft.com/search/fuzzy/json?api-version=1.0&subscription-key=xxxxxxxxxxxxxxxxxxxxxxxxxxx&query=2 5 Donlands Ave 4 Toronto Toronto   &countrySet=Ca&maxFuzzyLevel=2&limit=1
As I mentioned, this was working and all of a sudden started failing on Logic Apps without making any changes.

A: I exactly have the same issue.
I use address rest api to retrieve cities from postal code.
Sample :
https://atlas.microsoft.com/search/address/structured/json?subscription-key=mySubcriptionKey&api-version=1.0&postalcode=35000&countrycode=fr&limit=1
Like you, if I use the query client side, I have a 400 bad request with message :
{
  "error": {
    "code": "400 BadRequest",
    "message": "Bad request: one or more parameters were incorrectly specified or are mutually exclusive."
  }
}
Please note that the query is OK for google chrome, but return a 400 bad requests with Brave, Edge (chromium) and Firefox.
Note also that the sample web sdk have the same issue and is not updated.
Currently, I don't have any idea about where is the problem.
Edit : After some investigation, i'm pretty sure that it's a Microsoft issue.
So, I found a workaround.
If I try my query with Firefox, by default I have a 400 and a 200 with chrome.
I compare the header and the issue is with the accept-language.
By default, on Chrome, I Have : Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
On Firefox (Brave, Edge also maybe), I Have : Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Please note the inversion between fr-FR and fr.
If I change my Accept-Language on Firefox from fr,fr-FR to FR-fr,fr. It's working.
If I set my Accept-Language to "fr" only, I still have a 400. Work with "Fr-fr".
So after some test, my conclusion is that atlas have an issue with two letter header accept-langage.
So on my TS/JS code, just add accept-language with 4 letters to work again.
xhr.open('GET', url, true);
xhr.setRequestHeader("Accept-Language", this.acceptLanguage);
xhr.send();

My opinion is that it's a server/ atlas issue, I can't imagine this kind of code evolution from Microsoft ^^


text:
Q: SvelteKit async load not awaiting sort // $lib/types.ts
export type GlobResults = Record<string, ()=>Promise<unknown>>

// $lib/utils.ts
export const LoadGlobsOneByOne = async (globs: GlobResults) => {
    let results = []
    for (const path in globs) {
        let data = await globs[path]()
        results.push(data)
    }
    return results
}

export const LoadGlobsAllAtOnces = async (globs: GlobResults) => {
    let results = await Promise.all(Object.values(globs).map(fn=>fn()))
    return results
}

// $lib/routes/members/+page.ts
/** @type {import('./$types').PageLoad} */
import type {Members} from '$lib/types'
import {LoadGlobsAllAtOnces, SortMemberByImage} from '$lib/utils'

// NOTE: originally had it as a single JSON
//       now each member is in a separate YML file.
// import members from '$lib/data/members.json'
const yamls = import.meta.glob(
    '/src/yaml/members/*.yml',
    {import: 'default'}
)

export async function load({ }) {
    let members = (await LoadGlobsAllAtOnces(yamls) as Members)
        .sort(SortMemberByImage)

    return { members };
  }

No matter what I try I get all of the yamls in the order they are named in under /src/yamls/members/*1 instead of the sort order. I have tried wrapping the sort in another async function and awaiting that. I have tried in the +page.svelte waiting with an async block, as well as declaration to a $: sorted = .... How do I wait or enforce that the results are returned once sorted?

A: Have you tried like this?
 let members = await LoadGlobsAllAtOnces(yamls) as Members
 let sortedMembers = members.sort(SortMemberByImage)
 return { sortedMembers };


text:
Q: Durandal Custom View Location Strategy I am trying to figure out how to use a custom view location strategy, I have read the documentation at this page http://durandaljs.com/documentation/Using-Composition/ but I don't exactly understand what the strategy function should look like.
Can anybody give me a quick example of what the implementation of this function would be like and the promise that returns (even a simple one) etc?
Thanks in advance,
Gary
p.s. This is the code in my html:

and this is the code in my myCustomViewStrategy:
define(function () {

    var myCustomViewStrategy = function () {

        var deferred = $.Deferred();

        deferred.done(function () { console.log('done'); return 'simpleModelView'; });
        deferred.fail(function () { console.log('error'); });

        setTimeout(function () { deferred.resolve('done'); }, 5000);

        return deferred.promise();
    };

return myCustomViewStrategy;
});

but I get the error:
Uncaught TypeError: Cannot read property 'display' of undefined - this is after done has been logged in the console window.

A: Okay I solved this by creating my custom view strategy by the following:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {

    var myCustomViewStrategy = function () {
        return viewEngine.createView('views/childRouter/first/sModelView');
    }

    return myCustomViewStrategy;

});

A: As I found the documentation a bit lacking on compose binding's strategy setting I checked the source code how it works. To summ it up:
The module specified by the compose binding's strategy setting by its moduleId

*

*must return a function named 'strategy'

*which returns a promise which results in the view to be bound

*as a HTML element object.

*As a parameter the strategy method receives the compose binding's settings object

*with the model object already resolved.

A working example:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {

    var strategy = function(settings){
        var viewid = null;
        if(settings.model){
            // replaces model's module id's last segment ('/viewmodel') with '/view'
            viewid = settings.model.__moduleId__.replace(/\/[^\/]*$/, '/view');
        }
        return viewEngine.createView(viewid);
    };

    return strategy;
});

Durandal's source:
// composition.js:485

for (var attrName in settings) {
    if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) {
        /*
         * strategy is unwrapped
         */
        settings[attrName] = ko.utils.unwrapObservable(settings[attrName]);
    } else {
        settings[attrName] = settings[attrName];
    }
}

// composition.js:523

if (system.isString(context.strategy)) {
    /*
     * strategy is loaded
     */
    system.acquire(context.strategy).then(function (strategy) {
        context.strategy = strategy;
        composition.executeStrategy(context);
    }).fail(function(err){
        system.error('Failed to load view strategy (' + context.strategy + '). Details: ' + err.message);
    });
} else {
    this.executeStrategy(context);
}

// composition.js:501

executeStrategy: function (context) {
    /*
     * strategy is executed
     * expected to be a promise
     * which returns the view to be bound and inserted to the DOM
     */
    context.strategy(context).then(function (child) {
        composition.bindAndShow(child, context);
    });
}


text:
Q: Placing toolbar into Windows taskbar (ala language bar) I'm currently in the process of writing a Windows MFC app to quickly search our corporate DMS. The idea is to have a button placed at the right hand edge of the windows taskbar much like the language bar, that when clicked, would popup the search interface.
I can't seem to find much regarding how placing items in the taskbar like this is performed, can anyone point me to some useful resources or examples?
I'd prefer native API resources (that is, not .NET) if possible.
Thanks!

A: Such toolbar is named a Deskband.
Here's an example: http://www.codeproject.com/KB/shell/dotnetbandobjects.aspx

A: You could look at the StExBar. It implements an explorer toolbar which can also be added to the taskbar. Doesn't use MFC though, just plain win32.


text:
Q: When window state is maximized then the window is behind the taskbar
Possible Duplicate:
Borderless application on maximize is hiding behind the task bar in Win 7 and Win 8

my windowstyle is none and I maximized the window the window is behind the task bar and
I cannot see the while window properly.
i tries this but it doesn't work:
this.MaxHeight = SystemParameters.VirtualScreenHeight;
this.MaxWidth = SystemParameters.VirtualScreenWidth;

A: Something you could start with:
    [DllImport("user32.dll")]
    private static extern int FindWindow(string lpszClassName, string lpszWindowName);
    [DllImport("user32.dll")]
    private static extern int ShowWindow(int hWnd, int nCmdShow);
    private const int SW_HIDE = 0;
    private const int SW_SHOW = 1;

    public void WindowsToolbar(bool visible)
    {
        int hWnd = FindWindow("Shell_TrayWnd", "");
        ShowWindow(hWnd, visible ? SW_SHOW : SW_HIDE);
    }

    public void HideTaskBarIfNeeded(Form form)
    {
        if (Screen.PrimaryScreen.Equals(Screen.FromRectangle(Screen.GetBounds(form))))
        {
            WindowsToolbar(false);
        }
    }


text:
Q: How to retrieve unspec'd headers with openapi-generator (spring) For our REST APIs, we have certain HTTP Request headers which will be set by infrastructure components, and should not be published to consumers in the OpenAPI spec.
In the Spring Web based implementation code that we build (implementing the openapi-generator's generated interfaces), what is the right way to retrieve something like this from the HTTP Request? For example, a header which is not specified on the interface.
I do not see any options in the openapi-generator itself to add the HttpServletRequest as a parameter to the generated methods. I am hoping there is a more generic way to get a handle to it in Spring / Spring Web.

A: Okay, so this turns out to be pretty simple and elegant using the open-api-generator's generated Spring code, at least in the "delegate" pattern that I am using.
The Delegate class creates a getRequest() method which you simply override like so:
private final NativeWebRequest nativeWebRequest;

@Override
public Optional<NativeWebRequest> getRequest() {
    return Optional.ofNullable(nativeWebRequest);
}

You may have to add the NativeWebRequest to your constructor or make it @Autowired. (We are using lombok to generate constructor.)
Then in your API method you can just do something like:
String headerValue = getRequest().get().getHeader("my-header-name");


text:
Q: Euphemism for "non-useful" I was just about to tell someone how something "wouldn't really be much useful" if they leave it the way it is — which is like a much more polite version of useless, but I just couldn't find the word. I'm guessing I just don't know it.
What is an idiomatic euphemism for non-useful?
EDIT:
It was actually an answer to a question, and I was wondering how I would say this answer is not really useful without hurting the person.

A: According to this list of British "euphemisms"...

"Very interesting" means "I don't agree/I don't believe you"

(the hapless American assumes the Brit means "I am impressed", so the euphemism has worked!). But I personally think it's a good way of saying "Although what you say is interesting, and might be useful in some other context, it has no practical value in relation to my current problem."
Older Americans may recall Rowan & Martin's Laugh-In, featuring the catchphrase

"Very interesting ... but stupid!"

A: The appropriate euphemism for "completely useless but still quite nice" is entirely decorative. See for example its use on Wikipedia, for Dutch Gable and this review of some headphones.
Edit: Another option might be well-intentioned.  This would even be applicable for the edited version of this question; that is, the "useless" thing is an answer to a question.

A: "This answer doesn't suit (or doesn't fit) my needs."  In my opinion, this puts the perception of shortcoming on my needs instead of their answer.

A: "Not exactly the thing" or "not quite it".

A: In the context of addressing an answer, I think it's fine to be direct (no need to be euphemistic or use a substitute word like "interesting"), as long as you do it politely. You don't have to use the word "useless" but don't hide what you are trying to say either behind a word that does not mean what you are actually trying to say. The exact wording would depend upon the question asked and the answer given, but some examples might look like:

I appreciate the input, but unfortunately that doesn't work in this
  case.

or

Thanks, but I don't think that can be applied to this problem.

As long as you thank them for trying and acknowledge that what they offered was a fair attempt at helping, they probably will not be offended/upset/hurt that it happens to not be useful to your particular circumstance.

A: "Thanks, that's certainly the most recent answer I've received."

A: One of these days I'm going to surprise you by making use of your gems of wisdom.
Your excellent advice has been duly noted.
Wait, I'm just going to write it all down.


text:
Q: java.lang.NoSuchMethodError: No such DSL method 'bash' found among steps I want to run bash commands throw Jenkins pipeline, I'm calling a function that has some bash commands but I'm getting this error:

 java.lang.NoSuchMethodError: No such DSL method 'bash' found among steps

This is the function:

def copy_tools(){
   // tools
   bash '''#!/bin/bash
   mkdir X6//CX6
   cp ${x6_tools_path} .
   unzip CX6.zip -d .\\X6
   '''

}

can you please help?

A: You want to use sh, not bash. You aren't directly running bash in your code. You need to run the sh pipeline step, which will run the configured shell.
def copy_tools(){

   // tools
   sh '''#!/bin/bash
   mkdir X6//CX6
   cp ${x6_tools_path} .
   unzip CX6.zip -d .\\X6
   '''
}


text:
Q: Prevent page reload when setting session variable I have an asp button, and on the click event a session variable is set and the page is redirected. The problem is that this process requires two clicks - once to set the session and another to redirect. How can I set the session and redirect in one click? My code is as follows:
protected void btn_login_Click(object sender, EventArgs e)
{
       HttpContext.Current.RewritePath("AnotherPage.aspx");
       Session.Add("user-id", _id);
}

A: protected void btn_login_Click(object sender, EventArgs e)
{
    Session.Add("user-id", _id);
    Response.Redirect("AnotherPage.aspx");
}


text:
Q: Finding functional extremal with Euler-Lagrange equation I have $\int_1^2 (t\dot{x}^2+\frac{1}{t}x^2) dt$ with $x(1)=0$ and $x(2)=3$ and am trying to find the extremal. I know I need to start with the Euler-Lagrange equation $\frac{\partial f}{\partial x}-\frac{d}{dt} \frac{\partial f}{\partial \dot{x}}=0$ and have found $\frac{\partial f}{\partial x}=\frac{2}{t}x$ and that $\frac{\partial f}{\partial \dot{x}}=2t\dot{x}$ which leaves me with the EL equation $\frac{d}{dt}(t\dot{x})=\frac{1}{t}x$. However, at this point I get a bit stuck since the RHS of the equation depending on $x$ means I can't just integrate with respect to $t$. Does anyone have any tips on where to go from here?

A: Let $F(t,x,\dot x)=t\dot x^2+x^2/t$. As you have correctly stated, Euler-Lagrange yields $$\frac{dF_{\dot x}}{dt}=F_x\implies \frac d{dt}(2t\dot x)=\frac 2tx\implies \dot x+t\ddot x=\frac xt$$ using the Product Rule. The second-order ODE $$t^2\ddot x+t\dot x-x=0$$ is a simple Cauchy-Euler equation, from which you get $x=At+B/t$ for some constants $A,B$ that satisfy the boundary conditions.


text:
Q: Long equation spread across the whole page in two column format I use the strip environment for a long equation in a two-column page format, but the equation number appears at the edge of the first column and not after the equation ends.
\begin{strip}
\begin{equation}

f_{k+i,j} \left(
\bar{A}^{k+i+1}\hat{x}_{-1} +
 \bar{A}^{i+1}\bar{B}_k \begin{bmatrix} \Tilde{y}_0 \\ \vdots \\ \Tilde{y}_{k-1} \end{bmatrix} +
   \bar{B}_{i+1} \left(
\begin{bmatrix} {y}_k \\ CA\hat{x}_k \\ \vdots \\ CA^i\hat{x}_k  \end{bmatrix}
 +
\begin{bmatrix} M_s\delta_k \\ M_s\delta_{k+1} \\ \vdots \\ M_s\delta_{k+i} \end{bmatrix} \right) \right) \leq  h_{k+i,j}
 - \sqrt{f_{k+i,j}\Sigma_{\zeta_i}f_{k+i,j}^T}\Phi^{-1}\left(1 - \frac{\alpha}{s_{k+i}}\right)
 - \max_{\eta \in \Gamma} f_{k+i,j}\bar{A}^{k+i+1}\eta
\end{equation}
\end{strip}


text:
Q: string needs double quotationmarks VBA now confused to which quotationmarks are what I need to append a string to a text file which has double quotation marks throughout it. How do I do that cause VBA is very confused at the moment
What the string should say/append the text file to (load "c:\test.lsp")?

A: You can double the quotation marks inside the string:
"""The Professional"" is a killer movie."

Or use Chr(34):
Chr(34) & "The Professional" & Chr(34) & " is a killer movie."


text:
Q: sql select statement to check for previous records for same id I'm trying to build a query which would be checking records added for the current date. I would like to take the unique company_id for each record and check against each of these company_id's history if a records exists with almost the same document_date (previous year: f.eg.: doc date is 2014/12/31 and the previous record would have 2013/21/31).
So far I got to the point that I'm able to pull out each company_id from currently added records and show what is the latest document date available for a specific document type
In pseudo-code:
select company_id, MAX(document_date), document_type
from submissions
where company_id in
(
select distinct company_id
from submissions
where filing_date = current date
)
and document_type = 'annual'
group by company_id, document_type

I would like to be able to take the document_type value from the currently added record and check for a previous record with that same value but as mentioned where the document_date is for the previous year. Do I need to build a procedure for that or is it possible to do it in a select statement?

A: Try this:
; WITH cte AS (
  SELECT company_id
       , document_date
       , document_type
       , Row_Number() OVER (PARTITION BY company_id ORDER BY document_date DESC) As sequence
  FROM   submissions
  WHERE  document_type = 'Annual'
)
SELECT current_record.company_id
     , current_record.document_date
     , current_record.document_type
     , next_record.document_date As next_record_document_date
     , next_record.document_type As next_record_document_type
FROM   cte As current_record
 LEFT    /* outer join as we might not always have a "next" result */
  JOIN cte As next_record
    ON next_record.company_id = current_record.company_id
   AND next_record.sequence   = current_record.sequence + 1
WHERE  current_record.sequence = 1 /* Limit to the "first" record */
AND    current_record.filing_date = Current_Timestamp
;

This uses the windowed function Row_Number() to assign a... row number... to each record. The PARTITION BY clause resets this row number for each company_id. The order of the row number is determined by the ORDER BY part of this function (i.e. by document_date DESC).
Once we have this information we can then perform a self-join to get join the "current" and "next" records together.

A: select s1.company_id, s1.document_date, s2.document_date
  from submissions s1
  join submissions s2
    on s2.company_id = s1.company_id
   and s2.document_date = dateadd(yy, -1, s1.document_date)
   and s2.document_type = 'annual'
   and s1.document_type = 'annual'

A: The idea is to SELECT the documents from submissions table for the current date, and CROSS (or OUTER) APPLY it to the submissions table on the same company_id and document_type where filing_date is year from the current date:
select s.*, x.*
from submissions s
cross apply (
  select top (1) *
  from submissions s2
  where s.company_id = s2.company_id
  and s.document_type = s2.document_type
  and s.filing_date = dateadd(year, 1, s2.filing_date)
) x
where filing_date = @current_date

Pls replace the '*' with the column names needed.
TOP (1) is here to just pull a single row from the subquery.


text:
Q: How to check if a string is doesn't equal all of these? Trying to rewrite this using LINQ:
if (mode != "A" && mode != "B" && mode != "C" && mode != "D" && mode != "E" && mode != "F" && mode != "G")
{
   continue;
}

What would be the most clear and concise way to refactor this? I could have sworn I'd seen a post like this before but I cannot find it at the moment.

A: Write an extension method for the string class
public static bool In(this string s, params string[] values)
{
    return values.Any(x => x.Equals(s));
}

call it in this way
if (!mode.In("A", "B", "C", "D","E","F", "G")
{
    continue;
}

A: You can use Contains method from IList<T>:
IList<string> modes = new[]{"A","B","C","D","E","F","G"};
if (!modes.Contains(mode))...

A: var modes = new[] { "A","B","C","D","E","F","G"};

if (modes.All(a => mode != a))
    continue;

A: I use this extension method all the time
public static bool IsIn(this string source, params string[] parms)
{
    return parms.Contains(source);
}

And use it as follows:
if (!mode.IsIn("A", "B", "C", "D", "E", "F", "G"))
{
    continue;
}

The next step, if you use it much, is
public static bool IsNotIn(this string source, params string[] parms)
{
    return !IsIn(source, params);
}

and you get the slightly more readable
if (mode.IsNotIn("A", "B", "C", "D", "E", "F", "G"))
{
    continue;
}

A: string s = "ABCDEFG";
bool res = s.Any(item => { return (int)item > 64 && (int)item < 72; });


text:
Q: Textbox in modal popup inserts duplicate entries My textbox is supposed to enter one value and enters about 8 of the same thing. Anyone know why?

        <asp:LinkButton ID="FeatureButton" runat="server">Feature</asp:LinkButton>
        <asp:Panel ID="FeaturePanel" runat="server" CssClass="modalPopup"
         Style="display:none">

Add a Feature

            <asp:CheckBoxList ID="cbxAddFeature" runat="server"
             DataSourceID="dsNewFeatures" DataTextField="FeatureTitle"
             DataValueField="FeatureID"></asp:CheckBoxList>
            New Feature:<asp:TextBox ID="txtFeature" runat="server"></asp:TextBox>
            <asp:Label ID="FeatureError" runat="server" ></asp:Label>
            <asp:Button ID="SubmitFeatures" runat="server" Text="Submit" />
            <asp:Button ID="CancelSubmitFeatures" runat="server" Text="Cancel" />
        </asp:Panel>
        <asp:ModalPopupExtender ID="FeatureModal" runat="server"
         BackgroundCssClass="modalBackground"
         CancelControlID="CancelSubmitFeatures" DropShadow="True"
         DynamicServicePath="" Enabled="True" PopupControlID="FeaturePanel"
         TargetControlID="FeatureButton"></asp:ModalPopupExtender>
Protected Sub SubmitFeatures_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles SubmitFeatures.Click
    FeatureModal.Hide()
    For Each feature As ListItem In cbxAddFeature.Items
        If feature.Selected Then
            'SQL INSERT: Marketing Table
            Dim strSQL As String = "INSERT INTO Marketing (ProductID,
                                    MarketingTypeID, MarketingTitle, MarketingData)
                                    VALUES (@ProductID, 3, 'Feature', @MarketingData);
                                    UPDATE Product SET ModifyDate = getdate(),
                                    ModifyUser = @ModifyUser
                                    WHERE ProductID = @ProductID"

This is the code for the entire modal pop up, which includes an insert for checkboxes as well. If the user doesn't see an appropriate checkbox, they can enter a new value via textbox.
Protected Sub SubmitFeatures_Click(ByVal sender As Object, ByVal e
As System.EventArgs) Handles SubmitFeatures.Click
    FeatureModal.Hide()
    For Each feature As ListItem In cbxAddFeature.Items
        If feature.Selected Then

            Dim strSQL As String = "INSERT INTO Marketing (ProductID,
                                    MarketingTypeID, MarketingTitle, MarketingData)
                                    VALUES (@ProductID, 3, 'Feature', @MarketingData);
                                    UPDATE Product SET ModifyDate = getdate(),
                                    ModifyUser = @ModifyUser
                                    WHERE ProductID = @ProductID"

            Using cn As New SqlConnection
             (System.Configuration.ConfigurationManager.ConnectionStrings
             ("LocalSqlServer").ConnectionString)

                Using cmd As New SqlCommand(strSQL, cn)

                    cmd.Parameters.Add(New SqlParameter("@ProductID",
                    ProductID.Value))
                    cmd.Parameters.Add(New
                    SqlParameter("@MarketingData", feature.Value))
                    cmd.Parameters.Add(New SqlParameter("@ModifyUser",
                    System.Web.HttpContext.Current.User.Identity.Name))

                    cn.Open()

                    cmd.ExecuteNonQuery()
                End Using

                cn.Close()
            End Using
        Else
        End If
        If Not String.IsNullOrEmpty(txtFeature.Text) Then
            Dim featureSql As String = "INSERT INTO Feature (FeatureTitle)
                                        VALUES (@FeatureTitle);
                                        INSERT INTO Marketing(ProductID,
                                        MarketingTypeID, MarketingTitle, MarketingData)
                                        VALUES (@ProductID, 3, 'Feature',
                                        scope_identity());
                                        UPDATE Product SET ModifyDate = getdate(),
                                        ModifyUser = @ModifyUser
                                        WHERE ProductID = @ProductID"

            Using cn As New SqlConnection
            (System.Configuration.ConfigurationManager.ConnectionStrings
            ("LocalSqlServer").ConnectionString)

                Using cmd As New SqlCommand(featureSql, cn)

                    cmd.Parameters.Add(New SqlParameter("@FeatureTitle",
                    txtFeature.Text))
                    cmd.Parameters.Add(New SqlParameter("@ProductID",
                    ProductID.Value))
                    cmd.Parameters.Add(New SqlParameter("@ModifyUser",
                    System.Web.HttpContext.Current.User.Identity.Name))

                    cn.Open()

                    cmd.ExecuteNonQuery()
                End Using

                cn.Close()
            End Using
        End If
    Next
    'keep tab active and redirect to same page
    Session("ActiveTabIdx") = TabContainer1.ActiveTabIndex
    Response.Redirect(Request.RawUrl)
End Sub

A: Move out code for inserting new feature from the for each cycle.

A: I think it's because of this:
If feature.Selected Then
 ...
Else
  ....
End If

That means that for every item in the checkbox list it will always go into the Else block when the checkbox is not selected, which is causing multiple inserts.
Extra suggestions
Don't mix your UI code and your data access code on the same class/page. A good practice is to separate UI from Business Logic from Data Access logic. For example, this code:
Dim strSQL As String = "INSERT INTO Marketing (ProductID,
                                    MarketingTypeID, MarketingTitle, MarketingData)
                                    VALUES (@ProductID, 3, 'Feature', @MarketingData);
                                    UPDATE Product SET ModifyDate = getdate(),
                                    ModifyUser = @ModifyUser
                                    WHERE ProductID = @ProductID"

            Using cn As New SqlConnection
             (System.Configuration.ConfigurationManager.ConnectionStrings
             ("LocalSqlServer").ConnectionString)

                Using cmd As New SqlCommand(strSQL, cn)

                    cmd.Parameters.Add(New SqlParameter("@ProductID",
                    ProductID.Value))
                    cmd.Parameters.Add(New
                    SqlParameter("@MarketingData", feature.Value))
                    cmd.Parameters.Add(New SqlParameter("@ModifyUser",
                    System.Web.HttpContext.Current.User.Identity.Name))

                    cn.Open()

                    cmd.ExecuteNonQuery()
                End Using

                cn.Close()
            End Using

Can be moved entirely to another class that receives 3 parameters: UserID, ProductID and MarketingData. By doing this, you can reuse it on other places(pages, for example) instead of having to repeat the logic again and again.
Optimally, you should have a business layer that calls your Data Access layer (Above code will go into your Data Access Layer) but at least moving this code to a different place is a good start. Another advantage besides being able to reuse your code is that supposing that you detect an error on this routine, you can fix it on one place as opposed to having to go to different places on your app to correct your error.


text:
Q: How to use include_once in Apache/PHP?
*

*My development environment is: Win7, XAMPP 1.8.3.3 VC11.

*include_path in my PHP.ini file is: ".;C:\xampp\php\PEAR"

I have downloaded a package simplehtmldom_1_5 and kept in "C:\xampp\php\PEAR" folder so that my test file "C:\xampp\htdocs\test1.php" can include PHP files from this package. My test1.php looks like:
<?php
include_once('simplehtmldom_1_5/simple_html_dom.php');
echo file_get_html('www.google.com')->plaintext;
?>

As soon as I type http://localhost/test1.php, I get the below error:
Warning: file_get_contents(www.google.com): failed to open stream: No such file or directory in C:\xampp\php\pear\simplehtmldom_1_5\simple_html_dom.php on line 75

Notice: Trying to get property of non-object in C:\xampp\htdocs\test1.php on line 15

If I move the simplehtmldom_1_5 package from "C:\xampp\php\PEAR" to "C:\xampp\htdocs\simplehtmldom_1_5" and then try the above test1.php, I get the below error:
Warning: file_get_contents(www.google.com): failed to open stream: No such file or directory in C:\xampp\htdocs\simplehtmldom_1_5\simple_html_dom.php on line 75

Notice: Trying to get property of non-object in C:\xampp\htdocs\test1.php on line 15

I have spent considerable time in debugging this but gave up now. Please help where I am wrong.

A: You probably mean http://www.google.com and not a file called www.google.com

A: When using file_get_contents or similar function to open a URL you should specify the full protocol to tell PHP this is web address or external file not a local file.
Therefore,
file_get_contents('www.google.com')

Should be changed to:
file_get_contents('http://www.google.com');

A: you need to use http:// with url
<?php
include_once('simplehtmldom_1_5/simple_html_dom.php');
echo file_get_html('http://www.google.com')->plaintext;
?>

also you need to check you have file dir(simplehtmldom_1_5) on where test1.php located
like :-
C:\xampp\htdocs\simplehtmldom_1_5


text:
Q: Query Activities associated with Contacts I am building a lightning component on Account that takes the Account ID and returns the contacts and the most recent task associated with it.
@AuraEnabled
public static list<Contact> getRelatedContactList(Id recordId)
{

List<Contact> conList = [Select id,firstname,lastname,Contact_Salutation_First_and_Last_Name__c,(SELECT Id,Subject,OwnerId,ActivityDate,Owner.Name FROM Tasks where Status = 'Completed' ORDER BY LastModifiedDate DESC LIMIT 1) from Contact where AccountId =: recordId and Key_contact__c = true];
return conList;
}

The above logic works perfect when the Task is only associated with one contact/Primary contact. It doesnot return back the tasks in which the contact is not primary or If the tasks has multiple contact the above query doesnot return them. I read we can use 'TaskRelation' but I am not sure how to use them in here as I have only the Account ID and not the Tasks ID.

A: First principles - don't put your whole SOQL on 1 line - too hard to read/debug
If you have shared activities enabled, you'll need to query from Contact via relationship TaskRelations and because TaskRelation has a lookup field to the Task, you can filter on the TaskRelation that has the most recent Task.LastModifiedDate
return
    [SELECT Id,Firstname,Lastname,Contact_Salutation_First_and_Last_Name__c,
       (SELECT Task.Id,Task.Subject,Task.OwnerId,Task.ActivityDate,Task.Owner.Name
          FROM TaskRelations where Task.Status = 'Completed'
          ORDER BY Task.LastModifiedDate DESC LIMIT 1)
        FROM Contact where AccountId =: recordId and Key_contact__c = true];

Reference TaskRelation


text:
Q: Where are the DLL's referenced in my .net C++ Dll/Tlb? I created a .net C++ dll, which I then converted to a tlb file for use in a native C++ application. I referenced other external dll's in my dll. Now, I am trying to deploy, and want to copy over the referenced dll's to the deployment computer. Where do they reside in my .net C++ project?

A: The default behavior is for the build system to copy any referenced assemblies to your build output directory.  So that you can debug the result.  This copy won't happen when the reference assembly is in the GAC, like is the case with any .NET framework assembly.
In other words, you should find them back in your Release build directory after building.


text:
Q: Mysql populate serial number column based on pattern I need to populate a table with x number of serial numbers.  Each serial number should follow the pattern A000001, A000002, A000003, etc.
I have the following I wrote from SQL Server but having issues converting it to mysql.
SELECT CHAR(ASCII('A') + @var / 1000000) + RIGHT('000000' + CONVERT(varchar(6),(@var % 1000000)),6)

Basically, I can just stick this into a WHILE loop and replace @var with the next number.
Any help is appreciated.

A: You can use the LPAD() function to add the prefix before the number:
SELECT LPAD(@var, 7, 'A000000')


text:
Q: primefaces poll dynamic interval I wrote example code like this :
@ViewScoped
@Named
public class SampleBean implements Serializable {

    private int interval = 1;

    public void execute() {
        switch (interval) {
            case 1:
                System.out.println("1 Executed ...");
                break;
            case 2:
                System.out.println("2 Executed ...");
                break;
            case 3:
                System.out.println("3 Executed ...");
                break;
        }
    }

    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }
}

and this xhtml :
<h:form>
        <p:selectOneButton value="#{sampleBean.interval}">
            <f:selectItem itemLabel="1" itemValue="1"/>
            <f:selectItem itemLabel="2" itemValue="2"/>
            <f:selectItem itemLabel="3" itemValue="3"/>
        </p:selectOneButton>

        <p:poll interval="#{sampleBean.interval}" listener="#{sampleBean.execute}" id="poll"/>

    </h:form>

I want to update interval time of primefaces poll component dynamically but not changed with my example code . sleep always executed every 1 second .
What is wrong in my code ?

A: You need to tell the p:poll component to refetch it's backing bean values. You can easily accomplish this by invoking a new rendering phase (via PrimeFaces update or via f:ajax render) on the component.
So to make it work, you just have to do something like this,
<h:form>
    <p:selectOneButton value="#{sampleBean.interval}">
        <f:selectItem itemLabel="1" itemValue="1"/>
        <f:selectItem itemLabel="2" itemValue="2"/>
        <f:selectItem itemLabel="3" itemValue="3"/>
        <f:ajax render="@form"/>
    </p:selectOneButton>
    <p:poll interval="#{sampleBean.interval}" listener="#{sampleBean.execute}" id="poll"/>
</h:form>

Notice the f:ajax invocation above.
You need to target the enclosing (parent) component to get it to refresh - this is why we are targeting the form instead of the poll component directly.


text:
Q: c doubly-linked list display method showing redundant elements I have a small doubly-linked list application. I want to add elements inside the list and then display the list normally. At the output i get my inserted elements allright, but after them i get a bunch of strange numbers( such as .... 28482 -20048 2817 ......  )
I believe it's a problem of space allocation.
Any help is appreciated, thanks in advance!
# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <stdlib.h>

typedef struct elem {
    int number;
    struct elem * urm;
    struct elem * prec;
}nod;

nod *prim=NULL,*ultim=NULL, *local=NULL, *p=NULL;

void insert_element(int numb){

    nod *local=(nod *)malloc(sizeof(nod));
    local->number = numb;

    if (prim==NULL){
        prim=local;
        ultim=local;
    }
    else{
        ultim->urm = local;
        local->prec = ultim;
        ultim=local;
    }
}

void load_data()
{
    int i,n;
    nod *c = (nod *)malloc(sizeof(nod));
    printf("\n cate elemente va avea lista?");
    scanf("%d", &n);
    printf("avem %d elemente", n);
    for(i=1;i<=n;i++){
    printf("\n number: ");
    scanf("%d", &c->number);
    insert_element(c->number);
    }
}

void list_left_to_right()
{
    nod *p = (nod*) malloc(sizeof(nod));
    p=prim;

    while(p){
    printf("%d ", p->number);
    p=p->urm;
    }
    printf("\n");
}

int main()
{
    int op;

    do{
    printf("\n1.Enter some data\n");
    printf("2.Display left - > right the data\n");
    printf("0.Exit\n");
    printf("choice : ");
    scanf("%d",&op);

    switch(op){
    case 1: load_data(); break;
    case 2: list_left_to_right(); break;
    case 0: break;}
    }
    while (op!=0);
    return 0;
}

A: (1) You have a memory leak in list_left_to_right():
nod *p = (nod*) malloc(sizeof(nod));
p=prim;

This leaks the block returned by malloc().
(2)
void insert_element(int numb) {
    nod *local=(nod *)malloc(sizeof(nod));
    local->number = numb;
    // TODO: set local->urm and local->prec to NULL

    if (prim==NULL) {
        prim=local;
        ultim=local;

OK, so the first time insert_element() is called, the new element is both the head and the tail.
Bug: You need to set the urm and prec fields to NULL.  They have undefined values initially.
    }
    else {
        ultim->urm = local;
        local->prec = ultim;
        ultim=local;
    }
}

After that, the subsequent elements are inserted as a new tail (ultim).
Bug: But again you need to make sure that local->urm is set to NULL.


text:
Q: Bootstrap 4: fix contents bottom inside container I have an app wrapped around a
, in which I have an editor and a few buttons, which I always want to be shown at the bottom, something like so:

  // some content....

  // this should be shown always at the bottom!

I have tried changing the min-height, and height properties of html, body and container to be 100% and added important to this rules, but that doesnt make my div container stretch any more downwards. When I use the "fixed-bottom" bootstrap class, the #bottom div stretches horizontally over the container boundaries, which makes the layout completely ugly.
any suggestions? :)

A: Wrap your "submit-form" with another container or use col-* for positioning.
For example:

Manipulate your div size by col-* class (bootstrap grid contains 12 columns, so below  div will cover 4 columns of screen size)  :

After that this form will be aligned to the left side of the screen.
Use d-flex for positioning your bootstrap column:

If you want to create responsive web site, you should read something about bootstrap grid system and use col-md-*, col-sm-* etc. instead of col-*:
https://getbootstrap.com/docs/4.0/layout/grid/

A: If you are using the BS4, then there is lots of classes provided by BS, use those to achieve your output.
I have added some height to row, just to show you desired result, As we will have some content in container then you would not need any height on row.
NOTE: If you do not want to use row, just in case, then use class d-flex on container and rest will remain same.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Button


text:
Q: No Views in web service project I've got a web service project that runs and shows a webpage that is located in Project_directory\Views\Home\Index.cshtml.
I have created a simple web service, but when I run I get the following error:

How can I generate a Views directory in my project and get the system to load Index.cshtml ?


text:
Q: C# Semaphore state test thread saftey public class ThreadDemo
{

    Semaphore sem = new Semaphore(0, 1);//Semaphore with maxCount of 1

    public ThreadDemo()
    {
        Thread worker = new Thread(WorkerThread);
        worker.Start();
    }

    public void NotifyNewData()
    {
        //New data added to queue

        //WorkerThread could be in one of two states
        //1) still working or
        //2) waiting for new data

        if (sem.WaitOne(0) == false)//If worker thread is waiting for new data
            sem.Release();//tell worker thread to process new data
    }

    private void WorkerThread()
    {
        while (true)
        {
            while(/*data in queue*/)
            {
                //process data in some queue
            }
            sem.WaitOne();//Worker thread processed all data, wait for more
        }
    }
}

See the above example.
I have a worker thread processing data from a queue and I want it to imediatly start processing new data when notified by another thread.  I don't want to poll for new data.
Will the above solution work?  Or, could this code potentialy result in the worker thread being blocked even when there is data that could be processed?  Maybe if both threads called sem.WaitOne() at the same time.


text:
Q: Get values from Django's form in efective way I'm getting values from form in django like this:
            tantou1 = request.POST.get("1tantou", "")
            tantou2 = request.POST.get("2tantou", "")
            tantou3 = request.POST.get("3tantou", "")
            tantou4 = request.POST.get("4tantou", "")

            hidzuke1 = request.POST.get("1hidzuke", "")
            hidzuke2 = request.POST.get("2hidzuke", "")
            hidzuke3 = request.POST.get("3hidzuke", "")
            hidzuke4 = request.POST.get("4hidzuke", "")

which works, but I have a lot of values to get and this way took too much space in my code. I would like to ask, if there is not a way to define this variables in (for example) loop? Something like:
data_vars = [tantou1="", tantou2="", tantou3="", tantou4="", hidzuke1="", hidzuke2="", hidzuke3="", hidzuke4=""]

for var in data_vars:
    var = request.POST.get(str(var.__name__), "")

or so?

A: You should just pass request.POST into your form's __init__, like so:
def view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)

        if form.is_valid():
            form.save()
    else:
        ...

A: The docs say that HttpRequest.POST is a dictionary-like object.
According to this post you can unpack a dict to variables a number of ways, but they recommend namespacing. I've just tried this and it works:
from types import SimpleNamespace

n = SimpleNamespace(**request.POST.dict())

You can then access your variables as:
n.tantou1
n.tantou2


text:
Q: Very peculiar network issue on Debian 9 - Realtek network cards My OS: OS in question, and my primary OS: Debian 9.1 (fresh install) with i3 window manager (no DE). Other OSes (dual booted): Ubuntu 14.04 and Windows 10.
Kernel: 4.9.0-3-amd64
Network cards info: Realtek 8101 ethernet controller which works out-of-the-box (verified many times in Debian 9, Ubuntu, ...) and a Realtek 8723be Wireless network adapter which needs additional tweaking (Installation of a driver patch - due to a fault in the default drivers - tried by myself, it worked fine.).
I installed network-manager-gnome to manage my networks (although ethernet is unmanaged by it since eno1 (my ethernet) appears in /etc/networks/interfaces)
Problem: Network (neither ethernet nor WiFi) doesn't work on fresh reboot. By this I mean that - if I directly boot into Debian and try accessing the internet, it doesn't work. But, if I first boot into say, my Ubuntu, login to the internet there (see Additional info 1 below) and come back to Debian, it works! I have tried this a lot of times and the pattern is always that.
Additional info 1: I am accessing internet from a university campus, so there's a network login page that I must first visit and login. I can't open this login page upon a fresh restart, but if I already login and come to Debian, I can! I find this very strange.
EDIT: There's no proxy server involved. Just a login page.
Additional info 2: There's a known kernel-panic bug associated with my particular Wireless network adapter, network-manager-gnome and Debian. I experienced it as follows: If I don't install that said driver patch for my Wireless adapter, I experience kernel-panic during bootup (sometimes multiple times) and if I do install it, there's no kernel-panic.
To confirm this is indeed the reason for kernel-panic, I checked the syslog at /var/log/syslog and observed something on the lines of wlo1... just prior to the kernel-panic entry.
And please note, with that driver patch I can use my Wireless adapter perfectly fine (provided I login to internet in my Ubuntu for a and come back!).
My question: Why does my network show such a strange pattern, how do I correct it? Any leads would be appreciated. Thanks a lot!

A: At the bottom of:
https://wiki.debian.org/DualBoot/Windows
It says to add NETDOWN="no" to /etc/default/halt so that linux doesnt 'shutdown' with out the win drivers permission.


text:
Q: What does rf in rm -rf stand for? What does rf in rm -rf in Unix stand for?
More generally, I have a hard time remembering Unix commands and options because I don't understand what they stand for. Is there a resource that explain the meaning of these shorthands?

A: In rm,

*

*-r stands for recursive

*-f stands for force
Doc :
man rm

said :

    -f, --force
           ignore nonexistent files and arguments, never prompt

    -r, -R, --recursive
           remove directories and their contents recursively

A: -r

Recursively removes directories and  subdirectories
                in the argument list. The directory will be emptied
                of files and removed. The user is normally prompted
                for  removal of any write-protected files which the
                directory contains. The write-protected  files  are
                removed  without  prompting,  however,  if  the  -f
                option is used, or if the standard input is  not  a
                terminal and the -i option is not used.

A: I believe it is recursive force

A: rm means remove
r means recursive, which you have to use when removing an entire folder
f means force removal
combined, rm -rf someDirectory means force the recursive removal of someDirectory


text:
Q: How to retrieve specific information from a certain website? I am developing a java web application and I want to know how to take a certain field (table and/or output-text) value from a certain website. Assuming that this component has always the same ID does anyone know how can I retrieve this information?
I don't know if anyone has ever faced this issue but if anyone has any idea please share.
Thank you.

A: In general:
 1.) Retrieve the pages markup by reading it through an HTTPConnection to the URL in your application
 2.) Parse the Markup using a framework like jsoup and retrieve the value you need.
More specifically, here is some example code for jsoup:
HttpClient http = new DefaultHttpClient();
String htmlcode = "";
HttpGet request = new HttpGet("http://www.example.com");
HttpResponse response = null;
try {
    response = http.execute(request);
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
if(response != null){
    BufferedReader read = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    String line = "";
    while((line = read.readLine()) != null){
        htmlcode += line;
    }
}
// at this point we have the pages markup
Document doc = Jsoup.parse(htmlcode);
Elements lis = doc.getElementsByTag("li"); // get all entries in lists
for(Element el : lis){
    String val = el.text().trim();
    // do something for each list entry
}

A: You are talking about web scraping, check this library for php:
http://simplehtmldom.sourceforge.net/


text:
Q: How get a value from NSDictionary and move it to an NSArray I'm sure this question has been asked dozens of times on here, but I can't seem to find anything even close to what I need. I'm having a little bit of a problem getting this right. I need to get a value out of an NSDictionary and place it into an NSArray.
    NSDictionary *dictionary = @{@"ID1":@{
                                   @"mainPhone": @"<number>",
                                   @"Address": @"<address>",
                                   @"City": @"<Tulsa, OK>",
                                   @"Date": @"1-1-2017",
                                   @"Person1": @{
                                               @"First": @"<FirstName>",
                                               @"Last":  @"<LastName>",
                                               @"Phone": @"<number>",
                                               @"Email": @"email@gmail.com",
                                               @"Birth": @"<date>",
                                               @"ID":    @"12345",
                                   },
                                   @"Person2": @{
                                               @"First": @"<FirstName>",
                                               @"Last":  @"<LastName>",
                                               @"Phone": @"<number>",
                                               @"Email": @"email@gmail.com",
                                               @"Birth": @"<date>",
                                               @"ID":    @"12345",
                              },
                              @"ID2":@{
                                   @"mainPhone": @"<number>",
                                   @"Address": @"<address>",
                                   @"City": @"<Tulsa, OK>",
                                   @"Date": @"1-1-2017",
                                   @"Person3": @{
                                               @"First": @"<FirstName>",
                                               @"Last":  @"<LastName>",
                                               @"Phone": @"<number>",
                                               @"Email": @"email@gmail.com",
                                               @"Birth": @"<date>",
                                               @"ID":    @"12345",
                                   },
                                   @"Person4": @{
                                               @"First": @"<FirstName>",
                                               @"Last":  @"<LastName>",
                                               @"Phone": @"<number>",
                                               @"Email": @"email@gmail.com",
                                               @"Birth": @"<date>",
                                               @"ID":    @"12345",
                              },
              };

In my example dictionary above, I need to get the key First under the 3rd layer dictionary and load it into an array. The dictionaries marked ID and Person will be assigned separate ID numbers will be the only keys that will not be static. Thanks in advance.

A: For this you can go loop through the dictionary and first idKey then access that dictionary and access its detail by loop through it.
for (NSString *key in dictionary) {
    NSDictionary *idDic = [dictionary objectForKey:key];
    for (NSString *idDicKey in idDic) {
        if ([[idDic objectForKey:idDicKey] isKindOfClass:[NSDictionary class]]) {
            NSString *firstName = [dictionary valueForKeyPath:[NSString stringWithFormat:@"%@.%@.First",key, idDicKey]];
            NSLog(@"%@",firstName);
        }
    }
}


text:
Q: Calculate area enclosed by 4 curves I am trying to find the area enclosed by 4 piecewise smooth curves. As can be seen from the figure,
BLACK curve is a segment of a circle, C
X = 25*cos(a)
Y = 25*sin(a)
-0.8622 <= a <= 2.3262

ORANGE curve is a segment of an ellipse,E1
X = 18*cos(a) + 0
Y = 55*sin(a) + 35
3.4520 <= a <= 4.3982

GREEN curve is a line,L
X = -5.5623 + a*(9.4362 -5.5623)
Y = -17.3081 + a*(-2.6817-17.3081)
0 <= a <= 1

and RED curve is a segment of another ellipse E2
X = 20*cos(a) + 25
Y = 35*sin(a) + 35
3.8206 <= a <= 4.2607

I know all the parametric equations for the curves and the parameters of each vertex with respect to the curve equations.
For example, the vertice at (-17.14,-18.2) has the parameter of 2.3262, in the range of [0, 2*pi], with respect to C.
To find the area enclosed by these curves, I tried to use the brute force way, that is, to integrate each curve segment equations. It works fine for the segment of the curve where X - Y values are bijective. Otherwise, the integration of some part of the curve will cancel out some other part of the curve. An example is the BLACK curve.
To my understand, Green's theorem can solve this. But how do I setup the curves to use Green's theorem? And also, Is there other ways to find the area enclosed by these curves conveniently?
Thanks

A: I would add a new straight line segment, colored blue for purposes of naming, from the blue vertex, through the green vertex and extending to the black circle and add a new blue vertex at that intersection.  This new blue segment is a chord of your black circle.  I would also add straight arcs joining the black and brown vertices and the green and red vertices.  You now have as diagram with 5 distinct areas. Two of these are triangles and one of is a segment of a circle — each of these is easy to compute.  The remaining two areas can easily be turned into basic integrals (after rotating) which can be computed either by hand, if the parametric formulas are particularly nice, or numerically. Edit: since you've now added the parameterizations for the curves and noted they are all segments of ellipses it will be straightforward for you to compute the 5 areas mentioned above by hand.  Hint: put each ellipse segment in standard position.


text:
Q: Why using this declare a global variable in functions? I have this code:
function boo() {
    this.is_global = "Yes!";
}

When I run the boo();, I have is_global in window object, I mean the is_global goes into global context.
I expected to have is_global in boo function only.
Is this a normal behavior?

A: Yes, this is normal behaviour. If your function is defined globally, this is just window and anything added to window is global.

A: this refers to the window. If you want to refer to the function, use:
arguments.callee.is_global = "Yes!";

Now:
window.is_global; //undefined
boo.is_global; //"Yes!"

An alternative way would be to simply refer to boo by its own name when adding properties to it.
function boo() {
    boo.is_global = "Yes!";
}

Note that this modifies the original boo function object. If you wish to modify all instances of boo resulting from using it as a constructor instead, please see the other answers here.

A: To have this be "the function being called", you have to call the function as an object constructor (using new).
var foo = new boo();

This will create an instance of boo with the property is_global. This will not create a property on the constructor function itself. See a demo.
If you don't use new (or a method such as apply), then this is "The object on which the function is called". Since there is no object in this case, the default object is used. In the context of a web browser, the default object is window. So:
var foo = boo();

is the same as
var foo = window.boo();

and this is window inside boo.

A: Check out MDN's introduction to the this keyword.
I guess you wanted to declare a local variable, so use a var statement.


text:
Q: Count cells on image using python and OpenCV I'm trying to write an algorithm to count dots (cells) on an image.
Here is the script I've made so far :
import numpy as np
import cv2
import os

for dirname in os.listdir("images/"):

    for filename in os.listdir("images/" + dirname + "/"):

        # Image read
        img = cv2.imread("images/" + dirname + "/" + filename, 0)

        # Denoising
        denoisedImg = cv2.fastNlMeansDenoising(img);

        # Threshold (binary image)
        # thresh – threshold value.
        # maxval – maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.
        # type – thresholding type
        th, threshedImg = cv2.threshold(denoisedImg, 200, 255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) # src, thresh, maxval, type

        # Perform morphological transformations using an erosion and dilation as basic operations
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
        morphImg = cv2.morphologyEx(threshedImg, cv2.MORPH_OPEN, kernel)

        # Find and draw contours
        contours, hierarchy = cv2.findContours(morphImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        contoursImg = cv2.cvtColor(morphImg, cv2.COLOR_GRAY2RGB)
        cv2.drawContours(contoursImg, contours, -1, (255,100,0), 3)

        cv2.imwrite("results/" + dirname + "/" + filename + "_result.tif", contoursImg)
        textFile = open("results/results.txt","a")
        textFile.write(filename + " Dots number: {}".format(len(contours)) + "\n")
        textFile.close()

Here is my input image :

Here is my result :

For now this script works pretty well with that input but when I switch to other inputs like this one :

I get a very blobby result :

I would like to be able to only keep the dots which are :

*

*Well rounded

Or :

*

*Which are in the top 10% of the other dots in terms of brightness

*Which are "big" enough (relative to the image so let's say eliminate dots which are in the bottom 10% in terms of surface).

I read things about creating a "is_contour_bad" function which I could use to determine if a contour is bad and should be removed.
https://www.pyimagesearch.com/2015/02/09/removing-contours-image-using-python-opencv/
I tried to implement it but didn't get any results. Still, the idea seems good to me.
I also though of adjusting the threshold and erosions/dilatations depending of the image but really the best would be to be able to act on each parameters enumerated before. Still if you have ideas to automatically find the useful properties of an image to apply the right filters on it, it can be interesting.
If you have any idea or piece of code, even small, to help me reach that goal it would be awesome.
Thanks in advance for your help.

A: One way of removing the dots which are not well-rounded and which are small is to use the opening operation (that you are already using) with a circular structuring element of the minimum dot size that you want (every dot smaller than the structuring element will be removed). In the following images there is a similar example to your problem where the small dots are removed this way (source: https://homepages.inf.ed.ac.uk/rbf/HIPR2/open.htm). Also, OpenCV has an implementation of this operation (https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html).

In fact, you already use this operation, but in my opinion the structuring element defined in the following line seems to be too small:
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))

Also, as you are apparently using images with different resolutions, you can adapt the size of the structuring element depending on the resolution of the image.


text:
Q: Javascript - Calculate Kappa When drawing ellipses curves in HTML5, Canvas there's no inbuilt function, you have to scale, or make your own, I've seen this:
function drawEllipse(ctx, x, y, w, h) {
  var kappa = .5522848,
      ox = (w / 2) * kappa, // control point offset horizontal
      oy = (h / 2) * kappa, // control point offset vertical
      xe = x + w,           // x-end
      ye = y + h,           // y-end
      xm = x + w / 2,       // x-middle
      ym = y + h / 2;       // y-middle

  ctx.beginPath();
  ctx.moveTo(x, ym);
  ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  //ctx.closePath(); // not used correctly, see comments (use to close off open path)
  ctx.stroke();
}

But where does that "kappa" come from? How do you calculate it, is it an infinite number (in decimals)?

A: Kappa is calculated this way:

Source
However, it will never produce a mathematical correct ellipse. For that you can use a method like this instead:
function drawEllipse(ctx, cx, cy, rx, ry) {

    var step = 0.01,                 // resolution of ellipse
        a = step,                    // counter
        pi2 = Math.PI * 2 - step;    // end angle

    /// set start point at angle 0
    ctx.moveTo(cx + rx, cy);
    for(; a < pi2; a += step) {
        ctx.lineTo(cx + rx * Math.cos(a), cy + ry * Math.sin(a));
    }
    ctx.closePath();
}

An ellipse() method is actually a part of the specification and as Loktar points out in comments it is available in Chrome and will be in the other browsers later.

A: In differential geometry, the curvature of a curve is given by κ (kappa).
Thus, the value of kappa determines the curves of your ellipse, and .5522848 might just be a choice of the developer behind this piece of code.
According to this table (from wikipedia), a positive curvature determines an ellipse :