text:
Q: Microsoft Graph user/getMemberGroups fails despite correct Permissions I am using Graph explorer to test some requests. I logged in with my tenant account and I am trying to list Tasks from another User:
https://graph.microsoft.com/v1.0/users/{id}/getMemberGroups

I get the following error :
{
    "error": {
        "code": "",
        "message": "You do not have the required permissions to access this item.",
        "innerError": {
            "request-id": "8e9c5b30-ad4a-4c4c-80c2-f14b110b3fee",
            "date": "2020-05-18T16:08:36"
        }
    }
}

I currently have (among others) the following permission during that test :
Group.Read.All
Group.ReadWrite.All
User.Read.All
User.ReadWrite.All

Referring to the documentation, this should be enough :

Delegated (work or school account): User.ReadBasic.All and GroupMember.Read.All, User.Read and GroupMember.Read.All, User.Read.All and GroupMember.Read.All, User.ReadBasic.All and Group.Read.All, User.Readand Group.Read.All, User.Read.All and Group.Read.All, Directory.Read.All, Directory.ReadWrite.All, Directory.AccessAsUser.All
Delegated (personal Microsoft account): Not supported.
Application: User.Read.All and GroupMember.Read.All, User.Read.All and Group.Read.All, Directory.Read.All, Directory.ReadWrite.All

Any idea on what is going wrong?

A: Although you have requested Permissions, you cannot authorize this permission until you have received "Consent" from an Administrator. Also, You need to be the member of the group you are requesting via graph if you are doing any changes to group.
If you're using the Azure Portal to register you app (aka the v1 Endpoint) then your admin can either use the Admin Consent workflow or directly grant permission within the portal. You can read more about the Consent Framework in Integrating applications with Azure Active Directory.


text:
Q: Publish Azure Website to non-root folder from PowerShell I'm testing my assumptions at the moment. I have my Asp.Net MVC application located at www.myapp.com/app and a third-party CMS system on www.myapp.com/.
The web-site is set up like described in this answer
At the moment I can publish both of the applications separately and manually from Visual Studio and it works fine.
However, I'm trying to publish my application from a build server where I'm using Azure Power-Shell scriplets:
PS> Publish-AzureWebsiteProject -Name myApp -Package MyWebDeployPackage.zip

However, documentation does not mention if you can publish with this scriplet to a non-root folder.
Any way I can publish an application to ~/app from a command line?
UPD: I can publish from msbuild via
msbuild .\SolutionName.sln /p:DeployOnBuild=true /p:PublishProfile=ProfileName /p:Password=passwordForAzurePublishing /p:AllowUntrustedCertificate=true

Where ProfileName is a web-deploy profile configured to deploy to sub-folder of Azure Web-Site and Password is deployment password from Azure profile.
However this is not an optimal solution: to deploy to test and to production environment, I need to build the application twice, which I'd like to avoid: if I compile views, it takes 7-10 minutes (we have 800 views). Doing this twice is a waste of time.
UPD 2: Created an issue on Azure SDK Tools repository: https://github.com/Azure/azure-sdk-tools/issues/2667

A: I don't think this is possible from PowerShell, but I might be mistaken. Looking at their publish code here https://github.com/Azure/azure-sdk-tools/blob/master/src/ServiceManagement/Services/Commands.Utilities/Websites/WebsitesClient.cs#L1136-L1168
and also here https://github.com/Azure/azure-sdk-tools/blob/master/src/ServiceManagement/Services/Commands.Utilities/Websites/WebsitesClient.cs#L1218-L1229
they don't have a parameter for the app name, and the code in the second link builds the site name/slot manually.
I would say open an issue here https://github.com/Azure/azure-sdk-tools/issues for this and somebody from the Azure PowerShell team should look at it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirection during ajax call I am new to AJAX/jQuery. I have 2 buttons. On each button click I need to send an AJAX request to server. But also during this process, I have to check if user is signed in or not. If the user is not signed in he should be redirected to the login page and after login he should come back to same page. Also in AJAX call the application which is specified in URL checks if user is signed in or not and redirects him to login page.The application contains the function to build the URL for login page. If user is already signed in then an another function will be called in application. The problem I am facing now is success function is not getting called when I run the whole project. Instead the error function is called. But if I pass the parameters to URL as query parameters then I am getting redirected to login page.
eg:www.abc.com/application?X=1&Y=2
Any ideas would be appreciated.
{
  $.ajax({
    type: "GET",
    data: {
      X:param1,
      Y:param2,
    },
    url: "/application",
    success: function(data, status)
    {
      if (data.redirect) {
        window.location.href = data.redirect;
      } else {
        alert("success message");
      }
    },
    error:function()
    {
      alert("error message")
    }
  });
}

A: data.redirect will work assuming data is a json object.
To make sure add
    dataType: "json",
to the above and it should work.
Use Chromes Network panel to check if the server is talking back correctly.
Also check what Mime-Type it is returning. should be 'application/json'.
Error Function fires when the request is unsuccessful.
It takes 3 arguments but the 2nd is a Error String can be "timeout", "error", "abort", and "parsererror".
Try this instead and you may find more debug info;
{
  $.ajax({
           type: "GET",
           data: {
                  X:param1,
                  Y:param2,
               },
           url: "/application",
           success: function(data, status)
           {
             if (data.redirect) {
               window.location.href = data.redirect;
             } else {
               alert("success message");
             }
           },
           error:function(jqXHR, text)
           {
             alert("error message: "+text);
           }
    });

}


text:
Q: Thymeleaf creating and sending multipart form object by itself to controller even though user is not selecting any file I'm trying to upload a Multipart file using Thymeleaf and spring boot,
but even though I am not selecting any file to upload after clicking on Submit button Thymeleaf is creating and sending the Object to controller by itself.

                            Upload Image:

                        Android:

                                    <input type='file' id='android' class="uploadimge" name="android"  onchange="readURL(event, this)" />

                         Cancel
My Controller Code is Here -
    @RequestMapping("/saveCategory")
    public String saveCategory(@ModelAttribute("saveCategory") MultipartFile android,HttpServletRequest request,Model model){
        System.out.println("In Controller saveCategory() "+android);

        // code to perform operation on File. .

         return "redirect:category";
}

