text:
Q: PyDev Interactive Console: Using project files I have two questions in regards to the PyDev (Python editor for Eclipse) and its interactive console.
Here is my current situation: whenever I run the interactive console (ctrl + alt + enter), the console requires that I then import the file in the project to use any functions in that file.  Furthermore, when calling the function, I must put the file name in front of it.  So, for example: I go to my properties for the project, go to the PyDev PYTHONPATH, and add a source folder for the project I am currently working on.  By doing so, I can then import a file, let's call it "homework", into the interactive console.  If my file has a function called "calculate", I will have to first type "import homework", then type "homework.calculate()" in order to use the said function.  Otherwise, it won't work (I cannot simply call "calculate").
This brings me to my first question (#1): Why does this not apply for imported modules, such as "math" and such?  Why do I need to do so much work for a local project file?
My second question is related (#2): How do I set-up my PyDev such that it automatically imports the current project's files into the interactive console?  Or, even if I have to manually add my project file, how do I make it so I don't have to call the "file name" + "function name" in order to use the function?
Much help would be appreciated.  Thank you.

A: Actually, in PyDev, provided you have the PYTHONPATH all properly set, you should be able to do (considering your example: homework.calculate()):
calcu <- request code-completion and choose: calculate (homework)
Then it should add the import for you as well as the function you selected.
Aside from that, you'd have to write some code that iterated all your modules, made imports for that and loaded the tokens under the current context (which is not usually a good idea, as you'd have modules overriding names from other modules).
Also note that you can edit the initial set of commands that the interactive console executes at:
window > preferences > pydev > interactive console > initial interpreter commands
So, you may add more imports there which you'd like to have by default.


text:
Q: C++ Linker error on template class and template function Test.h
typedef enum oflags_t : uint8_t
{
    FLAG_CREAT = O_CREAT
  , FLAG_RONLY = O_RDONLY
  , FLAG_RDWR = O_RDWR
} oflags_t;

template <uint8_t flags>
class Test {

public:

    template <uint8_t flags_in = flags>
    Test(const std::string &p_name);

};

using Test_1 = Test<FLAG_RONLY>;

Test.cpp
template <uint8_t flags>
template <uint8_t flags_in>
Test<flags>::Test(const std::string &p_name) {

}

template class Test<FLAG_RONLY>;

main.cpp
 Test_1 obj1("Obj");

When i try to build this, i get linker error "unresolved external symbol...".
What can i do to solve the issue? Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Post input value into table I'm trying to get the text from a input textfield and place the value in a table row, but each time someone posts something the oldest post moves down 1 row, here's what I have but I'm very confused now

<FORM NAME="thisPost">

Post this: <INPUT TYPE="TEXT" NAME="postHere">

<INPUT TYPE="Button" Value="Post" onClick="thisPost(this.form)">

</FORM>

A: There's a number of syntax errors in your code, so I'm not sure how you are able to run it in its current state. Also, your markup and approach is fairly dated. I would highly recommend investing time in a cross-browser DOM framework like jQuery and then an good front-end MVW and templating framework. That aside, I've re-worked your code into a more usable form. Hopefully this will get you going.

function thisPost(){
  //Use getElementById to retrieve the DOM elements you're looking for
  var txtPost = document.getElementById('txtPost');
  var post = txtPost.value;
  if (post == "") {
      alert("Hey! You didn't enter anything!")
  } else {
    alert("The field contains the text: " + post);

    //Get a reference to your table
    var table = document.getElementById('posts');

    //TODO: This is unsafe and subject to script injection.
    //http://en.wikipedia.org/wiki/Code_injection#HTML_Script_Injection
    table.innerHTML = '
' + post + '
' + table.innerHTML;
    txtPost.value = "";
  }
}

//from: http://stackoverflow.com/a/10150042/402706
// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));
        });
    }
}

//Don't bind events in your HTML markup, instead bind them in JavaScript.
addEvent(document.getElementById('btnPost'), 'click', thisPost);
table{
  width:100%;
}
<form name="thisPost">

    Post this: <input type="Text" name="postHere" id='txtPost'>

    <input type="Button" value="Post" id='btnPost'/>

</form>

A: Demo on Fiddle
HTML:
Post this:
<input type="text" name="postHere" />

<button>Post</button>

JavaScript:
var btn = document.getElementsByTagName("button")[0];
var inpt = document.getElementsByName("postHere")[0];
var cnt = 0;

btn.onclick = function() {
    if (!inpt.value) alert("Hey! You didn't enter anything!");
    else alert("The field contains the text: " + inpt.value);
    var tbl = document.getElementsByTagName("table")[0];
    var row = tbl.insertRow(cnt++);
    var cell = row.insertCell(0);
    var txt = document.createTextNode(inpt.value);
    cell.appendChild(txt);
};


