text:
Q: Combine multiple maps into a map whose value for a given key is the sum of the values of the key in the combined maps I have written a program that identifies all unique words in a text document and counts how many times each of the words appears. To improve the performance of my program I am trying to break up the word counting into several goroutines that can run in parallel.
Initially, I tried using a single map that was passed by reference to each goroutine, where each goroutine would count the words in part of the document. This caused a panic because the program was trying to write to the same map from multiple goroutines simultaniously. To solve this issue, I created a mutex that would prevent multiple goroutines from writing to the map simultaniously. At this point, the program functioned as expected, but with no performance difference compared to the original sequential implementation of the WordCount function. At second thought, this is not surprising given that the mutex forces the other goroutines to wait before writing to the map, hence preventing parallel computation.
Below is the code that uses a mutex to avoid the described runtime panic, but also fails to count words in parallel.
func WordCount(words []string, startWord int, endWord int, freqs map[string]int, waitGroup *sync.WaitGroup, mutex *sync.Mutex) {
    mutex.Lock()
    for i := startWord; i < endWord; i++ {
        word := words[i]
        freqs[word]++
    }
    mutex.Unlock()
    waitGroup.Done()
}

func ParallelWordCount(text string) map[string]int {
    // Split text into string array of the words in text.
    text = strings.ToLower(text)
    text = strings.ReplaceAll(text, ",", "")
    text = strings.ReplaceAll(text, ".", "")
    words := strings.Fields(text)
    length := len(words)

    freqs := make(map[string]int)

    var mutex sync.Mutex
    var waitGroup sync.WaitGroup
    waitGroup.Add(2)
    defer waitGroup.Wait()

    threads := 2
    wordsPerThread := length / threads // always rounds down
    wordsInLastThread := length - (threads-1)*wordsPerThread
    startWord := -wordsPerThread
    var endWord int
    for i := 1; i <= threads; i++ {
        if i < threads {
            startWord += wordsPerThread * i
            endWord += wordsPerThread * i
        } else {
            startWord += wordsInLastThread
            endWord += wordsInLastThread
        }
        go WordCount(words, startWord, endWord, freqs, &waitGroup, &mutex)
    }

    return freqs
}

I belive that I could achieve parallel word counting if I would create a local map of word frequencies for each goroutine and in the end combine the local frequency maps into a single map with the word counts for the entire text file. The problem I am currently facing is how to combine the local frequency maps. Concretely, I need to know how to combine multiple maps into a map whose value for a given key is the sum of the values of the key in the maps to be combined.
To clarify the underlying logic of what I am trying to do I have included the below example. The ConcurrentSum function returns the sum of the elements in an array by computing the lower and upper halves of the array concurrently. In my case, I want to, in parallel, count words in different parts of my text file and, ultimately, combine the word counts into a single map of word counts representative of the entire document.
func sum(a []int, res chan<- int) {
    var sum int
    for i := 0; i < len(a); i++ {
        sum += a[i]
    }
    res <- sum
}

// concurrently sum the array a.
func ConcurrentSum(a []int) int {
    n := len(a)
    ch := make(chan int)
    go sum(a[:n/2], ch)
    go sum(a[n/2:], ch)
    return <-ch + <-ch
}

A: I believe you could create an array of maps each one being used for each process and then reading in each map using a list to keep track of the words you've already counted. Assuming that each word is a key to the number of times counted, that's how it looks.
     Parallel processing here might not be the best choice considering the concurrency side since everything needs to be kept separate for a real performance increase. If you have the storage space then you most certainly can use a list and get at worst case O(N) efficiency from the integration of the maps. You will need to keep the the integration of the maps in a single thread or a single process.


text:
Q: Memoise Function Compilation Error in LINQpad The following does not compile in LINQpad (Language=VB Program):
'    Hans-Christian Holm - Case study: Making use of functional programming techniques in .NET
'    [https://vimeo.com/97541187]
'    http://www.yr.no/

readonly Memos = new ConcurrentDictionary(of string, XElement)

function Memoise(f as Func(of XElement), key as string) as Func(of XElement)
    return function() Memos.GetOrAdd(key, function(k) f()) 'ERROR here!
end function

function ViewItem(temperature as integer) as XElement
    return
<%= temperature %>

end function

function ViewList(temperatures as integer()) as XElement
    return
<%= temperatures.Select(addressof ViewItem) %>

end function

function GetData() as integer()
    dim s as string = "Getting data..."
    s.Dump()
    return {2, 3}
end function

function ListComponent() as XElement
    dim data = GetData()
    return
<%= ViewList(data) %>

end function

sub Main
    dim c = Memoise(addressof ListComponent, "my-component")
    c().Dump()
    c().Dump()
end sub

This is the error message:
Overload resolution failed because no Public 'GetOrAdd' can be called with these arguments:
    'Public Function GetOrAdd(key As String, value As System.Xml.Linq.XElement) As System.Xml.Linq.XElement':
        Argument matching parameter 'value' cannot convert from 'VB$AnonymousDelegate_0(Of Object,XElement)' to 'XElement'.
    'Public Function GetOrAdd(key As String, valueFactory As System.Func(Of String,XElement)) As System.Xml.Linq.XElement':
        Argument matching parameter 'valueFactory' cannot convert from 'VB$AnonymousDelegate_0(Of Object,XElement)' to 'Func(Of String,XElement)'.

A: In LinqPad select Edit > Preferences > Advanced > Compile VB queries in strict mode > True; change your first line to:
readonly Memos as ConcurrentDictionary(of string, XElement) = new ConcurrentDictionary(of string, XElement)

and change funcion(k) to function(k as string) inside your Memoise() function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Editing category-xxx.php just as editing a page I have several category-xxx.php each with a specific introductory text.
How to enable my client to edit this text in the dashboard, in the same manner as when he edits the content of a page ? (that is, NOT in appearance > editor)

A: Use the category_description tag in your category template. Your user can then edit this text from "Posts > Categories" in the Admin area.


text:
Q: Hugo does not build without '-t' parameter Currently I am using Hugo on GitHub Pages with ease but I have a few problems in which you could possibly help me to solve. Thanks in advance if you take your time to care a bit about my question, I highly appreciate that. I am trying to be as short as possible.
My short introductory page is located here
My blog (which needs fixes) is located here

*

*Both sites are set up via the Hugo Quick Start, therefore I used the submodule way of getting the themes instead of cloning.

*Both sites are deployed into separate repositories. I have asked in other channels what would be the best and cleanest form of maintaining these sites, then some said, GitHub Project Pages is nice.

*To reach this feature, I have set publishDir to docs in both projects

*Set the master branch with /docs folder option at GitHub Pages in both cases.

The content of my introductory page loads fine while - by default - the CSS of my blog does not really want to load. (The browser wants to search it at the root - where nothing is located - instead of /Blog).
I have avoided the problem by building my Hugo site with hugo -t blog and it works fine, you can check on the link above.
When I tried to link this to Netlify, it did not work. Unfortunately, it did not build with the default version of Hugo they provide, but I was able to fix this with the creation of netlify.toml where I set 0.36 for Hugo's version.
So after that at Netlify I had to provide a build command. There hugo should go, but it did not work. CSSs are not loaded. Unfortunately, providing hugo -t blog as build command did not help either.
What I would like to acheive:
To be able to build my site without parameters just as in the other case. :)
Repositories of the projects:
Homepage
Blog
Thanks,
Armand

A: The -t parameter instructs Hugo to use the specified theme. You can instruct Hugo to use the same theme via "theme" setting in your config file instead of the -t command line parameter.


