text:
Q: responsive navbar with bootstrap 3 When viewed on mobile devices I would like my navbar not to collapse, but stay as in the original desktop website. I have achieved this by overwriting the CSS in a media screen (code below). I would like, however, the navbar to stretch across the whole width, and this I cannot achieve.
I tried changing background-color of navbar-default to black, but it adds some margin which I can't seem to remove.

@media screen
  and (min-width: 320px)
  and (max-width: 767px)
  and (orientation: landscape) {
    body{
      margin: 0 auto;
      background-image:  url(../images/background_vm.jpg);
      /*background-repeat:no-repeat;*/
      background-attachment: fixed;
      background-size:100% auto;
      font-family: 'Tinos', 'Times New Roman';
      font-size: 22px;
      margin-top: 0px;
    }
    .head-bg{
      width: 100%;
      height: 50px;
      background: url(../images/nadpis2_bg.jpg);
      background-size:100% 100%;
      background-attachment: fixed;
    }
    .flags{
      margin-top: -25px;
      padding-right: 35px;
    }
    .flags img{
      width: 35%;
    }
    .container{
      max-width: 760px;
    }
    .content{
      padding: 15px;
    }
    .height{
      height: 50px;
      background-color: transparent;
    }
    /* Always float the navbar header */
    .navbar-header {
      float: left;
    }
    /* Undo the collapsing navbar */
    .navbar-collapse {
      display: block !important;
      height: auto !important;
      padding-bottom: 0;
      overflow: visible !important;
      visibility: visible !important;
    }
    .navbar-toggle {
      display: none;
    }
    .navbar-collapse {
      border-top: 0;
    }
    /* Always apply the floated nav */
    .navbar-nav {
      background-color: #000;
      float: none;
      display: inline-block;
    }
    .navbar-nav > li {
      float: left;
    }
    .navbar-default {
      background-color: transparent;
      border-color: transparent;
      border-top-color: white;
    }
    .navbar-default .navbar-nav > li > a {
      padding-left: 20px;
      padding-right: 20px;
      padding-top: 3px;
      padding-bottom: 3px;
      color: white;
      font-size: 12px;
    }
    /* Redeclare since we override the float above */
    .navbar-nav.navbar-right {
      float: right;
    }
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

ЗА НАС

СТУДИО

ГАЛЕРИЯ

НОВИНИ

Е-МАГАЗИН

КОНТАКТИ

Here is a photo of what it looks like now:

And here is a photo of what I would like it to be:

A: The solution was to apply style to the ul inside the navbar-collapse div. Here is the css.
.navbar-collapse > ul {
    width: 100%;
    margin: 0 auto !important;
}

Here is the fixed example:

@media screen
  and (min-width: 320px)
  and (max-width: 767px)
  and (orientation: landscape) {
    body{
      margin: 0 auto;
      background-image:  url(../images/background_vm.jpg);
      /*background-repeat:no-repeat;*/
      background-attachment: fixed;
      background-size:100% auto;
      font-family: 'Tinos', 'Times New Roman';
      font-size: 22px;
      margin-top: 0px;
    }
    .head-bg{
      width: 100%;
      height: 50px;
      background: url(../images/nadpis2_bg.jpg);
      background-size:100% 100%;
      background-attachment: fixed;
    }
    .flags{
      margin-top: -25px;
      padding-right: 35px;
    }
    .flags img{
      width: 35%;
    }
    .container{
      max-width: 760px;
    }
    .content{
      padding: 15px;
    }
    .height{
      height: 50px;
      background-color: transparent;
    }
    /* Always float the navbar header */
    .navbar-header {
      float: left;
    }
    /* Undo the collapsing navbar */
    .navbar-collapse {
      display: block !important;
      height: auto !important;
      padding-bottom: 0;
      overflow: visible !important;
      visibility: visible !important;
    }
    .navbar-collapse > ul {
        width: 100%;
        margin: 0 auto !important;
    }
    .navbar-toggle {
      display: none;
    }
    .navbar-collapse {
      border-top: 0;
    }
    /* Always apply the floated nav */
    .navbar-nav {
      background-color: #000;
      float: none;
      display: inline-block;
    }
    .navbar-nav > li {
      float: left;
    }
    .navbar-default {
      background-color: transparent;
      border-color: transparent;
      border-top-color: white;
    }
    .navbar-default .navbar-nav > li > a {
      padding-left: 20px;
      padding-right: 20px;
      padding-top: 3px;
      padding-bottom: 3px;
      color: white;
      font-size: 12px;
    }
    /* Redeclare since we override the float above */
    .navbar-nav.navbar-right {
      float: right;
    }
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

ЗА НАС

СТУДИО

ГАЛЕРИЯ

НОВИНИ

Е-МАГАЗИН

КОНТАКТИ


text:
Q: Aws SDK: CredentialsProviderError while integrating AWS v3 Javascript SDK I am trying to integrate Amazon STS v3 javascript sdk and am getting the below error.It seems to be requiring credentials in the new STS() initialization.What exact credentials is it expecting since I want to get the AWS credentials from Assume Role Command response.
CredentialsProviderError: Could not load credentials from any providers
import  { STS , AssumeRoleCommand } from '@aws-sdk/client-sts'

    function test() {

      const client = new STS({ region: 'us-east-1'});
      const params = {
        RoleArm: 'arn:aws:iam:21212134:role/app',
        RoleSessionName: 'Session1',

      }
      const command = new AssumeRoleCommand(params);
      const response = await client.send(command);

    }

A: You need to change RoleArm to RoleArn

redpajama_set_name: RedPajamaStackExchange


text:
Q: How the "OK" message looks like? I have a device that sends data to a server.
            Data
[ Client ]  == >  [ Server ]

After the validation on the server I want to return a message:
            OK
[ Client ] < == [ Server ]

Is there a standard "OK" message to return? And an "ERROR" message? How does it looks like? (e.g. ":0011", ":110F")

A: You've got to design an application-level protocol.  TCP is a byte stream, so even the definition of "Data" in your client->server piece needs some protocol so that the receiver can know what bytes make up the data (when to stop reading).
A couple of common types of protocols are...

*

*Length-delimited chunks.  Every message starts with a 16 or 32-bit length prefix.  Then that many bytes follow.  The length needs to be in a defined byte order (see htons, ntohs, etc).  Everyone who uses this protocol knows to read the length prefix then read that many bytes.  Having defined that "chunk" on the network, you might put a header on the contents of the chunk.  Maybe a message type (ACK, NAK, Data, etc) followed by some contents.

*ASCII newline delimited.  Each message is a line of ASCII (or UTF8, etc) text.  It ends at a newline.  Newline endings for the lines play the same role as the length prefix for the chunks above.  You then define what's in each line (like space or comma-delimited ASCII/UTF8/whatever fields).  Somewhere in that you'd define what data looks like, ACK, etc.

I'm sure you could come up with other ideas, but that's the basic job: defining your application-level protocol on top of TCP's byte stream.


text:
Q: Codeigniter where_in JSON column i need a Codeigniter query to get results from a JSON column MYSQL table.
Sample column data bellow.
["1","2","6","4","3","5","7","9","8"]

Currently im using bellow code for this but it's not working.
$DOCUMENTS = $this->db->select('*')->where('JSON_CONTAINS(BELONG) = '.$_POST['ID'].'')->get('SOLIDARITY_REQUESTED_FILES')->result_array();

A: If your JSON formatted as array like your data, you can concatenate the ID to the commas and quotes. then TRIM the square bracket and find by LIKE statement.
$concat = "CONCAT(',\"',TRIM(LEADING '[' FROM TRIM(TRAILING ']' FROM BELONG)),'\",')";
$theId = ',"'.$_POST['ID'].'",';
$DOCUMENTS = $this->db->select('*')->like($concat, $theId)->get('SOLIDARITY_REQUESTED_FILES')->result_array();

Hope this help.

A: Suppose i'm doing to get record where city_id should be in following list.
1,2,3,4,5,6,7,8
then following line you can add into your code
    $city_id_list = "1,2,6,4,3,5,7,9,8";
    $this->db->where_in('city_id', $city_id_list);

A: JSON_CONTAINS function required two minimum arguments. check more details HERE
It is dangerous to add $_POST data into query. Codeigniter having input class to fetch data from POST request.
$id = $this->input->post('ID');

$DOCUMENTS = $this->db->select('*')->where("JSON_CONTAINS(BELONG, $id)>0")->get('SOLIDARITY_REQUESTED_FILES')->result_array();

Feel free if you need further guidance.


text:
Q: Multiple media queries in css not working I have multiple queries in my stylesheet where the code@media only screen and (min-width : 768px) and (max-width : 1024px) { } works perfectly fine but under it I have @media screen and (min-device-width : 176px) (max-device-width : 360px) {} does not work.
CSS:
@media only screen and (min-width : 768px) and (max-width : 1024px) {
body {background: red; } }

@media screen and (min-device-width : 176px) (max-device-width : 360px) {
body {background: green; } }

A: For multiple width for same style, use ,:
@media (max-width: 360px), (max-width: 768px) {

    /* style goes here */

}

A: You're missing the AND between (min-device-width : 176px) (max-device-width : 360px).
@media screen and (min-device-width : 176px) and  (max-device-width : 360px) {
    body {background: green; }
}

The other issues here is you are using min-device-width.(referring to the resolution of the device vs browser width)  which is what @NoobEditor is saying below.
Are you doing that on purpose?  If not you should be using min-width && max-width

@media screen and (min-width : 176px) and  (max-width : 360px) {
    body {background: green; }
}

A: check this fiddle, change the browser width to see the the media query in action
@media screen and (max-width : 1500px) {
    body {
        background: #000;
        border-top: 2px solid #DDDDDD;
    }
}

@media screen and (min-width : 768px) and (max-width : 1024px) {
    body {
        background: #fff;
        border-top: 2px solid #DDDDDD;
    }
}

This fiddle works fine, but if you change the order of the media queries it wont work...try it for yourself!
CSS always selects the last style that was declared if multiple style are found for an attrib.
for e.g :
@media (max-width: 1024px) {
  body {
    background: black;
  }
}

@media (max-width: 768px) {
  body {
    background: white;
  }
}

for 765px ( since both m.q cover this width ) color selected would be white

A: I found the solution. You have to make 2 CSS files, in the first code the first media query and in the second write yout second media query code. I know it is an elegant way to do it but it works.


text:
Q: Why do programmers sometimes silently swallow exceptions? I know it's evil, but I've seen swallowed exceptions in code written by a good programmer. So I'm wondering if this bad practice could have at least one positive point.
In other words, it is bad but why do good programmers, on rare occasions, use it?
try
{
    //Some code
}
catch(Exception){}

A: Because sometime even good programmers make mistakes.
Either that or your opinion of a good programmer isn't the same as some (because a good programmer would have left some reasoning behind as to why the Exception was swallowed rather than something being done with the information).

A: Because something has to be finished for a presentation the boss spontaneously does tomorrow and nothing is worse than the program crashing or showing a nasty error message, while when something is just not working he can always "talk around" that.
After the presentation, no one will improve those "quick fixed" parts of course. ;-)

A: I believe it's because of Java's checked exceptions. I personally hate them because of this because people tend to think they need exception-handling code everywhere. IMO in 99% of the code you should just be throwing your exception up the stack and not handling it. I'd be happy if the default signature for any new method created had 'throws Exception' in it so that I don't have to deal with exceptions unless I want to.
IMO you only need exception-handling in two places:
 1. For resource cleanup like closing an input stream, database connection or deleting a file.
 2. At the very top of the stack where you catch the exception and either log it or show it to the user.
There are places where you really don't need to do anything in the catch such as handling the InterruptedException from Thread.sleep() and there you should at least have a comment to make it clear that you really don't want anything to happen there.

A: Looking in my own code, I found a place in my logging code where, after failing to write to a file and failing to write to the event log, it swallows the error as there is no place left to report it.  That's one example: there aren't many others.

A: Yes, I use them quite often in exception cleanup code so that I don't mask the original exception.
For example, if your catch handler is trying to rollback a transaction and close a connection before rethowing the exception, there could be several reasons that the rollback/close itself could fail (since you're already in some busted up as a result of the original exception).  So, may want to wrap the clean in a try block with an empty catch handler, basically saying "if something goes wrong in the cleanup, that's sort-of-OK, since we have bigger problems to report"

A: Because sometimes the programmer has more knowledge than the compiler.
E.g. (in some fictional language where division by zero is regarded as an error):
try {
    x = 1 / (a*a + 1);
} catch (DivisionByZeroException ex) {
  // Cannot happen as a*a+1 is always positive
}

As some languages (e.g. Java) require to catch some/many/all exceptions, the compiler might complain while the programmer knows it is not possible. Sometimes the only way to get the compiler to shut up, is to explicitely swallow the exception.
In languages where the compiler doesn't complain, the empty catch usually is not written at all.
Edit: In practice, I would add an assert(false) in the catch block. If theoretically something cannot happen, it is a very serious problem when it does happen in practice ;)
Edit2: Java only requires to catch checked exceptions. Reworded my statement a bit.

A: I'd argue that a good programmer wouldn't do that without explaining it.
try
{
    //Some code
}
catch(Exception e) {
    // Explanation of why the exception is being swallowed.
}

I'm very unlikely to just silently swallow the base Exception class though, for any reason.  I'd at least try to log the error.

Here's a concrete example that I just happened to run across today in my project.  This is part of a JavaScript function that gets an XMLHttpRequest supported by the browser.
var XMLHttp = null;

if( window.XMLHttpRequest ) {
    try {
        XMLHttp = new XMLHttpRequest();
    } catch(e) {} // we've already checked that this is safe.
}
else if( window.ActiveXObject ) {
...
}

Since the try is wrapped in an if...else if that checks the type of object to be created, it's safe to swallow the exception.

A: I do it when an exception can't be handled effectively, it shouldn't impact the normal operation of the application, and/or it might represent a transient condition that is known but has little overall impact.
A simple example is logging.  You don't need the app to blow up just because some logging information won't be saved to your backing store.
Another example might be where you have alternative means of handling the situations, like this:
private Boolean SomeMethod() {
   Boolean isSuccessful = false;
   try {
      // call API function that throws one of several exceptions on failure.
      isSuccessful = true;
   } catch(Exception) { }

   return isSuccessful;
}

In the above example, you may not have a fall back position, but you don't want it to filter up.  This is ok for SHORT methods where the return value is only set to a successful status as the last step in the try block.
Unfortunately there are many calls that will throw exceptions instead of simply returning an error code or false condition in the result.  I've also seen calls that throw more exceptions than what their documentation suggests which is one of the reasons why I'll put a catch all around them.

A: I stumbled on this old thread and was surprised to not see the only justifiable reason why good code would simply swallow exceptions (with or without commenting).
When you write code using libraries and code that is outside your control, there are frequently situations where you need to call a method to get some value that may or not be there, or perform an operation that may not be allowed at a given point in time.  If the method you are calling throws an exception if it cannot return a valid result instead of providing a control-flow alternative, then you are forced to swallow the exception as a signal that the value is not available or the operation cannot be performed.
Good programmers will make every effort to avoid using exception handling to drive control flow except in real failure scenarios that are likely to bubble up to the user as an error.  However, good programmers also extensively reuse libraries and frameworks for efficiency, and understand that rewriting the libraries to provide better alternatives (like TryGetValue patterns), is not always an option.

A: I can only think of two kinds of cases where I've swallowed exceptions.

*

*When closing files or database connections. If I get an error on the close, what am I going to do about it? I suppose I really should write out some sort of error message, but if I've already successfully read the data, it seems superfluous. It also seems like a very unlike event to happen.

*More justified: Inside error handling. If I fail trying to write to the log file, where am I going to write the error that says that I couldn't write an error? In some contexts you could try to write to the screen, but depending on the app, that might be impossible, e.g. a background job with no screen; or just confusing to the user who won't be able to do anything about the error anyway.
Another poster mentioned cases where you know the exception is impossible, or at least, that for it to happen there would have to be major problems with your compiler or operating environment, like it did not add two numbers together correctly, in which case who says the exception is meaningful?
I heartily agree that in these rare cases where it is legitimate, you should include a comment to explain why the exception is irrelevant or impossible. But then, I'd say that anytime you write code that is potentially cryptic, you should include an explanatory comment.
Side note: Why is it that programmers routinely include comments like "x=x+1; // add 1 to x", like duh, I never would have figured that out without the comment, but then throw in really cryptic code with no explanation?
Addendum four years after my original post
Of course the REAL reason why even good programmers sometimes swallow exceptions is: "I'm trying to get the basic logic working, I'm not sure what to do if this exception happens, I don't want to mess with it right now, I'm having too much trouble with the normal logic flow but I'll get back to it later." And then they forget to get back to it.
BTW a bad reason I've heard from several people who I generally think are pretty good programmers is: "I don't want to display a cryptic error message to the user. That would just confuse them. Better to silently swallow the error." That's a bad reason because, (a) You could still write something to a log file. And (b) Is a cryptic error message really worse than giving the user the impression that the operation succeeded when it didn't? Now the customer thinks their order is being processed when it really isn't, or they think the ambulance is being dispatched to help their child who is screaming in agony but really the message never went through, etc. Even in the most trivial of cases, a bland post on a forum didn't happen or some such, I would much rather get a cryptic message that at least gives me the idea that something went wrong and if I care I should try again or call somebody, then just say "update complete" when it really isn't.

A: Without claiming to be a good programmer, I can at least explain why I sometimes catch and ignore. There are times when what I'm working on has to deal with an exception to compile, but is not the appropriate place to actually handle the exception. For instance, I was recently working in a program which parses a good deal of XML as one of its tasks. The actual XML parser opened a file, which generated an exception. The XML parser was not the best place to generate a dialog informing the user of bad file choice, though. Rather than get sidetracked with throwing the exception to the right place and handling it there, I silently caught the exception, leaving a comment and TODO (which my IDE tracks for me). This allowed me to compile and test without actually handling the exception. Sometimes, I will forget to take care of the TODO immediately, and the swallowed exception sticks around for a while.
I know this is not the best programming practice, and I certainly am not an expert programmer, but I think this is an example of why someone would want to do this.

A: I've done this when there some is some piece of code where regardless of it failing I want the program to continue. For example I've opened an optional log file and regardless of why it failed to work I want to continue the execution of the program.
Even so though, it's not good code as you can get exceptions like out of memory exceptions that ignoring makes no sense at all so even though i've done it, it's still not the best idea and I wouldn't admit to doing it in public. (oops...)
I've done it on programs that are intended to be run once to convert some data or something just to shut the compiler up. That's an entirely different situation to any form of production code though.
Basically there is no good reason for doing this other than lazyness.

A: we use exceptions for runtime errs. because of users and sometimes requirements and such things that occurs when there is a problem. and if we want to show the error to the user we might raise exceptions.
eg:-

*

*when the software is running there might be a requirement err and it can be solved by the
program itself. so in such cases, the programmer chose to use try statements and there may be a hardware requirement that can't be solved by the software in such cases the programmer chooses the path of raising an exception to alert the user.

and there are many cases that we choose the path of raising an exception or handling exceptions the situation matter.

A: at the very least write it to the output window
try
{ }
catch (exception ex)
{
System.Diagnostics.Debug.Writeline(" exception in method so and so : " ex.message);
}

A: How about when performing a progress-control update?  I've updated the state variables used by a control's drawing routine, so the next time the control is drawn it will show the proper state.  I then perform:

  Try
    MyControl.BeginInvoke(MyControlUpdateDelegate);
  Catch Ex as Exception
  End Try

If the control still exists, it will update.  If it gets disposed, I won't care whether it gets updated or not.  If the control isn't disposed, but can't be updated for some other reason, I still won't really care whether it gets updated or not because I'm not apt to be able to do anything sensible about it anyway.
Note that I could add "If Not MyControl.IsDisposed Then..." but that would just add work to the common case, and wouldn't prevent the exception from occurring if the control gets disposed during the BeginInvoke.

A: Due to the nature of the applications I write, virtually every exception I catch needs to be logged to a file.
Exceptions should never be eaten without any kind of rethrow, logging, or even a comment explaining why the exception was silently eaten.  In my earlier years I would often eat exceptions if I knew that I was the only person working on the code.  Of course when it came time to revisit the code I would forget what that exception really meant, and I'd have to retest everything to figure it out again.


text:
Q: second image in footer and styling I have my wordpress theme built but there are 2 problems, the first the twitter feed I have in my footer (not a widget) is taking the styling for something else instead of the styling I gave it. I styled the links etc for the feed but it's not styling properly. Also I want to have an image behind my footer but not be part of it. In my site I have my footer image that repeats horizontally and an image behind it. My issue is when I put the image in it acts like part of the footer and not the background (it's not my background image just on top of it). Here is a link to my blog (the code is too long to post here):
http://blog.zombiesarefierce.com/
also here is a pic of what my footer is supposed to look like, any help would be greatly appreciated:
http://www.freeimagehosting.net/jq19y