text:
Q: Debug innards of IEnumerable.Join() How can I debug the innards of the Join() extension method?
I am NOT asking how to debug/see things in between chained method calls.  NOT tring to look between the dots in this example: myThings.Where().Join();
Instead, I want to see the intermediate values or the internal inner/outer sequences that the Join() method uses to work its mojo.  I have: myThings.Join( a bunch of lambdas ); My keySelectors seem be to returning the correct data.  But my resultSelector is never getting called so I want to see the sequences themselves and debug.
I feel like someone will recommend resharper (I don't have $150 to shell out, so please only offer free alternatives).
Please answer the question: "How can I debug the innards of Join()?"

A: To get a conceptual look at how Join is implemented have a look at Jon Skeet's re-implementation as part of EduLinq: "Reimplementing LINQ to Objects: Part 19 - Join". I would start here because it will probably give you much more insight into what is going on than just starring at the generated code.
If you still want to decompile the generated code using a free tool there is e.g. JustDecompile available for free.

A: I think in VS there is an debug option to let you debug .net source code. It should be in menu Debug->Options->General

A: Using Reflector .NET  7 and newer you're able to debug framework types. You're basically debugging the decompiled versions of the framework. It's a great way to learn.


text:
Q: Onkeypress - how to use different numbers to trigger specific videos Creating an interactive webpage where I want videos to play when a user presses the number keys. Each time a user presses key "1", a certain video will play, when they press key "2" a different video plays.
Right now I am only able to have one video be triggered at a time in javascript, my "1" key turns on the first video, but when I add a second video with the javascript using "2" key, only the second video works by pressing "2", the "1" no longer activates the first video.
here is my html and java
HTML
<!DOCTYPE html>
<html>
<body>
    <video id="vid" src="video/IMG_8873.mp4" type="video/mp4">
  </video>

  <video id="ocean" src="video/OCEAN_8873.mp4" type="video/mp4">
  </video>
</body>
  <script type="text/javascript" src="index.js"></script>
</html>

JAVASCRIPT

var video = document.getElementById('vid');

document.onkeypress = function(e) {
  console.log(e)
  if (e.key === "1" ) {
   { video.paused ? video.play() : video.pause(); }
  }
};

var video = document.getElementById('ocean');

document.onkeypress = function(f) {
  console.log(f)
  if (f.key === "2" ) {
   { video.paused ? video.play() : video.pause(); }
  }
};

A: You are overriding your event handler with your second callback.
Change your code to read:
document.onkeypress = function(e) {
  console.log(e)
  if (e.key === "1" ) {
   var video = document.getElementById('vid');
   video.paused ? video.play() : video.pause();
  } else if (e.key === "2" ) {
   var video = document.getElementById('ocean');
   video.paused ? video.play() : video.pause();
  }
};


text:
Q: python web crawler,when I crawl a URL, the status_code displays 405 Recently, I was learning python. When I  use BeautifulSoup and requests to get the html, I get a status that 405. What's more,the soup is wrong. I visited the URL.
Here is my code:
def craw(url):
    user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0'
    headers = {'User_Agent':user_agent,
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Host':'www.qichacha.com',
'Referer':'http://www.qichacha.com/search?key=%E5%A9%9A%E5%BA%86',
}
    response = requests.get(url,headers = headers)
    if response.status_code != 200:
        response.encoding = 'utf-8'
        print(response.status_code)
        print('ERROR')

    soup = BeautifulSoup(response.text,'lxml')
    print(soup)
if __name__ == '__main__':
url = r'http://www.qichacha.com/search?key=%E5%A9%9A%E5%BA%86'
s1 = craw(url)

the output:

405
ERROR
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>
<meta content="a3c0e" name="data-spm"/>
<title>405</title>

很抱歉,由于您访问的URL有可能对网站造成安全威胁,您的访问被
阻断。

误报反馈

提示:X

感谢您的反馈,应用防火墙会尽快进行分析和确认。

------------------
(program exited with code: 0)

请按任意键继续. . .

According to my output, I know that I got soup is not the page I want. But where is the problem? I'm a novice.

A: I try to deal with the problem.Fortunately,I have solved the problem by use the complete header.
 headers = {
'Host':'www.qichacha.com',
'User-Agent':r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101
Firefox/55.0',
'Accept':'*/*',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Referer':'http://www.qichacha.com/',
'Cookie':'use your cookies'
'If-Modified-Since':'Wed, 30 Aug 2017 10:48:38 GMT',
'If-None-Match':'"59a69806-80"',
'Cache-Control':'max-age=0',}


text:
Q: How can I add a button on the bar at the bottom of the screen for Qt Nokia? I am developing an application for my Nokia N8 running Nokia Belle and would like to add buttons in between the left arrow button and the menu button on the bar at the bottom of the screen.
An example of what I mean can be seen when playing a station in the Nokia Internet Radio application, which, I understand, is a Mobile Qt Widget Application (not Qt Quick).
After searching around (http://www.developer.nokia.com/Community/Discussion/showthread.php?233396-QMenu-in-Symbian-Belle-in-Qt-C), I tried this code, but the button does not appear:
QAction *pDeleteButton = new QAction(style()->standardIcon(QStyle::SP_TrashIcon),QString(tr("Delete")), this);
pDeleteButton->setSoftKeyRole(QAction::NoSoftKey);
addAction(pDeleteButton);

I put this code in the constructor of the mainwindow.cpp.
Thank you for your help!

A: I am no expert in programming for mobile phones, but the QAction you are creating has no parent widget. If you look at the example you are linking, you will find that the original poster assigned a menu for the action via setMenu(). Did you try something like this already? If so, I would suggest you add some more context to your code and maybe a minimal example.


text:
Q: mySQL how to unpivot dynamic columns I have the following table below:
Table name: STAT
Region   M07  M08 M09
---------------------
P1       0    1   0
P2       0    0   0
P3       2    0   0
P4       0    0   0
P5       0    0   0
P6       0    0   0
P7       9    0   3

I would like to UNPIVOT the months columns, which contain numerical values. This Months column headers are DYNAMIC and will be changing, but the total number of columns will remain the same.
Expected Result
---------------------
Region   Month  Qty
---------------------
P1      M07    0
P1      M08    1
P1      M09    0
P2      M07    0
P2      M08    0
P2      M09    0

It would be great if I can have some help writing this SQL statement to UNPIVOT and then also consider the dynamic nature of the numerical columns.
It should written in mySQL.

A: Sadly, mysql does not have an UNPIVOT function.
Your best option is the UNION ALL solution, like :
SELECT region, 'M07' AS month, M07 AS qty from stat
UNION ALL
SELECT region, 'M08', M08 AS from stat
UNION ALL
SELECT region, 'M09', M09 AS from stat

It would be possible to create a piece of SQL code (as a stored procedure for example) that would generate this SQL query dynamically by first querying the INFORMATION_SCHEMA to retrieve the columns names, and using the results to build the query text.


text:
Q: Accessing Dictionaries inside a Dictionary by Index in Obj-C I'm currently trying to learn Objective-C and I've stumbled across a little problem.
I want to build an iPad Application for collecting simple Numbers,which the User enters, by Date and Time.
To do that I thought of this Structure:

*

*Dictionary("main")

*

*Dictionary("27012013") //this holds all data for the 27th of January 2013

*

*Index = 0

*3:33pm = 123 //this would mean at 3:33pm there was a value of 123

*..other values to follow

*Dictionary("28012013") //and so on

So basically there is one big Dictionary called "main" which holds the dictionaries for all days which then hold their index and all recorded values.
I get the Value's by a UIAlertView Input which then calls the
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

delegate method in which then the current time and date is saved in NSString's like this:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateStyle:NSDateFormatterNoStyle];
[format setTimeStyle:NSDateFormatterShortStyle];
NSString *time = [format stringFromDate:[NSDate date]];
NSLog(@"Time: %@ and entered Text:%@",time,returnvalue.text);
 //Which Date do we have
[format setDateStyle:NSDateFormatterShortStyle];
[format setTimeStyle:NSDateFormatterNoStyle];
NSString *date = [format stringFromDate:NSDate.date];
NSLog(@"Found Date:%@",date);
NSString *identifier =
  [[date componentsSeparatedByCharactersInSet:
                 [NSCharacterSet punctuationCharacterSet]] componentsJoinedByString:@""];
NSLog(@"Identifier:%@",identifier);

where returnvalue.text holds the entered text. I then check if the dictionary called like the NSString identifier already exist and if not add it to main:
        if([main objectForKey:identifier] == nil){
        //No Dict Available for current Date so create one:
        //there should be no more than 30 Entries per Day
        NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithCapacity:30];
        [d setObject:identifier forKey:@"Name"];
        NSNumber* tmpi = [NSNumber numberWithInteger:main.count];
        [d setObject:tmpi forKey:@"Index"];
        //and store the recieved value in it
        [d setObject:returnvalue.text forKey:time];
        [main setObject:d forKey:identifier];
    }
    else{
        NSMutableDictionary *d = [main objectForKey:identifier];
        [d setObject:returnvalue.text forKey:time];
    }

The First question here is: Do I have to use main.count or main.count+1?
Furthermore I want to display they information in tableView in which each day should have his own section. For the method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

I therefore need to address they dictionaries inside the main dictionary by Index or e.g. filter them by their Index key to return the number of values inside of them.
I do now I could use a giant NSArray for main but this would make the method for determining if the dictionary for the day already exist more complicated and would rather not want to do this.
So could anyone please help me?
Thanks in Advance

A: First Answer:
it depends on you but "main.count" will return the number of objects in dictionary may be it's zero. So if you want to start from zero then it's good otherwise +1.
Second Answer:
here is function of NSDictionary "allKeys" which return all the keys as "NSArray" then you can get each key by index if you don't know about the "key" just get it using index from array.


text:
Q: Adding no results message to jQuery search script I have a jQuery search script based on the Bing API. When a user searches and their are results for their query they are displayed without a problem. However when there are no results for their search then the page is just blank.
How can I add a message in such as "No results found." when there are no results to prevent having a blank page?
My current code is:
$(document).ready(function(){
    function search(){
        $.ajax({
            type:"GET",
            url:"http://api.bing.net/json.aspx?AppId=AppIdHere&Query=SearchTermsHere&Sources=Web&Adult=Strict&Web.Count=10&JsonType=callback&JsonCallback=?",
            dataType:"jsonp",
            success:function(query){
                $("#results").html(results(query));
            }
        });
    }
    function results(response){
        var output=[];
        $.each(response.SearchResponse.Web.Results,function(i,result){
            output.push('
'+result.Title+'

'+result.DisplayUrl+'

'+result.Description+'
');
        });
        return output.join('');
    }
    search();
});

A: success:function(query){
   if(query != null)
       $("#results").html(results(query));
   else
       $("#results").html('
No results found
');
}

A: Change the return line of the results function to:
return (output.length == 0 ? 'No results found.' : output.join(''));

=== UPDATE ===
If you have an javascript error, change the results function to:
function results(response){
    if (typeof response.SearchResponse.Web.Results == 'undefined') {
        return 'No results found.';
    }
    var output=[];
    $.each(response.SearchResponse.Web.Results,function(i,result){
        output.push('
'+result.Title+'

'+result.DisplayUrl+'

'+result.Description+'
');
    });
    return output.join('');
}

or you have to add an error-handler:
    $.ajax({
        ...,
        error:function(){
            $("#results").html('No results found.');
        }
    });


text:
Q: Flash poor performance with vector art (.svg) When using multiple pieces of vector art I've noticed that performance gets rather sloppy, so I created a simple test program that displays 100 copies of the same graphic and allows zooming. I used what I believe to be a fairly simple vector image (can see links below). However, fps drops massively when zooming in or out. I know zooming requires a lot of calculations, but I have an above average system (i5 2500k processor) that I would expect to handle such demands. Is there something I'm missing?
Picture of image - http://i.imgur.com/Cj50O.png
SVG file - http://pastebin.com/MjBLebFQ
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;

public class Main extends Sprite
{
    [Embed(source = "../lib/Doctor.svg")]
    private var Doctor:Class;

    private var container:Sprite = new Sprite();

    public function Main():void
    {
        container = new Sprite();
        for (var i:int = 0; i < 10; i++) {
            for (var j:int = 0; j < 10; j++) {
                var s:Sprite = new Doctor();
                s.x = i * 20;
                container.addChild(s);
            }
        }
        this.addChild(container);
        this.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
    }

    private function onMouseWheel(event:MouseEvent):void
    {
        if (event.delta > 0) {
            container.scaleX += 0.1;
            container.scaleY += 0.1;
        }else {
            container.scaleX -= 0.1;
            container.scaleY -= 0.1;
        }

    }
}

}


text:
Q: Power supply for Precision Current Source for Medical Instrument I am trying to implement power supply for constant current source(LM334) for medical application. I have 24V,3A SMPS to generate required output (38V) to operate LM334 Constant current source of 10mA.
LM334 is followed by I/V converter and OP-amps and then ADC.

Considering fact that LDO generate less noise than switching converter and LM334 has less error at higher operating voltage, I have come up with 2 schemes as mentioned below:
Scheme 1:

Scheme 2:

Which is better option ( in terms of noise , since signal strength is very less )to generate 38V for LM334 ? Please someone guide.
Thanks in advance !


text:
Q: Quotient metric on a complete Riemannian manifold Suppose $(M,g)$ is a complete Riemannian manifold on which a Lie group $H$ acts properly and isometrically. Then the induced Riemannian distance function $d:M\times M\rightarrow\mathbb{R}$ is a complete, proper $H$-invariant metric (in the sense of metric spaces).
The orbit space $M/H$ is a locally compact space that inherits a length metric $d'$ defined by letting $d'([x],[y])$ be the infimum of $d(w,z)$, where $w$ and $z$ range over elements in the orbits $[x]$ and $[y]$ respectively.
My question: is $d'$ a proper metric?
Thoughts: I think this would follow if $d'$ was a complete metric on $M/H$, but I'm not sure if it is.
Thanks!


text:
Q: Assign Joomla article to a always open under a menu Is it possible in Joomla 3 to create articles and category blog layout that will open articles from certain category under a certain menu.
Explanation:
1) I have a HOME page: www.example.com/
2) I have a Main Menu and a Menu Item - News: www.example.com/news
This menu item is a category blog layout with news title, short description and readmore buttons (clasical)
PROBLEM:
So, when user clicks one of the news - for example How to make soup
It redirects them to the link: www.example.com/1-how-to-make-soup
And what I want is to open it under the menu like this:
www.example.com/news/how-to-make-soup

A: You have a category :news
you have a menu (category blog) that is linked to "news" category
you have also some articles in "news" category
now if you browse "news" menu you can see intro of articles, when you click on "read more" you will go to www.yoursite.com/news/article-name
unless that special article is linked to another menu somewhere else directly
because in Joomla the priority for making URLs is making menu for them


text:
Q: Return result after reader read image convert to base 64 I have a test on the functions after click the button the image will convert to base64 and return the result but it gives me blank. Why?
    $("#addNewProduct").click(function(){
        var uploadpImg1 = converttobase64(document.getElementById("uploadpImg1-input"));
        var uploadpImg2 = converttobase64(document.getElementById("uploadpImg2-input"));
        var uploadpImg3 = converttobase64(document.getElementById("uploadpImg3-input"));
        alert(uploadpImg1);
    });
 function converttobase64(element) {
      var result ="";
      var file = element.files[0];

      var reader = new FileReader();

      reader.onloadend = function() {

        result = reader.result;

      }

        reader.readAsDataURL(file);
        return result;
    }

A: This is due to image load ( asynchrone process ) , using callck back function fix the problem
You'll see always an empty string even the base64 image is generated , because of the asynchrone proccess ,
What you can do is pass a callback function , in which you can put your after generation intruction ( your alert )
 , and call this last on the  onloadend by passing the result as param in the callback function
See below Snippet :

$("#addNewProduct").click(function() {
  var uploadpImg1 = converttobase64(document.getElementById("uploadpImg1-input"), function(result) {
    alert(result);
  });

});

function converttobase64(element, callback) {
  var result = "";
  var file = element.files[0];

  if (typeof(file) == 'undefined') return;

  var reader = new FileReader();

  reader.onloadend = function() {

    result = reader.result;
    callback(result);
  }

  reader.readAsDataURL(file);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" id="uploadpImg1-input" />

<button id="addNewProduct">add</button>


text:
Q: How to use cookies in Salesforce lightning pages I created new page from Salesforce community and I have set some component on that page so How i can set set cookies for that page how to access that value in another page?

A: Generally speaking, it would be easier to use sessionStorage to share data:
window.sessionStorage.setItem('somekey','somevalue');

...
var data = window.sessionStorage.getItem('somekey');

...
If you wish to persist the data longer than a single session, you can also use localStorage instead.
I recommend this method because working with document.cookie is inherently more frustrating than it needs to be, as you have to consider the possibility that other cookies will also exist in the string, so you have to do some parsing. Web Storage resolves this problem by giving each key its own space, so no additional parsing is required.

A: Example: Create component with below inputs which saves cookies:
<lightning:input aura:id="myData" onchange="{!c.saveCookie}" />
<lightning:input aura:id="otherData" onchange="{!c.saveCookie}" />

Save cookies using below in JS:
saveCookie : function(component, event, helper) {
    document.cookie = "myData="+component.find("myData").get("v.value");
    document.cookie = "otherData="+component.find("otherData").get("v.value");
}

Now, when you want to access them from different component just get by document.cookie
doInit : function(component, event, helper) {
    console.log(document.cookie);
}

You will see below log

myData=Data entered in myData input; otherData=Value in otherData

Its stored as name-value pairs.
Further read: https://www.w3schools.com/js/js_cookies.asp
--added based on sfdcfox recommendation--
Session storage and local storage are also other options. However, for choosing one over the other:

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.
On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.
localStorage vs. sessionStorage vs. Cookies
  In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

This difference between cookies/session/local storage has been taken from https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies


text:
Q: If $X$ is a covering space of $Y$ with the covering map $p$ and $Y$ is connected, then $p^{-1}(y)$ have the same cardinality for every $y\in Y$. I need to show that if $X$ is a covering space of $Y$ with the covering map $p$ and $Y$ is connected, then $p^{-1}(y)$ have the same cardinality for every $y\in Y$.
I have this hint: A function $f:W\to Z$ is locally constant iff each $w\in W$ has
an open neighbourhood $U$ such that $f\restriction_U$ is constant. Show that any
locally constant function is continuous.
I've also found a solution which I didn't understand: Let $k$ be a cardinality. Denote those $y$'s by $B_k$ for which $|p^{-1}(y)|=k$. By the "local triviality" (now I absolutely don't know what does that mean, perhaps it has something to do with the hint I found somewhere else), every $B_k$ is open. But they are also closed at the same time because they are all complements of unions of open sets. Since $Y$ is connected, there is a $k$ such that $Y=B_k$.
If you can explain the meaning of "local triviality" and its connection with the hint and also the hint itself I would be very thankful.

A: The idea (along the lines of the hint) is to define $f:Y\to X$ by $f(y)=|p^{-1}(y)|$. For every $y\in Y$ we have some neighborhood $U$ of $Y$ such that $p^{-1}(U)$ consists of $k$ connected components, each of which are mapped homeomorphically (hence injectively) onto $U$ (incidentally, this is what is meant by the "local triviallity" of $p$, that locally $p$ is just a map from $k$ copies of $U$ to $U$). For any $u\in U$, we have that $|p^{-1}(u)|=k$, since there is exactly $1$ preimage of $U$ in each connected component of $p^{-1}(U)$ by injectivity. Hence $p$ is locally constant. Once you show that $f$ is locally constant, you have that it is continuous. But the image is some ordinal $\omega$ (or if you are only looking at finite coverings, $\mathbb N$) with the discrete topology, and any continuous function from a connected space to a discrete space is constant, hence $f$ is constant.


text:
Q: Upload videos with PHP and Google+ profile identity Just a little background:
After youtube offered me to get a Google + profile for my channel I accepted.
Now, when I log on my channel's google account, it shows like I have 2 channels: the one with the name I selected, and another one empty with my e-mail.
So, I used to upload videos using the zend gdata api, so I can download files using wget on my server and avoid downloading and uploading from my pc.
After that change, whenever I try to upload a video, I get this error:
NoLinkedYouTubeAccount
As far as I know, this error comes when your youtube account is not linked to your Google Account, which is not the case here. I'm pretty sure it have something to do with the new google+ integration features.
The code I'm using is an adaptation of this -> https://github.com/JWhy/Youtube-Uploader
Note 1: I've test the script out of the box, without any changes, it doesn't work.
Note 2: I've test both scripts using a youtube account which is not linked to google+ and IT DOES work.


text:
Q: trouble moving socketio server from localhost to ssl nginx Some of the stesp I have taken include

*

*modifying nginx setup
  map $http_upgrade $connection_upgrade {
      default upgrade;
      ''      close;
  }

  server {
    server_name services.parleyvale.com;
  ...
  location /s2gio/ {
    proxy_pass http://127.0.0.1:3222;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_cache_bypass $http_upgrade;
  }...

but network tab gave me 404's so on my client (react) app added

*

*modifying client
  //var socket = io.connect(cfg.urls.socket)

  var socket = io.connect(cfg.urls.socket,{
    secure: true,
    rejectUnauthorized: false,
    path: '/s2gio/socket.io'
  });

slightly better but the server was not responding so on the server added

*

*modifying server
  //const io = require('socket.io')(server)

  const io = require('socket.io')(server,
  {
    secure: true,
    rejectUnauthorized: false,
    path: '/s2gio/socket.io'
  });

  io.of('/s2gio')

now the messages from client show up on server but they do not 'emit' from the server.
comparing the ssl nginx debug file
  2020-03-12T19:12:36.309Z socket.io:socket emitting event ["message",{"lid":"Jutebi","product":"Avacado","done":1,"jsod":"","loc":"produce"}]
  2020-03-12T19:12:36.309Z socket.io:socket dispatching an event ["message",{"lid":"Jutebi","product":"Avacado","done":1,"jsod":"","loc":"produce"}]

that's all I get before they both go back to writing 2's and 3's. But localhost does encodes, encoding, writing and sending
  2020-03-12T19:12:36.309Z socket.io:socket emitting event ["message",{"lid":"Jutebi","product":"Avacado","done":1,"jsod":"","loc":"produce"}]
  2020-03-12T19:12:36.309Z socket.io:socket dispatching an event ["message",{"lid":"Jutebi","product":"Avacado","done":1,"jsod":"","loc":"produce"}]
  message:  { lid: 'Jutebi',
    product: 'Red potatoes',
    done: 0,
    jsod: '',
    loc: 'dairy' }
    socket.io-parser encoding packet {"type":2,"data":["message",{"lid":"Jutebi","product":"Red potatoes","done":0,"jsod":"","loc":"dairy"}],"nsp":"/"} +16ms
    socket.io-parser encoded {"type":2,"data":["message",{"lid":"Jutebi","product":"Red potatoes","done":0,"jsod":"","loc":"dairy"}],"nsp":"/"} as 2["message",{"lid":"Jutebi","product":"Red potatoes","done":0,"jsod":"","loc":"dairy"}] +0ms
    socket.io:client writing packet ["2[\"message\",{\"lid\":\"Jutebi\",\"product\":\"Red potatoes\",\"done\":0,\"jsod\":\"\",\"loc\":\"dairy\"}]"] +15m
    engine:socket sending packet "message" (2["message",{"lid":"Jutebi","product":"Red potatoes","done":0,"jsod":"","loc":"dairy"}]) +17ms
    engine:ws writing "42["message",{"lid":"Jutebi","product":"Red potatoes","done":0,"jsod":"","loc":"dairy"}]" +19ms
    qry.sql:  INSERT INTO items SET `lid` = 'Jutebi', `product` = 'Red potatoes', `done` = 0, `jsod` = '', `loc` = 'dairy' ON DUPLICATE KEY UPDATE `lid` = 'Jutebi', `product` = 'Red potatoes', `done` = 0, `jsod` = '', `loc` = 'dairy'

the server is pretty simple
  const io = require('socket.io')(server);

  io.on('connect', (socket) => {
    io.emit('message', 'connected io')

    socket.on('switch2room', (room)=>{
      console.log('swwwwww')
      console.log('switch2room: ', room)
      socket.leaveAll()
      socket.join(room, ()=>{
        console.log('subscribe ', socket.rooms);
        io.in(room).emit('message', `inside ${room} party people?`)
      })
    })

    socket.on('message', (message)=>{
      console.log('message: ', message)
      io.in('/s2gio/'+message.lid).emit('message',message)
      if(message.done==-1){
        const qry=conn.query('DELETE FROM items WHERE lid=? AND product=?',[message.lid,message.product],()=>{
          console.log('qry.sql: ', qry.sql)
        })
      }else{
        const qry = conn.query('INSERT INTO items SET ? ON DUPLICATE KEY UPDATE ?', [message,message], (error,results)=>{
          console.log('qry.sql: ', qry.sql)
        })
      }
    })
  });

  server.listen(cfg.port.socket);
  console.log('wss listening on '+cfg.port.socket);

I also tried adding 'namespace' in emit on the server
  io.on('connect', (socket) => {
    io.emit('message', '/s2gio/connected io')
  ...

Any ideas would be greatly appreciated


text:
Q: If you have many columns some with NULL Values-- exclude without explicitly naming columns If you have many columns eg a 100, but only want to return columns in a row which are NOT NULL is it possible to do so without explicitly naming each column?
Is there anyway around this?
Thank you.

A: There's no way to automatically omit columns where all values are null from a result set, no.
You'll have to handle this client side.
The good news is that sending nulls is extremely efficient, so the network impact of lots of null columns is minimal.


text:
Q: Gaps in dates while rolling up quarters into a single row I am attempting to roll-up rows from a data set with similar measures into a consolidated row. There are two conditions that must be met for the roll-up:

*

*The measures (ranging from 1-5) should remain the same across the
rows for them to be rolled up to a single row.

*The dates should be continuous (no gaps in dates).

If these conditions are not met, the code should generate a separate row.
This is the sample data that I am using:
id,measure1,measure2,measure3,measure4,measure5,begin_date,end_date
ABC123XYZ789,1,1,1,1,1,1/1/2019,3/31/2019
ABC123XYZ789,1,1,1,1,1,4/23/2019,6/30/2019
ABC123XYZ789,1,1,1,1,1,7/1/2019,9/30/2019
ABC123XYZ789,1,1,1,1,1,10/12/2019,12/31/2019
FGH589J6U88SW,1,1,1,1,1,1/1/2019,3/31/2019
FGH589J6U88SW,1,1,1,1,1,4/1/2019,6/30/2019
FGH589J6U88SW,1,1,1,2,1,7/1/2019,9/30/2019
FGH589J6U88SW,1,1,1,2,1,10/1/2019,12/31/2019
253DRWQ85AT2F334B,1,2,1,3,1,1/1/2019,3/31/2019
253DRWQ85AT2F334B,1,2,1,3,1,4/1/2019,6/30/2019
253DRWQ85AT2F334B,1,2,1,3,1,7/1/2019,9/30/2019
253DRWQ85AT2F334B,1,2,1,3,1,10/1/2019,12/31/2019

The expected result should be:
id,measure1,measure2,measure3,measure4,measure5,begin_date,end_date
ABC123XYZ789,1,1,1,1,1,1/1/2019,3/31/2019
ABC123XYZ789,1,1,1,1,1,4/23/2019,9/30/2019
ABC123XYZ789,1,1,1,1,1,10/12/2019,12/31/2019
FGH589J6U88SW,1,1,1,1,1,1/1/2019,6/30/2019
FGH589J6U88SW,1,1,1,2,1,7/1/2019,12/31/2019
253DRWQ85AT2F334B,1,2,1,3,1,1/1/2019,12/31/2019

I have implemented the code below which seems to address condition # 1, but I am looking for ideas on how to incorporate condition # 2 into the solution.
import pandas as pd
import time

startTime=time.time()
data=pd.read_csv('C:\\Users\\usertemp\\Data\\Rollup2.csv')

data['end_date']= pd.to_datetime(data['end_date'])
data['begin_date']= pd.to_datetime(data['begin_date'])

data = data.groupby(['id','measure1','measure2', 'measure3', 'measure4', 'measure5']) \
    ['begin_date', 'end_date'].agg({'begin_date': ['min'], 'end_date': ['max']}).reset_index()
print(data)
print("It took %s seconds for the collapse process" % (time.time() - startTime))

Any help is appreciated.

A: You can do the following.
import pandas as pd
import numpy as np
from datetime import datetime, timedelta

# Convert begin_date and end_time to datetime
df['begin_date'] = pd.to_datetime(df['begin_date'], format='%m/%d/%Y')
df['end_date']= pd.to_datetime(df['end_date'], format='%m/%d/%Y')

# We create a new column which contains the end_date+1 from the previous row
df['end_date_prev'] = df['end_date'].iloc[:-1] + timedelta(days=1)
df['end_date_prev'] = np.roll(df['end_date_prev'], 1)

# Create a cumsum that resets when begin_date and end_date_prev doesn't match
df['cont'] = (~(df['begin_date'] == df['end_date_prev'])).astype(int).cumsum()

# Since we need all measures to match we create a string column containing all measurements
df['comb_measure'] = df['measure1'].astype(str).str.cat(df[['measure{}'.format(i) for i in range(2,6)]].astype(str))

# Get the final df
new_df = df.groupby(['id', 'comb_measure', 'cont']).agg(
    {'measure1':'first', 'measure2':'first', 'measure3':'first', 'measure4':'first', 'measure5':'first',
     'begin_date':'first', 'end_date':'last'})


text:
Q: Problem with making .exe from python file by PyInstaller My script .py work  perfectly, but .exe sadly doesn't work. Im running on newest PyInstaller.
Here is my script
I already tried everyting that i can think of here is options that i used:
Options used

*

*-w : does't have .exe file

*-- onefile -w and -F -w : The specified module could not be found.

*--F , --onefile and no option used : Only shows this option for like half a second

A: Not all python code can be compiled into a .exe.

A: I was able to work around this issue by importing pywintypes into my script before win32print module.


text:
Q: Dotnetnuke cannot process with port other 80 I have a dotnetnuke application that works well when I am using the default http port (80). But it doesn't work with any other port. That means that it works well if the portal is at http://localhost/app, but it doesn't work at http://localhost:81/app.
I tried with setting
<add key="UsePortNumber" value="True"></add>

but it still won't work.
I appreciate your help. Thank you all in advance.

A: HOST SETTINGS > Advanced Settings > Friendly Url Settings > Use Friendly Urls (make it false - unchecked) and update.
but you will lose Friendly Urls like: /home.aspx it will look like /Default.aspx?tabid=55
Also you will have page not found or DNS error when try to update, add, delete modules or when you login to the portal for the first time because DNN will redirect you to port 81 or whatever port you are using.


text: Q: Does dockerd process cpu contain the cpu used by the containers? We have a CentOS machine running Docker with a couple of containers. When running top, I see the process dockerd which sometimes is using a lot of cpu. Does this cpu utilization contain the cpu usage inside the containers?


text:
Q: Start Service when new contact is added I am making a small whats app like  chat application . As i know whenever a new
contact is added to android device , what's app sends request to what's app server
for verifying that contact number is active on what's app or not , if it is active
it adds what's app icon to that contact. Same thing i want to apply for this .
whenever  a new contact is added to contact list , it must send request to
server .
So how can i do this in my app. how can i start new service whenever a new
contact is added .
Plz help .
Thank you.

A: There's no broadcast when a contact is added/changed. However, when you look up your contacts in the RawContacts table you have a DIRTY column which is 1 if the contact was changed since the last sync, which is pretty much what I was looking for.
Source: Broadcast on contact add/change?
In this way, when you know that a contact is dirty, you start a service (or make a broadcast that your receiver will receive).


text:
Q: How to force google translate to translate the page after the script loads?

The scripts loads, but after it loads it doesn't translate the page. I need to select the language from the selectbox. How to make it auto translate without selecting the language from the select box?

A: The basic idea that you need to add cookies that google translate looks for when it's loading the element, and then you can even hide google translate elements using CSS.
Here is a short example using js.cookie:

CSS to hide the google translate elements:

A: Based on the code snippet you don't above there appears to be a couple things wrong. I would probably restructure like so...

You need to make sure that the google translate script file is loaded prior to your code attempting to execute. Then you need to execute your function...


text:
Q: Item view from search results is broken When I click on an item in my Discussion List, it opens that topic beautifully in a page called Topic.aspx.
But if I do a search, then click on an item in the search results, I'm brought to the Flat view of that item, and it looks terrible - it's the Flat view but all fields are laid out horizontally.
In Topic.aspx, the item appears within the Discussion List Web Part, which says the current view is Default - assuming that's either Flat or Subject.  But it looks great.
I have other sites set up where search results items do not go to Topic page, they appear in Flat, and they look fine.
I've turned Launch Forms in a Dialog off/on.  I've modified and created new default views, played with View Style and Folders/Flat.
I've been flummoxed by this for a while; any insight/help will be hugely appreciated.
Thanks,
Matthew

A: When you click a discussion item from e.g. search ,the discussion item's link is generated so that it uses the current default view of the list the discussion item belongs to. Therefore it appears that Topic.aspx is the default view in this Discussion list. You can change the default view to Flat.aspx in your Discussion list's list settings.


text:
Q: Tuning a SQL query I am trying to tune the following query which is got 500k IOs against the INVENTTABLE which I thought would be a good place to start.  The complexity of all the joins has beaten me though and I have been unable to wrap round where a good start would be with this?
Thanks in advance for any tips.
SET STATISTICS IO ON

DECLARE
@paramCompany       varchar(3),
@paramCreatedBy     varchar(8000),
@paramCustomer      varchar(100),
@paramBlanketId     varchar(20)

SET @paramCompany = 'adf'
SET @paramCreatedBy = 'All'
SET @paramCustomer = NULL
SET @paramBlanketId = NULL

SELECT
 un.MAINSALESID,
 un.DATAAREAID,
 Sum(un.Quantity) as 'Quantity',
 Sum(un.SalesValue) as 'SalesValue'
INTO #desprel
 FROM
 (SELECT
  stl.MAINSALESID,
  st.DATAAREAID,
  sl.SALESQTY as 'Quantity',
  sl.SALESQTY * sl.SALESPRICE as 'SalesValue'
 FROM
  DynamicsV5Realtime.dbo.SALESTABLE st
 INNER JOIN
  DynamicsV5Realtime.dbo.SALESLINE sl
 ON
  sl.SALESID = st.SALESID
  and sl.DATAAREAID = st.DATAAREAID
 INNER JOIN
  DynamicsV5Realtime.dbo.INVENTTABLE it
 ON
  it.ITEMID = sl.ITEMID
  and it.DATAAREAID = sl.DATAAREAID
 INNER JOIN
  DynamicsV5Realtime.dbo.SALESTABLELINKS stl
 ON
  stl.SUBSALESID = st.SALESID
  and stl.DATAAREAID = st.DATAAREAID
 INNER JOIN
  DynamicsV5Realtime.dbo.SALESTABLE st1
 ON
  st1.SALESID = stl.MAINSALESID
  and st1.SALESTYPE = 5
 --to get Order created by
 inner JOIN
  --TR
  vw_R000_EmployeeList pm
 ON
  --st1.SALESTAKER = pm.emplid
  CASE WHEN st1.SALESTAKER = 'balla' THEN 'gende' ELSE st1.SALESTAKER END = pm.emplid
  and (pm.[NAME] in (SELECT * FROM       udf_MultiValueParameterHandlingString(@paramCreatedBy)) or @paramCreatedBy = 'All')
 WHERE
  st.DATAAREAID = 'adf'
  and st.SALESTYPE = 3 -- Release Order
  and st.SALESSTATUS in (2,3)
  and sl.SALESSTATUS <> 4
  and it.ITEMGROUPID <> 'G0022A'
  and sl.SALESQTY > 0
  and st1.CUSTACCOUNT = IsNull(@paramCustomer,st1.CUSTACCOUNT)
  and st1.SALESID = IsNull(@paramBlanketId,st1.SALESID)
 UNION ALL
 SELECT
  stl.MAINSALESID,
  st.DATAAREAID,
  sl.SALESQTY as 'Quantity',
  sl.SALESQTY * sl.SALESPRICE as 'SalesValue'
 FROM
  DynamicsV5Realtime.dbo.SALESTABLE st
 INNER JOIN
  DynamicsV5Realtime.dbo.SALESLINE sl
 ON
 sl.SALESID = st.SALESID
 and sl.DATAAREAID = st.DATAAREAID
 INNER JOIN
  DynamicsV5Realtime.dbo.INVENTTABLE it
 ON
  it.ITEMID = sl.ITEMID
  and it.DATAAREAID = sl.DATAAREAID
 INNER JOIN
  DynamicsV5Realtime.dbo.SALESTABLELINKS stl
 ON
  stl.SUBSALESID = st.MARIMSSALESID
  and stl.DATAAREAID = st.DATAAREAID
 INNER JOIN
  DynamicsV5Realtime.dbo.SALESTABLE st1
 ON
  st1.SALESID = stl.MAINSALESID
  and st1.SALESTYPE = 5
 --to get Order created by
 inner JOIN
 --TR
  vw_R000_EmployeeList pm
 ON
 --st1.SALESTAKER = pm.emplid
  CASE WHEN st1.SALESTAKER = 'balla' THEN 'gende' ELSE st1.SALESTAKER END = pm.emplid
 and (pm.[NAME] in (SELECT * FROM   udf_MultiValueParameterHandlingString(@paramCreatedBy)) or @paramCreatedBy = 'All')
 WHERE
  st.DATAAREAID = 'adf'
  and st.SALESTYPE = 3 -- Release Order
  and st.SALESSTATUS in (2,3)
  and sl.SALESSTATUS <> 4
  and it.ITEMGROUPID <> 'G0022A'
  and sl.SALESQTY < 0
  and st1.CUSTACCOUNT = IsNull(@paramCustomer,st1.CUSTACCOUNT)
  and st1.SALESID = IsNull(@paramBlanketId,st1.SALESID)
            ) un
GROUP BY
 un.MAINSALESID,
 un.DATAAREAID

A: Is it just me or is this particular section a bit confusing? I'd tackle this first.
inner JOIN
  --TR
  vw_R000_EmployeeList pm
 ON
  --st1.SALESTAKER = pm.emplid
  CASE WHEN st1.SALESTAKER = 'balla' THEN 'gende' ELSE st1.SALESTAKER END = pm.emplid
  and (pm.[NAME] in (SELECT * FROM udf_MultiValueParameterHandlingString(@paramCreatedBy)) or @paramCreatedBy = 'All')

Can you trying using a temp table to figure out the SALESTAKER ID's beforehand and then join to that? Using a udf and case statement in a join condition is probably not the best idea.

A: Your idea to have a look at the inventtable is good. It is evident, that none of its fields are shown in the results and it is not needed as a link to join two other tables. So it is only there to guarantee that an appropriate record in inventtable exists. This can be done in an EXISTS clause.
Then check why there are two almost similar joins glued with UNION ALL. All the tables are accessed twice. Is this necessary? One time you want all sl.salesqty < 0 and you link via stl.subsalesid = st.marimssalesid. The other time you want all sl.salesqty > 0 and you link via stl.subsalesid = st.salesid. Maybe you can do this one select statement and access each table only once.
The result has one field of salestable (st). This is st.DATAAREAID. But this is a search and join criteria actually, so you can replace it with either sl.DATAAREAID or even with the literal 'adf'. So no field from table st. Maybe also only an EXISTS thing?
Same again, when salestable is read again as st1. It is not part of the selected columns, so maybe it can be converted into an EXISTS clause.
This is just on first glimpse, so I may be mistaken here and there. It is just to give you a something to start with.


text:
Q: Is there a mechanism to provide a dimension or scale as input to an instance of a symbol? I realize that a symbol, by design, will have mostly static features.  The exceptions are annotations.  A particular instance of a symbol may have property values associated with it which are variable between instances.  A resistor, for instance, will have the same lines on the background path between instances, but we may indicate different values by a string, property = value unit, placed at a node.
I would like to create a symbol for a resistor-like symbol which has two parts; the body is simply divided into two sections by means of a vertical line.  I would, however, like to be able to adjust the relative horizontal position of the vertical line such that the relative widths of the compartments could be varied.  I am not aware of a mechanism that would allow one to pass a scale value to the particular instance of the symbol.  Maybe the same way we adjust the overall size of the symbol, we can adjust the position of the vertical line/divider.
Code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\usetikzlibrary{circuits,circuits.ee.IEC}
\makeatletter
\pgfdeclareshape{symbol shape}{%
    \inheritsavedanchors[from=rectangle ee]
    \inheritanchor[from=rectangle ee]{center}
    \inheritanchor[from=rectangle ee]{north}
    \inheritanchor[from=rectangle ee]{south}
    \inheritanchor[from=rectangle ee]{east}
    \inheritanchor[from=rectangle ee]{west}
    \inheritanchor[from=rectangle ee]{north east}
    \inheritanchor[from=rectangle ee]{north west}
    \inheritanchor[from=rectangle ee]{south east}
    \inheritanchor[from=rectangle ee]{south west}
    \inheritanchor[from=rectangle ee]{input}
    \inheritanchor[from=rectangle ee]{output}
    \inheritanchorborder[from=rectangle ee]
    \inheritbackgroundpath[from=rectangle ee]
    \behindbackgroundpath{%
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}%
    \pgf@xa\pgf@x\pgf@ya\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}%
    \pgf@xb\pgf@x\pgf@yb\pgf@y
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{0pt}}%
    \pgfpathlineto{\pgfqpoint{1.5\pgf@xa}{0pt}}%
    \pgfpathmoveto{\pgfqpoint{\pgf@xb}{0pt}}%
    \pgfpathlineto{\pgfqpoint{1.5\pgf@xb}{0pt}}%
    \pgfpathmoveto{\pgfqpoint{0pt}{\pgf@ya}}%
    \pgfpathlineto{\pgfqpoint{0pt}{\pgf@yb}}%
    }
}
\makeatother
\tikzset{
    circuit declare symbol=symbol,
    set symbol graphic={
    shape=symbol shape,
    draw,
    transform shape,
    circuit symbol size=width 8.12936 height 2.03233,
}
}
\begin{document}
\begin{tikzpicture}[circuit ee IEC]
\node[symbol] at (0,0) (thesymbol) {};
\end{tikzpicture}
\end{document}

The vertical separating line is currently defined by the code:
\pgfpathmoveto{\pgfqpoint{0pt}{\pgf@ya}}%
\pgfpathlineto{\pgfqpoint{0pt}{\pgf@yb}}%

The x-component/first argument of the \pgfqpoint command is what I'm interested in making variable.  Appropriate lower and upper bounds are \pgf@xa and \pgf@xb.
Note that the code here was largely written by forum user Qrrbrbirlbel in an answer to this question.
Any suggestions are welcomed.

A: The following code uses the value of the key /pgf/symbol shape ratio (initial value is .5) to calculate the x value of the vertical bar. Additional correction are done so that the vertical line as well as the horizontal additional lines do not cross the border line but only touch it (this will be appreciated if transparency will be used). I also changed the definition of the horizontal lines so that they always are the same length (namely a quarter of the shape's width). Again, this really only matters in the (probably non-existent) case the shape is used with text (as with my example below) but it doesn't really hurt.
I have not changed the definition of the .west and .east anchor. The additional horizontal lines will not be recognized for placement and connections.
As a little exercise I have added three anchors

*

*bar north,

*bar south, and

*bar center.

Their positions can be observed in the example image below. If you do not need them you can simply remove the \anchor commands.
Anchors that are defined via \anchor will be calculated when they are accessed and not when the shape will be drawn. For the rectangle shape (and via inheritance also our shape) only the \northeast and the \southwest anchor are saved. Every other anchor can be calculated from these two. Because the symbol shape ratio may have changed when we access the bar * anchors we save the current value (for this shape) in a \savedmacro.
As an additional note: It is possible to check whether the input ratio is between 0.0 and 1.0 by the following code.
\ifdim\barratio pt<0pt\relax
  % the ratio is < 0
\else\ifdim\barratio pt>1pt\relax
    % the ratio is > 1
  \fi
\fi

Code
\documentclass[tikz,convert=false]{standalone}
\usetikzlibrary{circuits,circuits.ee.IEC}
\makeatletter
\pgfkeys{/pgf/symbol shape ratio/.initial=.5}
\pgfdeclareshape{symbol shape}{%
    \savedmacro\barratio{%
      \pgfmathsetmacro\barratio{\pgfkeysvalueof{/pgf/symbol shape ratio}}%
      \ifdim\barratio pt<0pt\relax
        % the ratio is < 0
      \else\ifdim\barratio pt>1pt\relax
          % the ratio is > 1
        \fi
      \fi
    }
    \inheritsavedanchors[from=rectangle ee]
    \inheritanchor[from=rectangle ee]{center}
    \inheritanchor[from=rectangle ee]{north}
    \inheritanchor[from=rectangle ee]{south}
    \inheritanchor[from=rectangle ee]{east}
    \inheritanchor[from=rectangle ee]{west}
    \inheritanchor[from=rectangle ee]{north east}
    \inheritanchor[from=rectangle ee]{north west}
    \inheritanchor[from=rectangle ee]{south east}
    \inheritanchor[from=rectangle ee]{south west}
    \inheritanchor[from=rectangle ee]{input}
    \inheritanchor[from=rectangle ee]{output}
    \anchor{bar north}{%
      \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{0pt}}}%
      \pgf@xa\pgf@x
      \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{0pt}}}}%
      \advance\pgf@x-\pgf@xa
      \advance\pgf@xa\barratio\pgf@x
      \pgf@x\pgf@xa
    }
    \anchor{bar south}{%
      \pgfmathsetmacro\pgf@tempa{\pgfkeysvalueof{/pgf/symbol shape ratio}}%
      \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{0pt}}}%
      \pgf@xa\pgf@x\pgf@ya\pgf@y
      \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{0pt}}}}%
      \advance\pgf@x-\pgf@xa
      \advance\pgf@xa\barratio\pgf@x
      \pgf@x\pgf@xa
      \pgf@y\pgf@ya
    }
    \anchor{bar center}{%
      \pgfmathsetmacro\pgf@tempa{\pgfkeysvalueof{/pgf/symbol shape ratio}}%
      \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{0pt}}}%
      \pgf@xa\pgf@x\pgf@ya.5\pgf@y
      \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{0pt}}}}%
      \advance\pgf@x-\pgf@xa\pgf@y.5\pgf@y
      \advance\pgf@xa\barratio\pgf@x
      \pgf@x\pgf@xa
      \advance\pgf@y\pgf@ya
    }
    \inheritanchorborder[from=rectangle ee]
    \inheritbackgroundpath[from=rectangle ee]
    \behindbackgroundpath{%
      \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}%
      \pgf@xa\pgf@x\pgf@ya\pgf@y
      \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}%
      \pgf@xb\pgf@x\pgf@yb\pgf@y
      % The center point: c = .5 * (a + b)
      \pgf@xc.5\pgf@xb
      \advance\pgf@xc+.5\pgf@xa
      \pgf@yc.5\pgf@yb
      \advance\pgf@yc+.5\pgf@ya
      % we don't want to overdraw lines and subtract/add half the line width (not affected by outer seps)
      \pgfutil@tempdima\pgf@xa
      \advance\pgfutil@tempdima-.5\pgflinewidth
      \pgfutil@tempdimb-.5\pgf@xc
      \advance\pgfutil@tempdimb1.5\pgf@xa
      \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdima}{\pgf@yc}}%
      \pgfpathlineto{\pgfqpoint{\pgfutil@tempdimb}{\pgf@yc}}%
      \pgfutil@tempdima\pgf@xb
      \advance\pgfutil@tempdima+.5\pgflinewidth
      \pgfutil@tempdimb-.5\pgf@xc
      \advance\pgfutil@tempdimb1.5\pgf@xb
      \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdima}{\pgf@yc}}%
      \pgfpathlineto{\pgfqpoint{\pgfutil@tempdimb}{\pgf@yc}}%