text:
Q: Posting Data and Getting Response for SOAP Client Almost all of my development experience has been in desktop applications.  I am currently using Delphi 2010 and I need to write a SOAP client to access the web service that the California EDD maintains for electronically handling payroll data.  I gave up on the Delphi WSDL Importer because there was too much happening behind the curtain and I did not seem to be able to make any progress.  I downloaded Fiddler2 and have been using that to view what I have been writing to the web.  I found this procedure for posting and I feel that I am getting somewhere now.
//from StackOverflow Andreas Rejbrand 06/04/2012
procedure WebPostData(const UserAgent: string; const Server: string; const Resource: string; const Data: AnsiString); overload;
    var
      hInet: HINTERNET;
      hHTTP: HINTERNET;
      hReq: HINTERNET;
    const
      accept: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);
      header: string = 'Content-Type: text/plain';
    begin
      hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
      try
        hHTTP := InternetConnect(hInet, PChar(Server), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
        try
          hReq := HttpOpenRequest(hHTTP, PChar('POST'), PChar(Resource), nil, nil, @accept, 0, 1);
          try
            if not HttpSendRequest(hReq, PChar(header), length(header), PChar(Data), length(Data)) then
              raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
          finally
            InternetCloseHandle(hReq);
          end;
        finally
          InternetCloseHandle(hHTTP);
        end;
      finally
        InternetCloseHandle(hInet);
      end;
    end;

I changed the Content-Type because the original seemed to never return.
I have been calling it like this:
procedure TForm1.Button1Click(Sender: TObject);
var sl: TStringList;
    s: String;
begin
  sl := TStringList.Create;
  sl.LoadFromFile('C:\Documents and Settings\Jack\Desktop\My Reading\FSET Development\Ping.xml');
  s := sl.Text;
  sl.Free;
  WebPostData('BNWebSvc', 'FSETTESTPROD.EDD.CA.GOV','fsetservice', s);
end;

In my browser, the host (FSETTESTPROD.EDD.CA.GOV) exists and responds that it is available.  When I post, I get a 404 error maybe because the web service name is appended. In Fiddler2, the output looks like this:
POST http://FSETTESTPROD.EDD.CA.GOV/fsetservice HTTP/1.1
Accept: */*
Content-Type: text/plain
User-Agent: BNWebSvc
Host: FSETTESTPROD.EDD.CA.GOV
Content-Length: 2190
Pragma: no-cache
Cookie: __utma=158387685.1851397844.1321382260.1321382260.1321382260.1; __utmz=158387685.1321382260.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=calif%20edd%20eft%20payroll%20processor%20batch%20processing

<?xml version="1.0" encoding="utf-8"?>
<log>
  <inputMessage utc="3/2/2007 10:45:44 PM" messageId="urn:uuid:c07c9aef-28db-4843-8dfc-c5b4d3dc363b">
    <processingStep description="Unprocessed message">
      <soap:Envelope xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
        <soap:Header>
          <wsa:Action>//edd.ca.gov/Ping</wsa:Action>
          <wsa:MessageID>urn:uuid:c07c9aef-28db-4843-8dfc-c5b4d3dc363b</wsa:MessageID>
          <wsa:ReplyTo>
            <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
          </wsa:ReplyTo>
          <wsa:To>http://localhost:3031/EDD.DMRC.FSET.WebServices/FsetService.asmx</wsa:To>
          <wsse:Security soap:mustUnderstand="1">
            <wsu:Timestamp wsu:Id="Timestamp-0983e8c1-e822-4648-8066-33839f54a6a0">
              <wsu:Created>2007-03-02T22:45:41Z</wsu:Created>
              <wsu:Expires>2007-03-02T22:50:41Z</wsu:Expires>
            </wsu:Timestamp>
            <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-0d55d82c-d16d-4c0e-826b-21bf7c805a0f">
              <wsse:Username>MyUserName</wsse:Username>
              <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">MyPassword</wsse:Password>
              <wsse:Nonce>w6dgDz1DMzKntFsFdEcjhw==</wsse:Nonce>
              <wsu:Created>2007-03-02T22:45:41Z</wsu:Created>
            </wsse:UsernameToken>
          </wsse:Security>
        </soap:Header>
        <soap:Body>
          <Ping xmlns="http://edd.ca.gov/">
          </Ping>
        </soap:Body>
      </soap:Envelope>
    </processingStep>
  </inputMessage>
</log>

I will need to send this using HTTPS when this is working and I probably need to incorporate that to get it working.
Am I going in the right direction?
The procedure from Andreas did not indicate how to retrieve the response.  How do I retrieve the response?

A: I think I am making some progress.  I changed WebPostData into a function and copied some code from elsewhere to use SSL and to return a result.  It now looks like this:
function WebPostData(const UserAgent: string; const Server: string; const Resource: string; const Data: AnsiString): String;
var
  hInet: HINTERNET;
  hHTTP: HINTERNET;
  hReq: HINTERNET;
  BufStream: TMemoryStream;
  BytesRead: Cardinal;
  aBuffer     : Array[0..4096] of Char;
  flags       : DWord;
const
  accept: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);
  header: string = 'Content-Type: text/plain';
begin
  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  try
    hHTTP := InternetConnect(hInet, PChar(Server), INTERNET_DEFAULT_HTTPS_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
    try
      flags := INTERNET_FLAG_SECURE or INTERNET_FLAG_KEEP_CONNECTION;
      hReq := HttpOpenRequest(hHTTP, PChar('POST'), PChar(Resource), nil, nil, @accept, flags, 1);
      try
        if not HttpSendRequest(hReq, PChar(header), length(header), PChar(Data), length(Data)) then begin
          raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
        end else begin
           BufStream := TMemoryStream.Create;
            try
              while InternetReadFile(hReq, @aBuffer, SizeOf(aBuffer), BytesRead) do
              begin
                if (BytesRead = 0) then Break;
                BufStream.Write(aBuffer, BytesRead);
              end;

              aBuffer[0] := #0;
              BufStream.Write(aBuffer, 1);
              Result := PChar(BufStream.Memory);
            finally
              BufStream.Free;
            end;
        end;
      finally
        InternetCloseHandle(hReq);
      end;
    finally
      InternetCloseHandle(hHTTP);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;

And I now get two results in Fiddler, one successful and one not.
The successful one:
CONNECT fsettestprod.edd.ca.gov:443 HTTP/1.0
User-Agent: BNWebSvc
Host: FSETTESTPROD.EDD.CA.GOV:443
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Major Version: 3
Minor Version: 1
Random: 4F 28 1F 92 96 EA 2C 64 91 59 12 84 D1 F3 F8 ED BA 89 A5 44 94 D6 50 E0 CF 9B FA 12 5F 57 AD EB
SessionID: empty
Ciphers:
    [0004]  SSL_RSA_WITH_RC4_128_MD5
    [0005]  SSL_RSA_WITH_RC4_128_SHA
    [000A]  SSL_RSA_WITH_3DES_EDE_SHA
    [0009]  SSL_RSA_WITH_DES_SHA
    [0064]  TLS_RSA_EXPORT1024_WITH_RC4_56_SHA
    [0062]  TLS_RSA_EXPORT1024_WITH_DES_SHA
    [0003]  SSL_RSA_EXPORT_WITH_RC4_40_MD5
    [0006]  SSL_RSA_EXPORT_WITH_RC2_40_MD5
    [0013]  SSL_DHE_DSS_WITH_3DES_EDE_SHA
    [0012]  SSL_DHE_DSS_WITH_DES_SHA
    [0063]  TLS_DHE_DSS_EXPORT1024_WITH_DES_SHA

And the unsuccessful one:
POST https://FSETTESTPROD.EDD.CA.GOV/fsetservice HTTP/1.1
Accept: */*
Content-Type: text/plain
User-Agent: BNWebSvc
Host: FSETTESTPROD.EDD.CA.GOV
Content-Length: 2190
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: __utma=158387685.1851397844.1321382260.1321382260.1321382260.1; __utmz=158387685.1321382260.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=calif%20edd%20eft%20payroll%20processor%20batch%20processing

<?xml version="1.0" encoding="utf-8"?>
<log>
  <inputMessage utc="3/2/2007 10:45:44 PM" messageId="urn:uuid:c07c9aef-28db-4843-8dfc-c5b4d3dc363b">
    <processingStep description="Unprocessed message">
      <soap:Envelope xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
        <soap:Header>
          <wsa:Action>//edd.ca.gov/Ping</wsa:Action>
          <wsa:MessageID>urn:uuid:c07c9aef-28db-4843-8dfc-c5b4d3dc363b</wsa:MessageID>
          <wsa:ReplyTo>
            <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
          </wsa:ReplyTo>
          <wsa:To>http://localhost:3031/EDD.DMRC.FSET.WebServices/FsetService.asmx</wsa:To>
          <wsse:Security soap:mustUnderstand="1">
            <wsu:Timestamp wsu:Id="Timestamp-0983e8c1-e822-4648-8066-33839f54a6a0">
              <wsu:Created>2007-03-02T22:45:41Z</wsu:Created>
              <wsu:Expires>2007-03-02T22:50:41Z</wsu:Expires>
            </wsu:Timestamp>
            <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-0d55d82c-d16d-4c0e-826b-21bf7c805a0f">
              <wsse:Username>***MyUserName***</wsse:Username>
              <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">***MyPassword***</wsse:Password>
              <wsse:Nonce>w6dgDz1DMzKntFsFdEcjhw==</wsse:Nonce>
              <wsu:Created>2007-03-02T22:45:41Z</wsu:Created>
            </wsse:UsernameToken>
          </wsse:Security>
        </soap:Header>
        <soap:Body>
          <Ping xmlns="http://edd.ca.gov/">
          </Ping>
        </soap:Body>
      </soap:Envelope>
    </processingStep>
  </inputMessage>
</log>

I stepped through my code and watched Fiddler react.  Both messages came when I stepped over the HTTPSendRequest line.  In my button click event, I assign the results of the function to a memo control, but all I get are a bunch of squares indicating unprintable characters.
Does the result I am getting indicate that the process is good but the content is bad?
Could this still be a problem because you can't access a WebService this way?
How can I decrypt the results or will this happen automatically when I get the process right?

A: I have now done more research, bought a decent book on web services "Teach Yourself Web Services" (thank you rooted Nook), and spoke briefly with someone at the agency whose web service I am attempting to use.  So I think I have some answers to the questions I have been asking and I will summarize them here in case it is helpful for anyone else starting down this same path.  If you see that I have misstated something and you can correct or improve it, I would appreciate it if you would take the time to enter your improvements.
In the graphics where it is shown that web services ride on HTTP it means that if you are using a component that can make a request to a website, you can probably also use it to create a web service client.
You should probably install Fiddler2 right away.  The feedback you will get from it will be essential to making progress.
A WSDL file may be helpful to create a web services client but maybe not.  My experience with the Delphi WSDL importer is that it does an incomplete job.  The Wikipedia article on web services has a section on Big Web Services that points out that the WSDL file is not necessary but can help automate the design of a web service client.  If it isn't helpful, don't use it.
You don't need to use the HTTPRIO component to access a web service.  You can use the WinInet unit with some code like above that I plagiarized from some StackOverflow postings.
The schemas referenced in the WSDL file don't have to exist at the locations shown.  Technically, these are URIs rather than URLs (identifiers rather than locations).
Writing a web service client by hand may be an acceptable alternative to automatic generation when the automatic generation doesn't work.  Besides, like so many black box solutions, it only works when it works.  When it doesn't work, there may be no other choice.  Also, you will learn more and have better control over the output.
Sending your request using SSL seems to be automatic if you use the the PostWebData routine above.  Getting the response is also included in this routine.
Getting the two responses I got from the web service seems to be indicating that my process is good but my content is bad.  I now have to look into the actual SOAP envelope and supply acceptable data to go to the next step.
If the results are not decrypted when I complete that next step, then I will have to do more research.
I hope this is helpful for someone else trying to find his or her way in web services.


text:
Q: CircleCI gems caching Is it possible to cache gems, so that bundle install will not install bunch of gems for every build? This takes 5 minutes on every build, that is too much.
I've added this to the circle.yml config:
dependencies:
  cache_directories:
    - "/home/ubuntu/.rvm/gems/ruby-2.1.2/gems/"

This is the common directory which is provided by bundle show gem_name where all system gems are put.
After this addition system writes such log:
restoring cache v4/company/repo_name/dependency/circle-ci/42/mGWhlYQIxyOy0GZtt4QmCw__.tar.gz
restoring home/ubuntu/repo_name/vendor/bundle, home/ubuntu/.m2, home/ubuntu/.ivy2, home/ubuntu/.go_workspace, home/ubuntu/.gradle, home/ubuntu/.rvm/gems/ruby-2.1.2/gems

So, as far as I understand, it restores system gems and gems installed into vendor/bundle, however, I still see this (and this takes a lot of time):
Installing rake 10.4.2
Installing i18n 0.7.0
Installing json 1.8.2
Installing minitest 5.5.1
...

instead of
using rake 10.4.2
using i18n 0.7.0
using json 1.8.2
using minitest 5.5.1
...

So, it seems, it should work, but it does not. What can be wrong?

A: The solution is simple: CircleCI runs some commands by default and caches gems also by default in vendor/bundle, so there is no need to add anything to cache_directories.
Among those default commands is bundle check --path=vendor/bundle || bundle install --path=vendor/bundle --jobs=4 --retry=3, that checks presence of gems in the cache directory and installs them if they are not there.
In my case I had project consisting of multiple applications (main application, common UI, API client and API mock) split into 4 different repos. Most of them needed bundle install commands.
The only thing I had to do is to replace all my bundle install commands (that always installs gems) with bundle check --path=vendor/bundle || bundle install --path=vendor/bundle --jobs=4 --retry=3. In such case all gems are installed only the first time I run tests and all the following builds use previously cached gems.


text:
Q: error in Firebase connection in android Gradle library dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.1'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.github.ittianyu:BottomNavigationViewEx:1.2.4'
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.google.firebase:firebase-core:16.0.0'
    implementation "com.google.android.gms:play-services-base:11.4.2"
    implementation 'com.google.firebase:firebase-auth:11.4.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

*

*List item
private  void setUpFirebaseAuth(){
    mAuth = FirebaseAuth.getInstance();
   mAuthStateListener = new FirebaseAuth.AuthStateListener() {

       @Override
       public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
           FirebaseUser user = firebaseAuth.getCurrentUser();

           // check the user is login
           checkCurrentUser(user);
           if(user != null){
              // user is login
           }else {
               // user signed out
           }

       }
   };
}