A: download addon fire bug
Right click on image and click on inspect eliment with fire bug then chang the css of your image
in your case
.art-footer img
{
border-width: 1px;
}

and make it
 border-width: 0px;

n here is the screen shot of your site


text:
Q: Access is denied when I create a file in programfiles folder I created a wpf application. It will create a text file and store some data. In the time of implementation it's working fine(visual studio 2015). After I create a setup and install it in the same system I get the error:

Access denied to create file C:\programFiles\test\hello.txt

This is my code :
using (StreamWriter file = File.CreateText("hello.txt"))

When debugging the file is created in the debug/bin folder.

A: You can't just write to that folder without having the appropriate permissions. Your application should run elevated as administrator to be able to write to that folder.
I would advise you to use a folder that is writable without elevation, like the %PROGRAMDATA% folder.


text:
Q: Is it safe to run locate/updatedb on WSL Linux? While I think using "locate" to search files on my disks (C: and externals) would be quite useful, I worry the likelihood using locate and/or (sudo) updatedb might cause some serious problems on the Windows system (C:). For example on the other day I used "stat" to a bunch of files including some system files or kinds, the WSL stopped working and unable to kill, I needed to reboot the machine. Fortunately it seemed it didn't cause any problem on my machine, I'm concerning using locate or updatedb to scan all the files may make WSL crash or at worst make Windows system crash.
So, is it safe to use locate/updatedb on Windows WSL linux (ubuntu etc)?