The message it is printing on Console After clicking on Submit button (even when I'm not selecting and uploading any image) is  :-
org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@14de417d


text:
Q: Falha no WHERE ao associar uma coluna para consulta em uma view Estou passando alguns parâmetros para uma view onde preciso receber o retorno dessa consulta. Ao definir os filtros no Where da minha query, o retorno da consulta informa o seguinte erro:

Nome de coluna 'competencia' inválido.

Sei que é falha minha de codificação, mas eu declaro no meu where as colunas para consulta
      public RelatorioDTO relatorio(DateTime compInicial)
    {
        // vw_relatorio: View

        string query = "select cpfCnpj from vw_relatorio where competencia <= @compInicial";

        string myConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

        SqlConnection connection = new SqlConnection(myConnectionString);

        SqlCommand dbCommand = new SqlCommand(query, connection);

        SqlParameter parameter = dbCommand.CreateParameter();
        parameter.ParameterName = "@compInicial";
        parameter.Value = compInicial;
        parameter.DbType = DbType.DateTime;
        dbCommand.Parameters.Add(parameter);

        dbCommand.Connection.Open();
        dbCommand.ExecuteReader();
        // retornar a consulta
    var retornoLista = new List<RelatorioDTO>();

        if (((SqlDataReader)(myReader)).HasRows)
        {
            while (myReader.Read())
            {
                retornoLista .Add(FiltroRelatorio(myReader));
            }
        }
        else
        {
            return null;
        }

        return retornoLista;
  }

Retornando item a item:
private RelatorioDTO FiltroRelatorio(IDataReader myReader)
    {
        var result = new RelatorioDTO ();
        result.CpfCnpj = myReader["CpfCnpj"].ToString().ToUpper();

        return result;
    }


text:
Q: Windows server 2012 Active Directory Groups Have a quick question.
I work in a large company and i've always been told that if a users needs let's say access his emails on the phone he has to be member of a specific group (apart from activating  active sync in the exchange console, of course) or if a user needs specific internet browsing permissions has to be member of another group or whatever resource or permission the user needs there is a group for it.
So, I have also been looking at the GPO's but i don't see any relationship between Gpo's and the groups, so how do they actually make the members of a specific group have access to what they want the user to have access to?

A: There isn't really a relationship between groups and group policies. In retrospect, group policies probably was not the best choice of names. Group policies are a mechanism to centrally manage settings and security policies that need to be applied to users and computers. Granting access to a resource is something where it is usually preferred to do so for a group, in case there are other people that may need this they only need to be added to the group, and that activity of requesting membership in a group is much simpler from an auditing and compliance perspective.

A: GPOs contain settings that apply to users and Computers. You can apply settings that effect things like Internet access etc. Groups can be used to filter the GPOs. In order for a GPO to apply to your user account or computer account the user or computer will need both the Read and Apply GPO permissions. If you deny either of these then the GPO will not apply. If your grant both of these permissions then the GPO will apply as long as it is linked to the OU (or linked to parent OU / Domain).
What we can do is use groups to filter the GPOs, lets say you want to grant a level of internet access to a set of users you can create the GPO, create a group called something like G_InternetAccess then make sure that the group has both read and apply permissions. link the group to the OUs that contain your users and it will work. alternatively if you have a set of people whom you do not what the GPO applied to make sure they don't have the read and apply permission.
Just be aware that the default permissions for any new GPO is AuthenticatedUsers Read and Apply, so by default GPOS apply to all users and computers when they are linked to an OU or Domain.
To edit permissions for the GPO go to its delegation tab, click advanced and you can see all the permission currently listed.

A: Group policies apply to container structures (organizational units). Users and computers that are members of the OU will get that policy applied.

A: You don't extra memberships or GPOs. Mailbox owners by default can access their mailbox through Active Sync. What you need is a direct connection to a Client Access server via Port 443.
To check if a device has connected type
Get-MobileDevice

in Exchange Management Shell.
Depending on your Exchange configuration you might need to unlock the newly added device from quarantine.


text:
Q: How to identify which table to delete a record when data coming from two tables? I have two tables where some same kind of information kept. One table has approved information and other one contains pending(waiting for approval) data. I fetch data from both table and display in a same view. So user will see data from both the tables. User can delete those records. But when deleting I've a trouble with finding out which table I should delete.
Assume, table1(Approved info), table2(Pending info)
table1

id | name  | description | creator |
-----------------------------------
10 | test1 | N/A         | 100     |
11 | test2 | N/A         | 100     |
12 | test3 | N/A         | 101     |
13 | test4 | N/A         | 200     |

table2

id | name  | description | creator |
-----------------------------------
10 | test1 | N/A         | 105     |
11 | test2 | N/A         | 103     |
12 | test3 | N/A         | 106     |
13 | test4 | N/A         | 202     |

table1 has a record with id of 10; and table2 has a record with id of 10 in that table. Id is the primary key of both tables. Both record will show to user. Let's say user wants to delete the record related to id 12 came from table2. So I want to delete that record from table2. But how can I figure out which table to delete that record. Because I can't use id to figure out the table. I have tried using some kind of data attribute attached with
data coming from table2 to differentiate them. But anyone can change them by inspecting it. So what is the proper way for solve this issue?

A: On any case, on any system, makes sense to have two to tables with same columns. That should be one of the firsts rules of database design. What's more, you discovered yourself how hard is to maintain a design like that. I see this on legacy systems developed with zero love to the code. In the future this will turn into a snowball. You should change it as soon as possible.
status column
The status of and entity or resource, is classic requirement, usually implemented with one little column which called : status, flag, mode, etc. In your case, it could have these values (@BhaumikPandhi comment):

*

*pending/approved/rejected

id | name  | description | creator | status |
--------------------------------------------
10 | test1 | N/A         | 100     | pending|

If you are worried to the database optimization, you could use a tinyint with these equivalence in your documentation:

*

*1 = pending

*2 = approved

*3 = rejected

status table
You could keep your first table called record
id | name  | description | creator |

And create another one called record_status with 2 columns, in which record_id is a FK of record table
record_id | status |

Anyway, the status column is the most easy a classic approach to your requirement.


text:
Q: using PARSENAME to find the last item in a list I am using Parsename in SQL and would like to extract the last element in a list of items.  I am using the following code.
Declare @string as varchar(1000)
set @string = '25.26.27.28'

SELECT PARSENAME(@string, 1)

This works and returns the value 28 as I expect.  However if I expand my list past more than 4 items then the result returns a NULL.  For example:
Declare @string2 as varchar(1000)
set @string2 = '25.26.27.28.29'

SELECT PARSENAME(@string2, 1)

I would expect this to return a value of 29 however only NULL is returned
I'm sure there is a simple explaination to this can anyone help?

A: PARSENAME ( 'object_name' , object_piece )
'object_name'
Is the name of the object for which to retrieve the specified object part.
This name can have four parts: the server name, the database name, the owner name, and the object name.
If we give more than 4 parts, it will always return null.
For Ref: http://msdn.microsoft.com/en-us/library/ms188006.aspx

A: PARSENAME is designed specifically to parse an sql object name. The number of periods in the latter example exempt it from being such a name so the call correctly fails.
Instead
select right(@string2, charindex('.', reverse(@string2), 1) - 1)


text:
Q: how to avoid long namespaces in Javascript We are starting a new project and we have decided to use javascript ""namespaces"" to organize our client side code. The thing is that we have noticed that we can end very easily with super-long namespaces that are dificult to remember like

myProject.components.myComponent.doSomethig();

Is there any better way to do this or create some kind of  "alias" somehow?
Thanks.

A: In JavaScript, you can make shortcut references to long namespaces stuff
 var myComp = myProject.components.myComponent;
 myComp.func1();

This is a reference only. You can do this with other long names and write less like this
 var getEl = document.getElementById,
     myEl = getEl('divId');

Also you can organize your code with RequireJS to organize your code
// file:  myProject/components/myComponent.js
 define(function(){
       var myComponent ={};
       myComponent.func1 = function(){
           ...
       }
       return myComponent;
 });

// file:  myProject/main.js
 require(['myProject/components/myComponent',  'myProject/components/myComponent2'],
 function(comp1, comp2){
         var main = {};
         main.init = function() {
             ...
             comp1.func1();
         }
 });

// file: myProject/index.html
 <script src="libs/require.js" data-main="myProject/main"></script>

A: If you use scoping functions around your module code (and if you don't, you should), then you can create local aliases quite easily as variables shared by all of the functions within a given module.
E.g., code defining the myComponent component:
(function() {
    var comp = {};

    // Export our component
    myProject.components.myComponent = comp;

    // add things to `comp`; since `comp` and `myProject.components.myComponent`
    // refer to the same object, adding to `comp` is adding to the one object
    // they both refer to and so you can access those things via either reference
})();

Similarly if you're writing app code that uses multiple components:
(function() {
    var thisComp = myProject.components.thisComponent,
        thatComp = myProject.components.thatComponent;

    // Use `thisComp` and `thatComp`
})();

A: You can always store a subnamespace in a local variable:
var myComponent = myProject.components.myComponent;


text:
Q: Finding time complexity between shortest path in Dynamic Programming and Brute Force What is the difference between shortest path in Dynamic Programming and Brute Force?
What is the time complexity in between two of them?
How to implement both algorithms in java?


text:
Q: Shell exit codes inconsistants with simple command I have an issue that should not be too hard to solve, I just can't figure what I'm doing wrong.
I need to test if a command is successful or not, and the command needs to be executed from a script. The command is:
curl 127.0.0.1:5000 &> /dev/null

Right now there is no server running, so it should always fail. And it does fail when I execute it from a command line. However when I run it from inside a shell script, it fails but the exit code is 0. What could the cause of that be?
Here is the script:
if curl 127.0.0.1:5000 &> /dev/null
then
    echo "sucess"
    exit 0
else
    echo "failure"
    exit 1
fi

And here is the output:
success
curl: (7) Failed to connect to 127.0.0.1 port 5000: Connection refused

However, it does work as expected if I remove the redirection (I'm quite a beginner in shell code, but the redirection shouldn't also redirect the exit code right? So I really don't know what this means)
here is the code without redirections that works as expected (therefore that indicates a failure and has an exit code of 1):
if curl 127.0.0.1:5000
then
    echo "sucess"
    exit 0
else
    echo "failure"
    exit 1
fi

Anyone has an idea?
Edit:
I was launching the script with sh script_name.sh in zsh. When I use zsh script_name.sh it now works normally. I still don't fully understand why but at least it works!

A: "&> /dev/null" is interpreted differently in Bourne shell (sh), The "&" puts the command in background, you can test it with "sleep 100 &>/dev/null". Since it successfully put the command in background, it is a success, and the exit status of the backgrounded command is disregarded.
If you want it to work in Bourne shell (sh), use the traditional syntax ">/dev/null 2>&1", and it will work in newer shells as well, i.e. it is more compatible.
In a system where sh is linked to bash, it will work as is.


text:
Q: Blank ID when saving new items on SobiPro I'm not sure how to describe this.  I am moving to a new host for various reasons and in the process of moving to a new host, I put my site back together and imported the database.  Everything looked good except for when I try to put in a new entry into SobiPro (What I use to manage my listing).
What happens is this:

*

*When clicking to add a new Category or Entry the ID comes up as 0.

*On the front end, there is a 'blank' spot where the new category or entry should be.

*When I try to delete it from the back end I get the error "Please select at least one item to perform this action" (I did make sure that I had it selected).

*In the back end even, there is a blank spot where the new entry should be (much like the front end).

*I am also using a module that is used to display all the artists in the listing, but when you start clicking links, names will duplicate in the list and creating redundant links (I have since disabled this because after you click enough times to navigate, the site crashes completely).

Images for Reference: Database Entry - Back End - Front End - Duplicate Links

*

*Current Link (What is should look like): http://eve-sounds.com

*New Link (The Rebuilt Site w/ Issues): http://djyumene.com/evesounds/
I wish I could give more details but I don't know what to look for.  I've never come across this before.  I know Joomla but I'm not very knowledgeable about how to fix database issues. I tried to turn on error reporting and debugging but I am getting literally no errors to go off of so all I can do is describe what's going on.


text:
Q: ruby activerecord find optimizes I have this in my code:
area_code_rec = @phone.area_codes.find_by_areacode(area_code)

It was brought to my attention that this may be more rails 3 like, but then
I am not sure if active record optimizes as the where() part should return
a full array or does it look at the rest of the statement and not do that ?
area_code_rec = @phone.area_codes.select(:id).where(:areacode => area_code).last


text:
Q: A generalization of maximum modulus principle Let $ \emptyset \neq U \subset \mathbb{C} $ be a bounded open connected set and let $ f_1, \dots, f_n $ be analytic in $ \overline{U} $. Prove that
$$ \max_{z \in \overline{U}} \sum_{j=1}^n |f_j(z) | = \max_{z \in \partial U} \sum_{j=1}^n |f_j(z) |. $$
Clearly we have "$\geq$" but I don't know how to reduce to the $ n = 1 $ case to use the usual maximum modulus principle. Help is appreciated.

A: I will give a proof for  $n=2$ because I have it typed out already. The same argument works for any $n$: given $f$ and $g$ analytic such that the maximum of $|f|+|g|$ on $\overline {U}$ is attained at an interior point $a$ we have $\left\vert f(a)\right\vert +\left\vert g(a)\right\vert \geq \left\vert
f(z)\right\vert +\left\vert g(z)\right\vert $ $\forall z\in \Omega .$
Replace $f$ by $e^{is}f$ and $g$ by $e^{it}g$ where $s$ and $t$ are chosen
such that $e^{is}f(a)$ and $e^{it}g(a)$ both belong to $[0,\infty ).$ This
reduces the proof to the case when $f(a)$ and $g(a)$ both belong to $%
[0,\infty ).$ We now have $$f(a)+g(a)\geq \left\vert f(z)\right\vert
+\left\vert g(z)\right\vert  \geq |f(z)+g(z)|$$  Maximum Modulus principle applied to $f+g$ shows that $f+g$ is
a constant. Now $$f(a)+g(a)\geq \left\vert f(z)\right\vert +\left\vert
g(z)\right\vert \geq \Re f(z)+\Re g(z)=\Re(f(z)+g(z))$$ $$=\Re (f(a)+g(a))$$ which implies that equality holds throughout. In particular $%
\left\vert f(z)\right\vert =\Re(f(z))$ and $\left\vert g(z)\right\vert
=\Re(g(z))$ for all z]. Hence $f$ and $g$ are both constants (because their imaginary parts vanish) in which case there is noting to prove.


text:
Q: Azure AD B2C redirect loop after successful login I'm trying to use Azure AD B2C for authentication & authorization in my dotnet core web app and web api by using this example project:

*

*I have a dotnet mvc web app as frontend that fetches data (todo items) from the web api:

*registered an application in my B2C tenant and use another app registered in Azure AD for openID connect authentication.

*The login & authentication works (see the following screenshot), but after login, the browser is in redirect loop between my b2c instance url and my localhost (https://localhost:44316/signin-oidc, see the screenshot below). The url https://localhost:44316/signin-oidc is set up as redirect url in my application registered in B2C tenant, but the path signin-oidc does not actually exist in my mvc web app. I guess this is why the redirect loop happens (?).

*Relevant code from my app:

*

*MVC app Startup.cs:

   public void ConfigureServices(IServiceCollection services)
           {
               services.AddControllersWithViews();
               services.AddOptions();

               services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
                   .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

               // Token acquisition service based on MSAL.NET
               // and chosen token cache implementation
               services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { Configuration["TodoList:TodoListScope"] }, configSectionName: "AzureAdB2C")
                       .AddInMemoryTokenCaches();

               // inject dependencies
               services.AddScoped<ITokenAcquisition, TokenAcquisition>();
               services.AddHttpContextAccessor();
               services.AddScoped<HttpClient, HttpClient>();
               services.AddScoped<ITodoListService, TodoListService>();

               services.AddRazorPages();
           }

*

*The web API controllers use the [Authorize] attribute to protect the API. I also exposed the API in the application registered in Azure AD tenant and set scope for it. API permissions has been admin consented/granted as well

What might be the cause of the redirect loop? should we use different redirect URI in the registered application in B2C tenant?


text:
Q: Сравнение использования связного списка в C и JAVA Хотелось бы подробнее понять разницу выполнения разных задач связного списка в двух диаметрально противоположных языках : c и java.
Конкретнее: сравнить и найти отличия в добавлении и удалении элемента в связной список/из связного списка.
И дело не в коде (он у меня имеется), а в технике применения.
Заранее спасибо за ответ!
Возьмем пример кода на с:
void deleteCar(char* reg) {

    struct LinearNode *current, *previous;
    bool found = false;

    if (isEmpty())
        printf("Error - there are no nodes in the list\n");
    else {
        printf("**************Sell car:**************\n");
        current = previous = front;

        while (!found && current != NULL) {
            //check by comparing if registration number exists and car is reserved
            if ((strcmp(reg, current->element->registration) == 0) && (current->element->reserved == true)) {
                found = true;
            }
            else { //go to the next node
                previous = current;
                current = current->next;
            }//end else
        } //end while

        if (!found)
            printf("Error - there is not such car with registration number %s or this car is not reserved\n", reg);
        else { //if found
            if (current == front) {
                front = front->next;
                free(current); //remove node from list
            } //end else
            else {
                previous->next = current->next;
                free(current);//remove node from list
            } //end else
            printf("Car with registration number %s has been deleted\n", reg);
        }//end else
    }//end else
}// end deleteNode

и вот метод для удаления элемент на джаве:
public boolean delete(T element){

    LinearNode<T> previous = list;
    LinearNode<T> current = list;
    boolean found = false;

    while (!found && current != null)
    {
        if (current.getElement ().equals (element)) {
            found = true;
        }
        else {
            previous = current;
            current = current.getNext();
        }
    }
    //found loop
    if (found)//we fount the element
    {

        if(current == this.list){

        this.list.getElement();
        this.list = this.list.getNext();
       }

       else
           if(current == this.last){

        previous.setNext (null);
        this.last = previous;
        }
           else{
               previous.setNext(current.getNext());
               current.setNext (null);
           }
    this.count--;
    }
    return found;
}

Можно ли после этих примеров сказать, что в java можно использовать код, который будет generic, в отличии от c?

A: В плане реализации самописного связного списка Java и C практически не отличаются, принцип одинаковый. Создаётся класс или структура элемента списка, в ней какая-то информация и ссылка на следующий элемент. В C указатель со 'звёздочкой', в Java без неё. Можно просто перечислить все различия синтаксиса языков.


text:
Q: What are the different levels of the Poké Finder? As you know, Pokémon Sun & Moon feature a Poké Finder, which upgrades as you gain likes for your photos.
I'm currently level 4.
So far, the improvements are :

*

*lvl2 : Zoom

*lvl3 : Better Zoom

*lvl4 : Maximum Zoom.

What happens starting at the fifth level?
Thank you!

A: Level 5 gives you the ability to press a button to call the Pokemon closer to you. There are no levels higher than level 5.
Source: https://www.reddit.com/r/pokemon/comments/5dx1dt/so_i_spent_a_few_hours_grinding_out_the_v5_pok%C3%A9/


text:
Q: Collision Detection and Ending So I created a little game with SpriteKit. Whenever the Human hits the BlockCategory, he should be able to jump 1 time. With my current code, the Human jumps 1 time after the beginning, and then switching every 0.1s between Contact and Contact lost. So he isn't really able to jump again after hitting the ground again. My Code :
-(void)Mensch{

Human = [SKSpriteNode spriteNodeWithTexture:HumanTexture1];
[Human setScale:1.0];
Human.position = CGPointMake(50 , 225);
[Human runAction:Run];

SKSpriteNode * HumanBody = [SKSpriteNode spriteNodeWithTexture:HumanTexture1];
HumanBody.size = CGSizeMake(30, 50);

Human.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:MenschKörper.size];
Human.physicsBody.dynamic = NO;
Human.physicsBody.allowsRotation = NO;
Human.physicsBody.usesPreciseCollisionDetection = YES;

Human.physicsBody.categoryBitMask = HumanCategory;
Human.physicsBody.collisionBitMask = BlockCategory | StoneCategory;
Human.physicsBody.contactTestBitMask = StoneCategory | BlockCategory;

[self addChild:Human];

-(void)spawnBlocks {

Block1 = [SKSpriteNode spriteNodeWithTexture:BlockTexture1];
[Block1 setScale:1];
Block1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:Block1.size];
Block1.physicsBody.dynamic = NO;
Block1.physicsBody.usesPreciseCollisionDetection = YES;
Block1.name = @"Blocks";
[self addChild:Block1];

Block1.physicsBody.categoryBitMask = BlockCategory;
Block1.physicsBody.collisionBitMask = HumanCategory;
Block1.physicsBody.contactTestBitMask = HumanCategory;

// and for the following 3 Blocks the same code

- (void)didBeginContact:(SKPhysicsContact *)contact
{

uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

if (collision == (HumanCategory | StoneCategory))
{
    [self GameOver];
    [self runAction:[SKAction playSoundFileNamed:@"Collision.mp3" waitForCompletion:NO]];
}

if (collision == (HumanCategory | BlockCategory))
{
    PlayerBlockContact = YES;
    NSLog(@"Contact");
}

}

-(void)didEndContact:(SKPhysicsContact *)contact
{

uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);

if (collision == (HumanCategory | BlockCategory))
{
    PlayerBlockContact = NO;
    NSLog(@"Contact Lost");
}

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */

if(PlayerBlockContact){
Human.physicsBody.velocity = CGVectorMake(0, 0);
[Human.physicsBody applyImpulse:CGVectorMake(0, 35)];
[self runAction:[SKAction playSoundFileNamed:@"Jump.mp3" waitForCompletion:NO]];
}

A: The contact and contact lost in rapid succession sounds like an issue with your objects'  restitution property. This can sometimes result in an unending series of bounces.
If objects make and lose contact in very quick succession, sometimes SpriteKit loses track of what the right condition is (objects that have contact show as not having contact).
Try setting the restitution on both objects to zero.
(yourObjectName).physicsBody.restitution = 0;


text:
Q: Tesseract giving errors This morning I tried to use tesseract and I'm getting the following error messages:
$ tesseract --list-langs
Error in pixReadMemTiff: function not present
Error in pixReadMem: tiff: no pix returned
Error in pixaGenerateFontFromString: pix not made
Error in bmfCreate: font pixa not made
List of available languages (6):
eng
fra
ita
mlt
osd
spa

I tried sudo apt purge tesseract* followed by a reinstall of tesseract-ocr and language files, but the error message remains.
Last week, I manually installed leptonica-1.7.8 and jbig2-enc libraries to use with ocrmypdf and everything was working fine.
Any clues on how to proceed to solve this issue?


text:
Q: How to store user data in game? (swift, spritekit) Let's say I had a game where in the beginning the user gets to choose a couple of things like name, gender, etc, and that will affect a lot of aspects in the game such as the sprite used to render the user, and the text that is displayed.
So every time I leave one area of the game and enter a new one I should figure out according to the user data - what sprite to use and what text to prep. Should I make a separate class with a dictionary just for the user's data and then just call it whenever I enter a new area?
Thanks yall.

A: There is a few ways to do this.
I prefer to use a singleton GameData class with NSCoding to house all the properties (arrays, dictionaries etc) that need to be saved permanently.
I like it this way because it makes code more readable and also has the advantage that you can access the properties from anywhere in your project. This way it's also easy to include icloud key value storage.
You can read these 2 questions I answered for a simple example of how this can look
SpriteKit: Why does it wait one round for the score to update? (Swift)
Is there a better way to save a custom class to NSUserDefaults than encoding and decoding everything with NSCoder?
There is a also few good tutorials around such as this
https://www.hackingwithswift.com/read/12/3/fixing-project-10-nscoding
To securely save data you can/should use keychain. To read more about it check out this question.
How secure is NSUserDefaults on iOS 8,9?


text:
Q: Decode base64-encoded PDF directly to string from Gmail Api in Node.js I'm using the Gmail API to get an attachment that is a pdf file.
The Gmail API returns the attachment as a base64-encoded string.
Is there a way to convert the base64-encoded string (the pdf document) directly to a string?
    function getAttachment(auth, attachmentId, messageId) {
      const gmail = google.gmail({version: 'v1', auth});
      gmail.users.messages.attachments.get({
        id: attachmentId,
        messageId: messageId,
        userId: 'me',
      }, async (err, res) => {
      if (err) {
        console.log(err);
      }
      console.log(res.data);
      const pdfAsString = Buffer.from(res.data.data, 'base64').toString('ascii')
      console.log(pdfAsString);
     });
   }

The Gmail API returns the following data
console.log(res.data).
Note that I'm not pasting the whole string here
{
size: 13409,
data: 'JVBERi0xLjukJb_...lJUVPRgo='
}

Is this possible? If not what are my other options?


text:
Q: Confused with DFS implementation
public void dfs(){
    ArrayList<Node> exploredList = new ArrayList<>();
    Stack s=new Stack();
    s.push(this.rootNode);
    while(!s.isEmpty()){
        Node n = (Node)s.pop();
        exploredList.add(n);
        printNode(n);
        ArrayList<Node> childList = getChildNodes(n);
        for (Node child : childList){
            if (!exploredList.contains(child) && !s.contains(child)) {
                s.push(child);
        }
    }
}

Output:
A D C F B E

I am confused with DFS algorithm. The above code adds all child nodes to the stack, removes it from the stack and visits until it reaches the end node, while the other implementation (following reference link) adds one node to the stack, visits until it reaches the end node and backtracks.
Is the above code implementation of the DFS algorithm? If yes? How it is different from other DFS implementations? The output of other DFS algorithm should be:
Output:
A B E F C D

Reference:
Introduction to Graph with Breadth First Search(BFS) and Depth First Search(DFS) Traversal Implemented in JAVA

A: What makes it a DFS (depth-first search) is the fact that it is traversing the graph by continuously visiting deeper and deeper nodes in the graph before backtracking and visiting other nodes which have been added to the stack. Note: this does not guarantee visiting the nodes in a specified order. Two perfectly good implementations of DFS can have entirely different outputs if they simply choose to visit the nodes in a different order, such as starting from the left (A -> B) rather than the right (A -> D) side.

A: The output is different but your implementation was correct. I do not know how you constructed your own graph but I think its different because the algorithm visited the neighbors of root node from right to left.
Your neighbors of root node (A) is an ordered array which are [D, C, B]
So A visited D first, then is C and so on... its just from right to left. After all, it really depends on the way you constructed your graph.
I'm assuming that your graph is reversed.


text:
Q: What in a form makes the browser back button not work? http://discoursedb.org/wiki/Special:RunQuery/Item_query
The above link has a form where if you enter a search item and click on any links in the result and then the back button the results are still there.
I have an identical form with additional fields (dropdown and checkboxes) where the back button doesn't work and the browser asks for confirmation to submit the data again.
What can cause this?
Update:
I just noticed that if I open Console in Chrome and test my implementation it works when cache is disabled and not otherwise. Maybe this helps in explaining the behavior?

A: Don't return a document from the result of a POST.  Instead, return a redirect to a document.  This helps solves many of these issues.  That's also what causes form re-submission warnings.  When you click back, you skip redirected links, but you do not skip 200 OK responses.  So if you are replying with 200 OK for your POST requests, you might be doing it wrong.  Reply with a 303 See Other or something similar, with the actual document URL in the Location header.
More detail:
POST requests are not typically cacheable.  POST requests are for performing some operation or adding some data.  If you make the same request again, you want to perform the operation again or add some new data.
GET requests typically are cacheable.  GET requests are for fetching resources.  When you request a resource at a specific URL, it is generally expected that same document will be returned if you make the same request again.
Either way, the server is going to respond with one of several status codes.  The most common is 200 OK, which tells the browser that everything went fine with the request and to display the response to the user.
The next most common is a redirect.  There are several varieties, but some of the most common are 301 Moved Permanently (appropriate when you are sending them to a canonical URL), 302 Found (sort of a catch all), and 303 See Other (this is typically what you want in response to a successful POST).  For all of these redirect cases, the Location header will contain a URL the browser should redirect to.
Currently, you are sending back a 200 OK result for the POST request.  This tells the browser that the response should be displayed to the user.  But because it's a POST request, the browser will not cache the response.  And you will get form re-submit warning because in order to refresh the page, you have to send the POST request and all its data all over again.
What SHOULD happen is the POST request responds with a 303 See Other and a URL in the Location header pointing to the response document.  When the browser sees the redirect, it will issue a GET request against this URL, which is cacheable and will not cause form re-submission issues when you try to refresh.
You may want to read the following for some more background.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

A: Its because your server has disabled Caching. This is an old post but the problem still prevails. Regardless of whether you respond to your POST with a page or a redirect Chrome will still block the back button if you have disabled Caching and this means backing into a form POST. In other browsers they simply go back through your history and return the last GET request ignoring the POST/form submission. In the case of Chrome it does not. You can try it by simply re-enabling Caching and Chrome will return the Cached responses from your POST requests. Chrome DOES cache post responses (See the attached image) but only if you have allowed it to.

How to enable/disable Caching
That is another topic but it's done most consistently by sending headers from the server-side that instruct the client not to cache the response. Simply adding headers to your meta tags in HTML is not effective in all scenarios but that is a possible place to "attempt" to prevent caching. An example for Java developers which can be ported to other languages. Java servlet how to disable caching of page


text:
Q: Pass errors from nginx to node.js when using nginx as a proxy server Why I want to pass errors from nginx to node.js
I want to limit the file size in a request when using nginx as a proxy server for Node.js and using multer for file upload. If I use limits using multer's options, multer wastes a lot of bandwidth in trying to upload the file and later checks if it exceeds the limit but I can use my own error handling through node.js. When using client_max_body_size in nginx, the request gets rejected altogether (more on that below).
The exact file size in the request is not the concern so client_max_body_size 100M; works well. 100M is just a dummy value and won't be used for every route. Here is my nginx config
upstream my_nodejs_upstream {
    server 127.0.0.1:5000;
    keepalive 64;
}

server {
    listen 80;
    client_max_body_size 100M;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;

        proxy_http_version 1.1;

        proxy_pass http://my_nodejs_upstream/;
        proxy_redirect off;
        proxy_read_timeout 240s;
    }
}

Now, if a request body exceeds the limit (100M), I get the error: 413: Request Entity Too Large. The error is returned as a static html page.
I'd like to know if an error for this status code (413) can be passed on to node.js and an error be sent from node.js instead. If not, what practice is generally used to handle such nginx errors in a consistent way while also keeping it maintainable?

A: Needing to pass an error from NGINX to the API server would not be a good practice.  Rather, in your front-end (e.g. web or mobile app) you could check for this 413 error and display it however you wish.
More generally, NGINX also supports custom error pages that you could read more about here: https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-to-use-custom-error-pages-on-ubuntu-14-04.
Another option here is for you to create your own API endpoint that simply checks whether the POST request will be valid (e.g.an OPTIONS call).  In this API endpoint, you can check the content-length of the request and return an error code back however you wish.  This will let your front-end clients that invoke this API know that the file length is exceeded, and there is no reason to actually send the file over to the backend server.  (Basically, you will pre-emptively catch this error before NGINX catches it when the file is actually transferred)


text:
Q: Best Curl Package/Replacement in NodeJS I was looking through other posts for replacements for Curl in nodejs, especially with complex behaviors as such:
 -H 'Authorization: Basic MjJCTUpROjczNzY0YzkwOWQ2MDczZDRjYzA0YWZhZDBlMDVhMThm' \
 --data "clientId=22BMJQ" \
 --data "grant_type=authorization_code" \
 --data "redirect_uri=https%3A%2F%2Fexample.com%2Fcallback" \
 --data "code=5f10eff73e8daf2049be22bb079beee57036c7a5" \
 -H 'Content-Type: application/x-www-form-urlencoded' \
https://api.fitbit.com/oauth2/token

Are there any packages you would recommend or have ideas on how the above request could be replicated in nodejs?

A: In case you don't only want to call OAuth 2.0 endpoints but also other endpoints with the curl alternative, I made good experiences with node-fetch. The code with node-fetch is more readable and you can work with response very easily in JavaScript.

A: Have a look at OpenId Client, which is a certified library. It will make life easier once you're familiar with it.
Here are a couple of links that you might find useful, to understand the basics of the coding model:

*

*Authorization Code Flow Tutorial

*API Sample Code of Mine


text:
Q: How to use images in GTK Stack Switcher using C I'm making application in gtk using C. I have a GtkStack with GtkStackSwitcher and I don't know how to set images/icons to buttons in stack switcher. I had similar problem with application in gtkmm and C++ but I was able to find required function in the documentation. This time, after searching the documentation for GtkStack, GtkStackSwitcher and GtkContainer, I didn't find anything useful in GtkStack and GtkStackSwitcher. In GtkContainer there is function gtk_container_child_set_property (). It may be the function I'm looking for but I have no idea how to put an icon-name into GValue and if it's possible.
To sum up - can I set icon to GtkStackSwitcher's button with mentioned functions or using any other method?
Edit:
Maybe it's possible to achieve this with css? Setting background-image for GtkStack and GtkStackSwticher doesn't work but setting background_image for buttons works. Works very bad but works. The image doesn't fit the button and button doesn't resize to be the image size (If i set button new from pixbuf the button does resize). So is it possible with css or is it a dead end?

A: From the GtkStack documentation, at Child Properties, you can see the property "icon-name":

The "icon-name" child property
"icon-name"                gchar *
The icon name of the child page.
Flags: Read / Write
Default value: NULL

As you pointed out, we can use gtk_container_child_set_property on the GtkStack (a GtkContainer) and set the icon. The problem is that the stack uses the icon or the title, not both.
Here is a simple example in C code:
#include <gtk/gtk.h>

int main (int argc, char** argv) {
   GtkBox *box;
   GtkStack *stack;
   GtkLabel *label1;
   GtkLabel *label2;
   GtkWindow *window;
   GtkStackSwitcher *switcher;
   GValue iconval1 = G_VALUE_INIT;
   GValue iconval2 = G_VALUE_INIT;

   gtk_init (&argc, &argv);

   g_value_init (&iconval1, G_TYPE_STRING);
   g_value_init (&iconval2, G_TYPE_STRING);

   window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
   box    = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 6));
   stack  = GTK_STACK(gtk_stack_new ());
   switcher = GTK_STACK_SWITCHER(gtk_stack_switcher_new ());

   label1 = GTK_LABEL(gtk_label_new("Stack Page 1"));
   label2 = GTK_LABEL(gtk_label_new("Stack Page 2"));

   gtk_stack_add_titled(stack, GTK_WIDGET(label1), "Page 1", "Page 1");
   gtk_stack_add_titled(stack, GTK_WIDGET(label2), "Page 2", "Page 2");

   gtk_widget_set_halign (GTK_WIDGET(switcher), GTK_ALIGN_CENTER);

   g_value_set_string(&iconval1, "zoom-in-symbolic.symbolic");
   g_value_set_string(&iconval2, "zoom-out-symbolic.symbolic");

   gtk_container_child_set_property(GTK_CONTAINER(stack), GTK_WIDGET(label1), "icon-name", &iconval1);
   gtk_container_child_set_property(GTK_CONTAINER(stack), GTK_WIDGET(label2), "icon-name", &iconval2);

   gtk_stack_switcher_set_stack (switcher, stack);
   gtk_box_pack_start (box, GTK_WIDGET(switcher), FALSE, FALSE, 6);
   gtk_box_pack_start (box, GTK_WIDGET(stack), TRUE, TRUE, 6);

   gtk_container_add (GTK_CONTAINER(window), GTK_WIDGET(box));

   g_signal_connect(G_OBJECT(window), "destroy", gtk_main_quit, NULL);

   gtk_widget_show_all (GTK_WIDGET(window));

   gtk_main ();

   return 0;
}