text:
Q: Does it make sense to form a set whose elements are proper classes? In chapter 4 of Handbook of Categorical Algebra, vol 1, the author defines a "subobject of $A$" as "an equivalence class of monomorphisms with codomain $A$" (for a suitable notion of equivalence). He then defines what it means for a category to be well-powered: "$\mathcal{A}$ is well-powered when the subobjects of every object constitute a set". Thus, for instance, the category of sets is well-powered.
I'm having trouble understanding exactly what it means to have such a set of subobjects. As far as I can tell, each element of a set should also be a set, but an equivalence class of monomorphisms could be a proper class: for instance, the class of singleton sets is not a set. On the other hand, it seems that one can cheat by defining a subobject to be a class containing one representative of each equivalence class of monomorphisms, even though this is not, strictly speaking, what's stated in the book.
How can one solve this problem? Is there a "normal" set theory where such a set of subobjects can contain proper classes? Or does one need to cheat like suggested above?

A: No, proper classes are not elements of other sets (or other classes, for that matters).
But this is the great power of universes. Classes of one universes are just sets in a larger universe. So when you want to talk about collections of classes, you move to a larger universe, where you can treat them formally as sets.
Another, more complicated method of solving this issue, is to talk about schema of definitions when it comes to equivalence, and then the collections are represented by one of the classes (and you can sometimes prove that this representative doesn't matter). Then the whole thing becomes a much more technical and involved from a formal point of view, which is not a bad thing. But I think that if you're interested in category theory and want to talk about larger and larger categories, then universes are probably the way to go.


text:
Q: Jmeter - how to pass cookie captured in one thread to another thread I am trying to use same cookie(i.e. capturing cookies in main thread and trying to pass it in support threads) in different threads in Jmeter. I have already read the article give at
https://blazemeter.com/blog/queen-jmeters-built-componentshow-use-beanshell
but its not working in my case. Can someone please help in recognizing what mistake I am doing while implementing the logic given in above link.
please find below steps I am following
  Test Plan
     - HTTP Cache Manager
     - HTTP Header Manager
     - HTTP Cookie Manager
     - Main Thread(login page under main thread)
        - Login (BeanShell PostProcessor under login)
           - BeanShell PostProcessor
         import org.apache.jmeter.protocol.http.control.CookieManager;
         CookieManager manager = ctx.getCurrentSampler().getProperty("HTTPSampler.cookie_manager").getObjectValue();
         props.put("cookiecount", String.valueOf(manager.getCookieCount()));
         for (int i = 0; i < manager.getCookieCount(); i++)
         {
            props.put("cookie_name" + i, manager.get(i).getName());
            props.put("cookie_value" + i, manager.get(i).getValue());
            props.put("cookie_domain" + i, manager.get(i).getDomain());
            props.put("cookie_path" + i, manager.get(i).getPath());
            props.put("cookie_expires" + i, String.valueOf(manager.get(i).getExpires()));
            props.put("cookie_secure" + i, String.valueOf(manager.get(i).getSecure()));
         }

     - Support Thread 1
          - BeanShell PreProcessor
              import org.apache.jmeter.protocol.http.control.CookieManager;
              import org.apache.jmeter.protocol.http.control.Cookie;
              import org.apache.jmeter.testelement.property.JMeterProperty;
    CookieManager manager = ctx.getCurrentSampler().getProperty("HTTPSampler.cookie_manager").getObjectValue();
    int count = Integer.parseInt(props.getProperty("cookiecount"));
    for (int i = 0; i < count; i++) {
        Cookie cookie = new Cookie(props.getProperty("cookie_name" + i),
                  props.getProperty("cookie_value" + i),
                props.getProperty("cookie_domain" + i),
                props.getProperty("cookie_path" + i),
                Boolean.parseBoolean(props.getProperty("cookie_secure" + i)),
                Long.parseLong(props.getProperty("cookie_expires" + i)));
                manager.add(cookie);
    }
    JMeterProperty cookieprop = ctx.getCurrentSampler().getProperty("HTTPSampler.cookie_manager");
    cookieprop.setObjectValue(manager);
    ctx.getCurrentSampler().setProperty(cookieprop);
           - HTTP Request

After running it for 1 thread - 1 loop getting different cookies for both threads something like below
- Main Thread
  Cookie Data:
JSESSIONID=PvRSWmBXNp9y65njGkRWbLlxLM1pvxLzpnyjThQDny3pMy6Gkcjv!486373045

- Support Thread
  Cookie Data:
JSESSIONID=YVGsWmQSXdGt1xqfDDvlkgkHLpqJ3WRD2sDyqXp62rChfTDbM0Vj!486373045

I have set CookieManager.save.cookies=true.

A: Just use 2 different HTTP Cookie Manager test elements for different thread groups.

P.S. If you already have CookieManager.save.cookies=true property set and you know cookie names - you can use __setProperty() function to pass variables which hold cookie values between thread groups like:

*

*In 1st Thread Group convert variable to property like ${__setProperty(JSESSIONID,COOKIE_JSESSIONID,)}

*In 2nd Thread Group refer the property as ${__P(JSESSIONID,)}
The approach is described in details in the  How to Use Variables in Different Thread Groups article.


text:
Q: Change option in select drop down using javascript Firstly apologies if this is a dumb question, I'm rather new to javascript.
I have a select box which is generated by my organisations CMS. I can't change the drop down's content or how it is generated. What I would like to do however is when the page is loaded, change the default (or "selected") option based on a particular value. The other problem is the default is already set in the select drop down is created in HTML. If I could actually change the way options for the select drop down I could easily create some javascript to set the default selection, unfortunately I can't. I'm completely lost. Any assistance would be greatly appreciated.
Code used:
I unfortunately cannot change this:
<select name="q528696:q1" id="q528696_q1"  class="sq-form-field"><option value="0" selected="selected">Address adult language literacy and numeracy | 688</option>*More options here*</select>

This is the javascript used. It's very simple:
<SCRIPT> window.onload=updateSelect();
function updateSelect() {
document.getElementById('q528696:q1').value=25;
};
</SCRIPT>

A: To change a selected option using JavaScript is very simple. But still, I'll break it down.
Let's start off with a simple drop down list with three options. The select tag will have an id of "change".
<select id="change">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>

We want it so that when we press a button "Two" will be the selected option instead of "One". We'll start making our button and making a basic function.
<input type="button" value="Change Selected Option" onclick="changeS()"/>
<script>
function changeS() {

}
</script>

In this function we add the following code
document.getElementById('change').getElementsByTagName('option')[1].selected = true;

Let's take a look at what it's doing.
First, we target the "select" tag with document.getElementById.
Then we get all the elements with a tag name of "option" in the "select" element.
The "[1]" means that we target the second option in the list. The reason we have "1" not "2" is because JavaScript starts counting at "0". If we wanted to target the third option, we would put "[2]".
After that, we just say that we want that specific option in the select tag to be the selected option.I hope it's simple enough and that my explaining was worthwhile :)

A: I'm answering to this question: How do I change the value of a select element's option? Here's code with comments to help out.
<!--First we'll make a a select element with an option-->
<select>
<option value="Unchanged Value" id="1"></option>
</select>
<!--Now we'll create a button that'll display the value of this option. Refer to the "displayOptionValue" function down below to find out how this is done-->
<input type="button" onclick="displayOptionValue()" value="Display Option Value"/>
<<input type="button" onclick="changeOptionValue()" value="Change Option Value"/>
<!--Here's where the value will display-->
<p id="demo"/>
<script>
//This will get the option's value and display it in the "p" tag
function displayOptionValue() {
var x = document.getElementById("1").value;
document.getElementById("demo").innerHTML = x;
}
//Now we'll change the value
function changeOptionValue() {
document.getElementById("1").value = "Changed Value";
}
</script>

That's what I understand the question to be. If it's not, tell me in the comments and I'll post another answer. Also, if you run the code in your browser, first press "Display Option Value" then "Change Option Value" and then press "Display Option Value" again to see the changes. Once again, if this isn't your question, let me know in the comments.


text:
Q: HTTP Error 403.14 - Forbidden in asp.net visual studio 2012 I was editing my CSS code and every thing was OK for hours but just for once i saved the code and reloaded the web page  this error (HTTP Error 403.14 - Forbidden) appeared.
i don't know what's wrong with it and why such problem appeared suddenly.
- I tried to use microsoft suggestion:  http://support.microsoft.com/kb/942062 but directory c:\windows\system32\inetsrv is empty (!) so inetmgr.exe could not be opened. - adding these to web.config:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

wasn't useful too.and setting the <modules runAllManagedModulesForAllRequests="false"> does not make any changes.I updated visual studio 2012 and it wasn't useful too.
(IIS 8.0 express  seems to be installed correctly , also visual studio 2010 is installed on my machine).
later I found out that if more than one vs2012 is opened this error could be displayed.
thanks in advance...

A: after updating my Visual studio i never faced such error , it seem there was a bug on my previous version of software , but this error also can appear when user is editing a class or web.config and start debugging the application . by the way if you have my problem re-install VS or just upgrade it , I hope it helps you and prevents wasting your time.


text:
Q: Meaning of "highlighted" in the given context I am not sure about the meaning of the word " highlighted" in the following sentence:

A number of offers from the best restaurants, with set menus,
  discounts and seasonal savings all highlighted.

The text is a description of the restaurant offers seen in the dining advertisements.
Thanks for your help.

A: When something is highlighted is means that the whomever is highlighting is trying to draw attention to it.  It can either be physically

or simply a list if the best features of what's being highlighted.


text:
Q: NetworkStream.Read - can it collect partial messages? I'm creating a client-server application and I'm just wondering about one thing.
Client serializes Query object to String and then uses NetworkStream to send it to the server.
Server reads bytes using GetStream().Read, writes it into a buffer, deserializes that string into a Query object and gets information stored in received query.
Is it possible that Read() method could return partial message (that has not already arrived completely)?
Or, for example, in case of immediate sending two messages, is it possible to read two messages as one string of bytes, by one call of Read() method?
Or maybe NetworkStream somehow knows how to recognize complete messages and each Read() is associated with each message?
Thank you in advance.

A:
Is it possible that Read() method could return partial message ?

Yes,
if you see MSDN Doc it says:

This method reads data into the buffer parameter and returns the number of bytes successfully read. If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method completes immediately and return zero bytes.

So Always check the returned (int) value of the Read() method and see if the method has read Expected number of Bytes.

In case of immediate sending two messages, is it possible to read two messages as one string of bytes, by one call of Read() method ?

Most Probably No.


text:
Q: htaccess not working for page other than index i want to hide variable from the url for a specific page like for domain/page.php?r=1 to domain/page/1
the htaccess is working for the index page but if i change the htaccess file for the specific page it stops working
here is my code
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?r=$1
RewriteCond %{reset_pass} !-d
RewriteCond %{reset_pass}\.php -f

from this code i can print value of r if the page is index. but if i change it to other page it is not working


text:
Q: Make pgfplot lines dashed automatically below maximum of functions I want to create a graph which displays linear functions whose maximum builds a piecewise-linear-function (PWLF) labeled max in the minimum working example below. Currently, to highlight the maximum, I'm adding a plot which calls max() and as arguments, takes the linear functions and overlays another plot in thick black to show the PWLF. The contributing functions are drawn as dashed manually to highlight the fact that they are "not contributing" in certain regions.
Really, what I'd like to do is have all the lines be dashed if they are not part of the maximum and otherwise be solid, to retain the color information in the PWLF as to which linear function makes up that segment of the plot.
Is there any way to do this descriptively, ideally without having to draw out the line segments manually? I really don't want to have to calculate the intersections for each example and then create appropriate plots every time.
The MWE currently generates this output:

MWE:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usetikzlibrary{positioning}
\usepackage{amsmath}

\pgfplotsset{
    legend entry/.initial=,
    every axis plot post/.code={%
            \pgfkeysgetvalue{/pgfplots/legend entry}\tempValue
            \ifx\tempValue\empty
                    \pgfkeysalso{/pgfplots/forget plot}%
            \else
                    \expandafter\addlegendentry\expandafter{\tempValue}%
            \fi
    },
}

\begin{document}

\begin{figure}
    \centering

    \begin{tikzpicture}

        \begin{axis}[width=\textwidth, enlargelimits=false, legend pos=outer north east, ytick=\empty, xtick={0, 1}, %
            xticklabels={1 - $S_0$, $S_0$}]
            \addplot[blue, dashed, thick, no marks, domain=0:1, legend entry=$a_1$]%
                ({x},{0.8 - 0.5*x});%

            \addplot[olive, thick, dashed, no marks, domain=0:1, legend entry=$a_2$]%
            ({x}, {0.6 - 0.2*x});%

            \addplot [red, thick, dashed, no marks, domain=0:1, legend entry=$a_3$]%
            ({x}, {0.3+0.4*x});%

            \addplot [orange, dashed, thick, no marks, domain=0:1, legend entry=$a_4$]%
            ({x}, {0.5+0.1*x});%

            \addplot [black, ultra thick, no marks, domain=0:1, legend entry=$\text{max}$] {max(0.8-0.5*x,0.3+0.4*x, 0.5+0.1*x)};

        \end{axis}
    \end{tikzpicture}
\end{figure}
\end{document}

A: The sagetex package can handle this. It's documentation is located on CTAN here. This allows you to farm out the work to a computer algebra system, SAGE, which has its website here. This means you will need to download SAGE to your computer and install it properly or open up a free Cocalc account. If you have a Cocalc account, just paste create a LaTeX document, copy/paste the code below into your document, save it, and then press build to see the result. EDIT: I've modified the code to fix a mistake in the legend and to make it look more like the plot the OP has posted. Putting max function into the legend colors it solid blue so I've left it out.
\documentclass[border=4pt]{standalone}
\usepackage{sagetex}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\begin{document}
\begin{sagesilent}
f1 = 0.8-0.5*x
f2 = 0.6-0.2*x
f3 = 0.3+0.4*x
f4 = 0.5+0.1*x
t = var('t')
LowerY = 0.0
UpperY = 1.0
LowerX = 0.0
UpperX = 1.0
step = .001

f1x = [t for t in srange(LowerX,UpperX,step) if     f1(t)==max(f1(t),f2(t),f3(t),f4(t))]
f1y = [f1(t) for t in f1x]
f2x = [t for t in srange(LowerX,UpperX,step) if f2(t)==max(f1(t),f2(t),f3(t),f4(t))]
f2y = [f2(t) for t in f2x]
f3x = [t for t in srange(LowerX,UpperX,step) if f3(t)==max(f1(t),f2(t),f3(t),f4(t))]
f3y = [f3(t) for t in f3x]
f4x = [t for t in srange(LowerX,UpperX,step) if f4(t)==max(f1(t),f2(t),f3(t),f4(t))]
f4y = [f4(t) for t in f4x]

output = r""
output += r"\begin{tikzpicture}[scale=.7]"
output += r"\begin{axis}[width=\textwidth, enlargelimits=false, legend pos=outer north east, ytick=\empty, xtick={0, 1}, xticklabels={1-$S_0$,$S_0$}]"

output += r"\addplot[blue, dashed, thick, no marks, domain=0:1]"
output += r"({x},{0.8 - 0.5*x});"
output += r"\addlegendentry{$f1$}"
output += r"\addplot[olive, thick, dashed, no marks, domain=0:1]"
output += r"({x}, {0.6 - 0.2*x});"
output += r"\addlegendentry{$f2$}"
output += r"\addplot [red, thick, dashed, no marks, domain=0:1]"
output += r"({x}, {0.3+0.4*x});"
output += r"\addlegendentry{$f3$}"
output += r"\addplot [orange, dashed, thick, no marks, domain=0:1]"
output += r"({x}, {0.5+0.1*x});"
output += r"\addlegendentry{$a4$}"

if len(f1x)>1:
    output += r"\addplot[blue,thick] coordinates {"
    for i in range(0,len(f1x)-1):
        output += r"(%f,%f) "%(f1x[i],f1y[i])
    output += r"};"

if len(f2x)>1:
    output += r"\addplot[olive,thick] coordinates {"
    for i in range(0,len(f2x)-1):
        output += r"(%f,%f) "%(f2x[i],f2y[i])
    output += r"};"

if len(f3x)>1:
    output += r"\addplot[red,thick] coordinates {"
    for i in range(0,len(f3x)-1):
        output += r"(%f,%f) "%(f3x[i],f3y[i])
    output += r"};"

if len(f4x)>1:
    output += r"\addplot[orange,thick] coordinates {"
    for i in range(0,len(f4x)-1):
        output += r"(%f,%f) "%(f4x[i],f4y[i])
    output += r"};"

output += r"\end{axis}"
output += r"\end{tikzpicture}"
\end{sagesilent}
\sagestr{output}
\end{document}

The output in Colcalc is shown below:

A close up view:

Python is the language used in SAGE. After defining your 4 lines as f1 through f4, the code
f1x = [t for t in srange(LowerX,UpperX,step) if     f1(t)==max(f1(t),f2(t),f3(t),f4(t))]
f1y = [f1(t) for t in f1x] creates a list of x and y coordinates for line f1. A point is added to f1x if f1 is the maximum point on all 4 lines, in which case the y value is added into f1y. It might be the case (such as 3  lines intersecting at the same point) that there is only 1 x-value for which a line achieves the maximum, in which case we don't plot that; any line truly part of the max function will have at least two points at which it achieves the max. So assuming f1 has more than one point in it, checked by if len(f1x)>1: the line will be plotted in as part of the max function.


text:
Q: Can't figure out how to scroll down/up by 50px in js when i click a button This is the code I have currently. What I want to do, is when I click a button - Move up- I want the text in area3 to move up by 50px. But right now its moving all the way back up to the top. This is for a h/w assignment and we're doing pretty basic js/jquery if that needs to be said? :) Any help will be appreciated! Thanks!