A: I wouldn't recommend it, just for performance reasons alone, especially if you are running WSL2.  WSL1 uses drvfs to access files under Windows, which is still slow than a "native" Linux filesystem, but WSL2 uses 9P, which can be up to 10x slower than WSL1 if you are accessing many small files.
There are some alternatives that are native Windows.  I'd probably just deal with having two separate commands/databases to search -- One for WSL/Linux, and the other for Windows drives/files.

A: Use Explorer - see Microsoft's own page on interoperability on this.  You can use the search bar which works pretty well in my experience.
Go to your terminal and enter explorer.exe .
This will open a Windows Explorer window in the directory you launched it from.  It is very handy if you need to move files around between Windows and Linux (Ubuntu in my case)


text:
Q: How to read from object with an at sign (@) prepended? How do I print out the value of category.uri when the object is defined like this:

If i try using object[0].category.@uri I get the following error:

Uncaught SyntaxError: Unexpected token +

And if I try without the @-sign, I get:

Uncaught TypeError: Cannot read property 'uri' of undef

Basically: how do I read the value when its prepended with an at sign? What does the at sign mean aka why is it there in the first place? (In this case I do not control the REST-API I am working against)

A: Javascript has two object access notations (called member operators): dot notation and square bracket notation. These are identical:
document.forms
document['forms']

You can always use square bracket notation, but you can't always use the dot notation. So if your property name does not conform to the rules for identifiers, you need to use the square bracket form.
object[0].category['@uri']

The rules are:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). (MDN)

A: Like this:
object[0].category['@uri']


text:
Q: Visual C# Office Addins for Mac I have a Office Addin which works well in MS Office 2007. Can I port this Addin to Mac? Is this possible?

A: Sorry, the VSTO framework used to develop Office Add-ins is for Windows only :-(
Take a look at Microsofts system requirements for the VSTO framework: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20479


text:
Q: JTabbedPane. Select tab on left mouse button click only I want to set the most common JTabbedPane mouse event behavior, but I cannot find appropriate options to set:

*

*Left mouse button click - Select tab.

*Right mouse button click - Open current tab' dropdown menu.

*Wheel mouse button click - Close the tab.
Question: Is there any way to implement them?
PS: Any example from here could be an SSCCE.

A: Tab selection is performed with left mouse button by default, so you don't need to add that feature. Everything else you can find in this small example:
public static void main ( String[] args )
{
    final JFrame frame = new JFrame ();

    final JTabbedPane tabbedPane = new JTabbedPane ();
    tabbedPane.addTab ( "tab1", new JLabel ( "" ) );
    tabbedPane.addTab ( "tab2", new JLabel ( "" ) );
    tabbedPane.addTab ( "tab3", new JLabel ( "" ) );
    tabbedPane.addTab ( "tab4", new JLabel ( "" ) );
    frame.add ( tabbedPane );

    tabbedPane.setUI ( new MetalTabbedPaneUI ()
    {
        protected MouseListener createMouseListener ()
        {
            return new CustomAdapter ( tabbedPane );
        }
    } );

    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE );
    frame.setVisible ( true );
}

private static class CustomAdapter extends MouseAdapter
{
    private JTabbedPane tabbedPane;

    public CustomAdapter ( JTabbedPane tabbedPane )
    {
        super ();
        this.tabbedPane = tabbedPane;
    }

    public void mousePressed ( MouseEvent e )
    {
        final int index = tabbedPane.getUI ().tabForCoordinate ( tabbedPane, e.getX (), e.getY () );
        if ( index != -1 )
        {
            if ( SwingUtilities.isLeftMouseButton ( e ) )
            {
                if ( tabbedPane.getSelectedIndex () != index )
                {
                    tabbedPane.setSelectedIndex ( index );
                }
                else if ( tabbedPane.isRequestFocusEnabled () )
                {
                    tabbedPane.requestFocusInWindow ();
                }
            }
            else if ( SwingUtilities.isMiddleMouseButton ( e ) )
            {
                tabbedPane.removeTabAt ( index );
            }
            else if ( SwingUtilities.isRightMouseButton ( e ) )
            {
                final JPopupMenu popupMenu = new JPopupMenu ();

                final JMenuItem addNew = new JMenuItem ( "Add new" );
                addNew.addActionListener ( new ActionListener ()
                {
                    public void actionPerformed ( ActionEvent e )
                    {
                        tabbedPane.addTab ( "tab", new JLabel ( "" ) );
                    }
                } );
                popupMenu.add ( addNew );

                final JMenuItem close = new JMenuItem ( "Close" );
                close.addActionListener ( new ActionListener ()
                {
                    public void actionPerformed ( ActionEvent e )
                    {
                        tabbedPane.removeTabAt ( index );
                    }
                } );
                popupMenu.add ( close );

                final JMenuItem closeAll = new JMenuItem ( "Close all" );
                closeAll.addActionListener ( new ActionListener ()
                {
                    public void actionPerformed ( ActionEvent e )
                    {
                        tabbedPane.removeAll ();
                    }
                } );
                popupMenu.add ( closeAll );

                final Rectangle tabBounds = tabbedPane.getBoundsAt ( index );
                popupMenu.show ( tabbedPane, tabBounds.x, tabBounds.y + tabBounds.height );
            }
        }
    }
}

Ofcourse you'd better save the displayed menu somewhere so it won't be recreated every time user opens it. You can also move the mouse listener to a separate class to use it every time you need menu and other features.
But my goal was to show you how those things can be done and not making a perfect example, so i guess it is more than enough to start working with tabbed pane :)


text:
Q: TabBar in React Navigation I need help in React Navigation when I create a tab bar  like I have button home and I want to access another screen in the Home with show tab bar inside it to keep selected on the Home icon.
First Screen
Second Screen
I want show tabBar with continue select Home button.

A: This solved my problem by A stack navigator for each tab.
https://reactnavigation.org/docs/tab-based-navigation/?fbclid=IwAR071_HAYPP9NYGbVHq88j1ZssyBn8226Qnne_PzUdGdIM56XrVD5shU10c#a-stack-navigator-for-each-tab

A: I think you should have a variable that would keep track of the home page and when you are on it and thus provide the styling you need on the homepage icon....and when you are in the second screen it should be still be set to true so nothing changes


text:
Q: Javascript push not outputing the right value I want to push this value to router.PORTS[i].packetdata
but it's not giving me the exact value.. the push function also loops
and give me the wrong value..
The wrong code is on line 72.
but when I tried
router.PORTS[i].packetdata = message;
on line 72.
the value is right but it's not pushing to the array.
            function Router(PORTS){
                rex = this;
            }

            Router.prototype = {
                "PORTS": [],
                connect: function(devicename,PORT){
                    devicename.PORT = PORT;
                    this.PORTS.push(devicename);

                },
                totalPackets: function(PORT){
                    if(PORT){
                        for (var i=0;i<rex.PORTS.length;i++)
                        {
                            if(rex.PORTS[i].PORT == PORT){
                                console.log('total packets by PORT', rex.PORTS[i])
                            }
                        }
                    }else{
                        return rex.packetdata.length;
                    }

                },
                totalBytes: function(){
                    totalBytes = [];
                    result = 0;
                    for (var i=0;i<rex.packetdata.length;i++)
                    {
                        totalBytes.push(rex.packetdata[i].message.length)
                    }

                    for (var i = 0; i< totalBytes.length; i++) {
                    result += totalBytes[i];
                    }
                    return result;

                },
                packetdata: []
            }

            function Device(ip){
                this.ip = ip;

            }

            Device.prototype = {
                DeviceName: "",
                IP: this.ip,
                PORT: "",
                data:[],
                incomingBuffer: "",
                totalPackets:"",
                totalBytes:"",
                emit: function(data,packets){
                    rex.packetdata.push(packets);
                },
                packetdata: []
            }

            function Packet(ip,message) {
              this.ip = ip;
              this.message = message;
              for (var i=0;i<rex.PORTS.length;i++)
                {
                    if(router.PORTS[i]['ip'] == ip){

                        router.PORTS[i].incomingBuffer = router.PORTS[i].incomingBuffer + this.message;
                        // I want to push this value to router.PORTS[i].packetdata
                        // my code router.PORTS[i].packetdata.push(message);
                        router.PORTS[i].packetdata = message;
                        console.log(ip, router.PORTS[i].ip);

                    }
                    else{
                        //console.log('invalid')
                    }
                }

            }

            Packet.prototype = {
              ip: this.ip,
              message: this.message
            };

            router = new Router(['WAN', 'LAN1', 'LAN2']);

                device1 = new Device('192.168.0.1');
                router.connect(device1, 'LAN1');

                device2 = new Device('192.168.0.10');
                router.connect(device2, 'LAN2');

                wan = new Device('62.88.120.10');
                router.connect(wan, 'WAN');
                wan.emit('data', new Packet('192.168.0.1', 'Hello '));
                wan.emit('data', new Packet('192.168.0.10', 'Hi,'));
                wan.emit('data', new Packet('192.168.0.10', ' guys'));
                wan.emit('data', new Packet('192.168.0.1', 'world!'));
                wan.emit('data', new Packet('192.168.0.1', 'shit!'));
                router.totalPackets();
                router.totalBytes();
                router.totalPackets('LAN1');