%
      \advance\pgf@xb-\pgf@xa%                                              \pgf@xb contains the width
      \advance\pgf@xa\barratio\pgf@xb%                                     left x value + ratio*width
      \advance\pgf@ya.5\pgflinewidth
      \advance\pgf@yb-.5\pgflinewidth
      \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
      \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
      \pgfsetbuttcap
      \pgfusepathqstroke
    }%
}
\makeatother
\tikzset{
  circuit declare symbol=symbol,
  set symbol graphic={
    shape=symbol shape,
    draw,
    transform shape,
    circuit symbol size=width 8.12936 height 2.03233,
  }
}
\begin{document}
\foreach \Ratio in {0,5,10,...,100,100,95,90,...,0}{% will typeset 42 pages!
\begin{tikzpicture}[circuit ee IEC]
\node[symbol, symbol shape ratio=.01*\Ratio] at (0,0) (thesymbol) {\Ratio};
\path[<-,blue] (thesymbol.bar north) edge node[above,inner sep=+0pt,at end]{\tiny\ttfamily .bar north} ++ (0,.25)
               (thesymbol.bar south) edge node[below,inner sep=+0pt,at end]{\tiny\ttfamily .bar south} ++ (0,-.25);
\draw[blue] plot[mark=x,mark size=1pt] (thesymbol.bar center);
\end{tikzpicture}}
\end{document}