Compile it with:
gcc -o test main.c `pkg-config --cflags --libs gtk+-3.0`

and the result should be:

EDIT:
As requested in the comments:

Can you tell me also how to change icon sizes of stack switcher icons?
  I see that stack switcher has property "icon-size"...

GtkStackSwitcher has the property "icon-size" but it was introduced in Gtk+ 3.20. So, in order to use this property there is this requirement.
To set a property to which Gtk+ does not provide a setter/getter you should use g_object_set (or set_full).
Using the code above:
   ...
   switcher = GTK_STACK_SWITCHER(gtk_stack_switcher_new ());

   g_object_set(G_OBJECT(switcher), "icon-size", GTK_ICON_SIZE_LARGE_TOOLBAR, NULL);

   label1 = GTK_LABEL(gtk_label_new("Stack Page 1"));
   ...

The property is a gint value so you can try out some values and verify the size. There is also a enumerated type containing default sizes for icons, it's GtkIconSize. In the example i've used GTK_ICON_SIZE_LARGE_TOOLBAR (24px).


text:
Q: How to avoid repeating kwargs in Python? Suppose there is a method:
def train_model(self, out_dir='./out/',
                test_size=0.2, train_size=None,
                random_state=None, shuffle=True, stratify=None,
                epochs=DEFAULT_EPOCHS, batch_size=DEFAULT_BATCH_SIZE):
    ...
    self.model.train(test_size=test_size, train_size=train_size, random_state=random_state, shuffle=shuffle, stratify=stratify, epochs=epochs, batch_size=batch_size)