A: This looks like a mistake:
Device.prototype = {
    // ...
    packetdata: []
}

That creates a single array that will be assigned as the packetdata attribute every time a new Device is instantiated. So when you modify one Device's packetdata (unless its packetdata attribute has been reassigned), you're modifying that one array, which affects every Device.
You can create a new packetdata array for each Device by creating it in the constructor.
function Device(ip) {
    this.ip = ip;
    this.packetdata = [];
}

Alternatively, you could stick with the original protoype, but treat the arrays as immutable values. So to add packet data to a device, instead of mutating the array
device.packetdata.push(message);

you could reassign it
device.packetdata = device.packetdata.concat(message);

But that would be a rather atypical design, since most javascript programmers don't think in terms of immutable data structures.


text:
Q: Loading Json File with Button Unity I have been working on a customization system that allows a player to customize their skin color and particle trail of their character. I have the system working and am now attempting to save the data through JsonUtility and then load it. I plan on saving the data with the play button then transitioning to a new scene and having it load at start() of the new scene. But, for testing I have been using a load button as it should still work...but it doesn't.
My current SaveSystem script is supposedly working since the DebugLog "Save file created" for saving files appears when the button is pressed. But, when pressing the load button nothing changes yet the DebugLog "Save file found and loaded" still appears. I am kinda lost as to where to go and how to load the data into the Customization script since I am still new to C# Json and serializing in general.
Here are my 3 scripts:
SaveSystem Script
using UnityEngine;
using System.IO;

public static class SaveSystem
using UnityEngine;
using System.IO;

public static class SaveSystem
{
public static string directory = "/saveData";
public static string fileName = "MyData.txt";

public static void SavePlayer(Customization CurrentCustomization)
{
    string dir = Application.persistentDataPath + directory;

    if(!Directory.Exists(dir))
        Directory.CreateDirectory(dir);
        Debug.Log("Save file created");

    string json = JsonUtility.ToJson(CurrentCustomization);
    File.WriteAllText(dir + fileName, json);
}

public static Customization LoadPlayer()
{
    string fullPath = Application.persistentDataPath + directory + fileName;
    Customization CurrentCustomization = new Customization();

    if(File.Exists(fullPath))
    {
        string json = File.ReadAllText(fullPath);
        CurrentCustomization = JsonUtility.FromJson<Customization>(json);

        Debug.Log("Save file found and loaded");
    }
    else
    {
        Debug.Log("Save file does not exist");
    }

    return CurrentCustomization;
}
}

CharacterCustomizaiton Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class CharacterCustomization : MonoBehaviour
{
public List<Customization> Customizations;
public int currentCustomizationIndex;
public Customization CurrentCustomization {get; private set;}

[SerializeField] private TextMeshProUGUI bodyColorText;
[SerializeField] private TextMeshProUGUI trailText;

public void Save()
{
    SaveSystem.SavePlayer(CurrentCustomization);
}

public void Load()
{
    CurrentCustomization = SaveSystem.LoadPlayer();
}

void Awake()
{
    foreach(var customization in Customizations)
    {
        customization.UpdateSubObjects();
        customization.UpdateRenderers();
    }
}

public void SelectBodyColor(bool isForward)
{
    currentCustomizationIndex = 0;
    CurrentCustomization = Customizations[currentCustomizationIndex];
    if(isForward)
    {
        CurrentCustomization.NextMaterial();
    }
    else
    {
        CurrentCustomization.PreviousMaterial();
    }

    bodyColorText.text = CurrentCustomization.materialIndex.ToString();
}

public void SelectLTrail(bool isForward)
{
    currentCustomizationIndex = 1;
    CurrentCustomization = Customizations[currentCustomizationIndex];
    if(isForward)
    {
        CurrentCustomization.NextSubObject();
    }
    else
    {
        CurrentCustomization.PreviousSubObject();
    }

    trailText.text = CurrentCustomization.subObjectIndex.ToString();
}

public void SelectRTrail(bool isForward)
{
    currentCustomizationIndex = 2;
    CurrentCustomization = Customizations[currentCustomizationIndex];
    if(isForward)
    {
        CurrentCustomization.NextSubObject();
    }
    else
    {
        CurrentCustomization.PreviousSubObject();
    }

    trailText.text = CurrentCustomization.subObjectIndex.ToString();
}
}

Customization Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Customization
{
public string DisplayName;

public List<Renderer> Renderers;
public List<Material> Materials;
public List<GameObject> SubObjects;
public int materialIndex;
public int subObjectIndex;

public void NextMaterial()
{
    if(materialIndex == Materials.Count - 1)
    {
        materialIndex = 0;
    }
    else
    {
        materialIndex++;
    }

    UpdateRenderers();
}

public void PreviousMaterial()
{
    if(materialIndex == 0)
    {
        materialIndex = Materials.Count - 1;
    }
    else
    {
        materialIndex--;
    }

    UpdateRenderers();
}

public void NextSubObject()
{
    if(subObjectIndex == SubObjects.Count - 1)
    {
        subObjectIndex = 0;
    }
    else
    {
        subObjectIndex++;
    }

    UpdateSubObjects();
}

public void PreviousSubObject()
{
    if(subObjectIndex == 0)
    {
        subObjectIndex = SubObjects.Count - 1;
    }
    else
    {
        subObjectIndex--;
    }

    UpdateSubObjects();
}

public void UpdateSubObjects()
{
    for(var i = 0; i < SubObjects.Count; i++)
        if (SubObjects[i])
            SubObjects[i].SetActive(i == subObjectIndex);
}

public void UpdateRenderers()
{
    foreach (var renderer in Renderers)
        if (renderer)
            renderer.material = Materials[materialIndex];
}
}


text:
Q: Why doesn't Kitty Pryde fall through the ground? Why doesn't Kitty Pryde fall through the floor when using her special powers to phase?  If she can move through walls, etc, surely she should just keep falling down.

A: From Wikipedia:

While phasing, she does not physically walk on surfaces, but rather interacts with the molecules of air above them, allowing her to ascend and descend, causing her to seemingly walk on air.

One could extrapolate that she interacts with other molecules to control how much she would phase through the ground, when she does so.
It has been shown, in a few stories, that she can walk high in the air, but she has to concentrate in order not to fall.
In Uncanny X-Men #143 (1981) it shows her "using her phasing ability to literally walk on individual molecules of air":


text:
Q: How to run a graphical installer from Oracle Linux 8 VM Iam new to oracle linux
i have to run a graphical installer program(.sh) as account dmadmin
but when i run xev it gives me the following
[dmadmin@cshost ~]$ xev
xev:  unable to open display ''
I dont know how to proceed from hereon . Kindly send me the detailed instructions on how to run it


text:
Q: how to find and replace special url patern (Markdown syntax to HTML) by re module in python I have a string and I want to search this string to find special pattern containing URL and it's name and then I need to change it's format:
Input string:
'Thsi is my [site](http://example.com/url) you can watch it.'

Output string:
'This is my site you can watch it.'

The string may have several URLs and I need to change the format of every one and site is in unicode and can be every character in any language.
What pattern should be used and how I can do it?

A: This should help
import re
A = 'Thsi is my [site](http://example.com/url) you can watch it.'

site = re.compile( "\[(.*)\]" ).search(A).group(1)
url = re.compile( "\((.*)\)" ).search(A).group(1)

print A.replace("[{0}]".format(site), "").replace("({0})".format(url), '{1}'.format(url, site))

Output:
Thsi is my site you can watch it.

Update as request in Comments:
s = 'my [site](site.com) is about programing (python language)'
site, url =  s[s.find("[")+1:s.find(")")].split("](")
print s.replace("[{0}]".format(site), "").replace("({0})".format(url), '{1}'.format(url, site))

Output:
my site is about programing (python language)

A: I'm not a markdown expert, but if this is indeed markdown that you're trying to replace, and not your own syntax, you should use an appropriate parser. Note that, if you paste your string directly into stackoverflow - which also uses markdown - it will be transformed into a link, so it would clearly be valid markdown.
If it is indeed your own format, however, try the following to transform
'This is my [site](http://example.com/url) you can watch it.'

into
'This is my site you can watch it.'

using the following match:
\[(.*?)\]\((.*?)\)

and the following replacement regex:
\\1<\/a>

In python, re.sub(match, replace, stringThatYouWantToReplaceStuffIn) should do the trick. Don't forget to assign the return value of re.sub to whatever variable should contain the new string.


text:
Q: Do the bigger maps still have only 10 buildings? Since v1.2, some towns have a 25*25grid, in stead of the old 12*12.
did the amount of buildings go up in these big maps or is it harder to find buildings?

A: Posts on the hero forums have confirmed that larger maps can have more buildings.  No confirmed report of the exact numbers but some people have reported up to 27x27 maps, and 15+ buildings.


text:
Q: Angular, object property lost after assignment I'm trying to set an new property to an object with Angular. I can see that the property is set with the right value, but when I want to save it with another function, the property is gone.
This is what I have so far:
$scope.confirmTask = function(taskId, taskString){
   campaignTaskCompleted(taskId, $scope.campaign._id).then(function(task){
      //Here completed == true
      console.log("task", task);
      $scope.saveSocialPortal();
   })
}

function campaignTaskCompleted(taskId, campaignId){
    return new Promise(function(resolve){
       for(var c =0; c < $scope.user.socialPortal.campaigns.length; c++){
          if($scope.user.socialPortal.campaigns[c]._id == campaignId){
             for(var i=0; i < $scope.user.socialPortal.campaigns[c].tasks.length; i++){
                if($scope.campaign.tasks[i]._id == taskId){
                   $scope.campaign.tasks[i].completed = true;
                   resolve($scope.campaign.tasks[i]);
                }
             }
          }
       }
   })
}

$scope.saveSocialPortal = function(){
   //here completed is completely gone
   console.log("save", $scope.user.socialPortal.campaigns[0].tasks);
   $api.put('user-social-portal', {socialPortal: $scope.user.socialPortal})
   .then(function(response) {

   })
   .catch(function(reason) {
       console.log(reason);
   })
}

What is the reason for this? What can I do to solve this?
Edit:
I was confusing different variables ($scope.campaign and $scope.user.socialPortal.campaigns) so some things are going wrong from the beginning on this page.
I completely rewrote the code to always use $scope.user.socialPortal, and that is working.

