text:
Q: Как сделать правильный вывод элементов? Есть код:
from itertools import permutations

n = str(input())
s = list(n)

for l in s:
    perm = permutations(s)

for i in list(perm):
    print(i)

Нужно сделать так,чтобы,допустим,при вводе ABC программа выводила не:
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

а выводила:
ABC
ACB
BAC
BCA
CAB
CBA

A: Склеить в строку элементы списка, кортежа или другой коллекции можно легко:
print(''.join(i))

P.S. А вообще весь ваш код можно сократить до одной строки, потому что половина преобразований у вас лишние:
from itertools import permutations

print(*map(''.join, permutations(input())), sep='\n')

Вывод при вводе ABC:
ABC
ABC
ACB
BAC
BCA
CAB
CBA

P.P.S. Немного поясню всё же по исходному коду:
from itertools import permutations

n = str(input())     # str лишнее - input() и так выдаёт строку
s = list(n)          # list не нужен, permutations и сам проитерирует строку

for l in s:          # цикл не нужен - вы делаете каждую итерацию одно и то же
    perm = permutations(s)

for i in list(perm): # list не нужен, цикл нормально проитерируется по perm и без него
    print(i)


text:
Q: Redirecting & masking only one specific subdomain with .htaccess I have the following .htaccess that is working perfectly for me. Now, I'm trying to mask just 1 subdomain with its folder. I've got everything set-up on the DNS end and right now when I type in app.domain.com it resolves to www.domain.com/app.
I need it to stay app.domain.com in the URL bar however, not just redirect to the folder.
I've been at this for 2 hours and can't figure it out. Anyone know what I should do?
Here's my .htaccess:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteCond %{HTTP_HOST} !^app.example.com

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

RewriteBase /
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

A: If I understand the issue correctly, a user goes to http://app.example.com, you'd like that user to be redirected to http://app.example.com/app. Is that right? If that is the case, then simply add an alias on your virtual host so that example.com and app.example.com are both valid hostnames for that directory.
Find your httpd-vhosts.conf file or equivalent and configure your virtual host with something to the effect of the following example:
<VirtualHost *>
    DocumentRoot /path/to/site/folder
    ServerName www.example.com
    ServerAlias app.example.com example.com
</VirtualHost>

Here is more information on the ServerAlias directive if you want to research it further.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ServiceStack Registration Feature, what am I missing? I have created a solution to test the Registration feature and managed to get the tables created using the OrmLiteAuthRepository. I followed the few examples and answers here on SO build the service, however I keep getting a NotImplementedException with the following text:
Could not find method named Get(Register) or Any(Register) on Service RegistrationService

Here is the code of my Configure override in my AppHost:
SetConfig(new HostConfig
        {
            HandlerFactoryPath = "api",
            DebugMode = true
        });

        container.Register<IDbConnectionFactory>(
        new OrmLiteConnectionFactory(SqlServerBuildDb, SqlServerDialect.Provider));

        using (var db = container.Resolve<IDbConnectionFactory>().Open())
        {
            db.CreateTableIfNotExists<User>();
        }

        Plugins.Add(new AuthFeature(() => new AuthUserSession(),
            new IAuthProvider[]
            {
                new BasicAuthProvider(), //Sign-in with Basic Auth
                new CredentialsAuthProvider() //HTML Form post of UserName/Password credentials
            }));

        Plugins.Add(new RegistrationFeature());
        container.RegisterAs<CustomRegistrationValidator, IValidator<Register>>();

        Plugins.Add(new ValidationFeature());

        container.Register<IUserAuthRepository>(c =>
                new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
        var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>();
        authRepo.InitSchema();

        //Set MVC to use the same Funq IOC as ServiceStack
        ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));

Any help would be highly appreciated.

A: ServiceStack doesn't expose the Registration Services by default, but they can be added by setting IncludeRegistrationService=true, e.g:
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[]
    {
        new BasicAuthProvider(),      //Sign-in with HTTP Basic Auth
        new CredentialsAuthProvider() //HTML Form post with UserName/Password
    }){
        IncludeRegistrationService = true
    });

Which just registers the RegistrationFeature which you can instead register manually with:
Plugins.Add(new RegistrationFeature());


text:
Q: Highlight exception throwers in IntelliJ IDEA I recently moved from Eclipse to IntelliJ IDEA, and there is a feature that I'm missing. In Eclipse, when you placed the caret on a checked exception, in throws declaration or catch block, it would highlight which method/constructor calls throw that exception.
Is there any way to do this in IntelliJ IDEA (Community edition)?

A: Place the caret on the catch keyword and press Ctrl+Shift+F7.
(Find | Highlight Usages in File). If you are using different keymap and the above shortcut doesn't work, use Help | Find Action to search for this action and see its keyboard shortcut:

If you want it to work automatically, enable Settings | Editor | Highlight usages of element at caret.
The same works on try and throws keywords with a choice of exceptions to highlight.
Here is a screenshot from IntelliJ IDEA Tip of the Day:

Note that there is no way to highlight it by particular exception class until you select this class from the list of suggestions:


text:
Q: Partition of graph into independent sets of consecutive vertices Sorry for my English.
Here is the question:
$G=(v,e)$, undirected graph, $V=\{v_1,v_2,\ldots,v_n\}$. the vertices are organized in sequence from the smaller one to the biggest $v_1,\ldots,v_n$.
We will define a spread distribution $(C_1,\ldots,C_k)$ as follows:

*

*For each $i,j$, $C_i \cap C_j = \emptyset$.

*$\bigcup_{i=1}^k C_i = V$.

*Every $C_i$ consists of consecutive vertices, i.e. $v_{j+1},\ldots,v_{j+d}$.

*The vertices in $C_i$ form an independent set.

I need to find a Greedy Algorithm for this problem in $O(|V|+|E|)$.
I tried many ways, but the main problem for me is to handle the situation where $(v_3,v_4) \notin E$ and $(v_4,v_1) \in E$ (I check in my algorithm only "neighboring" vertices, $v_1-v_2,v_2-v_3,\ldots,v_{n-1}-v_n$).
Any ideas? Thank you!


text:
Q: Selenium - parsing a page takes too long I work with Selenium in Python 2.7. I get that loading a page and similar thing takes far longer than raw requests because it simulates everything including JS etc.
The thing I don't understand is that parsing of already loaded page takes too long.
Everytime when page is loaded, I find all tags meeting some condition (about 30 div tags) and then I put each tag as an attribute to parsing function. For parsing I'm using css_selectors and similar methods like: on.find_element_by_css_selector("div.carrier p").text
As far as I understand, when tha page is loaded, the source code of this page is saved in my RAM or anywhere else so parsing should be done in miliseconds.
EDIT: I bet that parsing the same source code using BeautifulSoup would be more than 10 times faster but I don't understand why.
Do you have any explanation? Thanks

A: These are different tools for different purposes. Selenium is a browser automation tool that has a rich set of techniques to locate elements. BeautifulSoup is an HTML parser. When you find an element with Selenium - this is not an HTML parsing. In other words, driver.find_element_by_id("myid") and soup.find(id="myid") are very different things.
When you ask selenium to find an element, say, using find_element_by_css_selector(), there is an HTTP request being sent to /session/$sessionId/element endpoint by the JSON wire protocol. Then, your selenium python client would receive a response and return you a WebElement instance if everything went without errors. You can think of it as a real-time/dynamic thing, you are getting a real Web Element that is "living" in a browser, you can control and interact with it.
With BeautifulSoup, once you download the page source, there is no network component anymore, no real-time interaction with a page and the element, there is only HTML parsing involved.

In practice, if you are doing web-scraping and you need a real browser to execute javascript and handle AJAX, and you are doing a complex HTML parsing afterwards, it would make sense to get the desired .page_source and feed it to BeautifulSoup, or, even better in terms of speed - lxml.html.
Note that, in cases like this, usually there is no need for the complete HTML source of the page. To make the HTML parsing faster, you can feed an "inner" or "outer" HTML of the page block containing the desired data to the html parser of the choice. For example:
container = driver.find_element_by_id("container").getAttribute("outerHTML")
driver.close()

soup = BeautifulSoup(container, "lxml")


text:
Q: Catchable Fatal Error: Argument 1 passed to I have entity Acteur related to entity Categorieacteur but when I do persist and flush I have this error:

Catchable fatal error: Argument 1 passed to Acteur::setIdcategacteur()
  must be an instance of Categorieacteur, string given, called in
  D:\wamp\www\GestionDesEvenements\Ajout_Acteur.php on line 16 and
  defined in D:\wamp\www\GestionDesEvenements\entity\Acteur.php on line
  342

This is the relation in entity Acteur:
    /**
 * @var \Categorieacteur
 *
 * @ManyToOne(targetEntity="Categorieacteur")
 * @JoinColumns({
 *   @JoinColumn(name="idCategActeur", referencedColumnName="idCategActeur")
 * })
 */
private $idcategacteur;

    /**
 * Set idcategacteur
 *
 * @param \Categorieacteur $idcategacteur
 * @return Acteur
 */
public function setIdcategacteur(\Categorieacteur $idcategacteur = null)
{
    $this->idcategacteur = $idcategacteur;

    return $this;
}

/**
 * Get idcategacteur
 *
 * @return \Categorieacteur
 */
public function getIdcategacteur()
{
    return $this->idcategacteur;
}

and this is the code of persist :
<?php
require_once 'em.php';

$Ac = new Acteur();

$Ac->setMail($_POST['email']);
$Ac->setAdracteur($_POST['AdrAct']);
$Ac->setMotDePasse($_POST['MotDePasse']);
$Ac->setSiteWeb($_POST['SiteWeb']);
$Ac->setLogin($_POST['login']);
$Ac->setEtatacteur($_POST['etat']);

$Ca=new Categorieacteur();
$Ac->setIdcategacteur($_POST['categ']);

$em->persist($Ac);
$em->flush();

and this is the form (the form works fine):
        Catégorie:
        <select name="categ" size="1" id="categ" onChange="AfficherElement();">
        <?php
            require_once 'em.php';

            //print_r($_POST);
            $lc=$em->getRepository('Categorieacteur')->findAll();
            foreach($lc as $c)
            {
                echo "<option value='".$c->getidcatact()."'>".$c->getdesigncat()."</option>";
            }
        ?>

        </select>

?>

A: use
$Ac->setIdcategacteur($em->getRepository('MyBundle:Categorieacteur')->find($_POST['categ']));

instead of
$Ac->setIdcategacteur($_POST['categ']);


text:
Q: Selecting the row from table with equal colum values but newest date I have got a table with rows having the same kundennummer and same artikelnummer but not the same date. I want to delete all rows which do not have the newest date.
I have tried the whole evening with delete and insert.
Now i try to create a new table with this values. Kundennummer,
db0
kundennummer, artikelnummer, date,price
'11002', '00000010', '2013-07-04', 4.20 ''
'11002', '00000010', '2013-07-08', 4.13 ''<-- this as result
'33002', '00000020', '2013-07-04', 1.80 ''
'33002', '00000020', '2013-07-18', 1.60 ''<--and this as result

insert db1 (Kundennummer, Artikelnummer, Date, price)
select Kundennummer, Artikelnummer, max(date) as date, price
from db0
where kundennummer = kundennummer
and artikelnummer = artikelnummer;