And inside this function another method with the same signature will be called, then I have to pass all the params manually. I don't want to use kwargs in train_model as it's a public method that may used by others, so I hope to keep the typing information. I don't know if there are methods to allow me to keep the typing information in kwargs of outer function.
The same functionality in TypeScript can be achieved using the Parameters utility types. For example,
function sum(a: int, b: int) {
    return a + b;
}

type SumParamsType = Paramters<typeof sum>

// Then you can use the SumPramsType in other places.

A failed example of Python:
from typing import TypeVar
T = TypeVar('T')

def f1(a=1, b=2, c=3):
    return a+b+c

# Is there anything like T=Parameters(type(f1)) in Python?

def f2(z=0, **kwargs: T):
    return z+f1(**kwargs)

# T cannot capture the kwargs of f1 (of course it won't)

And this doesn't works either:
def f1(a=1, b=2, c=3):
    return a+b+c

def f2(z=0, **kwargs: f1.__annotations__['kwargs']):
    return z + f1(**kwargs)

# kwargs has the type Any

A: The closest you can get is to use a TypedDict with Unpack (available on Python < 3.11 via typing_extensions):
from typing_extensions import Unpack, TypedDict, NotRequired

class Params(TypedDict):
    a: NotRequired[int]
    b: NotRequired[int]
    c: NotRequired[int]