$("#moveUp").click(function(event){
  event.preventDefault();
  var scrollPos = $(".area").scrollTop();
  var newPos = scrollPos - 50;
  $(".area3").scrollTop(newPos);
})

 blah blah

  <button id="moveUp">Move Up</button>

A: $("#moveUp").click(function(event){
    window.scrollTo(0, window.scrollY - 50)
})

window.scrollTo(x, y) is a method which will scroll the screen to given coordinates where x is horizontal and y vertical. The top left corner of the screen is 0, 0. Than window.scrollY gets the current vertical position of the screen, you just need to subtract 50 to scroll 50px up from your current position

A: If I'm not wrong, I think this could help you:
$("#moveup").click(function(){
        $(".area3").css({"margin-top":"-=50px"});
    });

A: if you want just the text in area3 to move you should use some css to correctly implement this behavior with jQuery, using animate() to add some ease with smooth animation to the text.

$("#moveUp").click(function(event){
  event.preventDefault();
  $('.area3').animate({
    position: 'absolute',
    bottom: +50
  }, 'slow');
})
.area3 {
  position: relative;
  height: 200px;
}

.area3 span {
  position: absolute;
  bottom: 50px;
}

  blah blah

  <button id="moveUp">Move Up</button>

but if you want the whole window to scroll you can do that as following we using the same approach with different selectors body and html

$("#moveUp").click(function(event){
  event.preventDefault();
  $('body, html').animate({
    scrollTop: -50
  }, 500);
})
body, html {
  height: 1000px
}
.area3 {
  margin-top: 100px
}

  blah blah

  <button id="moveUp">Move Up</button>

if you wanna to do it with window interface you can occur that by changing the above code to
$("#moveUp").click(function(event){
  event.preventDefault();
  window.scrollTo(0, -50);
})

with this approach using window you can make it moving smoothly like we did above you can't use jQuery animate() API javascript gonna raise an error don't do that.


text:
Q: get a specific element from an array I have an array as follows and i want to get any specific element from this array: array is stored in a variable as.
   $results =

        Array
           (
        [0] => stdClass Object
                         (
        [id] => 1
        [calendar] => 1
        [time] => 2016-01-22 17:25:28
        [booked_time] => 01/22/2016 11:00
        [booked_time_unformatted] => 2016-01-22 11:00:00
        [name] => Shoaib
        [email] => shoaib@techleadz.com
        [phone] => 0987654321
        [question] => 123
        [quantity] => 1
        [buffered_date] => a:9:{s:5:"PRICE";s:2:"25";s:10:"COUPONCODE";s:0:"";s:8:"QUANTITY";N;s:4:"NAME";s:6:"Shoaib";s:5:"EMAIL";s:20:"shoaib@techleadz.com";s:5:"PHONE";s:10:"0987654321";s:8:"COMMENTS";s:3:"123";s:4:"DATE";s:10:"01/22/2016";s:4:"TIME";s:5:"11:00";}
        [submitted] => 1
    )

[1] => stdClass Object
    (
        [id] => 2
        [calendar] => 1
        [time] => 2016-01-23 10:39:30
        [booked_time] => 01/25/2016 15:00
        [booked_time_unformatted] => 2016-01-25 15:00:00
        [name] => Shoaib
        [email] => shoaib@techleadz.com
        [phone] => 0987654321
        [question] => dsadasd
        [quantity] => 1
        [buffered_date] => a:9:{s:5:"PRICE";s:2:"25";s:10:"COUPONCODE";s:0:"";s:8:"QUANTITY";N;s:4:"NAME";s:6:"Shoaib";s:5:"EMAIL";s:20:"shoaib@techleadz.com";s:5:"PHONE";s:10:"0987654321";s:8:"COMMENTS";s:7:"dsadasd";s:4:"DATE";s:10:"01/25/2016";s:4:"TIME";s:5:"15:00";}
        [submitted] => 1
    )

[2] => stdClass Object
    (
        [id] => 3
        [calendar] => 1
        [time] => 2016-01-23 11:27:22
        [booked_time] => 01/25/2016 11:00
        [booked_time_unformatted] => 2016-01-25 11:00:00
        [name] => test
        [email] => shoaib@techleadz.com
        [phone] => 0987654321
        [question] => asfas
        [quantity] => 1
        [buffered_date] => a:9:{s:5:"PRICE";s:2:"25";s:10:"COUPONCODE";s:0:"";s:8:"QUANTITY";N;s:4:"NAME";s:4:"test";s:5:"EMAIL";s:20:"shoaib@techleadz.com";s:5:"PHONE";s:10:"0987654321";s:8:"COMMENTS";s:5:"asfas";s:4:"DATE";s:10:"01/25/2016";s:4:"TIME";s:5:"11:00";}
        [submitted] => 0
    )

            )