Output


text:
Q: How to display pie chart with json data in flutter i'm still new to flutter and I've been trying to display some data from a http request in a pie-chart. I couldn't find any example for this.
I have been searching the internet for three days now and there is no complete example
I hope of you  help me :)
I worked on these two solutions but the json files  of both examples were not visible and I could not succeed    Pie chart through API call in Flutter  and    How to display json data in flutter charts

A: You can use the pie_chart to create a simple pie chart.
You can implement it like this:
main.dart
import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';

void main() => runApp(MyApp());

final Map<String, double> sampleData = {
  "Flutter": 5,
  "React": 3,
  "Xamarin": 2,
  "Ionic": 2,
};

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PieChartView(
        jsonData: sampleData,
      ),
    );
  }
}

class PieChartView extends StatelessWidget {
  const PieChartView({this.jsonData});

  final Map<String, double> jsonData;

  @override
  Widget build(BuildContext context) {
    return Center(child: PieChart(dataMap: jsonData));
  }
}


text:
Q: How can I fix this problems heroku web I'am new at this so please help me.
2020-10-01T09:37:17.833139+00:00 heroku[web.1]: State changed from crashed to starting
2020-10-01T09:37:23.403282+00:00 heroku[web.1]: Starting process with command node server.js
2020-10-01T09:37:25.308007+00:00 app[web.1]: Node LTS version v10.22.1 is supported
2020-10-01T09:37:25.310036+00:00 app[web.1]: Parsing config URL from IMPORT_CONFIG failed
2020-10-01T09:37:25.481614+00:00 app[web.1]: Setting up new connection to MongoDB
2020-10-01T09:37:25.528135+00:00 app[web.1]: (node:4) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2020-10-01T09:37:25.974982+00:00 heroku[web.1]: Process exited with status 0
2020-10-01T09:37:26.005597+00:00 heroku[web.1]: State changed from starting to crashed
2020-10-01T09:37:34.113589+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=reineholmensocker.herokuapp.com request_id=852dd0cf-cd9d-43ba-9f34-a2dd19d4423a fwd="2.67.142.46" dyno= connect= service= status=503 bytes= protocol=https
2020-10-01T09:37:34.407323+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=reineholmensocker.herokuapp.com request_id=6c611add-042e-48a3-a996-fa22cf4e98bd fwd="2.67.142.46" dyno= connect= service= status=503 bytes= protocol=https