def f1(**kwargs: Unpack[Params]):
    a = kwargs.pop('a', 1)
    b = kwargs.pop('b', 1)
    c = kwargs.pop('c', 1)
    return a + b + c

def f2(z=0, **kwargs: Unpack[Params]):
    return z + f1(**kwargs)

Note that your IDE may not support Unpack if it does not use mypy --enable-incomplete-feature=Unpack. VSCode supports it out of the box. PyCharm, probably not.
If you control both function definitions, you may find it easier to change your methods to accept a dataclass encapsulating all the parameters and their defaults instead of taking each parameter individually.

A: You could create a class containing the training arguments and pass it to the train method, as is done in the HuggingFace Transformers library
Here is the code from their GitHub:
from dataclasses import asdict, dataclass, field, fields

#...

@dataclass
class TrainingArguments:
    framework = "pt"
    output_dir: str = field(
        metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
    )
    overwrite_output_dir: bool = field(
        default=False,
        metadata={
            "help": (
                "Overwrite the content of the output directory. "
                "Use this to continue training if output_dir points to a checkpoint directory."
            )
        },
    )

    do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
    do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
    do_predict: bool = field(default=False, metadata={"help": "Whether to run predictions on the test set."})
    evaluation_strategy: Union[IntervalStrategy, str] = field(
        default="no",
        metadata={"help": "The evaluation strategy to use."},
    )
    prediction_loss_only: bool = field(
        default=False,
        metadata={"help": "When performing evaluation and predictions, only returns the loss."},
    )

    per_device_train_batch_size: int = field(
        default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."}
    )
    per_device_eval_batch_size: int = field(
        default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}
    )
    # ...

It is a bit verbose but very clear and will work with your IDE type hinting.

A: You will need a combination of locals() and .__code__.co_varnames:
def f2(b=5, c=7):
    return b*c

def f1(a=1, b=2, c=3):
    sss = locals().copy()
    f2_params = f2.__code__.co_varnames
    return f2(**{x:y for x, y in sss.items() if x in f2_params})

print(f1())
>>> 6

Edit
If you want to use **kwargs, try this:
def f2(b=5, c=7):
    return b*c

def f1(a=1, **kwargs):
    sss = locals()['kwargs'].copy()
    f2_params = f2.__code__.co_varnames
    return f2(**{x:y for x, y in sss.items() if x in f2_params})

print(f1(b=10, c=3))


text:
Q: How to check if row already exists in csv I'm trying to make a combined csv file from old files, which have some duplicates, but something is wrong in my code. 'test2.csv' is bigger and has new rows and 'test1.csv' is the new file I'm trying to make.
new = []
with open('test1.csv','rb') as file1:
    reader = csv.reader(file1,delimiter=',' )
    with open('test2.csv','rb') as file2:
        reader2 = csv.reader(file2,delimiter=',')
        for row in reader2:
            if row not in reader:
                new.append(row)

for row in new:
    print row

EDIT:
My test files look like this
test1.csv:
28/11 16    VwS (10)    Ha MaSSe (16)   mirage  Global Offensive Champions League Season 5  39247   6756    7472    2596    10  16  8459,9434,11307,9410,8460   11838,11837,12943,11840,12944
28/11 16    Ulti (0)    Signature (16)  mirage  fpsGOD Super League Winter  39251   7343    6774    2533    0   16  12429,12427,12430,12428,12431   9288,10664,9289,11248,12129

test2.csv:
28/11 16    Singularity (14)    Elements (16)   nuke    Global Offensive Champions League Season 5  39252   6978    7489    2596    14  16  9317,2822,8862,8875,7463    8726,7405,8727,8368,8410
28/11 16    eSuba (9)   Pathless (16)   cache   Gauntlet: Fight for the Crown   39253   5412    7433    2430    9   16  9666,10458,7723,9358,3143   9891,9412,12767,12945,12766
28/11 16    Pathless (16)   eSuba (13)  mirage  Gauntlet: Fight for the Crown   39248   7433    5412    2430    16  13  9412,12945,12767,9891,12766 9666,7723,10458,9961,9358,3143
28/11 16    VwS (10)    Ha MaSSe (16)   mirage  Global Offensive Champions League Season 5  39247   6756    7472    2596    10  16  8459,9434,11307,9410,8460   11838,11837,12943,11840,12944
28/11 16    Ulti (0)    Signature (16)  mirage  fpsGOD Super League Winter  39251   7343    6774    2533    0   16  12429,12427,12430,12428,12431   9288,10664,9289,11248,12129

So, I'm trying to add the missing rows to the test1.csv from test2.csv.

A: The file test1.csv isn't being modified in your snippet.  When the reader is created with csv.reader(file1,delimiter=','), the reader is not updated at all afterwards.
You are modifiying new in your loop, so check if your line is in there.
If you want to not print out the rows that are already in test1.csv, you need to read them in and check if they are not duplicates when iterating over the rows in the second file.
with open('test1.csv','rb') as file1:
    existingLines = [line for line in csv.reader(file1, delimiter=',')]

new = []
with open('test2.csv','rb') as file2:
    reader2 = csv.reader(file2,delimiter=',')
    for row in reader2:
        if row not in new and row not in existingLines:
            new.append(row)

for row in new:
    print row


text:
Q: Best practice for Installing missing 32-bit package on a 64-bit Fedora Linux I am using Fedora 13 64-bit. After reading few posts online it seems that most of 32-bit packages and libraries can easily be installed using the following command:
yum install *packagename*.i686

which is great. However, due to some constraints I was in need of 32-bit version of wireshark and wireshark-gnome packages. Installing wireshark was not an issue since the default 64-bit repo already had that package:
yum list | grep wireshark
wireshark.i686                           1.2.17-1.fc13                  updates
wireshark.x86_64                         1.2.17-1.fc13                  updates
wireshark-devel.i686                     1.2.17-1.fc13                  updates
wireshark-devel.x86_64                   1.2.17-1.fc13                  updates
wireshark-gnome.x86_64                   1.2.17-1.fc13                  updates

but there was no corresponding wireshark-gnome package in the default repo. What is the best way to install 32-bit packages when one such is not available in the default repo. I see that F13 updates repo has the wireshark-gnome package that I want.

A: As a warning installing the 32 bit version of the package means you're going to have to install every 32 bit dependency that might exist for that package, so there may be additional packages that you end up installing on the system. The repository you have linked to doesn't seem to have any metadata so you would need to install it manually after you download it via the RPM command. If this is on a local desktop I'd suggest creating a virtual 32 bit machine and working out of that.


text:
Q: How to fix "Bus error 10" after update to Xcode 10.2 I updated Xcode to new stable 10.2v. I tried to build my project and it was successful. When I'm trying to archive the project (workspace), I'm getting errors like on screenshot below:

What I've tried so far:

*

*Update cocoa pods to latest version -> COCOAPODS: 1.7.0.beta.3

*Clean DeliveredData folder

*Reinstall Xcode

*Remove repository, clone it again and install pods

*Totally remove all pods from project and add them back

A: While Lukas' answer of disabling optimization on the Cache pod works, I followed Alex's link to the issue in their GitHub repo and found there is an open pull request with a pretty simple code change that fixes it.  I unlocked the file and made the change locally.
Here's the PR: https://github.com/hyperoslo/Cache/pull/236
Apply this diff: https://github.com/hyperoslo/Cache/pull/236/commits/560f00a9a9549db161ca70d96eed74fc580b03e3#diff-9e53dc1370d4f7c9cdaaa103d26ff096
Which, to repeat here, is in the file MD5.swift change the safe_add function to be:
func safe_add(_ x: Int32, _ y: Int32) -> Int32 {
  return x &+ y
}

(Disclaimer: I do not claim to know the correctness of the change, but it seems the delay merging the PR is due to figuring out who is currently maintaining the repo.)

A: Temporary Workaround
For me it was only the Cache framework. Until they have fixed it, you can manually set SWIFT_OPTIMIZATION_LEVEL to -Onone for the configuration you want to use for archiving.

CocoaPods
You could even use your Podfile if you don't want Cococapods to overwrite the settings every time you run pod install
post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            if target.name == 'Cache'
                config.build_settings['SWIFT_OPTIMIZATION_LEVEL'] = '-Onone'
            end
        end
    end
end

Note that this is specifically checking for the Cache framework. If you have problems with other frameworks you might want to change or extend this condition.

A: The answer is here: https://github.com/hyperoslo/Cache/issues/238
We are waiting for the owners of this repo to make any sign of life...


text:
Q: "This site can't be reached" error while loading my WordPress site locally Tried every fix I could find on Youtube, no luck.
This is what it is showing:

Please give me a solution to this problem. It's being irritating from last 2 days.
Thank you.

A: Make sure port 8082 isn't being blocked by your firewall