Now i have an array like this so how i can get the the value for [submitted] foreach element in this array.

A: This is not an array . This is a StdClass  Object
To access information in stdClass
 $results[6]->submitted;

A: To randomly access a specific field use
echo $results[0]->submitted;
echo $results[0]->quantity;
echo $results[1]->submitted;
echo $results[1]->quantity;

Using a foreach loop
foreach ( $results as $result ) {
    echo $result->submitted . '
';

    echo $result->booked_time . '
';
    echo $result->name . '
';
    echo $result->time . '
';
    echo $result->email . '
';
}


text:
Q: using double quotes and if condition in excel I have cell that contains double quotes and comma and i want to check if the value of the cell has 0 or blank then i want to convert it into 0.00 so that is the basic idea of what i am trying to do here.  so here is my actual data look like:
A        B
001     "0",
002     "200",
003     "",
004     "320",

so i want to say if the cell contains this value:
 "0",

or this:
"",

then i want to change it into this:
"0.00",

this is my formula now and it does not work:
=if(B2=""0","0.00", , B2")

A: You need to escape all the double quotes, and use the or function to test both cases you want:
=if(or(B2="""0"",",B2=""""","),"""0.00"",",B2)


text:
Q: Studying inflation on my groceries, how to correctly show the increase of prices? I have price data from the last two years from my online groceries purchases on an online supermarket for all the products I bought. I want to study the increase of prices for the products that I usually buy; since I didn't always buy the same products, I am taking an average of a six months period for all the products that I take into account, so my data is resampled with a period of six months.
Now I am facing the problem that I don't know what is a correct way to show inflation/price change:

*

*Absolute differences don't tell much since the same absolute increase for different starting prices has a different impact

*Relative or percentage price increases are more suitable, however, what's a good way to show the increase of prices? If I am considering periods of six months, I could show the increase w.r.t. the previous period, but this can be misleading. For instance, if a 1\$ product increases 20%, the new price is 1.20\$, but if it now deceases 20% it will have a price of 0.96\$, so if I use relative increases I will see +20%, then -20%, which might lead to think that the price is the same as in the beginning, but that's not the case

*I could use the increase w.r.t. the original price, but not always the first price was the lowest. For some products, I noticed that their price went down on 2021 w.r.t. 2020 and up again in 2022.

What would be a good way to show how prices changed in the last two years?


text:
Q: Angular JS form validation is not working My form validation is not working on clicking of submit button. I have properly added controller in HTMl.Any lead will be appreciated.Thanks in advance :)
 <form id="formbody"  ng-submit="submit(user)" name="form" novalidate="">

      <ion-label class="labelstyle" > Select Service  </ion-label>
      <input  ng-click="goToPage()" name="selectsrve" type="text" class="formtext1 inputimg"  ng-model="user.firstname" placeholder=" Select from list" required="">

      </input>
      Please select the Service

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

        </form>

.controller('ExampleController',function($scope,$location,$scope, $stateParams){
     $scope.singleSelect='';

     $scope.goToPage=function(){
        console.log("selectservice");
        $location.path("/selectservice");
     }

     $scope.submit = function(){
    // Set the 'submitted' flag to true
    alert("In the submit button");
    $scope.submit=function(user){
        alert("user"+user.firstName);
    };

  }

    })

A: Your $scope.submit function should be like this. Remove the other $scope.submit function inside of it. And why do you have a ng-click inside your input? and it redirect when you click your input
$scope.submit = function(user){

     alert("user"+user.firstName);
}

A: I have made few changes in your code
in your span instead of user.firstname.$dirty && users.firstname.$error.required you should use form name and input field name form.$submitted && form.selectsrve.$invalid && form.selectsrve.$error.required
you can also use condition in your ng-submit to submit form only if it is valid ng-submit="form.$valid && submit(form)"
and in your controller use scope variable to get user
$scope.submit=function(){
        alert("user "+$scope.user.firstname);
    };

Please have a look at this plunker


text:
Q: Fill under a fractal curve I am creating a class that I will use for my notes and, as the front page, I intended to have a fractal running through the diagonal of the page and the two parts created by the path, filled with different colors.
As you can see in the image I managed to get the fractal but the fill does not properly work. I have tried different approaches: using \filldraw while creating the fractal, using path picture as shown in this question and answer, clipping and more but none of them gave different results than what you can see in the following picture.

This picture was created by the following code:
\documentclass{article}

\usepackage{tikzpagenodes}
\usetikzlibrary{decorations.fractals}

\begin{document}
\begin{tikzpicture}[overlay, remember picture]
  \fill[blue] (current page.north west) rectangle (current page.south east);
  \filldraw[fill=red,decoration=Koch curve type 2,draw=white,very thick]
    decorate {
      decorate {
        decorate {
          (current page.north west) --
          (current page.south east)
        }
      }
    };
\end{tikzpicture}
\end{document}

I am then trying to understand how I can properly achieve what I want. What options are there?
Thanks for your time!

A: As suggested by Phelype Oleinik in the comments, here's the fixed code:
\documentclass{article}

\usepackage{tikzpagenodes}
\usetikzlibrary{decorations.fractals}

\begin{document}
\begin{tikzpicture}[overlay, remember picture]
  \fill[blue] (current page.north west) rectangle (current page.south east);
  \fill[fill=red,decoration=Koch curve type 2,very thick]
    decorate {
      decorate {
        decorate {
          (current page.north west) --
          (current page.south east)
        }
      }
    } -- (current page.south west) -- cycle;
  \draw[draw=white,decoration=Koch curve type 2,very thick]
    decorate {
      decorate {
        decorate {
          (current page.north west) --
          (current page.south east)
        }
      }
    };
\end{tikzpicture}
\end{document}


text:
Q: Is it possible to call value type operators via reflection? As C# operators e.g. +, +=, == are overridable. It lets me think they are sort of methods, thus wonder if there is a way to call them using reflection, on Int32 for instance.

A: Yes, the custom operators are invokable using reflection (they have special names, such as op_Addition), but System.Int32 doesn't define them, as fundamental, built-in, types are handled directly by IL opcodes like add, rather than method calls.

A: What exactly is it you want to do? Dealing with the various meanings of operators (primitive  (mapped to specific IL instructions), custom (mapped to static methods), and lifted (provided as a pattern by the compiler)) makes this painful. If you just want to use the operators, then it is possible to write code that provides operator support via generics. I have some code for this that is freely available in MiscUtil (description and examples).

As an untyped example (an note that this isn't hugely efficient, but works):
object x = 123, y = 345; // now forget that we know that these are ints...
object result = Expression.Lambda<Func<object>>(
    Expression.Convert(Expression.Add(
        Expression.Constant(x), Expression.Constant(y)),
    typeof(object))).Compile()();

A: What about this, it's simple, small and works :)
public T Add<T>(object x, object y)
{
    return (T)Convert.ChangeType((dynamic)x + (dynamic)y, typeof(T));
}

A: It would be very inefficient if adding or comparing two integers required a method call so these simple operations on the fundamental types are code-generated as explained in another answer and cannot be invoked using reflection. One interesting built-in value type is decimal (or System.Decimal). This struct has support for literal values in C#, but behaves a lot like a real value type and exposes a lot of operators that can be invoked via reflection.
If you are curious you can use Reflector to browse all members exposed by System.Int32.

A: There are good answers here, so just to add something not mentioned yet:
A struct might have an operator overloaded. This means more options to check if you try to create some programmatic approach.
One nice thing to try out is, to try the expression tree approach. Here's a small sample. Of course, performance isn't too nice, but we know what we're getting into with Reflection, anyway.


text:
Q: Rhinomocks, how to verify that a stub/mock was never called at all? Using Rhinomocks, how can I verify that a Mock/stub was never called at all? Meaning no methods was called on the mock/stub?
I am aware of the AssertWasNotCalled method, but this method requires that I mention a method name. (Perhaps I have a class with 10 different methods that could be called).
 Log.AssertWasNotCalled(x => x.LogAndReportException(null, null), x => x.IgnoreArguments());

A: You can use a Strict mock, althought this is a feature that may go away in the future:
var mocks = new MockRepository();
var cm = mocks.StrictMock<ICallMonitor>();
cm.Replay();

cm.HangUp(); // this will cause VerifyAllExpectations to throw
cm.VerifyAllExpectations();

In this syntax, a Strick Mock only allows explicitly defined calls.

A: You can use the StrictMock method to create a strict mock - this will fail if any unexcepted method call is used. According to Ayende's site, this is discouraged, but it sounds like exactly the scenario where it would be useful.

A: When you are using mocks, you should not assert every single call was made or not. That couples your tests to a particular implementation and makes them fragile and a refactoring nightmare.
If I ever ran into this situation I would rethink why I wanted to assert that a dependency was never used.
Obviously, if the dependency is not used anywhere, just remove it. If it is needed for some operations, but all the operations in the dependency are destructive operations and you want to make sure some operation does not do harm with them, you should assert explicitly that the destructive operations were not called and allow the implementation to do whatever it wants with the non-destructive operations (if there are any). This makes your tests more explicit and less fragile.


text:
Q: Dynamically replace ListView table cell with textField wicket I have a listView which has a single column which needs to be editable only in certain cases. If the user needs to change the column, I want them to click a edit button for the row, then replace the label in the cell with a textField. When I call replace I can see the TextField is now in the place of the label, although it is never rendered. I have a AjaxLink to handle the event. I am using a container to repaint the listView. Here is my listview:
    parent = new WebMarkupContainer("emp-table-parent");

    parent.add(new AjaxLink<Object>(FIRST_NAME_HEADER_LINK) {

        /**
         *
         */
        private static final long serialVersionUID = -1937727929649333407L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            changeGlyphUpdateList(target, parent.get(FIRST_NAME_HEADER_LINK).get(FIRST_NAME_HEADER_ICON),
                    parent.get(LAST_NAME_HEADER_LINK).get(LAST_NAME_HEADER_ICON),
                    parent.get(EMAIL_HEADER_LINK).get(EMAIL_HEADER_ICON), parent.get(ELIGIBILITY_CLASS_HEADER_LINK).get(ELIGIBILITY_CLASS_HEADER_ICON),
                    parent.get(EMPLOYER_HEADER_LINK).get(EMPLOYER_HEADER_ICON));

        }

    }.add(new Label("first-name-header-label", Model.of("First Name")), new WebComponent(FIRST_NAME_HEADER_ICON)),
            new AjaxLink<Object>(LAST_NAME_HEADER_LINK) {

                /**
                 *
                 */
                private static final long serialVersionUID = -3438649095509412910L;

                @Override
                public void onClick(AjaxRequestTarget target) {

                    changeGlyphUpdateList(target, parent.get(LAST_NAME_HEADER_LINK).get(LAST_NAME_HEADER_ICON),
                            parent.get(FIRST_NAME_HEADER_LINK).get(FIRST_NAME_HEADER_ICON),
                            parent.get(EMAIL_HEADER_LINK).get(EMAIL_HEADER_ICON),
                            parent.get(ELIGIBILITY_CLASS_HEADER_LINK).get(ELIGIBILITY_CLASS_HEADER_ICON),
                            parent.get(EMPLOYER_HEADER_LINK).get(EMPLOYER_HEADER_ICON));

                }
    }.add(new Label("last-name-header-label", Model.of("Last Name")), new WebComponent(LAST_NAME_HEADER_ICON)),
            new AjaxLink<Object>(EMAIL_HEADER_LINK) {

                /**
                 *
                 */
                private static final long serialVersionUID = 2890934302751793454L;

                @Override
                public void onClick(AjaxRequestTarget target) {

                    changeGlyphUpdateList(target, parent.get(EMAIL_HEADER_LINK).get(EMAIL_HEADER_ICON),
                            parent.get(LAST_NAME_HEADER_LINK).get(LAST_NAME_HEADER_ICON),
                            parent.get(FIRST_NAME_HEADER_LINK).get(FIRST_NAME_HEADER_ICON),
                            parent.get(ELIGIBILITY_CLASS_HEADER_LINK).get(ELIGIBILITY_CLASS_HEADER_ICON),
                            parent.get(EMPLOYER_HEADER_LINK).get(EMPLOYER_HEADER_ICON));

                }

    }.add(new Label("email-header-label", Model.of("Email")), new WebComponent(EMAIL_HEADER_ICON)),
            new AjaxLink<Object>(ELIGIBILITY_CLASS_HEADER_LINK) {

                /**
                 *
                 */
                private static final long serialVersionUID = -4022209586109961448L;

                @Override
                public void onClick(AjaxRequestTarget target) {

                    changeGlyphUpdateList(target, parent.get(ELIGIBILITY_CLASS_HEADER_LINK).get(ELIGIBILITY_CLASS_HEADER_ICON),
                            parent.get(EMAIL_HEADER_LINK).get(EMAIL_HEADER_ICON),
                            parent.get(LAST_NAME_HEADER_LINK).get(LAST_NAME_HEADER_ICON),
                            parent.get(FIRST_NAME_HEADER_LINK).get(FIRST_NAME_HEADER_ICON),
                            parent.get(EMPLOYER_HEADER_LINK).get(EMPLOYER_HEADER_ICON));

                }

    }.add(new Label("eligibility-class-header-label", Model.of("Elig. Class")), new WebComponent(ELIGIBILITY_CLASS_HEADER_ICON)),
            new AjaxLink<Object>(EMPLOYER_HEADER_LINK) {

                /**
                 *
                 */
                private static final long serialVersionUID = -738777257301408437L;

                @Override
                public void onClick(AjaxRequestTarget target) {

                    changeGlyphUpdateList(target, parent.get(EMPLOYER_HEADER_LINK).get(EMPLOYER_HEADER_ICON),
                            parent.get(ELIGIBILITY_CLASS_HEADER_LINK).get(ELIGIBILITY_CLASS_HEADER_ICON),
                            parent.get(EMAIL_HEADER_LINK).get(EMAIL_HEADER_ICON),
                            parent.get(LAST_NAME_HEADER_LINK).get(LAST_NAME_HEADER_ICON),
                            parent.get(FIRST_NAME_HEADER_LINK).get(FIRST_NAME_HEADER_ICON));

                }

    }.add(new Label("employer-header-label", Model.of("Employer")), new WebComponent(EMPLOYER_HEADER_ICON)),
    new PageableListView<EmployeeSummaryPkt>("data", employeeSummaryModel.getObject(), 25) {

                /**
                 *
                 */
                private static final long serialVersionUID = -1697070076764699904L;

                @Override
                protected void populateItem(final ListItem<EmployeeSummaryPkt> item) {

                    item.setDefaultModel(new CompoundPropertyModel<EmployeeSummaryPkt>(item.getModelObject()));

                    item.add(new Label("firstName"),
                             new Label("lastName"),
                             new Label("employeeEmail"),
                             new Link<Object>("eligibility-class-data-link") {

                                /**
                                 *
                                 */
                                private static final long serialVersionUID = -3842291392813313171L;

                                @Override
                                public void onClick() {

                                    //LINK TO ELIGIBILITY CLASS OR MAYBE THE SECTION WITHIN THE EMP?

                                }
                    }.add(new Label("employeeEligibilityClassSummaryPkt.name")),
                             new Link<Object>("employer-data-link") {

                                /**
                                 *
                                 */
                                private static final long serialVersionUID = 6809571267919974106L;

                                @Override
                                public void onClick() {

                                    getIndex().getHomePanel().setNewContent(new EmployerDetailPanel("panel-content", item.getModelObject().getEmployerSummaryPkt().getId()));

                                }

                    }.add(new Label("employerSummaryPkt.name")),
                             new Label("employeeDateOfBirth"),
                             new Label("employee-code", Model.of(item.getModelObject().getEmployeeName())).setOutputMarkupId(true),
                             new AjaxLink<Object>("edit-employee-link") {

                                /**
                                 *
                                 */
                                private static final long serialVersionUID = 6061544430700059358L;

                                @Override
                                public void onClick(AjaxRequestTarget target) {

                                    logr.log(Level.FINER, "onClick for edit employee");

                                    logr.log(Level.FINER, "employee code pre: " + item.get("employee-code").getClass().getSimpleName());
                                    item.get("employee-code").replaceWith(new TextField<String>("employee-code", new Model<String>(item.getModelObject().getEmployeeName())).setOutputMarkupId(true));
                                    logr.log(Level.FINER, "employee code post: " + item.get("employee-code").getClass().getSimpleName());
                                    target.addChildren(parent, TextField.class);
                                    target.add(parent);
                                }
                    });
                }

As you can see, the label with the id "employee-code" is the label I wish to replace. Inside the AjaxLink onClick, you can see where I am getting the label and replacing it. Nothing is changing. Any direction or help is greatly appreciated.

A: A ListView recreates each if its items on each render, thus the altered listItem is thrown away immediately.
ListView#setReuseItems(true) should help.

A: An alternative to svenmeier's answer could also be to add only the specific item that has been changed to the AjaxRequestTarget. That is, replace
target.addChildren(parent, TextField.class);
target.add(parent);

With
target.add(item.get("employee-code"))

Which would cause only the piece of markup that concerns the change to be re-rendered, as opposed to the entire table. If your table is big and contains a lot of elements, whose models involve complicated retrieval mechanisms rendering the entire table would be a much more laborious process, and hence re-rendering only the item would be a better solution.
Having said that, in your particular case svenmeier's solution is better, as otherwise if you implement my solution and later on re-render the entire table, the changes would be lost.


text:
Q: How can I install the Opera browser from the terminal? Since this .deb bug is causing a lot of issues, I must resort to install the Opera browser using the terminal. Which is just fine, but I also need to add it to the repository for automatic updates.
Since I am no expert at all, I do not know how to perform the full installation of the browser. How do I go about it?
Thanks!
P.S. Please do not mark this as duplicate, because the other posts dont details how to go about installing Opera with adding it to the repository too for updates. Cheers.

A: To install opera via PPA on Ubuntu, run these commands
Setup key with:
wget -O - http://deb.opera.com/archive.key | sudo apt-key add -

Setup repository with:
sudo sh -c 'echo "deb http://deb.opera.com/opera-stable/ stable non-free" >> /etc/apt/sources.list.d/opera.list'

Setup package with:
sudo apt-get update
sudo apt-get install opera

Source
Alternatively, you can install the .deb via a terminal with
sudo dpkg -i path/to/your/deb

It already contains the PPA, if anyone else reading this is still facing the .deb issue with gnome-software, please report it here, it is supposed to be fixed.


text:
Q: How to save auth cookies in WebView? How can i save my cookies and set them on next application start using webView. I've read a lot of ways to do that, but most of them are deprecated yet.
So, the main thing i need - to register account and stay logged in every time i open my app, but all the code i wrote doesn't work(when app started i'm not logged in).
class WebActivity : AppCompatActivity() {
private lateinit var binding: ActivityWebBinding
private lateinit var preferences: SharedPreferences
private lateinit var cookieManager: CookieManager

@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityWebBinding.inflate(layoutInflater)
    setContentView(binding.root)

    preferences = getSharedPreferences(APP_SETTINGS, MODE_PRIVATE)
    cookieManager = CookieManager.getInstance()

    with(binding.webView) {
        settings.domStorageEnabled = true
        settings.javaScriptEnabled = true
        settings.databaseEnabled = true
        cookieManager.setAcceptThirdPartyCookies(this, true)
        webViewClient = object : WebViewClient() {

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                preferences.getString("COOKIES", "")?.let { cookieManager.setCookie(url, it) }
                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                val cookies = cookieManager.getCookie(url)
                if (!cookies.contains("userId=0")) { preferences.edit().putString("COOKIES",cookies).apply() }
            }
        }
        if (savedInstanceState != null) restoreState(savedInstanceState)
        else loadUrl(preferences.getString(SERVER_URL, EMPTY)!!)
    }
}

override fun onSaveInstanceState(outState: Bundle) {
    binding.webView.saveState(outState)
    super.onSaveInstanceState(outState)
}

}
i'm trying to setup my cookies from sharedPrefs(they are correct indeed - all the info about logged user) but i can't. So how to save account details as previously using deprecated "savePassword"?