A: Please read your error logs before posting them, also make sure to put them in codeblocks to make it readable.
As the error states, the failure is in the mongodb connection.
Initialize the mongodb connection after this:
mongoose.set("useUnifiedTopology", true);


text:
Q: Cakephp 3 unauthorizedRedirect not working I'm doing a page trying to set the unauthorizedRedirect for the auth component in the AppController and is not working, it does nothing.
i have tried putting it on false and nothing works
This is the app controller
public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Pages',
            'action' => 'display'
        ],
        'authError' => 'Seems like you have to use some kind of magic word.',
        'logoutRedirect' => [
            'controller' => 'Pages',
            'action' => 'display',
            'home'
        ],
        'unauthorizedRedirect' => [
            'controller' => 'Users',
            'action' => 'unauthorized'
        ],
    ]);

    //use model companies in all controllers
    $tableCategories = $this->loadModel('Categories');

    $categories = $tableCategories->find()
        ->contain([]);

    $this->set(compact('categories'));
}

public function beforeFilter(Event $event)
{
    $this->set('current_user', $this->Auth->user());
}

}
this is UsersController
class UsersController extends AppController

{
    var $breadcrump = 'Usuarios';
public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    $this->Auth->allow(['login', 'unauthorized']);
}

public function login()
{
    $this->viewBuilder()->layout('login');
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect(['controller' => 'pages', 'action' => 'display']);
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
}