text:
Q: Pass dynamic values through GCP cloud scheduler I need to trigger the Google dataflow jobs with the random/dynamic job_names from the cloud scheduler. I am able to pass the static job name and trigger the Dataflow by passing it in the scheduler body. Is there a way to dynamically set this job name through the scheduler?
If there is a way to set the current_timestamp or some random_numbers that would help.
I am aware that we can trigger the dataflow through the cloud function as well. But trying to avoid the no.of services here.
what I have:
{ "job_name": "test-run-df-job" }
What I need:
 { "job_name": "test-run-df-job" + CURRENT_TIME() }
Thank you for any help.

A: You can't add dynamic value in Cloud Scheduler. You can imagine other services, like Cloud Workflows to do that addition without any code to write (like with a Cloud Functions for instance) and then invoke your Dataflow


text:
Q: Error while creating Worker in Twilio TaskRouter I am working on contact center using Twilio in Node js for that I am using TaskRouter but getting error in below code.
 var capability = new twilio.TaskRouterWorkerCapability(accountSid,authToken, workspaceSid, workerSid);
    capability.allowActivityUpdates();
    capability.allowReservationUpdates();
    token = capability.generate();
    agent = new twilio.TaskRouter.Worker(token); // Here getting below error.

TypeError: Cannot read property 'Worker' of undefined

Is I am missing something? and how can I update the activity of the particular worker. I did the below code changes but it is not updating the status or activity of Worker.
client.workspace.workers(workerSid).update({
        /*attributes: '{"type":"support"}',*/
        ActivitySid:'WAa8affefa7a655a86201f05317bfd2ba4' // idle
    }, function(err, worker) {
        console.log(worker.sid);
    })

A: Twilio employee here.
Are you trying to update a Worker's activity from a client or on the node server?
The former is key for agents to update their state (this is the most common). Although if you want to force an agent into a particular state that TaskRouter doesn't automatically do, then you can do so server-side.
Updating Worker Activity from a JS Client
Everything looks good from the JWT generation perspective, however you need to return the token to the JS client-side to initiate the Worker JS.
<script type="text/javascript" src="//media.twiliocdn.com/taskrouter/js/v1.2/taskrouter.min.js"></script>
<script type="text/javascript">
    var workerToken = generateWorkerToken(); // calls your node server to generate the JWT
    var worker = new Twilio.TaskRouter.Worker(workerToken);
    worker.update({"ActivitySid":"WAa8affefa7a655a86201f05317bfd2ba4"},
        function(err, worker) {
            console.log(worker.sid);
        });
</script>

For more information on TaskRouter Worker.js, you can check this out here: https://www.twilio.com/docs/api/taskrouter/worker-js
Updating Worker Activity from a Node Server
If you're looking to update a Worker's Activity from a node server, there's no need to generate a JWT since this is for client side authentication.
You can simply utilize the function you're already doing:
var client = new twilio.TaskRouterClient('AC123', '123', 'WS123');
client.workspace.workers(workerSid).update({
    /*attributes: '{"type":"support"}',*/
    ActivitySid:'WAa8affefa7a655a86201f05317bfd2ba4' // idle
}, function(err, worker) {
    console.log(worker.sid);
})

The key is that twilio indicates node-server side use where as Twilio.TaskRouter.Worker indicates client-side use.


text:
Q: "You and I" - both subjects? I was talking about this with a friend yesterday, though the actual example was "thou and I", which sounded weird. I thought it should be "thee and I", due to "I" being a subject pronoun. I eventually conceded, but I'm still not sure - could you say (arguably) that "thou/you", when paired with "I", is an object? Or are they still both subjects?
Similarly, is "it" still the subject in a sentence like "the dog and it"?

A: Any case other than nominative/subjective (i.e. dative, accusative/objective, etc.) requires

"me, us, thee, him, her, them, and whom"

to be used in place of

"I, we, thou, he, she, they, who."

You (plural; variants include "y'all" and "youse guys," but they're colloquial and I wouldn't recommend using them unless you're absolutely sure you know what you're doing) is an exception. It remains unchanged regardless of the case.


text:
Q: disabling extra message after changing to new directory Whenever directory is changed, it is displaying the new directory name:
# cd /home/
Directory: /home/
# cd ~
Directory: /root

How to disable it?
We are logging into csh. We already verified /etc/csh.cshrc, /etc/profile, /etc/csh.login.

A: try looking in the user folder instead of only looking for the system wide files.
if you are logged in as root:
/root/.cshrc

or
/home/[USERNAME]/.cshrc

i do not know for additional csh files similiar to bash files (.bash_login .bash_logout) in the user folder, so you might need to check the existence with ls -a for showing the "hidden" . files.


text:
Q: C# setting String variables as argument for SQL string statement I'm coming from Java programming and I recently just tried to study C# for web (.aspx). I'm new and still getting myself familiar with the components and how C# components are bound to the SQL Server database.
I'm having trouble setting values from TextBoxes which are assigned to String variables into my SQL statement.
Here's my code.
 protected void Btn_additem_Click(object sender, EventArgs e)
 {
     String category = "";
     String itemName = Tb_itemname.Text;
     String code = Tb_itemcode.Text;
     String brand = Tb_brand.Text;
     String serial = Tb_serial.Text;
     String capacity = Tb_capacity.Text;
     String version = Tb_version.Text;

     if (Rbl_hardsoft.SelectedValue.Equals("Hardware"))
     {
         category = "Hardware";
     }
     else if(Rbl_hardsoft.SelectedValue.Equals("Software"))
     {
         category = "Software";
     }

     String SQL = "INSERT INTO ItemMasterData(item_code,item_category, item_name, item_brand,item_serialnumber, item_capacity, item_version) " +
            "VALUES(?,?,?,?,?,?,?)";
}

My goal is to be able to make the string variables category, itemName, code ...and so on to be arguments for the ?
In Java we usually make use of PreparedStatement wherein we use ? for arguments then we set its value thru setters. For instance,
ps.setString(1,"stringvalue or string variable"); // 1 for the first question mark
ps.setInt(2,intvalueOrintVariable); // 2 for the second question mark

How do I do that in C#? I'm not very familiar with DataSource yet and I would like to be able to assign parameters by code rather than by using the C# properties window.
I'd appreciate any help or practical example.
Thanks.

A: Use parameters
https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx
 protected void Btn_additem_Click(object sender, EventArgs e)
 {
     String category = "";
     String itemName = Tb_itemname.Text;
     String code = Tb_itemcode.Text;
     String brand = Tb_brand.Text;
     String serial = Tb_serial.Text;
     String capacity = Tb_capacity.Text;
     String version = Tb_version.Text;

     if (Rbl_hardsoft.SelectedValue.Equals("Hardware"))
     {
         category = "Hardware";
     }
     else if(Rbl_hardsoft.SelectedValue.Equals("Software"))
     {
         category = "Software";
     }

     using (SqlConnection connection = new SqlConnection(connectionString))
     using (SqlCommand command = connection.CreateCommand())
     command.CommandText = "INSERT INTO Contacts ItemMasterData(item_code,item_category, item_name, item_brand,item_serialnumber, item_capacity, item_version) VALUES (@item_code,@item_category, @item_name, @item_brand,@item_serialnumber, @item_capacity, @item_version)";
     command.Parameters.AddWithValue("@item_code", code );
     command.Parameters.AddWithValue("@item_category", category );
     command.Parameters.AddWithValue("@item_name", itemName );
     command.Parameters.AddWithValue("@item_brand", brand );
     .. the rest of parameters...

    connection.Open();
    command.ExecuteNonQuery();
}

A: It is entirely possible to build a SQL string via basic string concatenation and replacement. But for anything beyond the most simple test or if the string comes 100% for your code, do not.
In C# there is this whole concept of a parametrized query. It actually exists independent of a prepared statement. Which one to use depends on which database you use as this does directly work with the driver:
https://msdn.microsoft.com/en-us/library/bb738521(v=vs.90).aspx


text:
Q: Multiple columns from aggregate function, but apply only to rows matching a WHERE clause Sample dataset:
+----------+---------+-----+
| order_id | prod_id | qty |
+----------+---------+-----+
|        1 |       1 |   2 |
|        1 |       1 |   4 |
|        1 |       3 |   1 |
|        2 |       1 |   1 |
|        2 |       2 |   2 |
|        3 |       4 |   1 |
|        3 |       4 |   2 |
|        3 |       2 |   3 |
|        3 |       3 |   5 |
|        4 |       1 |   2 |
|        4 |       2 |   3 |
|        4 |       3 |   3 |
|        4 |       4 |   3 |
|        4 |       6 |   2 |
+----------+---------+-----+

What I'm trying to do is build a "report" view, that will aggregate certain totals based on the product code. So for example, I want one column with totals by order for product code 1, another column with aggregate total for products 2 and 3, and one for product code 4 and 6.
Note that the values for the product codes are coming from a product class table, so I'm actually looking to get all products in class 1, which would be product 1, then all products in class 2, which would be products 2 and 3, and then all products in class 3, which would be products 4 and 6.
+----------+--------+--------+--------+
| order_id | c1_tot | c2_tot | c3_tot |
+----------+--------+--------+--------+
|        1 |      6 |      1 |      0 |
|        2 |      1 |      2 |      0 |
|        3 |      0 |      8 |      3 |
|        4 |      2 |      6 |      5 |
+----------+--------+--------+--------+

I can do this for one column using a WHERE clause like this:
SELECT
    [order_id],
    SUM([qty]) AS [c2]
FROM [orders]
WHERE [prod_id] IN (SELECT [id] FROM [product_class] WHERE [class] = 2)
GROUP BY [order_id]

The other approach I came up with was a stored function, but this seems a long-winded way to do it:
SELECT DISTINCT
    [order_id],
    total_products_by_class([order_id],1) AS [c1_tot],
    total_products_by_class([order_id],2) AS [c2_tot],
    total_products_by_class([order_id],3) AS [c3_tot]
FROM [orders]

I suspect something could theoretically be done with analytic functions?...
Is there a way to do this without a stored function in something suitable for a view?
Update: make clearer about need to pull in values for products from a subquery.

A: A CASE statement might be what you need to do it in a simple query.
SELECT  [order_id],
      SUM(CASE WHEN prod_id = 1 THEN qty ELSE 0) AS p1_tot,
      SUM(CASE WHEN prod_id = 2 OR prod_id = 3 THEN qty ELSE 0) AS p2and3_tot,
      SUM(CASE WHEN prod_id = 4 OR prod_id = 6 THEN qty ELSE 0) AS p4and6_tot
FROM [orders]
    INNER JOIN [product_class] ON [orders].[prod_id] = [product_class].[id]
WHERE [product_class].[class] = 2
GROUP BY [order_id];