text:
Q: PHP syntax equivalent to SQL % I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '
';
while ($row = mysqli_fetch_assoc($result))
{
    echo '
    '
}
echo '
';
?>

I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want  to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.

A: The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
  echo '';
}

A: If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');

Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
    $file = $files[i];
    $prefix = explode("_", $file)[0];
    if ($prefix != $_GET['id'])
    {
        unset($files[i]);
    }
}

$files is now an array of only the file names prefixed with $_GET['id]

A: My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);


text:
Q: Sending a list from cs to ascx I'm pretty new to C# and am trying to rebuild something I build in PHP a few years back.
I'm trying to accomplish the following:
In the CS file I'm building a list of addresses (basically consists of name, address and coordinates) which I need in the ASCX file to build up a google map with some markers.
My code looks something like this:
var neighbors = new List<List<String>>();
var neighbor = new List<String>();

int x = 0;
String firstRowFirstColumnValue = "";

while (x < result.Result.Count) {
   GenericEntityData Resultrow = result.Result[x] as GenericEntityData;

    neighbor.Add(Resultrow .Properties[2].Value.ToString());
    neighbor.Add(Resultrow .Properties[3].Value.ToString());
    neighbor.Add(Resultrow .Properties[7].Value.ToString());

    neighbors.Add(neighbor);
    x++;
}