The result is only one row.
What is my mistake?

A: You want to add "GROUP BY artikelnummer" so you get values for each article.


text:
Q: How to format old laptop and install CentOS I have an old laptop with Windows 7.
I want to remove everything and install CentOS 7 to turn it into a server.
What I know is that I should format the old OS somehow and get iso image of CentOS and make it as bootable usb to install.
Is this what I should do to make it a linux server?
If I can keep Windows 7, I want to keep it, but how do I have both running in my old laptop?

A: Lambert 's comment (Dedoimedo page) gives you the basics that you need to understand the process of making the Windows partition smaller, and creating a new partition for CentOS in the space newly made available.
As for the process of obtaining the actual system and installing it, then yes, you have it right. To summarize:

*

*Download the appropriate ISO image.

*Either burn it to a blank DVD, or prepare a USB stick from the contents of the ISO.

*Boot the computer from the DVD or USB stick, and follow the installer program's instructions.

Since this may be the first time you do this, I would suggest going with the blank DVD instead of the USB, it may be more simple if the target computer has a DVD drive available to it. Many DVD burning programs are available to do this. Just make sure you are burning the ISO file as a disk image, and not adding it to a new DVD file structure. Look for an option to "burn an image" in the software you use.


text:
Q: Nuxt.js custom loader not loading instantly So my custom loader is not loading instantly only like a split second then it loads here is my site, my goals is to my custom components load. PS when i change ssr to false it works
here is my site: https://micahkwaka.dev
export default {
  loading: '~/components/LoadingBar.vue',

  loadingIndicator: false,

  ssr: true,

  pageTransition: {
    name: 'my-page',
    mode: 'out-in'
  },

  // Target (https://go.nuxtjs.dev/config-target)
  target: 'static',
}

A: EDIT: This loader is when you have an SPA, to wait for it to load before showing the content. Since you're using Nuxt as an universal app (ssr + client), you will have the static content first (before the JS kicks in, and therefore your animation). So, you could make one with static SVG/CSS but the backed-in JS loader is not the solution here.
The best way would be to disable the JS to test the final result. Still, I'm pretty sure that Google will give you a better rating if you do not have any loader. You could maybe add it to your page transitions tho.
For the animation itself, start with it, then setTimeout the removal of it after 500ms or alike. Plenty ways of doing it. But you will need to have it on the initial render of your page (before the JS hydration).

Why do you set the loadingIndicator to false if you want it ?
If you want a custom one, provide a path to key as explained in the documentation: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-loading-indicator/


text:
Q: Is there a difference between 'I thought to myself' and 'I thought.'? Is there any need for the ending of 'to myself'? How is it different from the alternative? Can you always replace 'I thought to myself' with 'I thought'?

A: Any need for it? No. It's redundant.
But redundancy is a feature of language, not a bug. Although the denotative meaning of "thought to myself" and "thought" are the same (barring telepathy), they can have different connotations, moods, or styles. Reputable authors have used the longer version, e.g. CS Lewis in The Voyage of the Dawn Treader:

And I thought to myself, oh dear, how ever many skins have I got to take off?

...which is in part of a story about an unusual personal experience related by an English schoolboy.  So in the end it's just a style choice, not really a meaning-based one.
EDIT: But there may be a difference in connotation. The connotation of "to myself" puts the emphasis on the reflexive nature of the thinking, and not simply on the thought. Many translations of Ecclesiastes 1:16 have something like:

I thought to myself, "Look, I have grown and increased in wisdom more than anyone who has ruled over Jerusalem before me".

where the KJV translation has:

I communed with mine own heart...

A: This is not redundant; it removes some ambiguity.  For example,

I thought that I left my keys on the table.

usually isn't really describing a specific thought - just a belief about what I did and where my keys are.  But it could also mean - a definite thought passed through my mind, and that thought was "I left my keys on the table".
If I wanted to express the latter sense, I could make it clear by specifically saying something like

I thought to myself that I left my keys on the table.

which would generally mean that a definite thought passed through my mind.

A: From the song "It's a Wonderful World":

And I think to myself
  What a wonderful world

AZLyrics
The redundancy is definitely in use. To me it sets a mood of being pensive.


text:
Q: Event Shift for one day for all-day event on fullcalendar Having problem for "all-day" event that an event with start Nov 10 and end Nov 12 will span only 2 days on the calendar.
Looks like the documentation for the old version has the right one that I want it to work.
But with the new version, is there a way I can make it span for 3 days instead of 2 days without changing the end date?
The problem of changing the end date is that I allow user to store the end date. I don't think changing the end date from the user input is a good idea.
Any suggestion?

A: Yes, it looks like it is defined in that way  in full calendar. For example if you drop some event on 3rd march for 1 day then
start  : Mar 03 2020 00:00:00
end    : Mar 04 2020 00:00:00
Hope it helps.


text:
Q: Salesforce Community custom login in mobile is not working properly I am using SF Community for native iOS/Android app. I created my community so that I could registered/logged in community via my desktop browser. I also configured enpoint for iOS/Android after that I have logged in SF Community via my mobile. I used this function:

SFAuthenticationManager.sharedManager().loginWithCompletion({
  (oAuthInfo : SFOAuthInfo!) -> Void in
              self.setupRootViewController()
          }, failure: { (oAuthInfo : SFOAuthInfo!, error : NSError!) -> Void in
              SFAuthenticationManager.sharedManager().logout()
          })

But the problem is the webview keeps opening the start url (chatter page) after login successfull. The completion closure is never called. I don't know how to fix it. I think I missed something or did wrong. Could anyone please let me know how can I fix it?