A: Maybe I'm reading your code wrong. But it seems you set the new completed property to true only on $scope.campaign.tasks[i] not on the $scope.user.socialPortal.campaigns[0]. Maybe they should be pointing to the same object? It's not clear if they do.
Wouldn't you at least need to somehow push the completed campaign into the $scope.user.socialPortal.campaigns array?


text:
Q: A rod lies on a smooth surface and a ball hits it at one end and gets stuck to it I know how to solve these kind of questions but here since it is an inelastic collision I have some doubts. I checked the solution where they conserved linear momentum as: $(M+m)v=mu$ [$v$ is final, $u$ is initial]. My doubt is that shouldn't it be $Mv+m(v+rw)=mu$, where $w$ is the angular velocity of the system and $r$ is the distance of the ball from the center of mass of the system.

A: No, it shouldn't be. For linear momentum, we simply use the mass of the system and the velocity of center of mass of system.


text:
Q: How did Darth Vader plan to approach Hoth?
VADER: The Rebels are alerted to our presence. Admiral Ozzel came out of light-speed too close to the system.
VEERS: He felt surprise was wiser...
VADER: He is as clumsy as he is stupid. General, prepare your troops for a surface attack.

Even if Admiral Ozzel came out of light-speed at an optimal distance from the system, how did they plan to approach (land to capture Luke Skywalker) Hoth without alerting the Rebels?
Also, didn't Darth Vader's ultimate plan to capture Luke Skywalker on Hoth require a surface attack anyway?


text:
Q: IE 10 not setting / sending cookies (from js) to server A while back I switched a large development project from using cookies to using localStorage.
However I've realized that I was a little bit gun-ho and that some of the cookies were actually need on the server.
I have set these back from localStorage to using cookies.
However in the interim I have installed IE10 on my Win7 dev box and also switched my development server from IIS Express to ISS 7.5 running locally.
To allow Fiddler to intercept my local traffic I access the development pages through the URL
http://local_iis/

which is identified in the Hosts file as:
local_iis 127.0.0.1

However IE10 fails to set Cookies when accessing pages from this domain with this test page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        document.cookie = "test=value";
        alert(document.cookie); // gives "" in IE 10
    </script>
</head>
<body>

</body>
</html>

However running my test page from either of the below sets the cookie (and alerts the value)
http://localhost/
http://127.0.0.1/

The cookie gets set and alerted correctly in both FF and Chrome, as I only ever use IE for development and testing I have changed the security settings down to allow everything in both the Privacy tab, and Local Intranet and Trusted Sites zones under the security tab.
I've added local_iis to the trusted sites as well.
Still no cookie being set.
Does anyone know why?

A: According to another topic found here and follow up of mentioned MS blog there this happens because you have underscore in the name of your machine! Wicked, huh?
See this:
Q5: IE won't set a cookie when the hostname/domain contains an underscore?
A: Correct. Technically, underscore is not a DNS character, and while Windows will let you use an underscore when naming your machine, it warns you that doing so may cause problems. One such problem is that WinINET blocks attempts to set cookies on such domains.


text:
Q: Application Signature for 2 days in android I wanted add application signature for some application, which will be valid only for 1 or 2 days. I did enough googling but did not find enough info. So Please let me know how can i make a application get expired in 2 days..

A: simply add an alarm of calculating time equals to 2 days at the very first start of the app.When the alarm gets expired you will get the callback and set a global flag as false.Code in your app that if that flag is false, display a lock screen

A: You could save the first start time in SharedPreferences and then on each start compare the current time with the saved one. If the 2 days have passed, you can do what ever action you want.
It will probably not be possible to automatically remove the app from the device though.

A: If your app sends data to a server, you should store the "first run time" there. Storing it locally on the phone (for example SharedPreferences) is not very safe as it's easily overcome by changing the phone's time settings.


text:
Q: How can i have one image with multiple products? I'm developing a website for jewelry, so basically in one image a model is showing 3 products (earnings, a ring and a neckless). When a client clicks on the image, it basically has to show the list of 3 products and its prices. How can i do it?

A: I think what your looking for is a group product. A group product is essentially a product page in which you can show multiple child products and have them be added to the cart depending on the quantity entered for each one.
If you need a hand setting one up I would recommend taking a look at the new user guide


text:
Q: Issue on Rendering List in Grid in C# I am trying to render a simple List into a Grid like
var sr = new BindingSource();
sr.DataSource = str;
dataGridView1.DataSource = sr;

I am not getting any error but not able to display the list in Grid. Here is the entire code
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Enum
{
    public enum Sex {Male, Female, Other };
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<Sex> str = new List<Sex>();
            str.Add(Sex.Female);
            str.Add(Sex.Male);

            var sr = new BindingSource();
            sr.DataSource = str;
            dataGridView1.DataSource = sr;
        }
    }
}

A: public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public class Person
    {
        public string Name { get; set; }
        public string Lastname { get; set; }
        public Sex Sex { get; set; }
    }

    public enum Sex { Male, Female, Other };

    private void button1_Click(object sender, EventArgs e)
    {
        BindingList<Person> persons = new BindingList<Person>();

        persons.Add(new Person() { Name = "Joe", Lastname = "Doe" , Sex = Sex.Male});
        persons.Add(new Person() { Name = "Nancy", Lastname = "Foo" , Sex = Sex.Female});

        dataGridView1.DataSource = persons;
    }
}

A: I don't think you can bind an enum to GridView. This is what I could get working
public class Person
{
    public Sex Gender { get; set; }
}