public function logout()
{
    return $this->redirect($this->Auth->logout());
}

public function unauthorized()
{
    var_dump();
    $this->autoRender = false;

    $message = false;

    echo json_encode($message);exit;
}

it only redirects to the login page

A: From the Docs

unauthorizedRedirect
  Controls handling of unauthorized access. By default unauthorized user is redirected to the referrer URL or loginAction or '/'. If set to false, a ForbiddenException exception is thrown instead of redirecting.

The unauthorizedRedirect option only applies to authenticated users. If an authenticated user tries to go to a URL they are not authorized to access, they will be redirected back to the referrer. By specifying unauthorizedRedirect, you are now redirecting the User to the URL specified rather than to referrer.
If you want to redirect user on a wrong login attempt, you will have to do that manually in the login method.
Hope that clears any doubts.


text:
Q: Liferay server fails to start on Windows When I start a Liferay server in the servers of Eclipse, it fails to start and I get this error in the Eclipse log file:

A fatal error has been detected by the Java Runtime Environment:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d99863d, pid=1908, tid=2196
JRE version: 7.0_03-b05
  Java VM: Java HotSpot(TM) Client VM (22.1-b02 mixed mode windows-x86 )
  Problematic frame:
  V  [jvm.dll+0x16863d]
Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
If you would like to submit a bug report, please visit:
    http://bugreport.sun.com/bugreport/crash.jsp

I installed the latest version of JDK but it didn't help.
Any suggestions for how to get Liferay running on Windows?

A: set jre6 in eclipse: Window -> Preferences -> Java -> Installed JREs
or set it only for Liferay Runtime Environment:  Window -> Preferences -> Server -> Runtime Envirenments -> Edit -> JRE


text:
Q: how to read the serial port on SWT text widget I am using the javax.comm package to read some data off the serial port.
The data is to be displayed on a SWT a text widget. I have added an
eventListener to the serial port object and made notifyOnDataAvailable
 true, so that my app gets notified when data arrives. Anyway, on the
event handler, I try to append the newly read data to the text widget,
but it does not append the read value with text widget. But when i try to print the same in console it does that perfectly. I have a similar app
written in AWT and it doesn't have this problem. Does it have anything
to do with the way SWT handles the main thread? Is there a way around my
problem?
Here is my code -
    public void serialEvent(SerialPortEvent evt) {
    if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
    {
        try
        {
            byte singleData = (byte)input.read();

            // READING THE SERIAL PORT VALUE HERE IN
            // TEXT AREA CALLED txtLog

            if (singleData != NEW_LINE_ASCII)
            {
                logText = new String(new byte[] {singleData});

              //  System.out.print(logText);
                txtLog.append(logText);
            }
            else
            {
              txtLog.append("\n");
            }
        }
        catch (Exception e)
        {
            logText = "Failed to read data. (" + e.toString() + ")";
            txtLog.setForeground(Color.red);
            txtLog.append(logText + "\n");
        }
    }
}


text:
Q: Show  values in PartialView ASP.NET Core I migrate project from ASP.NET MVC to ASP.NET Core
I was having Partial view with two daropdowns
So Controller method was like this
 public ActionResult AddPeopleToProposal()
    {
        ViewBag.Worker = new SelectList(db.People, "Id", "FIO").ToList();
        ViewBag.Proposal = new SelectList(db.Proposals, "Id", "Id").ToList();
        return PartialView("AddPeopleToProposal");
    }

And in View I was render it like this

Добавить работника на заявку

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

            @Html.Action("AddPeopleToProposal", "Manage")

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Отмена</button>
            <button type="button" id="peopleToProposalCreate" class="btn btn-primary">Создать</button>

And Partial View
<form>

    Працівник
    @Html.DropDownList("Worker", null, "XXXX", htmlAttributes: new { @class = "form-control", @id = "peopleIdAdd" })

    Оберіть заявку
    @Html.DropDownList("Proposal", null, "XXXX", htmlAttributes: new { @class = "form-control", @id = "proposalIdAdd" })

    Коментар
    <input type="text" class="form-control" id="commentVchasno" >

But as I know @Html.Action was depricated
I realize this in Core like this
Controller
public ActionResult AddPeopleToProposal()
    {
        ViewData["Worker"] = new SelectList(_context.People, "Id", "FIO");
        ViewData["Proposal"] = new SelectList(_context.Proposals, "Id", "Id");
        return PartialView("Partials/AddPeopleToProposal");
    }

And Partial View
<form>

        Працівник
        <select class="form-control" asp-items="ViewBag.Worker"></select>

        Оберіть заявку
        <select  class="form-control" asp-items="ViewBag.Proposal"></select>

        Коментар
        <input type="text" class="form-control" id="commentVchasno" >

</form>

And View from where I cal  Partial

Добавить работника на заявку

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

            @Html.Partial("Partials/AddPeopleToProposal")

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Отмена</button>
            <button type="button" id="peopleToProposalCreate" class="btn btn-primary">Создать</button>

But at Core I don't have values in selects. Where is my problem?

A: If you want to initialize the page directly when getting the Partial View, try to put the following two lines of code into the get request of the main View of the Partial View. More about Partial views
ViewData["Worker"] = new SelectList(_context.People, "Id", "FIO");
ViewData["Proposal"] = new SelectList(_context.Proposals, "Id", "Id");

Or you could use the ViewComponent instead of the Partial View to get the fill data of the dropdownlists from the Invoke method in the view component class. Try to the code like below
ViewComponent.cs
 public class AddPeopleToCountryViewComponent:ViewComponent
{
    private readonly MVCDbContext _context;

    public AddPeopleToCountryViewComponent(MVCDbContext context)
    {
        _context = context;
    }

    public async Task<IViewComponentResult> InvokeAsync(
    int maxPriority, bool isDone)
    {
        ViewData["Customer"] = new SelectList(_context.Customer, "Id", "Name");
        ViewData["Country"] = new SelectList(_context.Country, "Id", "Id");
        return View();
    }
}

The Default.cshtml of ViewComponent
<form>

    People
    <select class="form-control" asp-items="@ViewBag.Customer"></select>

    Country
    <select class="form-control" asp-items="@ViewBag.Country"></select>

    Comment
    <input type="text" class="form-control" id="commentVchasno">

Instead of the PartialView in the modal of the main view

     @await Component.InvokeAsync("AddPeopleToCountry", new {  })


text:
Q: Are there any portable Cloud APIs that allow you to easily change cloud hosts? I am creating a web-based RESTful service and want to cloud-enable it for scalability.
I don't want to get locked into one cloud provider though.  I'd like to be able to switched between Go Grid or Amazon EC2, etc. as pricing and needs evolve.
Is there a common API to control the launch, monitoring and shutdown of cloud resources?
I've seen Right Scale, but their pricing is just from another planet.
Similarly, is there a common API for cloud storage?

A: Take a look at libcloud