A: I took the sample data provided for the orders table and created the product_class table from the description in the 2nd paragraph of the question.
Sample Data:
create table #orders
    (
        order_id int
        , prod_id int
        , qty int
    )

create table #product_class
    (
        id int
        , class int
    )

insert into #orders
values (1, 1, 2)
    , (1, 1, 4)
    , (1, 3, 1)
    , (2, 1, 1)
    , (2, 2, 2)
    , (3, 4, 1)
    , (3, 4, 2)
    , (3, 2, 3)
    , (3, 3, 5)
    , (4, 1, 2)
    , (4, 2, 3)
    , (4, 3, 3)
    , (4, 4, 3)
    , (4, 6, 2)

insert into #product_class
values (1, 1)
    , (2, 2)
    , (3, 2)
    , (4, 3)
    , (6, 3)

Answer:
Starting with the first query written in the question as inspiration, I changed the reference to the product_class table to an inner join and added the class to the group by. After that, all that needs to happen is a pivot to get the classes to go across the columns instead of the rows.
select b.order_id
, isnull(b.[1], 0) as c1_tot
, isnull(b.[2], 0) as c2_tot
, isnull(b.[3], 0) as c3_tot
from (
    SELECT o.[order_id]
    , pc.class
    , SUM(o.[qty]) AS [c2]
    FROM [#orders] as o
    inner join #product_class as pc on o.prod_id = pc.id
    GROUP BY o.[order_id]
    , pc.class
    ) as a
pivot (max(a.c2) for a.class in ([1], [2], [3])) as b

Output matches the desired output exactly.


text:
Q: Twilio to have pause period when using loop to repeat voice call I tried repeating a message in voice call as python code here which was guided here but not working i.e. no pause at all whatever number for :length it is <Pause length="3">
call = client.calls.create(
    twiml = f'''
    <Response>
        <Gather>
            <Say loop="{loop}">{message}</Say>
            <Pause length="3"></Pause>
        </Gather>
        <Redirect>/gather.xml</Redirect>
    </Response>
    ''',
    to    = to,
    from_ = from_,
)

A: Take a look at SSML Pause.
Adding a Pause
SSML Break Tag
I tried out the below, and it worked. Don't forget your <Gather> action url.
<Response>
    <Gather>
        <Say loop="3">This is a message with a pause between loops<break time="3s"/></Say>
    </Gather>
    <Redirect>/gather.xml</Redirect>
</Response>


text:
Q: Compile error on assignment to array — VBA (Excel) I want to assign values to an Integer array, but instead I got a compile-time error.
Here is my code:
Private Sub A()
    Dim i As Integer
    Dim Width(3) As Integer
    Dim TempArray As Variant
    TempArray = Array(12, 6, 12, 5)
    For i = 0 To 3
        Width (i) = CInt(TempArray(i))
    Next i
End Sub

The error is on this line:
Width (i) = CInt(TempArray(i))

The error message is: "Compile Error. Expected:#".
I don't know what's wrong with this statement. Did I use a reserved word? I am new to VB, but I do need help. Thanks in advance.

A: Your comment led me to a little more research. Width isn't just an Excel reserved word, as in Column.Width. It's actually a VBA statement having to do with writing to text files, and it expects the number of a file opened for output.
Here's the text from Excel 2010 VBA help:

Width # Statement
Assigns an output line width to a file opened using the Open
  statement.
Syntax
Width #filenumber, width
The Width # statement syntax has these parts:
Part Description  filenumber Required. Any valid file number.  width
  Required. Numeric expression in the range 0–255, inclusive, that
  indicates how many characters appear on a line before a new line is
  started. If width equals 0, there is no limit to the length of a line.
  The default value for width is 0.
Example This example uses the Width # statement to set the output line
  width for a file.

Dim I
Open "TESTFILE" For Output As #1    ' Open file for output.
VBA.Width 1, 5    ' Set output line width to 5.
For I = 0 To 9    ' Loop 10 times.
    Print #1, Chr(48 + I);    ' Prints five characters per line.
Next I
Close #1    ' Close file.


text:
Q: Iron router routes from db I try to load my routes from db. My collection schema for routes is:
AsideMenu.attachSchema(
new SimpleSchema({
    name: {
        type: String,
        denyUpdate: true
    },
    path: {
        type: String,
        denyUpdate: true
    },
    controller: {
        type: String,
        denyUpdate: true
    }
})

);
I defined also a method for publish and subscribe and everything works well, i can get on client all the records on which he has access, but i cant get the router to register them.
    _.map(menuRoutes, function (route) {
    Router.route(route.path,
        {
            name: route.name,
            controller: route.controller,
        })
})

When I access in client console:
console.log(Router.routes) I get []

And if i print it in server console i get all routes:
I20150227-19:02:47.753(2)?   { [Function]
I20150227-19:02:47.753(2)?     getName: [Function],
I20150227-19:02:47.753(2)?     findControllerConstructor: [Function],
I20150227-19:02:47.754(2)?     createController: [Function],
I20150227-19:02:47.754(2)?     setControllerParams: [Function],
I20150227-19:02:47.754(2)?     dispatch: [Function],
I20150227-19:02:47.754(2)?     path: [Function],
I20150227-19:02:47.754(2)?     url: [Function],
I20150227-19:02:47.755(2)?     params: [Function],
I20150227-19:02:47.755(2)?     get: [Function],
I20150227-19:02:47.755(2)?     post: [Function],
I20150227-19:02:47.755(2)?     put: [Function],
I20150227-19:02:47.755(2)?     delete: [Function],
I20150227-19:02:47.756(2)?     options:
I20150227-19:02:47.756(2)?      { name: 'calendar.index',
I20150227-19:02:47.756(2)?        controller: 'CalendarController',
I20150227-19:02:47.756(2)?        data: [Function],
I20150227-19:02:47.756(2)?        mount: false },
I20150227-19:02:47.757(2)?     _actionStack: { _stack: [], length: 0 },
I20150227-19:02:47.757(2)?     _beforeStack: { _stack: [], length: 0 },
I20150227-19:02:47.757(2)?     _afterStack: { _stack: [], length: 0 },
I20150227-19:02:47.757(2)?     _methods: {},
I20150227-19:02:47.758(2)?     _path: '/calendar',
I20150227-19:02:47.758(2)?     handler:
I20150227-19:02:47.758(2)?      { options: [Object],
I20150227-19:02:47.758(2)?        mount: false,
I20150227-19:02:47.758(2)?        method: false,
I20150227-19:02:47.759(2)?        where: 'client',
I20150227-19:02:47.759(2)?        name: 'calendar.index',
I20150227-19:02:47.759(2)?        path: '/calendar',
I20150227-19:02:47.759(2)?        compiledUrl: [Object],
I20150227-19:02:47.759(2)?        handle: [Circular],
I20150227-19:02:47.917(2)?        route: [Circular] },

I want to know if this is possible because i couldnt find any example with this aproach.

A: Yes, this should be possible. I have a similar setup working just fine, the only difference being that I create the routes from a static array, not a db query. But that should make a difference.
This works for me, when executed during load:
_.each(routes, function(foo, route) {
    Router.map(function () {
        this.route(route, {
            path: route,
            action: function() { ... }
        });
    });
});

Where/when are you executing the _.map code you showed?

A: Iron router runs a reactive computation, but at the time your subscription to your route definitions collection is not ready. So if you put that block in your ready callback which is:
Meteor.subscribe('router-data-publication', function() {
  /* construct your routes here*/
});

or, you can do something safer, but essentially the same, using a handle within a Tracker and checking .ready() on the handler.


text:
Q: What is the difference between --to-latest and --to-current offset values Below is the comment in the Apache Kafka repository.
  --to-latest : Reset offsets to latest offset.
  --to-current : Resets offsets to current offset.

What is difference between two option? Aren't they both the same thing?

A: The latest option ignores committed offsets and seeks the group to the highest offset for all partitions.
The current option resets to the committed offsets, which I believe would be a no-op for any non-active consumer group.
For a group with zero lag, both options will do the same thing.
Source: https://github.com/apache/kafka/blob/3.0/core/src/main/scala/kafka/admin/ConsumerGroupCommand.scala
The current option is explained in KIP-122

When we want to only print out and/or backup the current offset by partition.


text:
Q: Is there a way to delay/organize page load without javascript? In the quest for fast (initial) page load, I'm wondering if there is a way to organize page load without using any javascript?
I don't know if you really need the delay capacity of javascript, if you could just order the way the content of your page loads (header-->content-->sidebars-->elements further down...
Or am I wrong about getting good page ratings without delaying?

A: Of course you can write a page without using js at all (for example pure html like it was in the beginning of web) and if you will use css3 then your page could look modern and dynamic. But it is hard to imagine any rich and modern functionality without support of scripting on client side (like autoload data on scroll via ajax, or collecting statistics or having local storage etc).
If you are thinking about fastest way to load initial page - try to think about caching static objects like images, js files etc, and to load static data first giving perception of a fast load,  loading dynamic data on a background using js.  However this is quite a spread topic and there are different techniques how to do such effect, i would recommend searching for topics about architectures  of modern high load web apps like facebook, youtube, twitter and so on.


text:
Q: Setting Max length of string/.text I use buttons to display letters in a bar now this is the code I use
-(IBAction) clicked: (id)sender{
NSString *titleOfButton = [sender titleForState:UIControlStateNormal];
NSString *newLabelText = titleOfButton;
labelsText.text = [NSString stringWithFormat:@"%@%@", labelsText.text, newLabelText];

 //if ([newLabelText length] >= 5) newLabelText = [newLabelText substringToIndex:5];
 }

The problem I got is that I want it to be able to put in 5 letters max Is there anyone who can tell me how to do this?
thanks

A: Add this line -
if ([newLabelText length] >= 5) newLabelText = [newLabelText substringToIndex:5];

...or apply the same to whatever string you want to truncate.
Check out the Apple Docs for some really useful NSString stuff


text:
Q: array.includes returning false where as searched name is in array If var c = familyArray.includes("Bart"); it will return false  but if var c = familyArray.includes("Homer"); it will return true
I want it to be true in the case of Bart as well because it is also included in the array.
Below is my array:

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var a = familyArray.indexOf("Bart");
var b = familyArray[2][0];
var c = familyArray.includes("Bart");

document.getElementById("demo").innerHTML = c;

console.log(a);
console.log(b);

A: Your issue is that you have a multi-dimensional array, and array includes will not search the inner array. Thus, you need to flatten your array before searching it. Here I have used Infinity as a parameter in the case that your array has more dimensions than just 2:

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var c = familyArray.flat(Infinity).includes("Bart");

console.log(c); // true;

See browser support for .flat() here. If you need better browser support you can use an alternative approach found here

A: You are using nested arrays, you can use .flat before hand:
familyArray.flat().includes('Bart')

A: You are searching in the inner array. You can do like this.

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];

console.log(familyArray[2].includes("Bart"));

A: you can do this :

var c = familyArray.flat(1).includes("Bart");

A: try flat method for this

var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var familyArrayFlatten = familyArray.flat();
var a = familyArrayFlatten.indexOf("Bart");
var b = familyArrayFlatten[2][0];
var c = familyArrayFlatten.includes("Bart");

console.log(a);
console.log(b);
console.log(c);


text:
Q: How to animate a numeric-based plot with Kivy in Python? I'm trying to understand the last answer given by a user in this post: Using kivy and matplotlib to animate a plot
My final goal is to get a real-time plot, receiving data from sensors (I'm new in this GUI-world, please be patient). For now, I wish to understand the animation process with simple numeric-defined plots (maybe using matplotlib).
Below is the code so far (based on the last answer from the linked post), but I get an error because I can't figure how to connect the class with the build method:

#TESTING: ANIMATION WITH KIVY

from kivy.app import App
import queue
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
from kivy.clock import Clock
from kivy.garden.matplotlib import FigureCanvasKivyAgg
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty

class PlotInputStream(BoxLayout):

    def __init__(self, queue):
        self.q = queue
        self.length = int((2048*2) * 44100 / (1000 * 10))
        self.plotdata = np.zeros((self.length, 1))
        self.fig, self.ax = plt.subplots()
        self.lineColour = 'blue'
        self.lines = self.ax.plot(self.plotdata, color=self.lineColour)
        # self.ani = FuncAnimation(self.fig, self.update_plot, interval=10, blit=False)
        Clock.schedule_interval(self.update_plot, 1 / 60.)

    def update_plot(self, frame):
        while True:
            try:
                data = self.q.get_nowait()
            except queue.Empty:
                break
            shift = len(data)
            self.plotdata = np.roll(self.plotdata, -shift, axis=0)
            self.plotdata[-shift:, :] = data
        for column, line in enumerate(self.lines):
            line.set_ydata(self.plotdata[:, column])
        self.fig.canvas.draw()
        return self.lines

class MainApp(App):

    box = ObjectProperty(None)

    def build(self):

        #self.figurecanvas = FigureCanvasKivyAgg(self.fig)
        #self.box.add_widget(self.figurecanvas)
        #self.ids.add_widget(self.figurecanvas)

        self.ids.add_widget(FigureCanvasKivyAgg(self.fig))

        return PlotInputStream()

MainApp().run()

Any help would be really appreciated! :)


text:
Q: Empty table while creating table My table is empty after executing.
I don't know why.
DROP TABLE N;
CREATE TABLE N(
BOOKNO int,
TITLE varchar(255),
PUBLICATION varchar(255),
 AUTHOR varchar(100),
PRICE decimal(6,2),
QUANTITY int,
EDITION int
);
SELECT* FROM N;

INSERT INTO N VALUES(1,'Funda of Database system','Pearson','Elmasri, Navathe',800,25,7);

A: You have put the select query before the Insert query
DROP TABLE N;
CREATE TABLE N(
BOOKNO int,
TITLE varchar(255),
PUBLICATION varchar(255),
 AUTHOR varchar(100),
PRICE decimal(6,2),
QUANTITY int,
EDITION int
);

INSERT INTO N VALUES(1,'Funda of Database system','Pearson','Elmasri, Navathe',800,25,7);
SELECT* FROM N;

A: It will work, try to follow below steps.
Step-1:
Drop Table with below query,
DROP TABLE N;

Step-2:
Create new table.
CREATE TABLE N(
BOOKNO int,
TITLE varchar(255),
PUBLICATION varchar(255),
 AUTHOR varchar(100),
PRICE decimal(6,2),
QUANTITY int,
EDITION int
);

Step-3:
Then run insert
INSERT INTO N VALUES(1,'Funda of Database system','Pearson','Elmasri, Navathe',800,25,7);

Step-4
and final check data inside table with select command.SELECT* FROM N;


text:
Q: Sharing news link from listview in social networking site How to get selected item of list view for sharing perticular text?
here is my code,I have tried this but it's not working
public class MainActivity extends ListActivity {

TextView content;
ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // list = (ListView) findViewById(R.id.list1);
    content = (TextView) findViewById(R.id.output);

    // listView = (ListView) findViewById(R.id.list);
    String[] values = new String[] { "Android Example ListActivity",
            "Adapter implementation", "Simple List View With ListActivity",
            "ListActivity Android", "Android Example",
            "ListActivity Source Code",
            "ListView ListActivity Array Adapter",
            "Android Example ListActivity" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values);

    // Assign adapter to List
    setListAdapter(adapter);

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    super.onListItemClick(l, v, position, id);

    // ListView Clicked item index
    int itemPosition = position;

    // ListView Clicked item value
    String itemValue = (String) l.getItemAtPosition(position);

    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("text/plain");

    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
            "Subject Here");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, itemValue);
    startActivity(Intent.createChooser(sharingIntent, "Share via"));

}

}