Now it seems like the list is populated the right way, but I can't figure out how to pass it to the ascx file. Any ideas?

A: This post is very similar:
Pass C# ASP.NET array to Javascript array
I like zerkms answer the best. It has the most votes. What is missing from his answer is that you list (which is much like the array in the provided link) should be accessible through a public property at the class level. So put this right under your class declaration:
    public List<List<String>> Neighbors {get; set;}

and at after your while loop is done:
    Neighbors = neighbors;

In the ascx page you can put the list into javascript like this:
    <% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
    var jsVariable = <%= serializer.Serialize(Neighbors) %>;

unrelatedly: You may want consider making your neighbor (singular) List a custom class, rather than a List of Strings.
I might mention that things like this are a lot simpler using asp.NET MVC. That's no help to you here, but still worth saying.

A: you can use session or application or make it as a static property, depends on your senario, if this list is unique for every user, you can set that on session, or if the list is unique for all users, you can set the list on application or create it as static property


text:
Q: Can conclusions of statistical mechanics be arrived at from considering only individual particle dynamics I should begin with the fact that although I have a first-year undergraduate level education in physics, I am not a physicist and so am not familiar with all the details of this field and so the question I am asking might seem trivial to an expert in physics. However, I am stating this question as this is something I am pondering about for quite some time.
Let's say I have a cube of edge length $a$ filled with ideal gas particles maintaining the following rules:
1) Each gas particle is spherical in shape with a uniform radius $r$, where $r<<a$,
2) The only way of interaction between the particles is through perfectly elastic collisions,
3) The particles also undergo perfectly elastic collisions with the container inner wall, which is supposed to be immovable.
4) In between any two collisions, a particle traverses with constant velocity.
From statistical physics, we can derive the velocity distribution of a gas particle assuming the particles are uniformly distributed throughout the container and have i.i.d. velocity components, and that the distribution is isotropic. While the derivation is very easy with these assumptions, fundamentally we are bypassing all the intricate dynamics and interactions between the particles and the container. So, in a way, we are converting a totally deterministic problem into a probabilistic one. However, I am really curious to know if there is any way to actually keep track of the intricate dynamics and arrive at the same conclusions about different properties of the gas particles, like their steady-state velocities, which is derived using statistical mechanics. Is there any reference on this? Thanks in advance.

A: In principle?  Sure - just list the positions and velocities of each of your $N$ particles, and advance them slowly in time with constant velocity, checking and correcting for collisions at each time step.
In practice?  No.  At a bare minimum you'd need to keep track of 3 velocity components and 3 position coordinates for each particle.  If we're charitable and represent each as a double precision number, my laptop would be totally filled up for $N=10^{10}$, which is an absolutely tiny number of particles on a thermodynamic scale.  It would take more storage space than exists on the planet Earth to keep track of all the positions and velocities of one mole of such a gas, and we haven't even done any computations yet.
Luckily, the questions which you might be interested in asking about a box full of ideal gas have precisely nothing to do with the individual dynamics of single particles - they are questions which are inherently statistical in nature.
Lucky us!


text:
Q: How To Make Object Jump Forward In Pygame? I'm trying to make a game with pygame and trying to make an object jump to the right or to the left, I use this code to move an object and also jump:
import pygame

pygame.init()

win = pygame.display.set_mode((500, 500))

playerX = 250
playerY = 250

vel_x = 10
vel_y = 10

jump = False

run = True

while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_a] and playerX > 0:
        playerX -= vel_x
    elif keys[pygame.K_d] and playerX < 500:
        playerX += vel_x
    elif jump == False and keys[pygame.K_SPACE]:
        jump = True
    elif jump == True:
        playerY -= vel_y * 4
        vel_y -= 1
        if vel_y < -10:
            jump = False
            vel_y = 10

    win.fill((0, 0, 0))

    pygame.draw.circle(win, (255, 255, 255), (int(playerX), int(playerY)), 15)

    pygame.time.delay(30)

    pygame.display.update()

pygame.quit()

But the code doesn't work, I mean it works when the space key is pressed but it stops moving when another movement key is pressed, for example when I press the space key the ball jumps but when I press the d key (to move to the left) the ball stops in the air and can only move left and right, but when I release the space key the ball falls back and forth as it was at the beginning, or If you don't understand what I'm talking about you can copy the code and try the code yourself.
The movement of the ball should look like in this video (from minute 8:10):
https://www.youtube.com/watch?v=am2Tb_tj8zM
Can someone tell me what's wrong with the code?

A: You have to separate the movement along the x and y axis. Just turn the elif to if, in the condition that evaluates if SPACE is pressed:
if keys[pygame.K_a] and playerX > 0:
    playerX -= vel_x
elif keys[pygame.K_d] and playerX < 500:
    playerX += vel_x

# elif jump == False and keys[pygame.K_SPACE]:
if jump == False and keys[pygame.K_SPACE]:
    jump = True
elif jump == True:
    playerY -= vel_y * 4
    vel_y -= 1
    if vel_y < -10:
        jump = False
        vel_y = 10

Complete example:

import pygame

pygame.init()
win = pygame.display.set_mode((500, 500))

playerX = 250
playerY = 250
vel_x = 10
vel_y = 10
jump = False

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_a] and playerX > 0:
        playerX -= vel_x
    elif keys[pygame.K_d] and playerX < 500:
        playerX += vel_x

    if jump == False and keys[pygame.K_SPACE]:
        jump = True
    elif jump == True:
        playerY -= vel_y * 4
        vel_y -= 1
        if vel_y < -10:
            jump = False
            vel_y = 10

    win.fill((0, 0, 0))
    pygame.draw.circle(win, (255, 255, 255), (int(playerX), int(playerY)), 15)
    pygame.display.update()
    pygame.time.delay(30)

pygame.quit()


text:
Q: Parse MongoDB query to Java I need to perform the following MongoDB query in Java:
db.ventas.aggregate([
{
    $sort: {"codArt._id": -1}
},
{
    $group:{
        _id: "$codArt._id",
        denominacion: {"$first": "$codArt.denominacion"},
        unidades: {"$sum": "$unidades"},
        importe: {"$first": {"$multiply": [{"$sum": "$unidades"}, "$codArt.pvp"]}},
        stock: {"$first": {"$subtract": ["$codArt.stock", "$unidades"]}}
    }
}
])

Is there any library, which can do it?
Unfortunately, I can't install MongoDB Compass.

A: You could use something like Hibernate, but no automatic translation is provided... you'll need to build your model. It will be useful though if you do not want to build the inner query or need some portability.
http://hibernate.org/ogm/

A: There is a great tool to learn MongoDB Java Syntax and to work with MongoDB in general: Studio 3T, there you can generate a MongoDB query for the Java driver. Trial 30 days.
P.S. I'm not sure if this software requires admin rights to be installed.


text:
Q: Better way to export data from one database to another (SQLSever) I'm importing a big flat file (about 400.000 rows and 255+ columns) into SQL Server Management Studio through the import wizard.
To get the right variables I use Suggest types, but I have found that I need to search through all the rows to get the right variable types. It takes a very long time. Is there a way to avoid this or do it faster?
Furthermore, my real goal is to transfer data from one sql server database to another on another computer. I do this by exporting it as a flat file. But maybe this is stupid since I lose the information about the correct format?
Thanks!

A: Backup your database and restores it on the other server (the tager server must be equal or higher version) or simply copy the database files to other server and attached it (when copying database files, you must ensures that either you have detached the database or stop the sql server service).

A: According to Copy one database to another database:

There are several ways to do this, below are two options:
Option 1

*

*Right click on the database you want to copy

*Choose 'Tasks' > 'Generate scripts'

*'Select specific database objects'

*Check 'Tables'

*Mark 'Save to new query window'

*Click 'Advanced'

*Set 'Types of data to script' to 'Schema and data'

*Next, Next
You can now run the generated query on the new database.
Option 2

*

*Right click on the database you want to copy

*'Tasks' > 'Export Data'

*Next, Next

*Choose the database to copy the tables to

*Mark 'Copy data from one or more tables or views'

*Choose the tables you want to copy

*Finish


text:
Q: Add 1 day to date from spreadsheet via Google App Script / Javascript- Month Keeps Reseting to current month I am trying to set up a Google App Script function that grabs a date (formatted dd/mm/yy) from the last column of a spread, and creates a new column with the date + one day.
I have seen previous solutions and tried to use the same, i.e.newDate.setDate(lastDate.getDate()+1) but have had issues getting the value formatted correctly in the script. This is a variation of my code that I'm using to loop through for a year's worth of values to see what I get:
for (var i=0;i<365;i++){

    var lastRow = outputSheet.getLastRow();
    var newDate = new Date();

    var lastDate = outputSheet.getRange(lastRow,1).getValue();
    var newDateRng = outputSheet.getRange(lastRow+1,1);
    Logger.log(lastDate + 1, typeof lastDate, typeof (lastDate + 1));
    newDate.setDate(lastDate.getDate());
    Logger.log(newDate);
    newDate.setDate((newDate.getDate() + 1));
    Logger.log(newDate);
    var newDateFormatted = Utilities.formatDate(newDate, ss.getSpreadsheetTimeZone(), "dd/MM/YY");
    Logger.log(newDateFormatted);
    newDateRng.setValue(newDateFormatted);
}

With a start date of "01/03/2020", I get the following behaviour:
01/03/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
...
etc. All the way through the year. Although the day increase, the month seems to reset after the first day of the month.
As a note, I am specifically looking to pick the date off of the spreadsheet rather than using new Date as today and new Date +1 as tomorrow.
Thanks

A: You need to use a different variable in the loop otherwise you will always return to the same month.
Also avoid using strings for the result, keep date objects and display it properly.
The code goes like this :
function otherTest(){
  var lastDate = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
  var date = new Date(lastDate); // create new date object
  var result = [];
  for (var i=0;i<365;i++){
    date=new Date(date).setDate(new Date(date).getDate()+1)
    Logger.log('date='+new Date(date))
    result.push([new Date(date)]);
  }
  SpreadsheetApp.getActiveSheet().getRange(1,2,result.length,1).setValues(result).setNumberFormat('dd/MM/yyyy');
}