A: If you are working with scala or java, you can also check jclouds(http://groups.google.com/group/jclouds)

A: For Java there is:

*

*typica

*jclouds

*Dasein

*AWS SDK for Java

A: What platform are you looking an API for? Our SecureBlackbox product offers CloudBlackbox package of components for uniform access to various cloud storages. Currently supported are S3 and Azure and Google (API for other services is possible on demand).
We don't have uniform API for computational functionality (at least at the moment).


text:
Q: How To Install 3rd Party Application on Windows Server 2012 Core Is it possible to install 3rd party components on a Windows Server 2012 Core installation that typically require a GUI? For Example, if I want to install a MySQL server on a Core installation, would that be possible? Eventually, the database server will run as a service and will require no GUI.
Am I basically limited to native Windows 2012 components in a core installation?

A: It depends on the installer of your software. Many installers wont run because they rely on Windows components that are not present in Server Core.
Many installers come with a -quiet or -silent switch to perform the installation without starting the GUI part of the installer. In many cases they have an answer file in which you can specify the components to install.
As Chris S. said, Server Core is not GUI-less, it has the normal Windows GUI with windows, what it is missing is Windows Explorer, IE, management console, WPF etc.
It is hard to tell whether a GUI program will run on Server Core, many small tools do. I even run the Netscape 3 browser sometimes for local troubleshooting
Some of my dot.NET Windows forms applications are running as well, while others don't because certain components are not present.
If the installer of your software does not run, you may still be able to get the software to run. In some cases I just installed the software on a GUI server, then copied the files and potentially registry entries over to the core server.
Over time more and more vendors will offer installers that work on Server Core.

A: Yes. You can install 3rd Part Applications so long as they don't rely on the parts of Windows that are missing. In your case, MySQL will install.


text:
Q: The SECRET_KEY setting must not be empty. Django docker i tried to find solution on stack and other websites but without result. Im fighting with django for some days.
I got my django app dockerized and it works fine. I'm using .env file to serve secret variables. And here start the problem. I can't use travis CI or debug mode in Visual Studio Code becouse my env variables are not visible. When im trying to run travis or debuger, im getting error "The SECRET_KEY setting must not be empty". The question is, how to properly configure my django app or docker instance to use env variables in every situation? Some days ago i tried to write secret_key without hidding it, but my debuger is failing on connection with database, so it seems that my variables are not visible at all. But as i said, when i run my app in normal mode or as a docker instance it works fine, my .env file is visible for django. Here you can find my settings.py
from os.path import join, dirname
import os
from dotenv import load_dotenv
from django.contrib.messages import constants as messages

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv('SEC_KEY')
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST'),
        'PORT': 5432

    }
}

And here is my docker-compose file:
version: '3.4'

services:
  electronicshop:
    image: electronicshop
    build:
      context: .
      dockerfile: ./Dockerfile
    ports:
      - "8000:8000"
    volumes:
      - .:/electronic_shop
    command: >
      sh -c "python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"
    # env_file:
    #   - .env
    environment:
      - DB_HOST=db
      - DB_NAME=${DB_NAME}
      - DB_USER=${DB_USER}
      - DB_PASS=&{DB_PASSWORD}
      - DEBUG=1
    depends_on:
      - db
    restart: always

  db:
    image: postgres:14.1-alpine
    environment:
      - POSTGRES_DB=${DB_NAME}
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    ports:
      - 5454:5454/tcp

A: Problem solved. I had to add secret_key to docker-compose environment.


text:
Q: How should I run delayed_job in production environment? I have no problems with running it in development mode via rake jobs:work. However, I'm somehow unable to figure out how to use it in production. I'm using Capistrano for deployment.
Thanks for any advice!

A: If you install delayed_job as a gem you need to run the generator in order to create the script scripts/delayed_job and set run permissions.
Then you can follow the instructions on How to configure Capistrano for Delayed Job to hook it up in your Capistrano file.

A: See this answer.  In a nutshell, use the Collective Idea fork of delayed_job.  It contains a script called delayed_job that can be used.

A: You can run the generated delayed_job script as follows:
RAILS_ENV=production script/delayed_job start

Hope this helps

A: My first thought will be to add a after deploy task in capistrano to run the rake jobs:work task. you might need to check if the process is already running and restart it.

A: If you are running it via rake then couldn't you just run however often you wanted via cron? The whenever gem is a great interface to this from ruby.


text:
Q: How to clear stdin before getting new input? I have read about 5-10 different advices how to clear stdin, but none of them suits my needs. The thing is that fflush(stdin) worked perfectly at my computer, but unfortunately it doesn't seem to work everywhere, so I need something with the same functionality. Every other way I tried clears stdin when it is not empty but requires user input when stdin IS empty, which means it requires input in a moment I dont want to get any (+ it discards it anyway).
The question is: Can I somehow make sure, that stdin IS empty before I require user input? (and if not, THEN and only then clear it somehow?)
something like:
if (stdin is NOT empty)
    while (getchar() != '\n')
        continue;

EDIT: the thing is that I load characters from stdin one by one and at some point, a part of the input from previous iteration might or might not get discarded. either way, I need to have clear stdin before I ask the user for another input to be processed. Clearing the buffer itself is not such a big deal, the problem is what happens when the input is empty when the program gets to the point of clearing stdin, because in that moment the program needs another input which is going to be eaten by the clearing function. Thats what I want to get rid of. (when I could use fflush(stdin); I just knew, that for the next line of my program the stdin WILL be empty no matter what, no questions asked...)

A:
How to clear stdin before getting new input?
  .. so I need something with the same functionality.

With portable C this is not possible.

Instead suggest a different (and more usual C) paradigm:
Insure previous input functions consumes all the previous input.
fgets() (or *nix getline()) is the typical approach and solves most situations.
Or roll your own.  The following reads an entire line, but does not save extra input.
int mygetline(char *buf, size_t size) {
  assert(size > 0 && size <= INT_MAX);
  size_t i = 0;
  int ch;
  while ((ch = fgetc(stdin)) != EOF) {  // Read until EOF ...
    if (i + 1 < size) {
      buf[i++] = ch;
    }
    if (ch == '\n') {  // ... or end of line
      break;
    }
  }
  buf[i] = '\0';
  if (i == 0) {
    return EOF;
  }
  return i;
}

A: From a similar question, Use poll() with fds.fd set to 0 (stdin), fds.events set to POLLIN, nfds set to 1, and timeout set to zero. After calling poll(), fds.revents will be set to zero if the buffer is empty, and to POLLIN otherwise.
struct pollfd fds = {0, POLLIN, 0};
poll(&fds, 1, 0);
if(fds.revents == POLLIN}
    printf("stdin buffer is not empty");

This solution will work on posix-compliant systems, but not Windows. Use select() for portability.

A: TL;DR fflush(stdin) invokes undefined behavior as per the standard, you should never use it.

Coming to your code (logic), instead of looking for a newline, you can look for EOF. It does not have a prerequisite that stdin should have some input before running this loop.
Something like
 while (getchar() != EOF);   //; is not a mistake

should meet your needs.

A: Use only fgets() to read stdin.
Use a large enough buffer and/or test for full lines.
Using fgets() you never have to worry about extra characters in stdin.
// read characters until 'X'
while (((ch = getchar()) != EOF) && (ch != 'X')) putchar(ch);
// discard X and the rest of the line
fflush(stdin); // UB except for Windows

// read full line
char tmp[1000], *p;
if (!fgets(tmp, sizeof tmp, stdin)) /* deal with error */;
if (!*tmp) /* embedded NUL detected: input is not a text file */;
if (tmp[strlen(tmp) - 1] != '\n') /* partial line */;
p = tmp;
while (*p && *p != 'X') putchar(*p++);
// ignore the X and all the subsequent characters

A: The select module offers a function called select that achieves exactly what you're looking for. select.select takes three arguments:
select.select(rlist, wlist, xlist)

Each argument should be a list of file descriptors (such as [sys.sdtin]) and it then waits until a specific IO operation is available. The IO operations are read, write or some other exception on the given file descriptors. It returns a tuple of corresponding lists populated with the file descriptors that are ready.
So, if there is input waiting in sys.stdin then the function would behave like so:
>>> import select
>>> import sys
>>>
>>> select.select([sys.stdin], [], [])
([sys.stdin], [], [])
>>>

By itself, this doesn't solve your problem because by default the function will wait until an IO operation is available. Importantly, however, select.select has an optional timeout argument denoting how long it will wait before giving up. We simply have to set the timeout to zero and we can check for input without blocking the program flow.
Let's see an example where there is no input waiting in sys.stdin:
>>> import select
>>> import sys
>>>
>>> timeout = 0
>>> select.select([sys.stdin], [], [], timeout)
([], [], [])
>>>

Knowing that we only want the first element of that tuple (the input streams) we're ready to make a useful if statement:
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
    print('Input is waiting to be read.')

That means clearing the input stream just needs some iteration:
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
    sys.stdin.readline()

And we can of course use this on any input stream, so lets put it in a function:
def clear_input(stream, timeout=0):
    '''Takes an input stream and discards each line in the buffer.
    The given timeout denotes how long in seconds to wait for
    further input when none is available.
    '''
    while stream in select.select([stream], [], [], timeout)[0]:
        stream.readline()

So let's demonstrate our function to achieve what you ask for in your question:
import select
import sys
import time

def clear_input(stream, timeout=0):
    while stream in select.select([stream], [], [], timeout)[0]:
        stream.readline()

if __name__ == '__main__':
    print('Type some lines now. They will be ignored.')
    time.sleep(5)

    print('Clearing input.')
    clear_input(sys.stdin)

    user_input = raw_input('Please give some fresh input: ')
    print(user_input)

The clear_input function can be used as a non-blocking way to clear input streams and should work in Python2 and Python3.


text:
Q: Web Application Nat Traversal We are deploying web applications in java using tomcat on client machines across the country.
Once they are installed, we want to allow a remote access to these web applications through a central server, but we do not want our clients to have to open ports on their routers.
Is there a way to tunnel the http traffic in a way that the central server can access the web application that is behind the firewall ?
The central server has a static ip address and we have full control over it.
We don't need to access the filesystem, we only want to access the web application itself through a browser.