A: You need to implement list.setOnItemClickListener(new OnItemClickListener()) and fetch values from your ArrayList or Array for particular ListItem as per ListItem position like:
list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {
            // TODO Auto-generated method stub

             String txt = text.getText().toString();
            Intent sharingIntent = new Intent(
                    android.content.Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBody = "Here is the share content body";
            sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                    "Subject Here");
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, yourarraylist.get(position));
            startActivity(Intent.createChooser(sharingIntent, "Share via"));

        }

    });

Update: go to this link for Create_Listview_With_ListActivity_-_Android_Example


text:
Q: Are MCMC based methods appropriate when Maximum a-posteriori estimation is available? I have been noticing that in many practical applications, MCMC-based methods are used to estimate a parameter even though the posterior is analytical (for example because the priors were conjugate). To me, it makes more sense to use of MAP-estimators rather than MCMC-based estimators. Could anyone point out why MCMC is still an appropriate method in the presence of an analytical posterior?

A: As I read it, this question is asking two somewhat orthogonal questions. One is should one use MAP-estimators over posterior means, and the other is whether one should MCMC if the posterior has an analytical form.
In regards to MAP estimators over posterior means, from a theoretical perspective, posterior means are generally preferred, as @Xian notes in his answer. The real advantage to MAP estimators is that, especially in the more typical case where the posterior is not in closed form, they can be calculated much faster (i.e. several orders of magnitude) than an estimate of the posterior mean. If the posterior is approximately symmetric (which often the case in many problems with large sample sizes), then MAP estimate should be very close to the posterior mean. So the attractiveness of the MAP is actually that it can be a very cheap approximation of the posterior mean.
Note that knowing the normalizing constant doesn't help us find the posterior mode, so having a closed form solution for the posterior technically doesn't help us find the MAP estimate, outside the case where we recognize the posterior as a specific distribution for which we know it's mode.
In regards to the second question, if one has a closed form the posterior distribution, generally speaking there's no reason to use MCMC algorithms. Theoretically, if you had a closed form solution for the posterior distribution, but didn't have a closed form for the mean of some function and couldn't take draws directly from this closed form distribution, then one might turn to MCMC algorithms. But I'm not aware of any cases of this situation.

A: No need to use MCMC in this case: Markov Chain Monte-Carlo (MCMC) is a method used to generate values from a distribution.  It produces a Markov chain of auto-correlated values with stationary distribution equal to the target distribution.  This method will still work to get you what you want, even in cases where the target distribution has an analytic form.  However, there are simpler and less computationally intensive methods that work in cases like this, where you are dealing with a posterior that has a nice analytic form.
In the case where the posterior distribution has an available analytic form, it is possible to obtain parameter estimates (e.g., MAP) by optimisation from that distribution using standard calculus techniques.  If the target distribution is sufficiently simple you might get a closed form solution for the parameter estimator, but even if it is not, you can usually use simple iterative techniques (e.g., Newton-Raphson, gradient-descent, etc.) to find the optimising parameter estimate for any given input data.  If you have an analytic form for the quantile function of the target distribution, and you need to generate values from the distribution, you can do this via inverse transform sampling, which is less computationally intensive than MCMC, and allows you to generate IID values rather than values with complex auto-correlation patterns.
In view of this, if you were programming from scratch, then there does not seem to be any reason you would use MCMC in the case where the target distribution has an available analytic form.  The only reason you might do so is if you have a generic algorithm for MCMC already written, that can be implemented with minimal effort, and you decide that the efficiency of using the analytic form is outweighed by the effort to do the required math.  In certain practical contexts you will be dealing with problems that are generally intractable, where MCMC algorithms are already set up and can be implemented with minimal effort (e.g., if you do data analysis in RStan).  In these cases it may be easiest to run your existing MCMC methods rather than deriving analytic solutions to problems, though the latter can of course be used as a check on your working.

A: It is unclear to me what you call an analytical posterior $\pi(\theta)$ and hence why this analyticity should preclude one from using MCMC. Even for a posterior distribution that is available in closed form, including its normalising constant, which is how I understand analytical in this setting, there is no reason for Bayes estimates to be available in closed form, as solving the minimisation problem$$\min_\delta\int_\Theta \text{L}(\theta,\delta)\,\tilde\pi(\theta)\,f(x|\theta)\,\text{d}\theta$$when $\tilde\pi(\cdot)\propto\pi(\cdot)$ strongly depends on the loss function.
When the normalising constant $$\int \tilde\pi(\theta)\,\text{d}\theta$$is not available, finding a posterior mean or median or even mode [which does not require to know the constant], most often proceeds through an MCMC algorithm. For instance, if I am given the joint density, when $x,y\in(0,1)$,
$$f_\theta(x,y)=\dfrac{1+\theta[(1+x)(1+y)-3]+\theta^2(1-x)(1-y))
}{[1-\theta(1-x)(1-y)]^3}\qquad\theta\in(-1,1)$$inspired by the Ali-Mikhail-Haq copula: it may be properly normalised (and is indeed), but the conditional expectation of $\Phi^{-1}(X)$ given $Y=y$ under this density, when $\Phi(.)$ is the Normal cdf, is not available in closed form. This is however a question of primary interest.
Note also that the maximum a posteriori estimator is not the most natural estimator in a Bayesian setting, since it does not correspond to a loss function and that closed-form representation of the density, even up to a constant, does not make finding the MAP necessarily easy. Or using the MAP relevant.

A: I would argue that MCMC methods aren't necessarily inappropriate, even when closed-form solutions exist. Obviously, it's nice when an analytical solution exists: they are usually fast, you avoid concerns about convergence (etc).
On the other hand, consistency is also important. Switching from technique to technique complicates your presentation: at best, it's extraneous detail that may confuse or distract the audience away from your substantive result, and at worst it could look like an attempt at biasing the outcomes.  If I had several models, only a few of which admit closed-form solutions, I would strongly consider running them all through the same MCMC pipeline even if it weren't strictly necessary.
I suspect this, plus inertia ("we have this script that works") accounts for most of what you're seeing.