You need to use BindingList as list does not implement IBindingList
var list = new List<Person>()
{
    new Person { Gender = Sex.Male, },
    new Person { Gender = Sex.Female, },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
dataGridView1.DataSource = source;

A: DataGridView cannot bind to a list of primitive values (like int, decimal, DateTime, enum, string etc.) because it requires a list containing objects with properties.
The easiest way is to use LINQ projection to an anonymous type with single property like this (BindingSource is not needed at all):
private void button1_Click(object sender, EventArgs e)
{
    List<Sex> str = new List<Sex>();
    str.Add(Sex.Female);
    str.Add(Sex.Male);

    dataGridView1.DataSource = str.Select(value => new { Sex = value }).ToList();
}


text:
Q: Reading Json string from a JsonObject in android I am having problems; I cannot read inner string from a jsonObject. It says JsonArray cannot be converted into JsonObject.
07-26 13:01:31.910 1798-1901/com.example.phuluso.aafs I/System.out: [{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]

Here's my JsonArray.  I am trying to read from AccommoAddress, but I get the  error below:
[{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]

Here's my code
    @Override
    protected void onPostExecute(String result) {

        progressDialog.dismiss();
        List<AccommoNearAPK> data = new ArrayList<>();
        progressDialog.dismiss();

        JSONObject jsonResponse = null;

        try
        {
            jsonResponse = new JSONObject(result);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");

            /*********** Process each JSON Node ************/

            int lengthJsonArr = jsonMainNode.length();

            for(int i=0; i < lengthJsonArr; i++)
            {
                /****** Get Object for each JSON node.***********/
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                /******* Fetch node values **********/
                String name       = jsonChildNode.optString("Street");
                String number     = jsonChildNode.optString("City");
                String date_added = jsonChildNode.optString("Longitude");
                String lat = jsonChildNode.optString("Lattitude");

                System.out.print("Street"+ name + "City" +number+ "Long" + date_added+" Lat" + lat);

                Toast.makeText(MapsActivity.this, date_added + name + number + lat, Toast.LENGTH_LONG).show();

            }

        } catch (JSONException e) {
            Toast.makeText(MapsActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        }
    }
}

A: "AccommoAddress" is a JSONObject not a JSONArray. So instead of this..
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");

Try this ..
/*String Accommo = jsonResponse.getString("AccommoAddress");
JSONObject AccomoAddress = new JSONObject(Accommo);*/
//simplifying the above code
JSONObject Accomoaddress = jsonResponse.optJSONObject("AccomoAddress");
String name = AccomoAddress.getString("Street");
String number = AccomoAddress.getString("City");
String date_added = AccomoAddress.getString("Longitude");
String lat = AccomoAddress.getString("Lattitude");

A: Your response is a JSONArray, not a JSONObject, similarly, AccommoAddress is a JSONObject, not a JSONArray. So you need to change the lines near the top to the following:
 JSONArray jsonResponse = null;

 try
 {
     jsonResponse = new JSONArray(result);
     JSONObject jsonMainNode = jsonResponse.optJSONObject("AccommoAddress");


text:
Q: Is the top Stiefel-Whitney number of a topological manifold the Euler characteristic mod two? Recall that the Stiefel-Whitney classes of a smooth manifold are defined to be those of its tangent bundle - this definition doesn't extend to topological manifolds as they don't have a tangent bundle. Wu's theorem states that for a closed smooth manifold, $w = \operatorname{Sq}(\nu)$. The expression $\operatorname{Sq}(\nu)$ makes sense for a closed topological manifold and therefore serves as a definition for the Stiefel-Whitney classes on such a manifold.
Recall that if $M$ is a closed smooth $n$-dimensional manifold, then $w_n(M)$ is equal to the mod $2$ reduction of $e(M)$, see Corollary 11.12 of Milnor and Stasheff's Characteristic Classes. In particular, the Stiefel-Whitney number $\langle w_n(M), [M]\rangle$ is the mod $2$ reduction of the Euler characteristic. Is this still true for closed topological manifolds?

Let $M$ be a closed topological $n$-dimensional manifold. If $w_n(M)$ is the top Stiefel-Whitney class of $M$, as defined above, is the Stiefel-Whitney number $\langle w_n(M), [M]\rangle$ the mod $2$ reduction of $\chi(M)$?

A: Elaborating on Mark's comment, associated to a manifold of type CAT=PL,DIFF,TOP or a menagerie of others we have a $\mathbb{R}^n$ bundle with structure group $CAT$. In all these cases, we can form the fiberwise one point compactification, and then identify these to get the Thom space. The normal proof of the Thom isomorphism goes through with the obvious notion of orientability of these bundles.
Recall that to define Stiefel-Whitney classes for a vector bundle, we only use Steenrod operations and the mod 2 Thom isomorphism. Since every disk bundle is oriented mod 2, we can use the exact same definition. As well, if we have an integrally oriented disk bundle we can use the exact same definition of Euler class, as a pullback of the Thom class by the zero section.
An oriented CAT manifold is easily seen to have an integrally oriented $\mathbb{R}^n$ bundle, so we have an Euler class. By picking a section of the disk bundle with isolated singularities (where it hits the zero section), we may mimic the proof in the DIFF case since the total index of the section of the disk bundle is the Euler characteristic of the manifold. This means the Euler class evaluates on the fundamental class to the Euler characteristic.
Then the same proof as the DIFF case shows that the CAT Stiefel-Whitney class is the mod 2 reduction of the CAT Euler class. And, again, the same proof as in the DIFF case shows that Stiefel-Whitney classes can be defined via your formula with the Wu classes, so this definition agrees with yours.

A: As you say, we define $w_n = \sum \text{Sq}^i \nu_{n - i}$, where $\nu_{n-i}$ is the Wu class, the class such that $\nu_{n-i} \cup c = \text{Sq}^{n-i} c$ for $c \in H^{i}$. So as a corollary we have $\text{Sq}^i \nu_{n - i} = \nu_i \cup \nu_{n-i}$.
Because $\nu_j$ vanishes for $j > n/2$, the sum over $i$ is only the term $\nu_{n/2}^2$ when $n$ is even, and $0$ when $n$ is odd. As the Euler characteristic of an odd-dimensional closed manifold vanishes, this gives the odd-dimensional case.
Now when $n = 2k$, using Poincare duality mod 2 we see that $\chi(M) = \text{rk } H^k(M;\Bbb Z/2) \pmod 2.$ So the claim is that $\langle \nu_k^2, [M] \rangle = \text{rk } H^k(M;\Bbb Z/2) \pmod 2.$
This is because $\nu_k$ is a characteristic vector for the symmetric bilinear cup-product form on $H^k(M;\Bbb Z/2)$; in fact, for any 'characteristic vector' $y$ for a nondegenerate symmetric bilinear form over a $\Bbb Z/2$-vector space $V$, meaning that $y \cdot x = x^2$ for all $x$, we have $\text{rk } V = y^2 \pmod 2$.
The most obvious way for me to see this is to classify nondegenerate symmetric bilinear forms over $\Bbb Z/2$ vector spaces: they are all sums of copies of $\begin{pmatrix}1\end{pmatrix}$ and $\begin{pmatrix}0 & 1 \\ 1 & 0\end{pmatrix}$, for which the respective characteristic vectors are $(1)$ and $(0,0)$.

A: It has been proved in the preprint (page 6) by Renee Hoekzema that the vanishing of the $w_{n}(M)$ implies $\chi(M)$ is even. The proof uses the fact that a symplectic vector space over $\mathbb{F}_{2}$ has even dimension. It is quite similar to the one Mike Miller given here without the induction procedure.
The author suggests there is a more direct proof generalizing the one from Milnor-Stasheff without using the Euler class. I am not sure it might be. The paper actually proved much more and I found it really interesting.


text:
Q: How can I use "documentation" from the Android app? I see no way to access documentation from the Android app.

A: You can't. The Documentation feature is only available from the website. There isn't a mobile view either.
You can post a feature request, but I don't think it is of much use at this moment. Let's find out how to use Documentation correctly first.


text:
Q: Understanding example code of ambiguity resolution The following codes are quoted from C++11 standard N3485 Section 6.8.3 about ambiguity resolution:
struct T1 {
   T1 operator()(int x)
   {
        return T1(x);
   }
   int operator=(int x)
   {
       return x;
   }
   T1(int) { }
};
struct T2
{
    T2(int){ }
};

int a, (*(*b)(T2))(int), c, d;

void f() {
    // disambiguation requires this to be parsed as a declaration:
    T1(a) = 3,
    T2(4),                   // T2 will be declared as
    (*(*b)(T2(c)))(int(d)); // a variable of type T1
                            // but this will not allow
                            // the last part of the
                            // declaration to parse
                            // properly since it depends
                            // on T2 being a type-name
}

I have no idea about how to parse this code:
 T1(a) = 3,
        T2(4),
        (*(*b)(T2(c)))(int(d));

What does it mean in this case? Could you explain it to me? This example code seems rather obscure to me.
Thank you very much.

A: It means that when something can be parsed as a declaration, it should be parsed as a declaration. In this case,
T1(a) = 3

Is a valid declaration, and it declares an object a of type T1, initialized from the value 3 (rather than constructing a temporary of type T1 initialized from a, then assigning 3 to that temporary). This is, in fact, equivalent to the following:
T1 a = 3

Now the remaining declarators:
T2(4)

Here T2 is the name of an object of type T1 initialized from the value 4, as in:
T1 a = 3, T2(4)

So T2 is the name of the object, not of a type, similarly to the case below:
int x = 42, y(1729)

Where x is an object of type int initialized from 42, and y is another object of type int initialized from the value 1729.
Then the last declarator cannot be parsed correctly, because T2 is not the name of a type, but the name of an object.


text:
Q: Cómo usar mariadb por fuera de un XAMPP y acceder desde ese phpMyAdmin? quería consultar lo siguiente: si instalo mariaDB mediante
brew install mariadb
me permitirá acceder por phpmyadmin? ya que tengo Xammp en mi Mac y al ajecutar el apache y apagar el mysql de xampp no tengo acceso a phpmyadmin,
me ayudarian si me brindan un manual de como instalar mariadb y como tener el entorno de phpmyadmin. no estoy seguro si es posible cuando se ejecute el xampp, espero me ayuden.

A: La cosa es que, hasta donde me da la memoria, phpMyAdmin crea sus propias tablas en una BD en ese mysql. Apagar la BD hace que no haya acceso a los datos de configuración de phpMyAdmin y tal.
No sé si sea tan transparente (porque no sé qué versión de mysql y de mariadb tienes), pero podríás resolver haciendo algo como:

*detener el mariadb, iniciar el mysql del xampp

*en la carpeta xampp/mysql/data copia la subcarpeta phpmyadmin adentro de la carpeta data en mariadb. Busca esta carpeta origen prendiendo el mysql, entrando a phpmyadmin y ejecutando SELECT @@datadir`
1.5) Detener el mysql del xampp

*En el archivo xampp/phpadmin/config.inc.php (líneas aproximadas) edita lo siguiente:
line 21 ajusta la clave
lines 31-32 ajusta el usuario

*reiniciar xampp y confirmartque el mysql del xampp está detenido

*iniciar mariadb
Por favor, haz backup de todo antes de mover cosas. Esto puede dañar tu instalación de xampp.


text:
Q: Scaling Literate Programming? Greetings.
I have been looking at Literate Programming a bit now, and I do like the idea behind it: you basically write a little paper about your code and write down as much of the design decisions, the code probably surrounding the module, the inner workins of the module, assumptions and conclusions resulting from the design decisions, potential extension, all this can be written down in a nice way using tex. Granted, the first point: it is documentation. It must be kept up-to-date, but that should not be that bad, because your change should have a justification and you can write that down.
However, how does Literate Programming Scale to a larger degree? Overall, Literate Programming is still just text. Very human readable text, of course, but still text, and thus, it is hard to follow large systems. For example, I reworked large parts of my compiler to use >> and some magic to chain compile steps together, because some "x.register_follower(y); y.register_follower(z); y.register_follower(a);..." got really unwieldy, and changing that to x >> y >> z >> a made it a bit better, even though this is at its breaking point, too.
So, how does Literate Programming scale to larger systems? Does anyone try to do that?
My thought would be to use LP to specify components that communicate with each other using event streams and chain all of these together using a subset of graphviz. This would be a fairly natural extension to LP, as you can extract a documentation -- a dataflow diagram -- from the net and also generate code from it really well. What do you think of it?
-- Tetha.

A: The book "Physically Based Rendering" (pbrt.org) is the best example of large-scale literate programming that I'm aware of. The book implements a complete rendering system, and both the book text and the raytracer code are generated from the same "source".
In practice, I've found that just using a system like Doxygen and really digging in and making use of all of its features is better than full-blown "literate" programming, except for things like this, i.e. textbooks, educational materials.

A: Excellent question. The motivation for literate programming will never go away, but I think it should be treated as fluid. It means "give the reader a break, and educate them to what you're trying to do". I don't think it means "make your code really wordy".
That said, the reader will have to put some effort into it, depending on what they already know. Presumably the code is worth understanding, and nothing comes for free.
I also think it means more than just making readable code. Most likely the reason someone is reading the code is because they need to make a change. You should anticipate the possible changes that might be needed, and tell them how to do it if necessary.

A: I did some literate programming with WEB some 15 years ago. More recently I tried extracting code from a wiki and generating documentation from a Squeak Smalltalk environment.
The bottom-up part can be handled relatively well by generating documents from TDD/BDD frameworks, but LP focuses on explaining the code to the reader.
There are a few issues:

*

*the story to tell is different for different stakeholders/readers;

*the project structure in most environments is not the structure needed for story-telling;

*support for successive refinement/disclosure is missing;

*in addition to text support for pictures is needed;

*from the comments in the source control system one can derive how the system was build.
The story should be how the system could have been build (with perfect hindsight).

For LP to work for larger systems, you need better IDE support than a wiki or an object browser.

A:
"Overall, Literate Programming is
  still just text"

False.
Diagrams are fine.

My thought would be to use LP to specify components that communicate with each other using event streams

That's just architecture, and that's fine.

you can extract a documentation -- a dataflow diagram -- from the net and also generate code from it really well. What do you think of it?

Data flow diagrams aren't really all that helpful for generating detailed code.  They're a handy summary, not a precise source of information.
A good writing tool (like LaTex) can encode the diagram in the document.  You could probably figure a way to the diagram from other parts of the documentation.
Bottom Line
In the long run, you're better off generating the diagram as a summary of the text.
Why?
Diagrams intentionally elide details.  A diagram is a summary or an overview.  But as a source for code, diagrams are terrible.  In order to provide all the details, the diagrams become very cluttered.
But a diagrammatic summary of some other LP markup will work out fine.

A: pbrt is a physically based ray tracer written in the literate style for the education of computer science graduates (and me), it is a moderately large scale system. As a non-specialist programmer this level of documentation is pretty essential for understanding what the program does and why it does it.
I also have access to a research-renderer, in Java, which is well-written but relatively undocumented but for a few SIGGRAPH papers. This is also relatively understandable, but I have access to the authors too.
I've also used ImageJ quite a lot, and looked under the hood at underlying Java - it's pretty difficult to follow without an idea of the underlying philosophy.
In sum, my view is that literate programming is great if someone can find the time to do it well and this is likely to be in educational settings. It's difficult to see it being done in commercial code production. I'm skeptical of the idea that code can be entirely self-documenting.

A: The idea behind literate programming is emphasis on the documentation, with code sprinkled through the documentation, rather than comments sprinkled through code.
This is an essentially different philosophy, and differences like longer variable names, namespaces, and classes don't affect the philosophy. Literate programming advocates meaningful variable names.
It scales up to larger systems, because the basic ratio of documentation to code scales linearly with the size of code.

A: 12.5 years later, there are finally some promising developments. GToolkit provides the integrated multiple views, entry points, and tools to do literate programming well.

A: Literate Programming was developed in an era where long variable and function names were simply not possible.  Because of this, code really wasn't that readable.
Obviously, a lot has happened since then.
In today's world, the code itself is the documentation, hence the term "self documenting code."  The realization is that no set of comments or external documentation can ever stay in sync with the underlying code.  So, the goal of a lot of today's programmers is to write the code in such a way that it is readable to others.

A: Try NanoLP - LP extensible tool, supports many document formats (Markdown, OpenOffice, Creole, TeX, Asciidoc and other), importing of another LP programs, templating and more. User can add own commands/macros (in Python), for example to do special importing, for example, from VCS...
http://code.google.com/p/nano-lp


text:
Q: "Separated" Chrome.storage for every tab So I have this situation where via content script I get data from DOM of web page. I need to pass this data to popup page of browser action extension.
It works well but chrome.storage variables are shared so I have same data everywhere.
For example: Let's have a script which gets URL after '/'. So from google.com/one on first tab and google.com/two on second, my extension gets only 'two'. My point is I need to separate these storage spaces for every tab or find another way to solve this.


text:
Q: how to handle flutter_countdown_timer pakage in flutter? I am using the package flutter_countdown_timer but I get this default message when the time is up: The current time a expired
              CountdownTimer(
                endTime: endTime,
                onEnd: fetchMainInfo,
              ),

and i define this function String fetchMainInfo , But I do not receive this message and I receive the default message The current time a expired of the package
  String fetchMainInfo() {
  return "example";
}


text:
Q: How does transitive dependencies for Microsoft.NETCore.App and Microsoft.NETCore.Platforms work I have a really hard time figuring out how version resolving of transitive dependencies works for the framework "metapackages".
The reason I am asking is that it seems to be each time we pull in an "old" dependency, for instance something that points to netstandard2.0 or 2.1 we end up with a long list of outdated packages (which again is reported by our build pipeline).
As an example:
Given a .net6 class library, created like this:
dotnet new classlib
dotnet add pakage System.Data.SqlClient

The resulting csproj looks like:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
  </ItemGroup>

</Project>

That seems like its fine. I have the latest SqlClient and im on .net6 \o/
Now when i execute dotnet list package --outdated --include-transitive
I get the following output:
Project `Outdated` has the following updates to its packages
   [net6.0]:
   Transitive Package                       Resolved   Latest
   > Microsoft.NETCore.Platforms            3.1.0      6.0.3
   > Microsoft.Win32.Registry               4.7.0      5.0.0
   > System.Security.AccessControl          4.7.0      6.0.0
   > System.Security.Principal.Windows      4.7.0      5.0.0

As far as I can tell Microsoft.Win32.Registry is part of the "shared framework" and would have expected it to use the latest version.
Can anyone explain why it does not use the latest version?
Alternatively how I can force dotnet to use the latest version without a direct dependency (if its possible - again i am trying to avoid a LONG list of outdated transient dependencies that exists in the shared framework...).

A: Going through various NuGet/dotnet Github issues and discussions.
It seems like the way NuGet restores dependencies is to blame. It defaults to the lowest version satisfying all requirements.
The "meta" packages are in fact not tied to the SDK version but have direct dependencies on other packages, such as the Microsoft.NETCore.App which targets Microsoft.NETCore.Platforms as version 2.2.4 or higher.
Since System.Data.SqlClient is a .NET Core 3.1 package, it refers Microsoft.NETCore.Platforms version 3.1.0 (or higher).
Since my project does not have a direct dependency on Microsoft.NETCore.Platforms well, NuGet chooses the lowest one.
I still really do not understand why the SDK reference does not cause a direct dependency, but I guess that reasoning have drowned in some GitHub issue discussion.
The following contains a description of the resolution strategy: https://learn.microsoft.com/en-us/nuget/concepts/dependency-resolution#dependency-resolution-rules
Long story short - Its currently only possible to get the latest versions with a long list of specific dependencies.
Edit
Maybe a variation is using Central Package Management: https://devblogs.microsoft.com/nuget/introducing-central-package-management/


text:
Q: Android (Kotlin) code coverage anomalies Code coverage (Jacoco) in Android connected tests is a very useful way to determine what methods/functions need some TLC. Now that I am switching to Kotlin over Java I have discovered some anomalies that I cannot explain, as this screen shot illustrates:

The methods starting with _$... are internal to Kotlin or Android, I strongly suspect. My questions are: 1) does anyone have any insight into why these methods are included in the Jacoco code coverage report, and 2) is there a way to exclude them?

A: Those methods are added when using the synthetic properties via Kotlin Android Extensions. Each Kotlin Activity using synthetic properties will have those methods added.

Kotlin Android Extensions is a plugin for the Kotlin compiler, and it does two things:
Adds a hidden caching function and a field inside each Kotlin Activity. The method is pretty small so it doesn't increase the size of APK much.
Replaces each synthetic property call with a function call.

Explanation on the official docs:
https://kotlinlang.org/docs/tutorials/android-plugin.html#under-the-hood
This articles does a pretty good job going into detail:
https://antonioleiva.com/kotlin-android-extensions/

A: In large part due to the answer from @triad, I was able to come up with a solution that is a work-around to what appears to be a Kotlin bug.  The work-around was documented in the Antonio Leiva post referenced by @triad.  In a nutshell the solution was to turn off caching in MainActivity. The complete solution is up on GitHub.
What I do not completely understand is the cost of this solution so I will hold off checking this answer in the hopes that a better solution is provided.


text:
Q: Windows Dual NIC - Will this setup cause an ip address conflict?
My company has three subnets total of which two subnets have the same set of ip addresses...  192.168.0.x.  This has not been an issue before but we are going to establish a VPN connection between two routers.  So now my network will look like the above diagram.
Client A is a standard windows desktop box with two nics installed.  Windows default settings.  No bridging.  Here is how I would like each machine to function...
Client A --> 192.168.0.70 --> Client C
Client B --> 192.168.0.70 --> Client D
My understanding is that by default windows routes outgoing traffic according to each NIC's ip address.  If so after I establish the VPN the routing should be functioning as descried correct?  If not what can I do to get that functionality?
P.S.
I do realize the ideal thing to do would be changing one of my 192.168.0.x subnets to something else.  For reasons outside my control this is not an option.

A: This is a bad idea.
Ok, that being said, as long as Client D will never, ever need to get to anythng on Client C or it's subnet this might work. Client A should have it's default gateway set on the NIC in the 192.168.111.0 subnet, and the NIC on the 192.168.0.0 subnet MUST NOT HAVE a default gateway set.  Or your packets will be very confused as to where to go.
I cannot stress enough how bad of an idea this is.  Especially if there is going to be more than one machine configured like Client A.


text:
Q: Почему выражение при аннотации переходит в group by в Django ORM делаю запрос,
result = (clients
          .values_list(Sum('summa') / kek)
          )

Результат:
ProgrammingError: (1111, 'Invalid use of group function')

А сам sql выход такой:
SELECT
    (
    SUM( `crm_orderhistory`.`summa` ) / COUNT( DISTINCT `crm_orderhistory`.`order_date`, `crm_orderhistory`.`client_id` )) AS `combinedexpression1`
FROM
    `crm_orderhistory`
WHERE
    ( `crm_orderhistory`.`order_date` >= "2022-01-18" AND `crm_orderhistory`.`order_date` <= "2023-01-20" )
GROUP BY
    EXTRACT( MONTH FROM `crm_orderhistory`.`order_date` ),
    COUNT(
    DISTINCT `crm_orderhistory`.`order_date`,
    `crm_orderhistory`.`client_id`)

Сюда зачем-то в GROUP BY падает то, что должно быть ТОЛЬКО в SELECT
вот clients
SELECT
    EXTRACT( MONTH FROM `crm_orderhistory`.`order_date` ) AS `month`
FROM
    `crm_orderhistory`
WHERE
    ( `crm_orderhistory`.`order_date` >= "2022-01-18" AND `crm_orderhistory`.`order_date` <= "2023-01-20" )
ORDER BY
    `crm_orderhistory`.`order_date` DESC

В clients не показывается GROUP BY который с order_date идет, но это неважно, главный вопрос, почему то что пошло в SELECT пошло и в GROUP BY, я про COUNT
переменная kek это самописаня функция для sql, вот её код:
class CustomCount(Func):
    function = 'COUNT'
    arg_joiner = ', '
    template = "%(function)s(DISTINCT %(expressions)s)"
    output_field = IntegerField()

Вот весь код представленный выше, только без обрезок:
class CustomCount(Func):
    function = 'COUNT'
    arg_joiner = ', '
    template = "%(function)s(DISTINCT %(expressions)s)"
    output_field = IntegerField()

@handle_data_for_chart
def get_average_receipt(clients: QuerySet[OrderHistory]):

    kek = CustomCount('order_date', 'client')

    result = (clients
              .values_list(Sum('summa') / kek)
              )

    return result

Декоратор handle_data_for_chart обрабатывает предварительно данные, кинул их они получаются в ссылке client но это тоже не важно.
Главный вопрос продублирую:

главный вопрос, почему то что пошло в SELECT пошло и в GROUP BY, я
про COUNT


text:
Q: Porter and Lancaster stemming clarification I am doing stemming using Porter and Lancaster and I find these observations:
Input: replied
Porter: repli
Lancaster: reply

Input:  twice
porter:  twice
lancaster:  twic

Input:  came
porter:  came
lancaster:  cam

Input:  In
porter:  In
lancaster:  in

My question are:

*

*Lancaster was supposed to be "aggressive" stemmer but it worked properly with replied. Why?

*The word In remained the same in Porter with uppercase In, Why?

*Notice that the Lancaster is removing words ending with e, Why?

I am not able to understand these concepts. Could you please help?

A: Q: Lancaster was supposed to be "aggressive" stemmer but it worked properly with replied. Why?
It's because Lancaster stemmer implementation is improved in https://github.com/nltk/nltk/pull/1654
If we take a look at https://github.com/nltk/nltk/blob/develop/nltk/stem/lancaster.py#L62, there's a suffix rule, to change -ied > -y
default_rule_tuple = (
    "ai*2.",   # -ia > -   if intact
    "a*1.",    # -a > -    if intact
    "bb1.",    # -bb > -b
    "city3s.", # -ytic > -ys
    "ci2>",    # -ic > -
    "cn1t>",   # -nc > -nt
    "dd1.",    # -dd > -d
    "dei3y>",  # -ied > -y
    ...)

The feature allows users to input new rules and if no additional rules are added, then it'll use the self.default_rule_tuple in parseRules where the rule_tuple will be applied https://github.com/nltk/nltk/blob/develop/nltk/stem/lancaster.py#L196
def parseRules(self, rule_tuple=None):
    """Validate the set of rules used in this stemmer.
    If this function is called as an individual method, without using stem
    method, rule_tuple argument will be compiled into self.rule_dictionary.
    If this function is called within stem, self._rule_tuple will be used.
    """
    # If there is no argument for the function, use class' own rule tuple.
    rule_tuple = rule_tuple if rule_tuple else self._rule_tuple
    valid_rule = re.compile("^[a-z]+\*?\d[a-z]*[>\.]?$")
    # Empty any old rules from the rule set before adding new ones
    self.rule_dictionary = {}

    for rule in rule_tuple:
        if not valid_rule.match(rule):
            raise ValueError("The rule {0} is invalid".format(rule))
        first_letter = rule[0:1]
        if first_letter in self.rule_dictionary:
            self.rule_dictionary[first_letter].append(rule)
        else:
            self.rule_dictionary[first_letter] = [rule]

The default_rule_tuple actually comes from the whoosh implementation of the paice-husk stemmer which aka as the Lancaster stemmer https://github.com/nltk/nltk/pull/1661 =)
Q: The word In remained the same in Porter with uppercase In, Why?
This is super interesting! And most probably a bug.
>>> from nltk.stem import PorterStemmer
>>> porter = PorterStemmer()
>>> porter.stem('In')
'In'

If we look at the code, the first thing that PorterStemmer.stem() does it to lowercase, https://github.com/nltk/nltk/blob/develop/nltk/stem/porter.py#L651
def stem(self, word):
    stem = word.lower()

    if self.mode == self.NLTK_EXTENSIONS and word in self.pool:
        return self.pool[word]

    if self.mode != self.ORIGINAL_ALGORITHM and len(word) <= 2:
        # With this line, strings of length 1 or 2 don't go through
        # the stemming process, although no mention is made of this
        # in the published algorithm.
        return word

    stem = self._step1a(stem)
    stem = self._step1b(stem)
    stem = self._step1c(stem)
    stem = self._step2(stem)
    stem = self._step3(stem)
    stem = self._step4(stem)
    stem = self._step5a(stem)
    stem = self._step5b(stem)

    return stem

But if we look at the code, everything else returns the stem, which is lowercased but there are two if clauses that returns some form of the original word that hasn't been lowercased!!!
if self.mode == self.NLTK_EXTENSIONS and word in self.pool:
    return self.pool[word]

if self.mode != self.ORIGINAL_ALGORITHM and len(word) <= 2:
    # With this line, strings of length 1 or 2 don't go through
    # the stemming process, although no mention is made of this
    # in the published algorithm.
    return word

The first if clause checks if the word is inside the self.pool which contains the irregular words and their stems.
The second checks if the len(word) <= 2, then return it's original form, which in the case of "In" the 2nd if clause returns True, thus the  original non-lowercased form returned.
Q: Notice that the Lancaster is removing words ending with e in "came", Why?
Not surprisingly also coming from the default_rule_tuple
https://github.com/nltk/nltk/blob/develop/nltk/stem/lancaster.py#L67, there's a rule that changes -e > - =)
Q: How do I disable the -e > - rule from default_rule_tuple?
(Un-)fortunately, the LancasterStemmer._rule_tuple object is an immutable tuple, so we can't simply remove one item from it, but we can override it =)
>>> from nltk.stem import LancasterStemmer
>>> lancaster = LancasterStemmer()
>>> lancaster.stem('came')
'cam'

# Create a new stemmer object to refresh the cache.
>>> lancaster = LancasterStemmer()
>>> temp_rule_list = list(lancaster._rule_tuple)
# Find the 'e1>' rule.
>>> lancaster._rule_tuple.index('e1>')
12

# Create a temporary rule list from the tuple.
>>> temp_rule_list = list(lancaster._rule_tuple)
# Remove the rule.
>>> temp_rule_list.pop(12)
'e1>'
# Override the `._rule_tuple` variable.
>>> lancaster._rule_tuple = tuple(temp_rule_list)

# Et voila!
>>> lancaster.stem('came')
'came'


text:
Q: Preserve swf transparency on forms vb Is there any way to include a .swf on my form and also preserve its original transparency? That is, so you can see any controls 'behind it' (obviously in the transparent areas). It's looking unlikely as I understand vb can't control the flash activex control (and hence the control's rendered background?) but wondering whether there's any workarounds?
relevant code thusfar:
    Dim flash1 As New AxShockwaveFlash
    .....
    flash1.Location = New System.Drawing.Point(300, 23)
    Me.Controls.Add(flash1)
    flash1.Movie = "C:\Users\Steve\Scripts\Projects\CPWizBiz\Assets\Test SWFs\Artwork4.swf"
    flash1.Size = New System.Drawing.Size(192, 400)
    flash1.Play()

A: In the absence of any other solutions, here's what I did:
Basically, I just created a new form with a transparetn background. You then overlay this onto your main form (you can link any forms to move and resize with each other etc). Then you set the flash background to match the form transparency key and you're done. Brief, illustrative code:
 Public Sub MarqueeFlash_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.TransparencyKey = Color.FromArgb(1, 4, 3)
        Me.BackColor = Color.FromArgb(1, 4, 3)

        dim FlashCtrl as As New AxShockwaveFlash
        Controls.Add(FlashCtrl)
        With FlashCtrl
            .BGColor = Me.BackColor.R.ToString("X2") & Me.BackColor.G.ToString("X2") & Me.BackColor.B.ToString("X2")
            .Movie = IndexedDR(0).Item("File")
            .Location = New Point(10,10)
        End With
        FlashCtrl.Play()
        FlashCtrl.Size = New Size(400,300)
end sub


text:
Q: Volusion template editing .asp code to include additional header graphic I hope someone can help as .asp is new to me and this is giving me a lot of head scratching!
Basically we have an ecommerce Volusion template, in the header we'd like to add a new graphic next to one that already exists, should be easy but some .asp code seems to be hiding elements in the header. I try to explain in the code:
ASP
    $("#content_area").find("table:contains('Home >')").css("display",     "none").html("");

   var a = $(".productnamecolorLARGE").html();
   if (document.location.href.indexOf("help")  == -1) {
      if ($(".productnamecolorLARGE").html() != 'Order Status') {
         if ($.browser.msie) {
            $(".productnamecolorLARGE").html("

" + a + "

");
         } else {
            $(".productnamecolorLARGE").html("

" + a + "

");
         }
      };
    } else {
     $("#content_area").find("img").eq(0).remove();
   }

   $("#lnk1").css("color","#79496a");
        $("#Header_ProductDetail_ProductDetails_span").parent().parent().parent().parent().parent().remove();
   $("#headerTop").find("a").eq(0).html("<ing border=0 src='/v/vspfiles/templates/192/images/view_bag_small.png'>");
   $(".video_container").css("padding", "17px 10px 16px 45px");

HTML

www.domain.com

   View Bag
   About
   My Account

This is what I am trying to do:

    <ing src="newgrahpic.jpg" width="100" height-"50">
   View Bag
   About
   My Account

When making this change the .asp seems to be adding the existing View bag graphic (line 2) against my new (line 1)  and then displays "My Account" to the right of it, whereas My account is hidden with the Display:none; assigned to it before I add the new line.
I appreciate this may sound like a load of nonsense but I hope someone can make some sense of what its doing?!
Thanks in advance for any help.
Rich

A: Actually it's impossible :( sorry to disappoint you. Volusion claims to have simple to use structure, but any changes made to template will not work. Only CSS changes work (due to their weird CMS ASP engine that seems to re-write our custom codes). Here is an article that shares in-depth look at complexity of volusion's templates: http://tech-hive.com/reviews/shopping-carts/volusion-every-themers-nightmare-20100615/#
The real question, is there any other reputable provider that has CML that would allow us to do custom coding? And that's the question I seek answer to.


text:
Q: What does the expression "as bad as it is" mean? What does the expression "as bad as it is" mean? Does it mean on top of that for e.g. as bad something (accident or something like that) is, something similarly bad?

I have been sick all week. As bad as it is, there are exams this weekend.

Or is it similar to "even though", like this expression:

As much as I like you, I don't agree with you on this.

A: In your examples it could be replaced by in spite of or despite.

In spite of the fact that I've been sick all week, there are exams this weekend [that I have to get through].
Despite how much I like you, I don't agree with you on this.

That should make the meaning clearer.

A: "As bad as it is" implies that while you think the situation is bad, it could be worse. At that point you either supply a reason that the situation is actually worse:

As bad as the report is, he now wants to add 5 pages about lint traps.

... or you provide a contrast to show it isn't as bad as it could be:

As bad as the movie is, at least they don't literally jump a shark.

A: It's wrong. It's common parlance now, and has been for 20 or 30 years; but it's still wrong.
These days we say
As bad as it is, it could be a whole lot worse
when we SHOULD say
Bad as it is, it could be a whole lot worse.
We should still say
I may be bad, but I'm not as bad as he is.
It may be too late to correct it now, but that doesn't mean it's right; and if you want to avoid being thought illiterate, do it as above.
(I'm old - 84 - but don't fall into the trap of thinking 'as bad as it is' is a new fashion in speech: it is, and always will be, simply wrong.)


text:
Q: Data Structure in Cassandra Is there a way to read the SSTable in Cassandra? I see from the documentation that sstabledump is an enterprise version, Is it possible to get the trial version of sstabledump?
Or is there a way to read the SSTable using the existing utilities in Cassandra/bin folder?

A: sstabledump is also available in apache cassandra.
It can be found in tools/bin directory in cassandra 3.x
Note: sstable2json was replaced by sstabledump in 3.0

A: You can use sstable2json for that.
http://docs.datastax.com/en/archived/cassandra/2.2/cassandra/tools/toolsSSTable2Json.html
https://www.datastax.com/dev/blog/debugging-sstables-in-3-0-with-sstabledump