A: For NATs what you usually have to do is get the web applications to make a request to your central server - which opens a "hole" in the NAT. Then your central server can take over this connection and access the web app.
This essentially becomes a persistent connection (since they're now way to "summon" web apps on demand, they always have to be connected to you). That is, the web apps have logic built in  to them that periodically says "am I connected to home base? No? Then phone home". This will get around NAT issues since it's client initiated.
This technique is used by Skype, Buildbot, and others.

A: Yes - but the question is very generic. Without knowing what OS you use / your clients use, its impossible to advise on what would work.
I'd suggest running ppp on top of ssh or stunnel if you've got POISX/BSD/Linux at both ends. Have a google for lots of examples.
C.


text:
Q: How to use animations in cocos2d I'm new to this and i'm making a game with SpriteBuilder and cocos2D (latest relase) but i cant manage to get animations working.
I have this code:
id scaleHorDown = [CCScaleTo actionWithDuration:duration 5/30.f scaleX:0.75f scaleY:1.0f];

id scaleHorBouncing = [CCEaseBounceIn actionWithAction:scaleHorDown];
id scaleVerDown = [CCScaleTo actionWithDuration:duration 5/30.f scaleX:1.0f scaleY:0.65f];
id scaleVerBouncing = [CCEaseBounceInOut actionWithAction:scaleVerDown];

id shrink = [CCSequence actions:scaleHorBouncing,scaleVerBouncing, nil];

id swell = [CCScaleTo actionWithDuration: duration * 15/30.f scale:1.10f];
id swellEase = [CCEaseElasticOut actionWithAction:swell];

id resetScale = [CCScaleTo actionWithDuration:duration * 5/30.f scale:1.0f];
id resetScaleBouncing = [CCEaseInOut actionWithAction:resetScale];

id buttonAction = [CCSequence actions: shrink, swellEase, resetScaleBouncing, nil];

[self runAction:buttonAction];

But it doesnt recognize most of the methods. I guess its a problem with the imports but i've tried a lot of things and nothing...
Thanks!


text:
Q: store each class in a separate file python I'm looking into organizing my modules and classes. All the time I collect my related classes in a relevant module so I can do things like:
from vehicles.car import engine

In directory vehicles there is a file named car which contains class engine. Clear.
Now I'm looking into the possibility that I can store a class in a file. So I can do something like:
from filters import air

and the air class is a file on its own. However it's not clear to me how I can have a class named air which is stored into its own file called air.py
If filters.py contained all my classes then this import would work, but that's not what I want.
Any tips or pointers?

A: Create a directory called filters, and files filters/__init__.py and filters/air.py.
In filters/__init__.py, have: from air import air, and in filters/air.py, define the class air.
Then:
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from filters import air
>>> air
<class 'filters.air.air'>
>>>


text:
Q: Share Power BI reports without pro account, only free account My company has been using free office 365 accounts, so they can neither share nor see each others Power BI reports/dashboards/ whatever. How do I work around this without paying for pro account 'If' such a workaround is possible.

A: Sharing is a Pro feature. With Free accounts you can use only Publish to web (Public), which is very limited feature, makes the data publicly available (so it is definitely not suitable for your use case) and must be explicitly enabled by your tenant administrator, or to share .PBIX files internally with your collogues (by e-mail, network share, or something similar).
As a conclusion, your best option is to start paying for it. If your company has development skills, you can also embed these use app owns data scenario, which is normally used to share Power BI elements with your customers outside of your organization, to share the reports with your co-workers.

A: To share without Pro licenses you can't share using the Power BI service.  But you're free to share your .pbix files with your colleagues using a file share, SharePoint, OneDrive, etc.  They will need Power BI Desktop to open the files.


text:
Q: when drawing a filled circle, gnuplot gives different output between x11 terminal and latex terminal, why? I switched from tikz to gnuplot for drawing math diagrams recently. I find them very different.
I want to draw a circle, so I created a .gpi file:
set terminal latex
set out 'gp.tex'
set xrange [-5:5]
set yrange [-5:5]
set object 1 circle at 0,0 size char 1 fillcolor rgb "black" fillstyle solid
plot NaN
set out
set terminal x11
plot NaN

And I loaded it in gnuplot.
The circle in x11 terminal is filled, as expected:
http://i.imgur.com/xDmlTa4.png
But the one compiled from gp.tex is a hollow circle:
http://i.imgur.com/7LNzvmW.png
Why? How can I produce a filled circle in the tex file as well?

A: The latex terminal is very old and doesn't support filled circles. You should use one of the other LaTeX-related terminals like epslatex, cairolatex or tikz which support filled circles.
See the output of the test command to see which features are supported by a terminal. For filled circles, filled polygons must be supported. For latex you get:


text:
Q: На сколько нормально использовать в приложении два PDO объекта ? Приветствую.
Так получилось что в приложении два готовых решения с github используют разные способы работы с одной и той же mysql базой данных.
Из одного компонента я могу получить PDO объект, он его вежливо отдает, а вторая либа поддерживает все возможные варианты соединения но просто передать туда уже готовый PDO объект нельзя. Вот и назревает вопрос, на сколько это вообще рационально использовать в приложении два различных соединения с бд ?
К слову, речь идет о либах RedbeanPHP и Illuminate/database
A: Никто не запрещает использовать два разных коннекта к одной и той же базе из разных компонент приложения. Так же надо иметь в виду, что по завершению работы скрипта все соединения освобождаются, так что о "рациональности" тут нужно задумываться только если у вас офигилиарт одновременных сессий и скрипт работает по 10 минут.
Но если прям совсем не нравится держать два подключения вместо одного, то можно использовать "постоянные" соединения.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

Тогда при попытке создания новых подключений будет возвращаться уже существующее.


text:
Q: How to format the content of a textfield while typing How can I format the content of a text field while the user is typing. Specifically, I want to add thousand separators to numbers.
(What to do in case of invalid/non-numeric input?  Ideally, the formatting would simply not be applied. But it would also be an acceptable solution to me to prevent invalid input in the first place - if there is a good way to do that!)
I've searched for a solution of this problem for a long time and tried lots of examples, but none of the existing answers (e.g. Question about JTextField and text format with numbers?) are satisfying.
Thanks a lot!

A: Java's controls don't do this very well by default. I recommend using something like ImprovedFormattedTextField, which is documented very well in this post:
Is there any way to accept only numeric values in a JTextField?
Your question is not exactly a duplicate, but you should be able to adapt the class to work as you expect. The background will turn red if the number is not formatted correctly.


text:
Q: Mediawiki api login doesn't accept token I'm trying to authenticate to the mediawiki api, but it doesn't accept the login token I requested. When I request (via POST) the token like this action=query&meta=tokens&type=login&format=json it returns me a a token, for example
batchcomplete:
query: {
    tokens: {
        logintoken: af69aa46ef0e505dca1b4b0ea696a55259258b4f+\
    }
}

But when I now try to authenticate with action=login&lgname=user&lgpassword=password&lgtoken=af69aa46ef0e505dca1b4b0ea696a55259258b4f%2B%5C&format=json I only getting this message back
warnings: {
    main: {
        *: Subscribe to the mediawiki-api-announce mailing list at for notice of API deprecations and breaking changes. Use [Special:ApiFeatureUsage]] to see usage of deprecated features by your application.
    }
    login: {
        *: Fetching a token via "action=login" is deprecated. Use "action=query&meta=tokens&type=login" instead.
    }
}
login: {
    result: NeedToken
    token: a26aa15ecc99c421db73b86e7581497959258b4f+\
}

It seems like it's not recognizing the token. I'm using a bot password to login.
Thanks for your help
Simon

A: Tgr's comment solved my question:

You need to issue the requests in the same session.

How can I use sessions in a php script?

Depends on what you use for making web requests. With curl, you need to use the cookie jar + cookie file options.


text:
Q: How to set multiple cell styles to one cell apache POI I am trying to add multiple cellStyles for a cell , but the last cellstyle is overwriting the existing cell style.How to add both the cellstyles??
...
CellStyle numberStyle = Workbook.createCellStyle();
 DataFormat numberFormat = Workbook.createDataFormat();
 numberStyle.setDataFormat(numberFormat.getFormat("0.00;[Red]0.00"));

CellStyle dollarStyle= Workbook.createCellStyle();
DataFormat dollarFormat = Workbook.createDataFormat();
dollarStyle.setDataFormat(dollarFormat.getFormat("$#,#0.00"));

cell5.setCellStyle(numberStyle);
cell5.setCellStyle(dollarStyle);

...


text:
Q: Difference between char* and wchar_t* I am new to MFC. I am trying to do simple mfc application and I'm getting confuse in some places. For example, SetWindowText have two api, SetWindowTextA, SetWindowTextW one api takes char * and another one accepts wchar_t *.
What is the use of char * and wchar_t *?

A: On Windows, APIs that take char * use the current code page whereas wchar_t * APIs use UTF-16.  As a result, you should always use wchar_t on Windows.  A recommended way to do this is to:
// Be sure to define this BEFORE including <windows.h>
#define UNICODE 1
#include <windows.h>

When UNICODE is defined, APIs like SetWindowText will be aliased to SetWindowTextW and can therefore be used safely.  Without UNICODE, SetWindowText will be aliased to SetWindowTextA and therefore cannot be used without first converting to the current code page.
However, there's no good reason to use wchar_t when you are not calling Windows APIs, since its portable functionality is not useful, and its useful functionality is not portable (wchar_t is UTF-16 only on Windows, on most other platforms it is UTF-32, what a total mess.)

A: char is used for so called ANSI family of functions (typically function name ends with A), or more commonly known as using ASCII character set.
wchar_t is used for new so called Unicode (or Wide) family of functions (typically function name ends with W), which use UTF-16 character set. It is very similar to UCS-2, but not quite it. If character requires more than 2 bytes, it will be converted into 2 composite codepoints, and this can be very confusing.
If you want to convert one to another, it is not really simple task. You will need to use something like MultiByteToWideChar, which requires knowing and providing code page for input ANSI string.

A: SetWindowTextA takes char*, which is a pointer to ANSI strings.
SetWindowTextW takes wchar_t*, which is a pointer to "wide" strings (Unicode).
SetWindowText has been defined (#define) to either of these in header Windows.h based on the type of application you are building. If you are building a UNICODE build then your code will automatically use SetWindowTextW.
SetWindowTextA is there primarily to support legacy code, which needs to be built as SBCS (Single byte character set).

A: char*   :   It means that this is a pointer to data of type char.
Example
// Regular char
char aChar = 'a';

// Pointer to char
char* aPointer = new char;
*aPointer = 'a';

// Pointer to an array of 10 chars
char* anArray = new char[ 10 ];
*anArray = 'a';
anArray[ 1 ] = 'b';

// Also a pointer to an array of 10
char[] anArray = new char[ 10 ];
*anArray = 'a';
anArray[ 1 ] = 'b';

wchar_t*    :  wchar_t is defined such that any locale's char encoding can be converted to a wchar_t representation where every wchar_t represents exactly one codepoint.


text:
Q: Best practices for working with sockets on a .NET 4.5 based game server? I'm working on a relatively small shooter game project in C# that has to send over map data in chunks of voxels, together with player movement data, combat data and probably other stuff in the future. I already decided on using protobuf-net for serialization/deserialization of data between server and client but I don't know what way I should send the packets themselves.
The example given by protobuf-net uses TcpListener.BeginAcceptTcpClient but warns that the example is in no way best practices. I'm aiming for supporting at least 30 users on a single server but of course I would prefer going up to 64 without it becoming too slow for the shooting gameplay to be even remotely practical. What way should I set up the TCP connection and handle packets?

A: It seems kind of strange to use TCP for real-time high performance data exchange (although in some situations and depending on your network skills, you can make a case for it). Since reliability is not a core requirement but rather getting real-time world data, it makes much more sense to use a UDP connection (e.g. using Lidgren), specially when you're in a LAN setup.
Finally, here is an interesting article on the difference between TCP and UDP from a Game point of view.


text:
Q: Angled brush in Paint.NET Does anyone know how I can use an angled paint brush on Paint.NET? Like the one in Microsoft's Paint (XP/Vista versions).
I want to use it for calligraphy:

Here's a close up of what I want:

A: It's a tremendous kluge, but you can try the CustomBrushesMini plugin.

A: I found the CustomBrushesMini inadequate, so I opened up GIMP, and saw that there were a few calligraphy brushes. I could even set the angle for my brush! It was good, but then I did some research, and found that Inkscape has a built in Calligraphy "brush". You can control many things about it, and it looks promising.
From now on, I'll use GIMP for Custom Brushes, Inkscape for calligraphy, and Paint.NET for other (which is actually more time than the other two Image Editors combined).