text:
Q: Go: invalid operation - type *map[key]value does not support indexing I'm trying to write a function that modifies original map that is passed by pointer but Go does not allow it. Let's say I have a big map and don't want to copy it back and forth.
The code that uses passing by value is working and is doing what I need but involves passing by value (playground):
package main

import "fmt"

type Currency string

type Amount struct {
    Currency Currency
    Value float32
}

type Balance map[Currency]float32

func (b Balance) Add(amount Amount) Balance {
    current, ok := b[amount.Currency]
    if ok {
        b[amount.Currency] = current + amount.Value
    } else {
        b[amount.Currency] = amount.Value
    }
    return b
}

func main() {
    b := Balance{Currency("USD"): 100.0}
    b = b.Add(Amount{Currency: Currency("USD"), Value: 5.0})

    fmt.Println("Balance: ", b)
}

But if I try to pass parameter as pointer like here (playground):
func (b *Balance) Add(amount Amount) *Balance {
    current, ok := b[amount.Currency]
    if ok {
        b[amount.Currency] = current + amount.Value
    } else {
        b[amount.Currency] = amount.Value
    }
    return b
}

I'm getting compilation error:
prog.go:15: invalid operation: b[amount.Currency] (type *Balance does not support indexing)
prog.go:17: invalid operation: b[amount.Currency] (type *Balance does not support indexing)
prog.go:19: invalid operation: b[amount.Currency] (type *Balance does not support indexing)

How should I deal with this?

A: You are trying to index on the pointer rather than the map itself.  Kind of confusing because usually with pointers vs. values dereferencing is automatic for structs.  If your struct is just a map, however, it's only passed in by reference anyway so you don't have to worry about creating methods that act on pointers to avoid copying the entire structure every time.  The following code is equivalent to your first snippet but using a pointer type.
package main

import "fmt"

type Currency string

type Amount struct {
    Currency Currency
    Value float32
}

type Balance map[Currency]float32

func (b *Balance) Add(amount Amount) *Balance {
    current, ok := (*b)[amount.Currency]
    if ok {
        (*b)[amount.Currency] = current + amount.Value
    } else {
        (*b)[amount.Currency] = amount.Value
    }
    return b
}

func main() {
    b := &Balance{Currency("USD"): 100.0}
    b = b.Add(Amount{Currency: Currency("USD"), Value: 5.0})

    fmt.Println("Balance: ", (*b))
}

But to answer how to deal with it: if your struct is just of type map, I wouldn't worry about writing your receiving functions to take pointers, and just receive the value since the value is only a reference anyways.  Do like in your original snippet.

A: You can simply dereference b: (*b)
https://play.golang.org/p/Xq6qFy4_PC
func (b *Balance) Add(amount Amount) *Balance {
    current, ok := (*b)[amount.Currency]
    if ok {
        (*b)[amount.Currency] = current + amount.Value
    } else {
        (*b)[amount.Currency] = amount.Value
    }
    return b
}

Update
@Serdmanczyk makes a good point... you can safely pass a map around by value, the underlying map will be updated, not a copy of the map.  That is to say; pass-by-value in the case of a map means passing the address of the map, not the contents of the map.
See https://play.golang.org/p/i7Yz4zMq4v
type foo map[string]string

func main() {
    a := foo{}
    a["hello"] = "world"
    fmt.Printf("%#v\n", a)
    mod(a)
    fmt.Printf("%#v\n", a)

}

func mod(f foo) {
    f["hello"] = "cruel world"
}

Which outputs:
main.foo{"hello":"world"}
main.foo{"hello":"cruel world"}


text:
Q: Calculate the X and Y (top and left) values for the shape after setting the rotation for it Need help in adjusting the top and left of the shape when rotation value is set.
For Ex :
<p:spPr bwMode="auto">
           <a:xfrm rot="5400000">
                <a:off x="2443049" y="-1042472" />
                <a:ext cx="304800" cy="4419600" />
            </a:xfrm>
            <a:prstGeom prst="rect">
                <a:avLst />
            </a:prstGeom>
            <a:ln>
                <a:headEnd />
                <a:tailEnd />
            </a:ln>

I have the above data. I have calculated the rotation angle accordingly. Now when creating the shape and displaying it in an html format, need to adjust the top and left (off x="2443049" y="-1042472") values to align it properly. Kindly provide a solution to calculate proper top and left values to set.
thanks

A: As mentioned in how to calculate the rotation value for the MS Office Powerpoint Shapes from the xml data given, their is no need to change the left and top of a shape - if it is rotated or not-rotated, the shape will have the same left/top as it is an in-place rotation (it rotates on the Center X/Y).
If you're looking for how to translate EMU to points/pixels so that it can be converted to a different format such as HTML, use EMU/12700. So in this case <a:off x="2443049" y="-1042472" /> would be left="192.37" top="-82.08" and <a:ext cx="304800" cy="4419600" /> would be width=24 height=348.


text:
Q: two histograms ratio I have two histograms and using listplot to draw both. Now, I want to draw a second plot, below the first, with the ratio of each bin. Does anyone know how to do this?
Many thanks.
This is the code I'm using to draw the histograms:
Needs["PlotLegends`"]

dadosGtop = Import["Gtop_PR.dat", "table"];

costhbGtop = Table[dadosGtop[[i]][[1]], {i, 1, Length[dadosGtop]}];

costhleGtop = Table[dadosGtop[[i]][[2]], {i, 1, Length[dadosGtop]}];

histPlot[data_, bins_, origin_, color_, label_, title_, nome_] :=
  Module[{countBorder1 =
     Partition[Riffle[Riffle[#1, #1[[2 ;;]]], Riffle[#2, #2]], 2] & @@
       HistogramList[data[[1]], bins],
    countBorder2 =
     Partition[Riffle[Riffle[#1, #1[[2 ;;]]], Riffle[#2, #2]], 2] & @@
       HistogramList[data[[2]], bins],
    },
   ListLinePlot[{countBorder1, countBorder2}, PlotRange -> All,
    PlotStyle -> {{color[[1]]}, {color[[2]], Dashed}},
    AxesLabel -> {Style[label[[1]], 14, Bold],
      Style[label[[2]], 14, Bold]}, AxesOrigin -> origin,
    LegendPosition -> {0.65, 0.1}, LegendSize -> 1,
    LegendShadow -> None,
    PlotLegend -> {Style[nome[[1]], 12, Bold],
      Style[nome[[2]], 12, Bold]},
    PlotLabel -> Style[title, Black, 14, Bold],
    TicksStyle -> {16, Bold}, ImageSize -> Scaled[0.6]]];

histPlot[{costhbGtop, costhneGtop}, {-1, 1, 0.1}, {-1, 0}, {Green, Blue}, {"\[Eta]",
  "\!\(\*FractionBox[\(dN\), \(d\[Eta]\)]\)"}, "Pseudorapidity of b", \
{"b", "ne"}]

Here is a data sample:
dadosGtop={
   {-0.68, 0.536, 0.316}, {-0.394, 0.187, 0.287}, {-0.874, 0.753, 0.474},
   {-0.202, 0.18, 0.066}, {-0.267,  0.894, -0.077}, {0.126, -0.144, -0.063},
   {0.952,  0.63, -0.953}, {0.671, 0.073, -0.84}, {-0.344,  0.72, -0.024},
   {0.824, -0.205, -0.741}, {0.718, -0.793, -0.268}, {-0.423, 0.568, -0.204},
   {-0.192, -0.096, 0.357}, {-0.03,   0.865, -0.629}, {-0.784, 0.39, 0.588},
   {0.98, 0.59, -0.953},   {-0.97,  0.682, 0.653}, {-0.654, 0.907, -0.201},
   {-0.35,   0.712, -0.176}, {-0.929, 0.654, 0.48}, {-0.479, 0.826, 0.099},
   {-0.54, 0.785,-0.724}, {-0.812, 0.818,-0.069}, {-0.988, -0.083, 0.89},
   {-0.559, 0.976,-0.188}, {0.748, 0.211,-0.994}, {0.507, -0.527,-0.266},
   {0.776, -0.025,-0.964}
   }

A: What would be the ratio for n/0 or 0/0. You can set easily in definition below:
SetAttributes[f, Listable]
f[0, 0] := 0;
f[_, 0] := 0;
f[x_, y_] := x/y;

If you want to stick with your Module, use Column as george2079 has said. Divisions are simply:
f[counts1, counts2]

I find following version a little more compact but the choice is yours.
data = {{-0.68, 0.536, 0.316}, {-0.394, 0.187, 0.287}, {-0.874, 0.753, 0.474},
        {-0.202, 0.18, 0.066}, {-0.267, 0.894, -0.077}, {0.126, -0.144, -0.063},
        {0.952, 0.63, -0.953},  {0.671, 0.073, -0.84}, {-0.344, 0.72, -0.024},
        {0.824, -0.205, -0.741}, {0.718, -0.793, -0.268}, {-0.423, 0.568, -0.204},
        {-0.192, -0.096, 0.357}, {-0.03, 0.865, -0.629}, {-0.784, 0.39, 0.588},
        {0.98, 0.59, -0.953}, {-0.97, 0.682, 0.653}, {-0.654,0.907, -0.201},
        {-0.35, 0.712, -0.176}, {-0.929, 0.654, 0.48}, {-0.479, 0.826, 0.099},
        {-0.54, 0.785, -0.724}, {-0.812, 0.818, -0.069}, {-0.988, -0.083, 0.89},
        {-0.559, 0.976, -0.188}, {0.748, 0.211, -0.994}, {0.507, -0.527, -0.266},
        {0.776, -0.025, -0.964}};

bg = data[[;; , 1]];
nl = data[[;; , 2]];

Module[{d, r, dat},
       d = BinCounts[#, {-1.1, 1.1, .1}] & /@ {bg, nl};
       r = Range[-1, 1, .1] /. n_Real :> {n, n};
       dat = Flatten[Transpose /@ Transpose[{r, Partition[#, 2, 1]}], 1
                    ] & /@ (d~Join~{f @@ d});

       With[{opts = Sequence[Axes -> False, Frame -> True, ImageSize -> 300,
                             ImagePadding -> 15, PlotRangePadding -> Scaled@.1]
            },
            Column[
                   ListLinePlot[##, opts] & @@@ {
                                   {dat[[;; 2]], PlotStyle -> {{Green}, {Dashed, Blue}}},
                                   {Last@dat}}

                  ]
           ]
       ]

A: the ratio plot:
ListLinePlot[
   MapThread[{#1[[1]], If[#2[[2]] != 0 ,  #1[[2]]/#2[[2]], 0 ]} &,
     {countBorder1 ,   countBorder2 }] ]

A simple way to put the plots together is to use GraphicsColumn[{plot1,plot2}]