text:
Q: Rendering a DOM-Node as a String without specifying namespaces in Java a project of mine using Java needs to output XML based on an abstract representation, which is modelled as an own class/datatype. Considering this function
public static String renderToString(Node element) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {
        transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    DOMSource source = new DOMSource(element);
    StreamResult result = new StreamResult(new StringWriter());
    try {
        transformer.transform(source, result);
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return result.getWriter().toString();
}

I have written a test that constructs an Element equivalent to
<FIELD ID="1" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="8000" COLLATION="SQL_Latin1_General_CP1_CI_AS" />

This is generated by the following function
public static Element createFieldElement(Document doc) {
    Element fieldElement = doc.createElement("FIELD");
    ...
    fieldElement.setAttribute("xsi:type", "CharTerm");
    return fieldElement;
}

Passing this Element to the function I now get an error telling me that the 'xsi' namespace is missing (which was used with the xsi:type attribute), which makes sense since the Element I try to render is no complete XML document.
Is there an option I must set or any way to bypass the XML Namespace declaration in order to keep my code testable?
Otherwise I would try to mock some functions to trick the Transformer into rendering the Element anyway, but I would not suggest that a convenient option.

A: Eventually I found no way to omit the namespace checking, but for the sake of testing I found a compromise by adding the namespace while testing.
@Test
public void IfColumnDescriptionGivenThenGenerateAccordingField() {
    Element element = XSDCreator.createFieldElement(doc, 1, ";");
    element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    String output = XSDCreator.renderToString(element);
    assertEquals(output, "Here comes the output");
}

This may not be the real output, but this should be sufficient for testing purposes. Another approach would be to generate a Document with a proper namespace declaration and render the whole document.


text:
Q: SSIS Multiple Data Destinations I'm quite new to Integration Services. Is it possible to have one data source that transfers data to multiple data destinations, or do I have to create as many sources as destinations? I have one CSV file containing data and I must distribute this data to different tables.

A: In SSIS Data Flow task data flows through "pipes" or "streams". Each pipe can get to one destination only. To split a pipe into several pipes use Multicast from the Toolbox, when you are on Data Flow tab. Then link several pipes to their destinations.

A: You can also have multiple Data Flow tasks.  So there can be multiple Data Flow tasks running in parallel (threads) or in sequence.  You can then take the data from one destination table and use it as the source for another Data Flow.


text:
Q: How to get the input cursor position in Winforms WebBrowser Control? We use the Winforms WebBrowser Control as simple editor.
Is there a way to get the position (character position in text) of the input cursor in the text. (Not in the input bar)
What do I need?
I need the implementation of SelectionStart in the WebBrowser control. (Where is the input cursor)
Why do I need this?
Since the RichtText control does not support properly links with alternative link text, we need the WebBrowser control as alternative editor.
Edit
My final goal is to retrieve the link data (such as "example.com") at the position where the cursor is located when the cursor is placed over a link without the user clicking on the link. In my case, there is no real link, but metadata used within the program logic. (Example: am12rp12300rt147600) instead of a real link like the mentioned "example.com"

A: You can get input cursor position via Javascript.

*

*Javascript on your html file:

function insertAtCursor(myValue) {
    //IE support
    if (document.selection) {
        sel = document.selection.createRange();
        sel.text = myValue;
    }
}

*Insert text at cursor

Dim result As String = WebBrowser1.Document.InvokeScript("insertAtCursor", New [Object]() {"TEST"})

*Download source code from my blog

Source code insert text at cursor (VB.NET)


text:
Q: How can I write, read and append parameter-value pairs of HTTP request to a file at Apache's server side? I am a newbie, and I'm writing an Apache module to handle http request. I want to store all of the http requests' parameters and their values to a txt file. And, here is my code, but it didn't succeeded.

Whenever, I tried to put some parameters in the URL, the page crashed. In the error.log of apache, it shows "Segmentation Fault (core dumped)". I am aware that there is API of APR_FILE_() here instead of using standard C library. But I am so dump to understand all of pointers of those functions and the API does not have any sample usage of the apr_file_() functions, thus being stuck with file I/O. So I would be really thankful if someone could help me with the problem.
For your ready reference: I paste my code here to:
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
/* The sample content handler */
static int learning_handler(request_rec *r)
{
    /* First off, we need to check if this is a call for the "example-handler" handler.
     * If it is, we accept it and do our things, if not, we simply return DECLINED,
     * and the server will try somewhere else.
     */
    //if (!r->handler || strcmp(r->handler, "example-handler")) return (DECLINED);

    /* Set the appropriate content type */
    ap_set_content_type(r, "text/html");

    /* Print out the IP address of the client connecting to us: */
    ap_rprintf(r, "
Hello, %s!
", r->useragent_ip);

    /* If we were reached through a GET or a POST request, be happy, else sad. */
    if ( !strcmp(r->method, "POST") || !strcmp(r->method, "GET") ) {
        ap_rputs("You used a GET or a POST method, that makes us happy!
", r);
    }
    else {
        ap_rputs("You did not use POST or GET, that makes us sad :(
", r);
    }

    /* Lastly, if there was a query string, let's save it file */
    if (r->args) {
        ap_rprintf(r, "Your query string was: %s", r->args);

        FILE * fp;
        fp = fopen ("params_file.txt", "w+");
        fprintf(fp, "%s",r->args);
        fclose(fp);
    }
    return DECLINED;
}

static void learning_register_hooks(apr_pool_t *p)
{
    ap_hook_handler(learning_handler, NULL, NULL, APR_HOOK_REALLY_FIRST);
}

/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA learning_module = {
    STANDARD20_MODULE_STUFF,
    NULL,                  /* create per-dir    config structures */
    NULL,                  /* merge  per-dir    config structures */
    NULL,                  /* create per-server config structures */
    NULL,                  /* merge  per-server config structures */
    NULL,                  /* table of config file commands       */
    learning_register_hooks  /* register hooks                      */
};


text:
Q: error: cannot find symbol purchase Here is my code:
import java.util.Scanner;

class CreatePurchase {
     public static void main(String args[])
     {
         Purchase purchase=new Purchase();
         Scanner s=new Scanner(System.in);
         System.out.println("Enter the details: ");
         while(true)
         {
             System.out.print("Enter invoice number[between 1000 and 8000]: ");
             int i=s.nextInt();
             if(i>=1000 && i<=8000){purchase.setInvoiceNumber(i);break;}
             else System.out.println("Wrong entry,enter again");
         }
         while(true)
         {
             System.out.print("Enter amount of purchase[should be non-negative]: ");
             int i=s.nextInt();
             if(i>=0){purchase.setAmountOfSales(i);break;}
             else System.out.println("Wrong entry,enter again");
         }
         purchase.display();
     }
 }

This is the exact error messages I keep getting:
C:\Users\Kenneth\Documents\NetBeansProjects\CreatePurchase\src\createpurchase  \CreatePurchase.java:9: error: cannot find symbol
     Purchase purchase=new Purchase();
symbol:   class Purchase
location: class CreatePurchase
C:\Users\Kenneth\Documents\NetBeansProjects\CreatePurchase\src\createpurchase\CreatePurchase.java:9: error: cannot find symbol
     Purchase purchase=new Purchase();
symbol:   class Purchase
location: class CreatePurchase
2 errors

I have no idea how to fix it and netbeans is not showing anything wrong with the code. Help is appreciated.
Here is the Purchase code, which compiled and ran fine.
class Purchase
 {
     int invoiceNumber;
     int amountOfSales;
     double amountOfSalesTax;
     static double rate=7.5;
     public void setInvoiceNumber(int i)
     {
         invoiceNumber=i;
     }
     public void setAmountOfSales(int a)
     {
         amountOfSales=a;
         amountOfSalesTax=(7.5*a)/100;
     }
     public void display()
     {
         System.out.println("The deatils are:");
         System.out.println("Invoice Number: "+invoiceNumber);
         System.out.println("Amount of Sales: "+amountOfSales);
         System.out.println("Amount of sales tax: "+amountOfSalesTax);
     }
 }


text:
Q: Ionic Android App stuck on white screen after upgrading to Angular 12. Error: goog.getLocale is not a function I recently tried upgrading Angular 11 to 12 in my Ionic App. It all went well, and the app is running with no errors in the browser.
However, when I tried to run it on an Android phone, after the splash-screen disappears, the app gets stuck in a white screen.
I tried using chrone://inspect tool and see if I get any errors and this showed up:

I also get the same error on the Android Logcat: E/Capacitor/Console: File: http://localhost/vendor-es2015.js - Line 15729 - Msg: ERROR TypeError: goog.getLocale is not a function
I tried adding timeout to the splash-screen, updating libraries, deleting node_modules and reinstalling them, but nothing worked. I can't find much info on the web about this error.
Can anyone tell me what this error means or why is the app stuck here? It works well if I go back to Angular 11.
My package.json looks like this:
"dependencies": {
    "@agm/core": "^3.0.0-beta.0",
    "@angular/common": "~12.2.3",
    "@angular/core": "~12.2.3",
    "@angular/forms": "~12.2.3",
    "@angular/platform-browser": "~12.2.3",
    "@angular/platform-browser-dynamic": "~12.2.3",
    "@angular/router": "~12.2.3",
    "@capacitor-community/background-geolocation": "^0.3.11",
    "@capacitor/android": "^2.4.6",
    "@capacitor/core": "^2.4.6",
    "@capacitor/ios": "^2.4.6",
    "@ionic-native/android-permissions": "^5.30.0",
    "@ionic-native/clipboard": "^5.31.1",
    "@ionic-native/core": "^5.30.0",
    "@ionic-native/device": "^5.31.1",
    "@ionic-native/diagnostic": "^5.32.1",
    "@ionic-native/insomnia": "^5.30.0",
    "@ionic-native/launch-navigator": "^5.30.0",
    "@ionic-native/location-accuracy": "^5.30.0",
    "@ionic-native/market": "^5.33.1",
    "@ionic-native/mobile-accessibility": "^5.36.0",
    "@ionic-native/splash-screen": "^5.30.0",
    "@ionic-native/status-bar": "^5.30.0",
    "@ionic/angular": "^5.6.14",
    "@ionic/pwa-elements": "^3.0.2",
    "@ngrx/effects": "^10.0.0",
    "@ngrx/entity": "^10.0.0",
    "@ngrx/schematics": "^10.0.0",
    "@ngrx/store": "^10.0.0",
    "@ngrx/store-devtools": "^10.0.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^6.0.0",
    "agm-direction": "^0.8.9",
    "cordova-clipboard": "^1.3.0",
    "cordova-plugin-actionsheet": "^2.3.3",
    "cordova-plugin-android-permissions": "^1.1.2",
    "cordova-plugin-device": "^2.0.3",
    "cordova-plugin-dialogs": "^2.0.2",
    "cordova-plugin-insomnia": "^4.3.0",
    "cordova-plugin-market": "^1.2.0",
    "cordova-plugin-network-information": "git+https://github.com/apache/cordova-plugin-network-information.git",
    "cordova-plugin-request-location-accuracy": "^2.3.0",
    "cordova.plugins.diagnostic": "^6.0.3",
    "core-js": "^3.8.3",
    "moment": "^2.28.0",
    "ngx-signaturepad": "^0.0.9",
    "phonegap-plugin-mobile-accessibility": "^1.0.5",
    "rxjs": "^6.6.3",
    "tslib": "^2.0.1",
    "uk.co.workingedge.phonegap.plugin.launchnavigator": "^5.0.5",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.3",
    "@angular/cli": "^12.2.3",
    "@angular/compiler": "~12.2.3",
    "@angular/compiler-cli": "~12.2.3",
    "@angular/language-service": "~12.2.3",
    "@babel/core": "^7.10.2",
    "@capacitor/cli": "2.4.6",
    "@ionic/angular-toolkit": "^4.0.0",
    "@storybook/addon-actions": "^5.3.19",
    "@storybook/addon-knobs": "^5.3.19",
    "@storybook/addon-links": "^5.3.19",
    "@storybook/addon-notes": "^5.3.19",
    "@storybook/addon-options": "^5.3.19",
    "@storybook/addons": "^5.3.19",
    "@storybook/angular": "^5.3.19",
    "@types/googlemaps": "3.39.12",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "agm-overlays": "^2.0.0",
    "babel-loader": "^8.1.0",
    "codelyzer": "^6.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^6.3.4",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "^7.0.0",
    "ts-node": "~7.0.0",
    "tslint": "~6.1.0",
    "typescript": "4.3.5"
  },

Thank-you!

A: @edit 09/2021
as a temporary fix avoid to call the getGlobalLocale().
Add this to your index.html
<script>
  var ngI18nClosureMode = false;
</script>

same here updating from angular@12.1 to @12.2.
meanwhile try to update to ^12.1


text:
Q: Java поведение оператора case     char g = 'a';
    switch(g){
        case 'a' :
            System.out.println("a");
        case 'с' :
            System.out.println("b");
            break;
        default :
            System.out.println("Default");
    }

Почему в консоли выводит "a" и затем "b", если переменная равна символу "a"?

A: char g = 'a';
switch(g){
    case 'a' :
        System.out.println("a");
        break;
    case 'с' :
        System.out.println("b");
        break;
    default :
        System.out.println("Default");
        break;
}

Не много поправил ваш код. Программа выводила сразу 2 значения, потому что вы упустили break;. Оператор break; ставится после каждой проверки условия. Как сказали в комментариях, если нет break или return, то выполнятся следующие case, в порядке, в котором они указаны, пока не встретится break или return.


text:
Q: Unable to resolve service for type 'AutoMapper.Configuration.IConfiguration' while attempting to activate 'Service.ServiceManager' I'm receiving the following error after attempting to implement Identity into an ASP.NET Core 3.1 application:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Services.Contracts.IServiceManager Lifetime: Scoped ImplementationType: Service.ServiceManager': Unable to resolve service for type 'AutoMapper.Configuration.IConfiguration' while attempting to activate 'Service.ServiceManager'.)'
InvalidOperationException: Unable to resolve service for type
'AutoMapper.Configuration.IConfiguration' while attempting to activate
'Service.ServiceManager'.

I'm really not sure why I'm running into this issue. Any help or input is greatly appreciated.

A: Alright, this one took some time. But here was the issue:
ServiceManager and AuthenticationService both had using statements for Automapper.Configuration. I replaced them with Microsoft.Extensions.Configuration and the issue was resolved.


text:
Q: How many times does the script used in spark pipes gets executed.? I tried the below spark scala code and got the output as mentioned below.
I have tried to pass the inputs to script, but it didn't receive and when i used collect the print statement i used in the script appeared twice.
My simple and very basic perl script first:
#!/usr/bin/perl
print("arguments $ARGV[0] \n"); // Just print the arguments.

My Spark code:
object PipesExample {
  def main(args:Array[String]){
    val conf = new SparkConf();

    val sc = new SparkContext(conf);

    val distScript = "/home/srinivas/test.pl"
    sc.addFile(distScript)

    val rdd = sc.parallelize(Array("srini"))

    val piped = rdd.pipe(Seq(SparkFiles.get("test.pl")))

    println(" output " + piped.collect().mkString(" "));

  }
}

Output looked like this..
 output arguments arguments

1) What mistake i have done to make it fail receiving the arguments.?
2) Why it executed twice.?
If it looks too basic, please apologize me. I was trying to understand to the best and want to clear my doubts.

A: From my experience, it is executed twice because spark divides your RDD into two partitions and each partition is passed to your external script.

A: The reason your application couldn't pick test.pl file is, the file is in some node's location. But the application master is created in one of the nodes in cluster. So prolly if the file isn't in that node, it can't pick the file.
You should always save the file in HDFS or S3 to access the external files. Or else pass the HDFS file location through spark command options.


text:
Q: Redis TTL is always -1 and can't be configured in a Spring Boot application I can't configure a TTL for the bucket4j configuration. It is always -1. Has this soemething to do with the weird key serialization, see screenshot? TTL configuration does work with other but not with bucket4j.
 @Bean
    fun redisCacheManagerBuilderCustomizer(): RedisCacheManagerBuilderCustomizer {
        return RedisCacheManagerBuilderCustomizer { builder ->
            builder
                .withCacheConfiguration(
                    "bucket4j",
                    RedisCacheConfiguration
                        .defaultCacheConfig()
                        .disableCachingNullValues()
                        .entryTtl(Duration.of(100, ChronoUnit.SECONDS))
                )
                .withCacheConfiguration(
                    "other",
                    RedisCacheConfiguration
                        .defaultCacheConfig()
                        .disableCachingNullValues()
                        .entryTtl(Duration.of(100, ChronoUnit.SECONDS))
                )
        }
    }

application.properties:
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=16379
spring.redis.password=mypass
spring.redis.timeout=60000

spring.cache.cache-names=other,bucket4j

A: You can try the config: spring.cache.redis.time-to-live


text:
Q: Modifying the shape for a subset of points with ggplot2 I'm attempting to plot a large scatter plot that varies along a large number of dimensions.
Here's my starting plot:
 p <- ggplot(mtcars, aes(wt, mpg, shape=cyl, colour=gear, size=carb)) +
      geom_point()

Using the mtcars dataset, I'm simply including various shapes, colours, and sizes.  Now what i'd like to add to this is some distinguishing mark around all points with carb==8.  For example, add in a big black circle around these points.
Doing
p + geom_point() + geom_point(colour="black", shape=1, size=5)

is close in that it gets the circles as I want, but all points get circles, I want to instead limit this to just some of the points.
I would greatly appreciate any suggestions for this problem.

A: Instead of initially putting your variables within the ggplot function, try to map your variables individually for every layer you add.
p <- ggplot(data = mtcars)+
geom_point(aes(wt, mpg, shape=as.factor(cyl), colour=gear, size=carb))+
geom_point(aes(wt[carb==8], mpg[carb==8]), colour="black", shape=1, size=7)


text:
Q: How do I get my docusaurus page to start with dark mode as default How do I get my docusaurus page to start with dark mode as default instead light mode as it comes by default ? thank you.

A: In your docusaurus.config.js, add/edit the following to
module.exports = {
  themeConfig: {
    colorMode: {
      defaultMode: 'dark',
      disableSwitch: false,
      respectPrefersColorScheme: false,
    },
  },
};

Reference: https://docusaurus.io/docs/api/themes/configuration#color-mode---dark-mode


text:
Q: performLongClick does not work in an activity android I am developing an auto-click application for android. By designing a floating window, the location of the desired place for clicking is found but performLongClick function does not work in the activity.
if (count == 0) {
            count = count +1;
            startrobot.setText("اجرای ربات");
            startService(new Intent(MainActivity.this, FloatingView.class));
        }
        else{
            Toast.makeText(v.getContext(), "ACTION_DOWN AT COORDS "+"X: "+FloatingView.X+" Y: "+FloatingView.Y, Toast.LENGTH_SHORT).show();
            v.performLongClick(FloatingView.X,FloatingView.Y);

        }

performLongClick does not work in both activity's View and webview.
Any help would be appreciated.


text:
Q: Angular 2+ - Adding DOM elements dynamically in HTML FORM I am trying to create a page which users can use to create custom forms. I will be giving the user a drop-down menu. From that drop-down menu, user will be able to select the type of question - like text box, radio button, check box, date and etc. - and then based on that selection, I want to add that  type of input into my DOM form.
On submit, I want to store the value of these questions in JSON format.
Any suggestions? What is best approach to tackle this or how I can implement it?

A: You don't need any package, the best way to do this is like this:

        DropDown

            Form 1

            Form 2

<form #form="ngForm">

    ...

    <button type="submit"></button>
</form>

And them in your component:
option1 = "false";
option2 = "false";

The doc of *ngIf is here

A: Have a look at ng-dynamic-forms. I've used it on a project before and it really helped creating forms dynamically.
It even provides an import / export functionality which you could use to store the form/questions including the provided answers in JSON format.
sidenote: I am in no way connected to the mentioned project.

A: EDIT: I feel an example like in this stackblitz shows how much control you have in terms of dynamic forms with the basic Angular utilities.
https://stackblitz.com/edit/deep-nested-reactive-form?file=app%2Fapp.component.html
Reactive Forms are your answer. There is no perfect way to do what you want. But I picked out a particular piece of an example from an old project. So, on one point I check for the type of comparators I have available due to my first choice. After that I check if I need a field that requires a simple input field or a datepicker. There are SO many ways to do this.

                    <input formControlName="value" type="text" class="form-control py-0" placeholder="Search for...">

                    <input type="text" formControlName="value" name="dateFrom" class="form-control py-0" style="text-align: center" [owlDateTimeTrigger]="dt3"
                     [owlDateTime]="dt3">
                    <owl-date-time [pickerType]="'calendar'" #dt3></owl-date-time>

                    <input type="text" formControlName="value" name="dateFrom" class="form-control py-0" style="text-align: center" [owlDateTimeTrigger]="dt3"
                     [owlDateTime]="dt3">
                    <owl-date-time [pickerType]="'calendar'" #dt3></owl-date-time>


text:
Q: Why can't I make a connection with AzureDataSudio? I am running SQL Server Linux container images with Docker on Debian Linux version 11.
I have connected successfully as 'root@sql1' from the command line with username 'SA':

I have downloaded AzureDataStudio, but can't make a connection:

Note that I am using the same password.
I have entered the port '1433' under Advanced Settings, and this leads to the following error:

Thank you.


text:
Q: how to render item always on top in react native I have a card inside the flatlist. When the user post something than card is rendered. But the card randomly fits in view. I want to render that card on the top of the screen, each time user post something. (like facebook, insta, twitter)
I need help


text:
Q: Send email from Xamarin.Forms app using Dependency Service In my app, for debugging purposes and testing purposes I need to send an email.
How do I present the mail controller, when the class that sends it does not contain a definition for PresentViewController ? The class needs to fire off the email app after the user clicks "yes" from the alert which fires.
    public async Task<bool> SendEmail(Exception ex)
    {
        var result = await SendNotificationToRequestSendingEmail();

        if (result)
        {

            if (MFMailComposeViewController.CanSendMail)
            {
                mailController = new MFMailComposeViewController();

                mailController.SetToRecipients(new string[] { "test@one.com", "test@two.com" });
                mailController.SetSubject("Details");
                mailController.SetMessageBody($"Message: {ex.Message}" +
                                              $"Exception: {ex.ToString()}"
                                              , false);

                mailController.Finished += (object s, MFComposeResultEventArgs args) =>
                {
                    Console.WriteLine(args.Result.ToString());
                    args.Controller.DismissViewController(true, null);
                };

                this.PresentViewController(mailController, true, null); //this line causes the error
            }
        }

        return true;
    }

How can I fix this problem or get around it? This is called from a Xamarin Forms page.

A: Please take a look at this answer:
Sending e-mail from Gmail in Xamarin.Forms app
besides that you can also do it with this NuGet package:
https://www.nuget.org/packages/Xam.Plugins.Messaging/


text:
Q: Program fail after EndPage() fucntion I am working with C++ MFC framework.
Unfortunatelly I met some trouble with EndPage() function.
I debugged code and got that program fail after calling EndPage() function. I have no idea why
I put code snippet below:
void Druk::DrawECG(short * pointer, int channel_nr, int channelLength)
{

pointer += startSample;
switch (mode)
{
case 1:
    int offsets[12];

    for (int z = 0; z < 2; z++)

    {
        StartPage(hDC);
    //  pointer = 0;

        DrawGrid(WYDRUK_I_START_X, WYDRUK_I_START_Y, WYDRUK_I_LIMIT_X, WYDRUK_I_LIMIT_Y, PEN_WIDTH);
        DrawScaleVertic(150, 300);
        SelectObject(hDC, hFontVertic);

        for (int i = 0; i < 12; i++)
        {
            offsets[i] = WYDRUK_I_OFFSET + i*WYDRUK_I_SPACE;
        }
        pointer += z*channel_nr*new_sign_len;
        //pointer += startSample;
        for (int i = 0; i < channel_nr; i++)
        {
            //pointer = memECG[channels[i]] + startSample;
            int current = channels[i];
            //new_sign_len = new_sign_len - startSample;
            rysujEKG_Vertical(pointer, WYDRUK_I_START_X, WYDRUK_I_LIMIT_X, offsets[current]);
            ExtTextOut(hDC, WYDRUK_I_CH_CAPTION_X, offsets[current], NULL, NULL, captions[current], 3, NULL);
            pointer += channelLength;
            //int diff = channelLength - new_sign_len;
        }
        DWORD error = GetLastError();
        EndPage(hDC);

    }
    break;

A: Your random call to GetLastError(); doesn't make sense.
You need to check the return value of every API call to see if it failed, THEN you should check that last error code.
Also, you do not do anything with DWORD error. Is its purpose just to see its value in Debugger? Then there is a better way: add $err to your Debugger's  Watch window to monitor its value. Or better yet, use $err,hr to get a string representation of that error.
Re: program fail after calling EndPage() function - did it fail "right after" that call? Like on the following line? Which line was it?


text:
Q: How to make npm install a scoped package without scope name? I'm trying to install some packages from Azure Artifacts Feed which was set up by my organization. I still need other external packages in https://registry.npmjs.org/. Although they have configured NPM as upstream source for feed, my 'Reader' permission doesn't allow me to add new packages. So I can only use NPM scopes to install private packages from a scope registry and public package from official registry. But I cannot install private packages simply with scope name.
I've config my user's .npmrc, get authentication using "vsts-npm-auth". It looks like this now:
    # $HOME\.npmrc
    proxy=http://my-enterprise-proxy.com
    noproxy[]=blah-blah-blah
    strict-ssl=false
    registry=https://registry.npmjs.org/

    @feed-scope:registry:=https://pkgs.dev.azure.com/[ORGANIZATION_NAME]/_packaging/[FEED_NAME]/npm/registry/
    always-auth=true
    //pkgs.dev.azure.com/<ORGANIZATION_NAME>/_packaging/<FEED_NAME>/npm/registry/:username=[ENTER_ANY_VALUE_BUT_NOT_AN_EMPTY_STRING]
    //pkgs.dev.azure.com/<ORGANIZATION_NAME>/_packaging/<FEED_NAME>/npm/registry/:_password=[BASE64_ENCODED_PERSONAL_ACCESS_TOKEN]
    //pkgs.dev.azure.com/<ORGANIZATION_NAME>/_packaging/<FEED_NAME>/npm/registry/:email=npm requires email to be set but doesn't use the value

Now I try to execute:
npm install @feed-scope/package-needed

And I get:
npm ERR! code E404
npm ERR! 404 Not Found - GET pkgs.dev.azure.com/<ORGANIZATION_NAME>/_packaging/<FEED_NAME>/npm/registry/@my-scope%2fpackage-needed - The package '@my-scope/package-needed' was not found in feed '[FEED_NAME]'
npm ERR! 404
npm ERR! 404  '@my-scope/package-needed@*' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

I've explored my org's feed, there is only a package named "package-needed". I doubt that the scope name I add to command just what the problem is. But I don't know how can I remove it.
PS: Please ignore those placeholders.

A: Unfortunately, that's not going to work. The scope is part of an npm package's name. You should work with the owners of your feed to get you the Collaborator  role, which is the same as the Reader role plus the ability to use packages from upstreams which have not yet been saved to your feed. This is distinct from the Contributor role which also adds the ability to publish packages directly to the feed.


text:
Q: A basic DHCP client I am coding a very simple DHCP client in C. I have trouble deciding whether it should use UDP or TCP, what basic commands should it support. I think it should be able to get at least DNS, SMTP, POP3 server information from server.
What else do I need to know? Is there a basic DHCP C implementation available which can help?

A: You shouldn't have trouble "deciding" whether to use TCP or UDP, you should rely on the actual DHCP spec to determine what protocol is used.  In fact, reliance on that spec will be more or less critical to implementing a DHCP client that does what it's supposed to do... since "what it's supposed to do" is defined in the spec.


text:
Q: Script correction for count positive values in text file Some time ago, I ask for help to generate a Perl Script that counts values in a text file divide into parts.
This script says to me when a positive value is present in some lines of a text file, then when beginning another part of the text, say to me again the number of positive values.
For example, this is my text file:
;YP_003858584.1_BtCoVBM48_gp2   25 NKSP   0.1462     (9/9)   ---
;YP_003858584.1_BtCoVBM48_gp2   66 NLTW   0.7837     (9/9)   +++
;YP_003858584.1_BtCoVBM48_gp2  116 NTTQ   0.7013     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  126 NGTH   0.7112     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  163 NCTY   0.7620     (9/9)   +++
;YP_003858584.1_BtCoVBM48_gp2  173 NIST   0.6556     (8/9)   +
;YP_003858584.1_BtCoVBM48_gp2  231 NITY   0.7442     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  273 NGTI   0.7109     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  322 NITQ   0.6116     (8/9)   +
;YP_003858584.1_BtCoVBM48_gp2  334 NITS   0.7296     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  361 NSSA   0.5388     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2  462 NPSG   0.4656     (5/9)   -
;YP_003858584.1_BtCoVBM48_gp2  541 NSTK   0.5883     (8/9)   +
;YP_003858584.1_BtCoVBM48_gp2  590 NASS   0.5643     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2  603 NCTD   0.7117     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  646 NSSY   0.5467     (4/9)   +
;YP_003858584.1_BtCoVBM48_gp2  665 NVSS   0.7980     (9/9)   +++
;YP_003858584.1_BtCoVBM48_gp2  695 NNTI   0.4537     (5/9)   -
;YP_003858584.1_BtCoVBM48_gp2  703 NFSI   0.5613     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  787 NFSQ   0.6209     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2 1060 NFTT   0.4540     (6/9)   -
;YP_003858584.1_BtCoVBM48_gp2 1084 NGTH   0.5408     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2 1120 NNTV   0.5803     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2 1144 NHTS   0.3828     (8/9)   -
;YP_003858584.1_BtCoVBM48_gp2 1149 NVSL   0.4879     (5/9)   -
;YP_003858584.1_BtCoVBM48_gp2 1159 NASV   0.5021     (3/9)   +
;YP_003858584.1_BtCoVBM48_gp2 1180 NESL   0.5770     (7/9)   +
;ADK66841.1_NA   25 NKSP   0.1462     (9/9)   ---
;ADK66841.1_NA   66 NLTW   0.7837     (9/9)   +++
;ADK66841.1_NA  116 NTTQ   0.7013     (9/9)   ++
;ADK66841.1_NA  126 NGTH   0.7112     (9/9)   ++
;ADK66841.1_NA  163 NCTY   0.7620     (9/9)   +++
;ADK66841.1_NA  173 NIST   0.6556     (8/9)   +
;ADK66841.1_NA  231 NITY   0.7442     (9/9)   ++
;ADK66841.1_NA  273 NGTI   0.7109     (9/9)   ++
;ADK66841.1_NA  322 NITQ   0.6116     (8/9)   +
;ADK66841.1_NA  334 NITS   0.7296     (9/9)   ++
;ADK66841.1_NA  361 NSSA   0.5388     (6/9)   +
;ADK66841.1_NA  462 NPSG   0.4656     (5/9)   -
;ADK66841.1_NA  541 NSTK   0.5883     (8/9)   +
;ADK66841.1_NA  590 NASS   0.5643     (6/9)   +
;ADK66841.1_NA  603 NCTD   0.7117     (9/9)   ++
;ADK66841.1_NA  646 NSSY   0.5467     (4/9)   +
;ADK66841.1_NA  665 NVSS   0.7980     (9/9)   +++
;ADK66841.1_NA  695 NNTI   0.4537     (5/9)   -
;ADK66841.1_NA  703 NFSI   0.5613     (9/9)   ++
;ADK66841.1_NA  787 NFSQ   0.6209     (9/9)   ++
;ADK66841.1_NA 1060 NFTT   0.4540     (6/9)   -
;ADK66841.1_NA 1084 NGTH   0.5408     (6/9)   +
;ADK66841.1_NA 1120 NNTV   0.5803     (6/9)   +
;ADK66841.1_NA 1144 NHTS   0.3828     (8/9)   -
;ADK66841.1_NA 1149 NVSL   0.4879     (5/9)   -
;ADK66841.1_NA 1159 NASV   0.5021     (3/9)   +
;ADK66841.1_NA 1180 NESL   0.5770     (7/9)   +

This file reports to me when a positive value is present: only 0.7 >= are positive values. The text file has two parts: one for YP_003858584.1_BtCoVBM48_gp2 and the other for ADK66841.1_NA. When you count the numbers of positive values (7>=) in each part, there are 9 positive values for each part.
I have a lot of files like this with hundreds of parts, for this reason, I ask for an idea about one script in Perl to count these values.
This is the script:
use strict;
use warnings;

my $cnt = {};
while(my $line = <STDIN>) {
    if($. == 1) {
        next;
    }else {
        my @cols = split(m{\s+},$line);
        if(@cols == 6) {
            my $potential = $cols[3];
            my $id = $cols[0];
            $id =~ s{^\;}{};
            if(0.7 >= $potential) {
                $cnt->{$id}++;
            };
        };
    };
};

my @ids_found = sort { $a cmp $b } (keys %$cnt);

for my $id (@ids_found) {
    print "PART $id:\n";
    print "$cnt->{$id} (values 0.7 >=)\n";
};

This works fine, however, I noticed that there is an error in the output.
The output:
$ cat Test00.txt | perl File_for_count_values.pl
PART ADK66841.1_NA:
18 (values 0.7 >=)
PART YP_003858584.1_BtCoVBM48_gp2:
18 (values 0.7 >=)

The output doesn´t look like just I want it, when counting values this script plus the positive values of each part (9 + 9 = 18).
The output must be:
$ cat Test00.txt | perl File_for_count_values.pl
PART ADK66841.1_NA:
9 (values 0.7 >=)
PART YP_003858584.1_BtCoVBM48_gp2:
9 (values 0.7 >=)

Any idea about what must change in the script to do that?
Any comment is welcome.

A: Your code counts the values which are less than or equal to 0.7.
If I change:
        if(0.7 >= $potential) {

to:
        if(0.7 <= $potential) {

then I get 9 for each part.  Output:
PART ADK66841.1_NA:
9 (values 0.7 >=)
PART YP_003858584.1_BtCoVBM48_gp2:
9 (values 0.7 >=)

A: Please investigate the following re-worked perl script for usefulness.
NOTE: original code assumes a header based on an instruction if($. == 1) -- see $.
A few changes was implemented to improve readability of the script

*

*a variable $threshold defined at top of the script

*skip the header/first line with next unless $. > 1 (next unless line counter more than one)

*split line not only on spaces but ; as well to avoid substitute

*$id,$potential filled from @cols array in one instruction

*field numbers adjusted as first field before ; will be empty

*write with format utilized for formatted output

NOTE: see $~ which defines current format for write output, utilized to close the table
This script utilizes __DATA__ block with originally posted data for output demonstration purpose.
Alter the code with while( <> ) instead while( <DATA> ), what would allow you accept input from STDIN or by specifying filename as an argument to the script (run as ./script.pl file.dat).
#!/usr/bin/env perl
#
# vim: ai ts=4 sw=4

use strict;
use warnings;

my($id,$counter);
my $treshold = 0.7;

while( <DATA> ) {
    chomp;
    next unless $. > 1;
    my @cols = split("[; ]+", $_);
    next unless @cols == 7;
    my($id,$potential) = @cols[1,4];
    $counter->{$id}++ if $potential >= $treshold;
}

my @sorted_ids = sort { $a cmp $b } keys %$counter;

for $id (@sorted_ids) {
    write;
}

$~ = "STDOUT_BOTTOM";
write;

exit 0;

format STDOUT_TOP =

Criteria:          potential >= @#.##
$treshold

+-----------------------------+-------+
| Part                        | Count |
+-----------------------------+-------+
.

format STDOUT =
| @<<<<<<<<<<<<<<<<<<<<<<<<<< | @>>>> |
$id,$counter->{$id}
.

format STDOUT_BOTTOM =
+-----------------------------+-------+

.

__DATA__
;YP_003858584.1_BtCoVBM48_gp2   25 NKSP   0.1462     (9/9)   ---
;YP_003858584.1_BtCoVBM48_gp2   66 NLTW   0.7837     (9/9)   +++
;YP_003858584.1_BtCoVBM48_gp2  116 NTTQ   0.7013     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  126 NGTH   0.7112     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  163 NCTY   0.7620     (9/9)   +++
;YP_003858584.1_BtCoVBM48_gp2  173 NIST   0.6556     (8/9)   +
;YP_003858584.1_BtCoVBM48_gp2  231 NITY   0.7442     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  273 NGTI   0.7109     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  322 NITQ   0.6116     (8/9)   +
;YP_003858584.1_BtCoVBM48_gp2  334 NITS   0.7296     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  361 NSSA   0.5388     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2  462 NPSG   0.4656     (5/9)   -
;YP_003858584.1_BtCoVBM48_gp2  541 NSTK   0.5883     (8/9)   +
;YP_003858584.1_BtCoVBM48_gp2  590 NASS   0.5643     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2  603 NCTD   0.7117     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  646 NSSY   0.5467     (4/9)   +
;YP_003858584.1_BtCoVBM48_gp2  665 NVSS   0.7980     (9/9)   +++
;YP_003858584.1_BtCoVBM48_gp2  695 NNTI   0.4537     (5/9)   -
;YP_003858584.1_BtCoVBM48_gp2  703 NFSI   0.5613     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2  787 NFSQ   0.6209     (9/9)   ++
;YP_003858584.1_BtCoVBM48_gp2 1060 NFTT   0.4540     (6/9)   -
;YP_003858584.1_BtCoVBM48_gp2 1084 NGTH   0.5408     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2 1120 NNTV   0.5803     (6/9)   +
;YP_003858584.1_BtCoVBM48_gp2 1144 NHTS   0.3828     (8/9)   -
;YP_003858584.1_BtCoVBM48_gp2 1149 NVSL   0.4879     (5/9)   -
;YP_003858584.1_BtCoVBM48_gp2 1159 NASV   0.5021     (3/9)   +
;YP_003858584.1_BtCoVBM48_gp2 1180 NESL   0.5770     (7/9)   +
;ADK66841.1_NA   25 NKSP   0.1462     (9/9)   ---
;ADK66841.1_NA   66 NLTW   0.7837     (9/9)   +++
;ADK66841.1_NA  116 NTTQ   0.7013     (9/9)   ++
;ADK66841.1_NA  126 NGTH   0.7112     (9/9)   ++
;ADK66841.1_NA  163 NCTY   0.7620     (9/9)   +++
;ADK66841.1_NA  173 NIST   0.6556     (8/9)   +
;ADK66841.1_NA  231 NITY   0.7442     (9/9)   ++
;ADK66841.1_NA  273 NGTI   0.7109     (9/9)   ++
;ADK66841.1_NA  322 NITQ   0.6116     (8/9)   +
;ADK66841.1_NA  334 NITS   0.7296     (9/9)   ++
;ADK66841.1_NA  361 NSSA   0.5388     (6/9)   +
;ADK66841.1_NA  462 NPSG   0.4656     (5/9)   -
;ADK66841.1_NA  541 NSTK   0.5883     (8/9)   +
;ADK66841.1_NA  590 NASS   0.5643     (6/9)   +
;ADK66841.1_NA  603 NCTD   0.7117     (9/9)   ++
;ADK66841.1_NA  646 NSSY   0.5467     (4/9)   +
;ADK66841.1_NA  665 NVSS   0.7980     (9/9)   +++
;ADK66841.1_NA  695 NNTI   0.4537     (5/9)   -
;ADK66841.1_NA  703 NFSI   0.5613     (9/9)   ++
;ADK66841.1_NA  787 NFSQ   0.6209     (9/9)   ++
;ADK66841.1_NA 1060 NFTT   0.4540     (6/9)   -
;ADK66841.1_NA 1084 NGTH   0.5408     (6/9)   +
;ADK66841.1_NA 1120 NNTV   0.5803     (6/9)   +
;ADK66841.1_NA 1144 NHTS   0.3828     (8/9)   -
;ADK66841.1_NA 1149 NVSL   0.4879     (5/9)   -
;ADK66841.1_NA 1159 NASV   0.5021     (3/9)   +
;ADK66841.1_NA 1180 NESL   0.5770     (7/9)   +

Output

Criteria:          potential >=  0.70

+-----------------------------+-------+
| Part                        | Count |
+-----------------------------+-------+
| ADK66841.1_NA               |     9 |
| YP_003858584.1_BtCoVBM48_gp |     9 |
+-----------------------------+-------+

Note:
The file you refer me to on GitHub does not include leading ; in data file. Due this reason count of number fields is less by one and causing not getting any result.
Please make following changes in perl script:
       next unless @cols == 7;
       my($id,$potential) = @cols[1,4];

to
       next unless @cols == 6;
       my($id,$potential) = @cols[0,3];


text:
Q: Show hidden files on OS X except .DS_Store I want to see all hidden files on my Mac except .DS_Store. Is there a way to do that?

A: As of macOS Sierra Beta, .DS_Store is actually always hidden from the Finder. Just show hidden files as you would normally and .DS_Store will be gone:
defaults write com.apple.finder AppleShowAllFiles -bool YES && killall Finder

A: There is this open source magic tool: asepsis. Sources are available on Github.
Version 1.4 now works with OS X Mavericks.
Update: Reported not working on El Capitan

Warning: Asepsis is no longer under active development and supported under OS X 10.11 (El Capitan) and later.

A: After many on/off years of searching for a solution, there are only a few alternatives, none of which quite match your original question; i.e. no solution exists to your specific question....yet

*

*One can specifically disable the .DS_store files from being created at all

*Leave Finder configured to not display hidden files

*Follow Adobe's nonsense and only browse folders with a command line shell

*Toggle hidden folders on-demand.  Check out this old wigit:

http://mac.softpedia.com/get/Dashboard-Widgets/Webcams/Miscellaneous/Hiddenfiles-Widget.shtml

A: This is what Adobe suggests:

To avoid creating .DS_Store files, do
  not to use the OS X Finder to view
  folders. An alternative way to view
  folders is to use UNIX command line.

Brilliant! ;)

A: This only addresses the Desktop, but as it's the most noticable and annoying place for .DS_Store files, it might be worth sharing:

*

*Drop to a terminal prompt

*cd ~/Desktop

*rm .DS_Store

*cd ~

*chmod 500 Desktop
This sequence removes your write permissions to the Desktop folder. Since Finder acts with your permissions, it also remove's Finder's ability to save a .DS_Store file to the Desktop.
Of course, it also stops you from saving to or modifying existing files on the desktop. Perfect if you like to have an ultra-clean setup.
Example of no .DS_Store on the Desktop without using special Apps:

note: Using these steps, it is still possible to drag items to the desktop as MacOS will prompt you for an admin login when needed.

A: You can show hidden files in Finder with a simple Terminal command:
defaults write com.apple.finder AppleShowAllFiles -bool YES

Then relaunch Finder by holding down the option key and right-clicking its dock icon.
However, you can't hide the .DS_Store files without hiding the rest of the hidden files. You probably just have to live one way or the other.

A: You can't hide it, but you can make it transparent, then drag it to the bottom-left or bottom right corner. So only you will see a string ".DS_Store", and there will be no icon.
Expert method:
Copy a transparent image from your favorite img editor, select the icon of the file in the file info window, and paste the transparent image when the original icon is selected on the top.
Step-By-Step method (Previous to Yosemite):

*

*Find a pure-white area in a folder, then press Shift-Command-Control-4, and drag out a square. Release the mouse when done, and the white area is now on your clipboard.

*Open Preview and press Command-V.

*Click and hold on the Select button in Preview's toolbar, and Instant Alpha from the drop-down menu.

*Click and drag across the white area until you see the displayed value reach 100%, then press Return.

*Copy the selected area (Command-C).

*On the desktop, select your new folder and press Command-I (File » Get Info).

*(Press Tab once in the Get Info window to) highlight the default icon.

*Paste the transparent icon from your clipboard into the default icon (Command-V).

Per @mliqu: In OS X Yosemite (10.10.1):

*

*Press Shift-Command-Control-4, and drag out a square over any area. Release the mouse when done, and the area is now on your clipboard.

*Open Preview and press Command-N to open a window with your capture.

*Press Command-A to select all, then press Delete.

*Press Command-C to copy this empty grey square to clipboard.

*Select ".DS_Store" and Command-I to get info.

*Select the icon in the top-left and Command-V to replace with transparency from clipboard.

A: Create an AppleScript/terminal service using Automator and save it to be accessible from the Finder>Services menu
The Automator action will be a two step process.
Step 1.  Add an AppleScript.  This script will toggle hidden files on or off (may not be properly formatted because I'm typing on my phone)
if (do shell script "defaults read com.apple.finder AppleShowAllFiles") is equal to "0"
    then
        do shell script "defaults write com.apple.finder AppleShowAllFiles 1"
    else
        do shell script "defaults write com.apple.finder AppleShowAllFiles 0"
end if

Step 2. Add a bash cron script.  This additional script will automatically search for and remove any .DS_Store files at the same time they would be triggered to display.  Once completed it will relaunch Finder and close the terminal.
#!/bin/sh
find ~ -name .DS_Store -exec /bin/rm -f -- {} \;
KillAll Finder
exit 0

This is not a perfect solution but it will achieve the result your looking for.
Alternatively, you could use this utility which will redirect the creation of DS_Store files to a cache directory but I prefer not to install software that will consume resources whenever possible.
The link is http://asepsis.binaryage.com/

A: I'm just adding my solution to this as I didn't like any of the other options. I am a web developer and I use /bin/zsh and oh-my-zsh ... either way you can add this to bash or sh.
It's simple, straight forward, and only 8 lines. I work a lot in the terminal though, so this is why this works best for my setup.
In my .zshrc I added the following lines to make switching easier.
function hideallfiles(){
    defaults write com.apple.finder AppleShowAllFiles -bool NO
    killall Finder
}
function showallfiles(){
    defaults write com.apple.finder AppleShowAllFiles -bool YES
    killall Finder
}

Then run . ~/.zshrc or for bash . ~/.bash_profile or logout of your Mac, and back in.
Then in terminal you can run showallfiles or hideallfiles and it'll change the config and restart Finder.
edit: confirmed working on 10.10 Yosemite

A: Using Terminal works to hide .DS_store files.
defaults write com.apple.finder AppleShowAllFiles -bool NO

This hides the hidden files. Can change NO to YES if you wish to see them again.

A: I'm using Xtra Finder (http://www.trankynam.com/xtrafinder) to toogle fast between hidden files. You can create your own shortcut for toogling. No need to kill finder. This is a little bit more handy and easier to use instead of typing commands or executing scripts.

A: For the  desktop annoying problem, my simple solution is hide the file behind the dock, you can change  momentary the dock position and put the file where will remain invisible. Not a very technical solution, but effective.

A: Install latest Sierra, set to see hidden files, all hiden files shown, but the .DS_Store files will not be shown (although they are there).

A: Definitely use the transparent icon. Then, just move it. Out of sight, out of mind.

A: El Capitan user here.
I like to keep an clean desktop; no icons or links at all.  I also need to see hidden files in Finder.
I "double clicked" the .DS_Store Icon and selected "Show View Options."  In that window, I scaled the icon down to 16x16, and text size to 10.  I set the Grid Size as small as possible as well.
I then dragged the icon down to the lower right, so I'm left with a tiny box in the lower right corner of the Desktop.

A: Transparent icon, move off screen, easy step-by-step here:
https://www.scottofford.com/2013/03/hide-ds-store-on-mac/
Via this Ask Different answer: https://apple.stackexchange.com/a/237999/6902.


text:
Q: Google Maps - Zoom out when info window is closed or other radio button filter is "ticked" I need this map to zoom out to "2" when 2 things happen:

*

*When you close the info window

*When you click another radio button

I have tried a few things but nothing seems to work.
Here is my code:
var map;

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(58, 16),
        zoom: 2,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}

var seg = {
    1:'invesCastProd',
    2:'forged',
    3: 'airframe',
    5: 'corp',
    6: 'structurals'

}

var comp = {
    1:'structurals',
    2:'airfoils',
    3: 'airfoils',
    4: 'wyman',
    5: 'energy',
    6: 'strucComp',
    7: 'mechHard',
    8: 'engineProd',
    9: 'corp',
    10: 'aero',
    12: 'timet',
    13: 'specMetals'

}

var myJSON = {};
var myMarkers=[];

$.getJSON("locations.json", function(json1) {
  myJSON=json1;
  $.each(json1, function(key, data) {
    var latLng = new google.maps.LatLng(data.latitude, data.longitude);
    // Creating a marker and putting it on the map
    var marker = new google.maps.Marker({
        position: latLng
    });
    myMarkers[key]=marker;
    marker.setMap(map);

    var infoWindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', function() {

      if (infoWindow) {infoWindow.close();}
      infoWindow = new google.maps.InfoWindow({
        content: "
" + data.display_name + "
" +
        "
" + data.street+ "
" +
        "
" + data.city + ", " + data.state + "   " + data.postal_code + "
" +
        "
" + data.telephone + "
" +
        "
" + seg[data.segment_id] + "
" +
        "
" + comp[data.component_id] + "
" +
        "Website"
      });
      infoWindow.open(map, marker);
      map.setZoom(15);
      map.panTo(this.getPosition());

    });

    filterMarkers = function(category){
        //console.log(category);

        console.log(category.data());
        var component = category.data("component_id");
        var segment = category.data("segment_id")

        // Clear markers
        setMapOnAll(null);
        //marker = [];
        var filteredMarkers=[];

        $.each(myJSON, function(key, data) {
          //console.log(key);

          if( (myJSON[key].component_id == component) && (myJSON[key].segment_id == segment) ){
            console.log("FOUND");

            filteredMarkers.push(key);
          }
        });

        for(i=0;i<filteredMarkers.length;i++){
          myMarkers[filteredMarkers[i]].setMap(map);
        }
      }

    function setMapOnAll(map) {
      for (var i = 0; i < myMarkers.length; i++) {
        myMarkers[i].setMap(map);
      }
    }
});

});
what is the best way to accomplish this?

A: On close of an InfoWindow is the question.
You need an event listener for that.
Just add this in your "marker click" listener:
   (google.maps.event.addListener(marker, 'click', function() {) - Line #55 of script.js.
google.maps.event.addListener(infoWindow,'closeclick',function(){
    console.log("CLOSE");
    map.setZoom(2);
    map.setCenter({lat:58,lng:16});
});

It sounds weird to add a listener into a listener, I know.
But that's where you define your infoWindow...
;)
It works!

EDIT
(I didn't took care of the second request in the above...)
So, have to move the above into a function:
function resetMapOrigin(){
    console.log("Reseting Map.");
    map.setZoom(2);
    map.setCenter({lat:58,lng:16});
}

Then call this "reset" function when you want.
;)
in google.maps.event.addListener(marker, 'click', function() {:
google.maps.event.addListener(infoWindow,'closeclick',function(){
    resetMapOrigin();    // See Plunker line #72
});

and in filterMarkers = function(category){, right after setMapOnAll(null);:
resetMapOrigin();    // See Plunker line #90

Updated Plunker


text:
Q: Get nearest continuous date period MySQL I have this MySQL table:
| Date           | Room | State |
|2015-06-15      | 26   | 1     |
|2015-06-16      | 26   | 1     |
|2015-06-17      | 26   | 1     |
|2015-06-18      | 26   | 1     |
|2015-06-20      | 26   | 1     |
|2015-06-21      | 26   | 0     |
|2015-06-22      | 26   | 0     |
|2015-06-23      | 26   | 1     |
|2015-06-24      | 26   | 0     |
|2015-06-30      | 26   | 1     |
|2015-07-01      | 26   | 1     |

I want to get the first date of the beginning of useful nearest (it means continuous day, State = 1) booking period (for example, 2 days).
How can I do it?

A: SELECT d.*
FROM   dates d
WHERE  EXISTS(SELECT `Date`
              FROM   dates
              WHERE  `Room` = d.`Room`
                     AND `Date` = Date_add(d.`Date`, INTERVAL 1 DAY)
                     AND `State` = 1)
       AND d.`State` = 1;

for 2 Days.
SET @days=3;

SELECT d.*
FROM   dates d
WHERE  (SELECT Count(`date`)
        FROM   dates
        WHERE  `Room` = d.`Room`
               AND `Date` <= Date_add(d.`Date`, INTERVAL @days - 1 DAY)
               AND `Date` >= d.`Date`
               AND `State` = 1) >= @days
       AND d.`State` = 1;

for dynamic days value.
And the testdata I used:
create table Dates(
`Date` DATE,
`Room` INT DEFAULT 26,
`State` BOOL DEFAULT 0);

INSERT INTO  Dates (`Date`,`State`) VALUES
('2015-01-01',1),
('2015-01-02',0),
('2015-01-03',1),
('2015-01-04',1),
('2015-01-05',0),
('2015-01-06',1),
('2015-01-07',1),
('2015-01-08',1),
('2015-01-09',0),
('2015-01-10',1),
('2015-01-11',1),
('2015-01-12',1),
('2015-01-13',1);

The query returns actually all posible dates. To get only one date add a LIMIT 1 at the end of the statement. But maybe it can be help full to get later Startdays that are Possible.
The second query returns with the testdata the following Dates:
2015-01-06  26  1
2015-01-10  26  1
2015-01-11  26  1


text:
Q: How do I iterate through an object but display then in separate rows? What I'm trying to accomplish is iterating through an object, each of the object has a type property. The goal is to iterate through each object and display them in a row designated by their type.
Right now it looks like this

What I'm trying to do is have the Frontend, Backend, and UI on separate rows.
I'm using Aurelia Framework, here's my View:
<template>

${project.type}

${project.name}

Here's my Model:
export class Portfolio {

constructor() {
    this.header = "Portfolio";
    this.projectTypes = ["Frontend", "Backend", "UI"];
    this.projects = [
        {
            name: "Project Name 1",
            type: "Frontend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 2",
            type: "Frontend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 3",
            type: "Backend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 4",
            type: "UI",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        }
    ]
}

}
Any and all feedback is accepted, thank you!

A: You are just looping through the project types but don't use that data for anything. The inner loop goes through all projects and lists them all, no matter what their type is.
You'll need to either restructure your data so that projectType acts as a container for all projects of that type, or add an if that checks that the project's type matches projectType like this: (pardon me, I've never actually used Aurelia so might not work as-is)

${project.type}

${project.name}


text:
Q: C# asp.net issue on Form with file type and text I'm going straight to the point here guys,
I have a form. when I save the form... it only gets the firstname, middlename and lastname.. it doesn't get the files... however, if I only get the photo and comment out other inputs... the photo is captured on my model.. I dunno why it behaves like this.. I'm really new to asp.net mvc.. so please bear with me..
@model Impulse.ViewModels.AgentViewModel

@{
    ViewBag.Title = "AgentForm";
    Layout = "~/Views/Shared/_SiteLayout.cshtml";
}

Add New Agent

   @using (Html.BeginForm("Save", "Agent", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {

                Profile Picture
                <input type="file" name="photo" id="photo" />

                        @Html.LabelFor(m => m.Agent.FirstName)
                        @Html.TextBoxFor(m => m.Agent.FirstName, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Agent.FirstName)

                        @Html.LabelFor(m => m.Agent.MiddleName)
                        @Html.TextBoxFor(m => m.Agent.MiddleName, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Agent.MiddleName)

                        @Html.LabelFor(m => m.Agent.LastName)
                        @Html.TextBoxFor(m => m.Agent.LastName, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Agent.LastName)

    <input type="submit" class="btn btn-primary" value="Save" />
   }

Controller
   [HttpPost]
    public ActionResult Save(AgentModel agent)
    {
        //I debug here to see the data passed by my view
        return Content("Sample");
    }

Model
public class AgentModel
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MiddleName { get; set; }
        [FileSize(10240)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase photo { get; set; }

    }

A: you can try like this
Model
public class UploadFileModel
{
    public UploadFileModel()
    {
        Files = new List<HttpPostedFileBase>();
    }

    public List<HttpPostedFileBase> Files { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
}

View
@using (Html.BeginForm("UploadData", "Home", FormMethod.Post, new { encType="multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.FirstName)

    @Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })

    <input type="submit" value="submit" name="submit" id="submit" />
}

Controller
public ActionResult UploadData(UploadFileModel model)
{
    var file = model.Files[0];
    return View(model);
}

A: *

*you are binding to view to AgentViewModel so you will get AgentViewModel when you post server. so the parameter to action save should be viewmodel. Or Else change view to bind to AgentModel.

*The file control that you have used is html input type. try using below code.

@Html.TextBoxFor(m => Model.File, new { type = "file" , accept=".pdf"})
@Html.ValidationMessageFor(m => Model.File)


text:
Q: Apostrophe use: patients' having received vs patients having received The article FDA advisory committee votes unanimously in favor of a one-shot COVID-19 vaccine approach – 5 questions answered on The Conversation uses an apostrophe in a way I haven't seen before:

By simplifying the vaccine schedule to include only a single vaccine formulation, the committee reasoned, it might be easier for competing vaccination platforms to break into the market. In other words, newer vaccine contenders would not have to rely on patients' having already received their primary series before using their products. Companies seemed ready to take advantage of that future flexibility, with researchers from Pfizer, Moderna and Novavax all revealing their companies' exploration of a hybrid COVID-19 and flu shot at various stages of clinical trials and testing.

Is an apostrophe correct there? Would it be correct without an apostrophe?


text:
Q: HttpConnectionParams odd syntax error I'm sure there's some simple fix I'm just not seeing but for some reason the following code:
private HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
private Gson gson = new Gson();

Gives syntax errors, like so: http://i.imgur.com/JF8zxPG.png
Please help, I have no idea why these are syntactically incorrect, it's attempting to tell me I need to delete the brackets.

A: You are trying to call a function (setConnectionTimeout()) in a class body, not in a method body.
Move theHttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); and HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); to some method (constructor on example), on example:
private HttpClient httpclient = new DefaultHttpClient();

public void initialize () {
  HttpParams httpParameters = new BasicHttpParams();
  int timeoutConnection = 3000;
  HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
  int timeoutSocket = 5000;
  HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
}

// rest of the code

Additionally, why do you need two instances of HttpClient?


text:
Q: Erro ao deletar FK Tenho uma tabela chamada:
solicitacaoemprestimo
codemprestimo, dataemprestimo, horaemprestimo
E outra tabela chamada:
emprestados, codemprestados, dataemprestimo, horaemprestimo, fk(solicitaremprestimo_codemprestimo)
e usei esse comando:
INSERT INTO emprestados (dataemprestimo,horaemprestimo, solicitacaoemprestimo_codemprestimo);

SELECT data emprestimo, horaemprestimo, codemprestimo FROM solicitacaoemprestimo WHERE codemprestimo = '13'

DELETE FROM solicitacaoemprestimo WHERE codemprestimo = '13';

erro que esta dando:

Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (trabalhoclubedodvd.emprestados, CONSTRAINT fk_emprestados_solicitacaoemprestimo1 FOREIGN KEY (solicitacaoemprestimo_codemprestimo)

Só que, na hora que eu vou deletar na tabela solicitacaoemprestimo porque meu dvd foi alugado, ele não deixa, mas eu gostaria de deletar porque esse item não será mais usado por que o dvd já foi alugado... Se alguém puder me ajudar desde já eu agradeço...

A: Isso é intencional — a ideia de criar uma chave estrangeira é impedir que uma coluna que faz referência a um ID em outra tabela armazene um valor inválido. Se a consulta que você quer fazer fosse permitida, uma linha teria o valor 13 para a coluna solicitacaoemprestimo_codemprestimo apesar de não existir nenhuma linha em solicitacaoemprestimo com codemprestimo igual a 13.
A motivação de apagar a linha correspondente em solicitacaoemprestimo é que a semântica que você tem em mente pra essa tabela é que ela só vai guardar solicitações ativas? Considere repensar o design do seu banco de dados e deixar todas as solicitações, pra sempre, nessa tabela — se você quiser filtrar só as solicitações que ainda não foram atendidas, você sempre pode fazer
…
WHERE codemprestimo NOT IN (SELECT solicitaremprestimo_codemprestimo FROM emprestados)

(mas aí seria importante você não mais repetir as colunas dataemprestimo, horaemprestimo na tabela emprestados)

A: Complementando a resposta do ctgPi você poderia criar um campo booleano para informar se a solicitação já foi alugada. Por exemplo:
ALTER TABLE solicitacaoemprestimo
ADD alugado BOOLEAN

E no seu caso ficaria:
UPDATE solicitacaoemprestimo SET alugado = 1 WHERE codemprestimo = '13';

Ao invés do DELETE.


text:
Q: Can a variable be both an object and undefined at the same time? I'm mocking chrome.storage using jasmine's spyOn function like this:
this.fakeChromeStorage = {};
chrome = { storage: { sync: {get: function() {}, set: function() {}}}};
spyOn(chrome.storage.sync, 'get').and.callFake(function(key, callback) {
    callback();
});

But then when my application calls:
console.info(chrome.storage);
console.info(typeof chrome.storage);
console.info(chrome.storage.type);
console.info(typeof chrome.storage.type);

It prints:
[object Object]
object
undefined
undefined

How is this even possible?

A: Yes, chrome.storage is an Object, chrome.storage.type is a property on the object chrome.storage which does not exists and therefor will be undefined.


text:
Q: How is Firebase's Realtime Database's rules working here? The task is to make a rule that stops us from reading a user's 'height' - but not their 'color'.
Database:
user: {
  ryan: {
    color: "red",
    height: 170,
  },
  kirsty: {
    color: "yellow",
    height: 150,
  }
}

Client code:
db.ref('user/ryan/height').on('value', (e) => {
  console.log(e.val());
})

Rule:
This seems to have worked - but I don't know why. Does height written here capture all db values named "height"?
{
    "rules": {
        ".write": true,
        "height": {
            ".read": false
        }
    }
}

A: You could try this { "rules": { ".read": true, "$color": { ".write": false } } }


text:
Q: Difficulty when constructing a nested data structure While trying to create a JSON message for an API, I found myself struggling to do something that I thought would be simple. I needed to create a message like the following:
{ "list": [ { "foo": 1, "bar": 2 } ] }

However, my first attempt did not work:
say to-json { foo => [ { a => 1, b => 2 } ] };
# {"foo":[{"a":1},{"b":2}]}

Trying to simplify things further confused me more:
say { foo => [ { a => 1 } ] };
# {foo => [a => 1]}
# Note that this is not JSON, but I expected to see curly braces

Then I tried to use some temporary variables, and that worked:
my @list = { a => 1 };
say to-json { foo => @list };
# {"foo":[{"a":1}]}

my %hash = ( a => 1 );
say to-json { foo => [ %hash ] };
# {"foo":[{"a":1}]}

What's going on here?
And is there a way I can achieve my desired output without an extra temporary variable?

A: You've discovered the single argument rule. Numerous constructs in Raku will iterate the argument they are provided with. This includes the [...] array composer. This is why when we say:
say [1..10];

We get an array that contains 10 elements, not 1. However, it also means that:
say [[1,2]];

Iterates the [1,2], and thus results in [1,2] - as if the inner array were not there. A Hash iterates to its pairs, thus:
{ foo => [ { a => 1, b => 2 } ] }

Actually produces:
{ foo => [ a => 1, b => 2 ] }

That is, the array has the pairs. The JSON serializer then serializes each pair as a one-element object.
The solution is to produce a single-element iterable. The infix , operator is what produces lists, so we can use that:
say to-json { foo => [ { a => 1, b => 2 }, ] };
#                        note the , here ^

Then the single argument to be iterated is a 1-element list with a hash, and you get the result you want.
Easy way to remember it: always use trailing commas when specifying the values of a list, array or hash, even with a single element list, unless you actually are specifying the single iterable from which to populate it.


text:
Q: Select com Inner join muito lento Estou com um problema em que o select está trazendo o resultado certo, mas demorando muito. Segue o select :
SELECT c.cod_paciente,
       p.nome,
       i.valor,
       i.quantidade,
       d.convenio,
       c.cod_conta
FROM caddadosclinico d
INNER JOIN cadcontapct c ON d.cod_paciente = c.cod_paciente
INNER JOIN cadcontitens i ON i.cod_conta = c.cod_conta
INNER JOIN cadmatmed m ON i.cod_matmed = m.cod_matmed
INNER JOIN cadpaciente p ON p.cod_paciente = c.cod_paciente
WHERE m.grupo = '1'
  AND c.dt_conta_aberta >= STR_TO_DATE('$dt_init', '%d/%m/%Y')
  AND c.dt_conta_aberta <= STR_TO_DATE('$dt_final', '%d/%m/%Y')
GROUP BY c.cod_paciente
ORDER BY p.nome

A: Cara você pode levar em consideração no seu JOIN também o tamanho de registros de cada tabela e fazer o Join de acordo com isso, por exemplo:
TDCUPANT = 900.000 registros
FINAFIM = 300.000 registros
OUTRA_TABELA = 1.000 registros

O seu join deverá começar pelas tabelas menores, ou seja, por
  OUTRA_TABELA, depois FINAFIM e por ultimo TDCUPANT. Por que isso?

Bem, quando o banco chegar na última tabela do join, grande parte dos registros já estarão separados, filtrados levando menos tempo dentro da tabela com 900.000 registros.
Claro que no seu caso não ajuda muito, mas deve melhorar um pouco a performance.
Você também pode criar índices para os campos envolvidos no relacionamento, no [i:19c2cdec39]where[/i:19c2cdec39] e no [i:19c2cdec39]order by[/i:19c2cdec39].

O que são índices?

Os índices são, grosseiramente falando, como o índice de um livro. É por ele que o banco de dados se orienta pra encontrar mais rapidamente os registros. Todo banco de dados tem este recurso.
Para se criar índice no Firebird por exemplo faça desta forma:
CREATE UNIQUE INDEX NOME_DO_INDEX ON FORNECEDORES (CNPJ,FANTASIA,RAZAO)

Aqui, estou criando um índice único com o nome
[b:b2b8d0c71d]NOME_DO_INDEX[/b:b2b8d0c71d], na tabela [b:b2b8d0c71d]FORNECEDORES [/b:b2b8d0c71d]com os campoas [b:b2b8d0c71d]CNPJ, FANTASIA e RAZAO[/b:b2b8d0c71d]. Por ser único ([b:b2b8d0c71d]UNIQUE[/b:b2b8d0c71d]) não poderei incluir um fornecedore com o mesmo [b:b2b8d0c71d]CNPJ, FANTASIA e RAZAO[/b:b2b8d0c71d] que já exista na base de dados.
Você pode criar quantos índices forem necessários para o seu banco de dados. Mas índice não é só pra esta utilidade. Os índices ajudam a integridade de dados como Checks, Constraints e Foreign Keys. Ajudam na ordenação e etc.
fonte: https://www.devmedia.com.br/forum/melhorar-o-desempenho-de-um-select-com-inner-join/31085


text:
Q: Add external js in magento using requires-config.js I have created a custom module and added requires-config.js (app\code\Namespace\Modulename\view\frontend).
var config = {
map: {
    '*': {
        test: 'https://example.com/test.js'
    }
}

};
After that I have deploy the static content, now I can see the external js has added in following location (pub\static_requirejs\frontend\Magento\luma\en_US),but still external js is not loaded in page source (using console).
Still I need to add the js files in layout?
<head>
    <link src="https://example.com/test.js"/>
</head>

A: Its good practise to put your js in Modulename/view/frontend/web/js folder rather than loading from url.
var config = {
    "map": {
        "*": {
            "test": "Modulename/js/test"
        }
    }
};

Also you don't need to add .js extenstion in the require js file.
then check it will load
Please clear the cache and also do static content deploy


text:
Q: Creating a relative path I am creating a require statement where I have a file, public_html/library/register_book.php that requires the file public_html/scripts/dial.php
What should the require statement's structure be? I've tried
require_once ('../scripts/dial.php');
require_once ('./scripts/dial.php');
require_once ('././scripts/dial.php');

etc.
Any help would be much appreciated


text:
Q: Difference between executing runables using Netbeans debugger vs without debugger What is the difference between the two.  I have a program which executes a series of runables and it works fine in debug mode but not in live mode.  I'm not sure if certain threads arent getting kicked off or if its potentially a speed factor in which debug mode is running slower and that has some affect.
Its difficult to link code as the code spans multiple classes.  I think the issue is in the following block of code though.
/**
 * The class that is used to load the track points in a background thread.
 */
protected class MonitorDirectory extends SwingWorker<Void, Void> {

    public boolean continuing = true;
    /**
     * The executor service thread pool.
     */
    private ExecutorService executor = null;
    /**
     * The completion service that reports the completed threads.
     */
    private CompletionService<Object> completionService = null;

    @Override
    protected Void doInBackground() throws Exception {
        //This is a test

        executor = Executors.newFixedThreadPool(1);
        completionService = new ExecutorCompletionService<>(executor);

        Path folder = Paths.get(directory);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        folder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        boolean valid = true;
        do {
            WatchKey watchKey = watchService.poll();
            if (watchKey != null) {
                for (WatchEvent<?> event : watchKey.pollEvents()) {
                    if (continuing == false) {
                        return null;
                    }

                    WatchEvent.Kind kind = event.kind();
                    if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
                        String fileName = event.context().toString();
                        File file = new File(directory + File.separator + fileName);
                        completionService.submit(Executors.callable(new ReadTrack(file, true)));
                        tracksModel.fireStateChanged(TracksModel.CHANGE_EVENT_TRACKS);
                        timeModel.setLoadingData(LiveTracksProvider.this.hashCode(), false);
                    }
                }
                valid = watchKey.reset();
            }
        }
        while (valid && continuing);
        return null;
    }
}

What I'm attempting here is to monitor a folder for new files and then they are passed off to a runnable and read.

A: The File monitor was seeing the file and attempting to read it before it completed being written. In debug mode because its slower it gave the program time to finish writing the file before reading it. I just put a threat.sleep(5) in after it see's the file to give it time to process it.  I give credit to finding my awnser to Joachim Rohde based on his comment.


text:
Q: Button Style Creators Update UWP I'm trying to get the effect of the button as in the windows 10 Creators Update apps.
Example Button Image
.
I have already inserted the acrylic effect using the SDK:
MainPage.xaml Code:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid x:Name="BaseGrid" Background="{ThemeResource SystemControlAcrylicElementBrush}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="1" HorizontalAlignment="Stretch" Background="White">
        </Grid>
    </Grid>
</Grid>

MainPage.xaml.cs Code:
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        Windows.UI.Xaml.Media.AcrylicBrush myBrush = new Windows.UI.Xaml.Media.AcrylicBrush();
        myBrush.BackgroundSource = Windows.UI.Xaml.Media.AcrylicBackgroundSource.HostBackdrop;
        myBrush.TintColor = Color.FromArgb(255, 202, 24, 37);
        myBrush.FallbackColor = Color.FromArgb(255, 202, 24, 37);
        myBrush.TintOpacity = 0.6;
        BaseGrid.Background = myBrush;
    }
}

But how is it possible to have the "light" effect of the mouse at its passage, the wave effect at the click?
Should it be a unique style?
thanks in advance!

A: I am extremely familiar with the example you posted from the Maps app. The effect you are looking for is called reveal. There are a number of styles you can use to enable the effect on various controls (e.g., ButtonRevealStyle for buttons). For AutoSuggestBox, you are looking to enable the effect on the items inside the suggestions list.

If you have a ListView and also have buttons or invokable content nested inside its ListViewItem elements, you should enable Reveal for the nested items.

To do this, you need to set the ItemContainerStyle property on AutoSuggestBox to a custom ListViewItem style that is based on the ListViewItemRevealStyle. If you are interested in what is going on in that style, you can check it out in generic.xaml.