How do I set a condition to only show a block to a group members?

Question: Is there a way to check whether a user is a group member when the user visits the group page? I have some blocks that should be hidden if an user is not a member.
Comment: Does this answer your question? [How can I control block visibility with code?](https://drupal.stackexchange.com/questions/203308/how-can-i-control-block-visibility-with-code)
Answer: Programmatically you can use Group::getMember() to determine if an account is a member of a group.
if ($group->getMember(\Drupal::currentUser())) {
  // the current user is a member of the group.
}

Note that Group::getMember() returns a GroupMembership entity.
You could then create a condition plugin, using the above methodology to determine if the current user is a member of the group. I've created a tutorial on how to use the Conditions API to create conditions plugins, using this example of a condition where a member is a member of the group: https://www.jaypan.com/tutorial/custom-block-visibility-plugins-and-condition-plugin-api
Comment: Nothing module based unfortunately, hopefully someone else will pop in. I've updated my post with a little more information, but implementing it requires an understanding of Drupal development, and how to create Drupal modules. The link provided explains how to create a condition plugin. These plugins are the options you have on block settings pages to determine whether a block should be shown or not.
Comment: I created a tutorial that explains how to do what you want, though you'll need to first learn how to create Drupal modules to follow it. I've linked to it in my response above.
Comment: Thanks! Where should I put this code? And is het possible to make a twig variabele, so I can do a if statement in a twig file?
Comment: Oh, sorry, I didn't read your post clearly to see you were looking for block visibility based on membership. My code won't help with that.
Comment: Oh, do you have any other suggestions for me?
Comment: Thanks! It's weird, right? This should be a default function in the Group module, that is the reason why people use groups. Because of the permissions. What if I develop a small module to check if an user is a member or not on the current group page. Which hook do I need?


How to add a document inside a transaction

Question: I need to create a document inside a transaction.
The transaction object doesn't have the add function, probably because it would create multiple documents in case the Firestore retry the transaction.
The only way i can think is to use GUID as document id, but they make very long indexes to lookup.
Is there any way around? Another approach?
Answer: I wouldn't be too concerned about the length of a document ID.  I don't think you'll find that performance will suffer if you use a GUID for an ID.  If you're concerned about size, only you can compute about how much of your storage is consumed by IDs.
If you want to limit the size of a random document ID, you can simply generate your own random data and convert that to a string that follows the rules for Firestore document IDs.  It could be something as simple as generating a X number of random letters and concatenating them.
Comment: transaction.set command have some optional parameters like merge. Do you know, as google advocate, of other possible options? here the only info i find https://firebase.google.com/docs/reference/js/firebase.firestore.Transaction.  If it was possible to tell the function to throw an error if the document already exists, like an sql duplicate validation, that would be great.
Comment: If you have a question that's different than the original, please ask it separately.
Comment: My idea of using a duplicate error if possible goes along with your suggestion. Generating random numbers can, sometimes, generate duplicates. If Firestore could somehow prevent from overriding a existent document, all that would be needed is pass the error to the user and let him try again. Another round from the user, another id generated, so the collisions would then been handled.


CDO Transaction Issue

Question: I am trying to deposit an EClass object which I have retrieved from a graphiti diagram to the CDO repository but I receive a write transaction error. The error doesn't appear if I create a new empty EClass object and store it to the CDO repository. I have included my code and the error message to this post.
Thank you in advance for any help you can provide in this problem.
John Anderson
Source code:
<code>package uk.man.ac.graphiti.toolbarbuttons;

import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.net4j.CDONet4jSession;
import org.eclipse.emf.cdo.net4j.CDONet4jSessionConfiguration;
import org.eclipse.emf.cdo.net4j.CDONet4jUtil;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.cdo.util.ConcurrentAccessException;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.platform.IDiagramContainer;
import org.eclipse.graphiti.services.Graphiti;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.net4j.Net4jUtil;
import org.eclipse.net4j.connector.IConnector;
import org.eclipse.net4j.tcp.TCPUtil;
import org.eclipse.net4j.util.container.IPluginContainer;
import org.eclipse.net4j.util.lifecycle.ILifecycle;
import org.eclipse.net4j.util.lifecycle.LifecycleEventAdapter;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;

public class Deposit extends AbstractHandler {

private static CDONet4jSession cdoSession;

public static CDONet4jSession openSession(String repoName) {
CDONet4jSession session = null;
try {
final IConnector connector = (IConnector) IPluginContainer.INSTANCE
.getElement( //
"org.eclipse.net4j.connectors", // Product group
"tcp", // Type
"localhost"); // Description

CDONet4jSessionConfiguration config = CDONet4jUtil
.createNet4jSessionConfiguration();
config.setConnector(connector);
config.setRepositoryName(repoName);

session = config.openNet4jSession();

} catch (Exception e) {
return null;
}

return session;
}

@Override
public Object execute(ExecutionEvent event) {
String msg = null;
EClass eclass = null;
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = win.getActivePage();
IEditorPart editor = page.getActiveEditor();
if (editor instanceof IDiagramContainer) {
IDiagramContainer graphitiEditor = (IDiagramContainer) editor;
System.out.println("total.pe.elements="+graphitiEditor.getSelectedPictogramElements().length);
PictogramElement pe = graphitiEditor.getSelectedPictogramElements()[0];
Object bo = Graphiti.getLinkService()
.getBusinessObjectForLinkedPictogramElement(pe);
System.out.println("in1");
if (bo == null) {
msg = "You must select an EClass object";
sendMessage(event, msg);
System.out.println("in2");
} else {
if (bo instanceof EClass) {
eclass = (EClass) bo;

try {
System.out.println("in3");
Net4jUtil.prepareContainer(IPluginContainer.INSTANCE);
TCPUtil.prepareContainer(IPluginContainer.INSTANCE);
cdoSession = openSession("graphiti");

if (cdoSession != null) {
CDOTransaction transaction = cdoSession
.openTransaction();
CDOResource resource = transaction
.getOrCreateResource("/depositUsingButtonResource");

List<EObject> eclasslist = resource.getContents();
Boolean exists = false;
EClass temp = null;
for (int i = 0; i < eclasslist.size(); i++) {
temp = (EClass) eclasslist.get(i);
if (temp.getName().matches(eclass.getName())) {
exists = true;
break;
}
}
if (exists == true) {
msg = "Object already exists in repository";
} else {
resource.getContents().add(eclass);
transaction.commit();
msg = "Successful Deposit";
}

sendMessage(event, msg);
} else {
msg = "Deposit failed";
sendMessage(event, msg);
}
cdoSession.close();
} catch (ConcurrentAccessException e) {
msg = "Deposit failed";
sendMessage(event, msg);
} catch (CommitException e) {
msg = "Deposit failed";
sendMessage(event, msg);
}

}
}
}
return null;
}

private void sendMessage(ExecutionEvent event, String msg) {
MessageDialog.openInformation(
HandlerUtil.getActiveWorkbenchWindow(event).getShell(),
"Result", msg);
}
}
</code>
Error Message:
<code>!ENTRY org.eclipse.ui 4 0 2014-03-19 12:00:04.847
!MESSAGE Unhandled event loop exception
!STACK 0
org.eclipse.e4.core.di.InjectionException: java.lang.IllegalStateException: Cannot modify resource set without a write transaction
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:63)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:850)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.handleWidgetSelection(HandledContributionItem.java:743)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.access$7(HandledContributionItem.java:727)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem$4.handleEvent(HandledContributionItem.java:662)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1057)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4170)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3759)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1113)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:997)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:138)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:610)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:567)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
at org.eclipse.equinox.launcher.Main.main(Main.java:1426)
Caused by: java.lang.IllegalStateException: Cannot modify resource set without a write transaction
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.assertWriting(TransactionChangeRecorder.java:348)
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.appendNotification(TransactionChangeRecorder.java:302)
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.processResourceNotification(TransactionChangeRecorder.java:272)
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.notifyChanged(TransactionChangeRecorder.java:238)
at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374)
at org.eclipse.emf.common.notify.impl.NotificationImpl.dispatch(NotificationImpl.java:1027)
at org.eclipse.emf.common.notify.impl.DelegatingNotifyingListImpl.addUnique(DelegatingNotifyingListImpl.java:305)
at org.eclipse.emf.common.util.AbstractEList.add(AbstractEList.java:303)
at uk.man.ac.graphiti.toolbarbuttons.Deposit.execute(Deposit.java:113)
at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:290)
at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56)
... 37 more
</code>
Answer: According to the stack trace you've provided this is not a problem with a CDO transaction, but rather with a transaction (or the lack thereof) from the EMF Transaction project "org.eclipse.emf.transaction".

CDO Transaction Issue


How to get DFA intersection?

Question: How do we combine two dfa using intersection method ?
Comment: Is this homework?  Otherwise, I am not familiar with the exact procedure spelled out in books, but I'm betting I could come up with a program to combine two DFAs that ran in time O(state transitions).
Comment: I asked a [similar question](http://stackoverflow.com/questions/7732815/calculate-if-two-infinite-regex-solution-sets-dont-intersect) who's [answer](http://stackoverflow.com/a/7732923/188044) will probably work for this question.
Comment: Specifically, the part after the EDIT: spells out how to make a DFA accepting L1 intersect L2, given DFAs accepting L1 and L2.
Answer: Use the cross product construction, explained formally here.
Essentially you cross product the sets of states in each one to get a list of meta states corresponding to any combination of states for each machine. This allows you to do a parallel evaluation to accept if both accept.

How to get DFA intersection?


Volley Android - GET para retornar lista de vídeos de uma playlist - JAVA

Question: Olá, estou usando a bibliteca android Volley para fazer uma chamada GET (https) para retornar pra mim o JSon dos vídeos de uma playlist específica qualquer.
Basicamente a minha requisição GET atual é essa:
String url ="https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLl-K7zZEsYLlRjj-mSComCq3Vd4IJese1&key="+YoutubeConfig.getApiKey();

Onde YoutubeConfig.getApiKey(); é a minha chave de API criada no console de desenvolvedor com chave AUTH 2.0 e cadastrado no SHA-1 do aplicativo.
Ao tentar fazer o GET na solução, o código me retorna um ErrorResponse e "null" como código de mensagem, assim:

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLl-K7zZEsYLlRjj-mSComCq3Vd4IJese1&key="+YoutubeConfig.getApiKey();

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        Log.i("onResponse", "onResponse: "+response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("ErrorOnResponse", "onErrorResponse: "+error.getLocalizedMessage());
            }
        });

        // Add the request to the RequestQueue.
        queue.add(stringRequest);

logCat:
2020-11-17 10:04:22.256 23662-23662/com.appX.a2f20 I/ErrorOnResponse: onErrorResponse: null

Ou seja, a solicitação GET nem validada conseguiu ser, não estou entendendo porque, o formato me parece estar correto e a playlistID é válida, alguém sabe o porquê deste erro acontecer?
Answer: Consegui resolver, o código de response que estava retornando era 403-Forbidden
Traduzindo basicamente àquela minha chave de API não tinha acesso a API Youtube de solicitações HTTP. O que eu fiz?
Fui no meu console das APIs do Google e adicionei no meu "Bibliotecas" a biblioteca de API do Youtube Data API V3, adicionando-a no meu projeto já existente, após isso, pude ir na minha chave de API usada no App e inserir na restrição a biblioteca Youtube Data API v3 que agora estava elegível para ser selecionada (como não tinha sido adicionada nas bibliotecas ela não era exibida antes, então achei que não era necessária).
Agora a solicitação GET funciona bem e me retorna o Json corretamente.
Acho que o maior problema não está na biblioteca Volley, mas sim na falta de clareza do Google na documentação ao falar sobre as bibliotecas que devem ser adicionadas no projeto para que sejam exibidas nas restrições de API.


Menu de links e imagens com float

Question: Tentei criar um menu com html e css sem nenhum framework, utilizei float:left para colocar a imagem com o logo a esquerda e resto das imagens que são ancoras deveriam ficar a direita mas ao utilizar  float:right não obtive o resultado esperado, poderiam me ajudar a identificar o problema?
Obs.:
Não precisa ser com float é que essa foi a forma que tentei. Vale lembrar que o menu acompanha o scroll do site.
Segue abaixo o código que tentei:

#wrap {
  width:calc(100% - 1px);
}

body {
  font-family: 'Open Sans';
  padding:0;
  margin:0;
}

body a {
  text-decoration:none;
}

body img {
  border: none;
}

.menu {
  position: fixed;
  top: 0;
  height: 80px;
  z-index: 1000;
  background-color: #f2f2f2;
}

.menu img {
  float:left;
  margin: 15px 0px 0px 20px;
  height: 70%;
}

.menu .menu-link {
  float:right;
}

.menu .menu-link a {
  line-height: 100px;
  color: #00497e;
  text-transform:uppercase;
  font-size: 11pt;
}

.menu .menu-link a:hover {
  border: 0;
  background-color: #e20613;
  color: white;
}

        Empresa

        Usuário

Meu objetivo era algo semelhante a isso:
Comment: Esso está errado width:100%-1; tem que ser width:calc(100% - 1px); onde esta 1px pode ser qualquer medida REM, EM, %
Comment: Obrigado pela informação, alterei o código para calcular o `width`corretamente.
Answer: Caique o seu código está muito bagunçado rss, então fiz um modelinho bem básico com algumas medidas em PX mesmo e com FlexBox para vc ter uma ideia.

html, body {
  font-family: 'Open Sans';
  padding:0;
  margin:0;
  width: 100%;
}

.menu {
    height: 80px;
    width: 100%;
    background-color: #666;
    position: fixed;
    top: 0;
    display: flex;
    justify-content: space-between;
}
img {
    max-height: 60px;
}
.logo {
    background-color: red;
    height: auto;
    width: 200px;
    padding: 10px;
    box-sizing: border-box;
}
.direita {
    display: flex;
}
.item {
    background-color: blue;
    margin: 0 10px;
    box-sizing: border-box;
    padding: 10px;

}
.item a {
    color: #fff;
    line-height: 80px;
    align-self: center;
}

                 Empresa

                 Usuário

Da uma estudada no código que vc vai ver que é bem tranquilo e funciona melhor que o Float.
Agora um modelo com Float:Left e Float:Right pra vc entender o conceito melhor já que era sua primeira opção

Manda exibir na tela inteira  para não aparecer bugado no executar do snippet

html, body {
  font-family: 'Open Sans';
  padding:0;
  margin:0;
  width: 100%;
  height: 100%;
}
.menu {
    height: 80px;
    width: 100%;
    background-color: #666;
    position: fixed;
    top: 0;
}
.logo {
    float: left;
}
.logo a img {
    max-width: 30%;
    height: auto;
    margin: 10px;
}
.item {
    float: right;
    display: inline-block;
    margin: 15px;
}
.conteudo {
    margin-top: 80px;
    height: 1000pxpx;
}

                 Empresa

                 Usuário

conteúdo

conteúdo

conteúdo

conteúdo

conteúdo

conteúdo

conteúdo

conteúdo

conteúdo

Modelo bem simples também, só para fins didáticos
Comment: Hugo, adaptei o código para trabalhar similar a sua resposta. Porém eu estou criando esse layout para o IE em modo de compatibilidade e acredito que a propriedade `display:flex;` não funciona como deveria. O menu quebrou em várias linhas.
Comment: Vou tentar com o float (sua resposta atualizou agora)

Menu de links e imagens com float


Unsure how to query hidden api in dev tools>network>xhr

Question: I have been trying to extract data from this website: https://www.webuycars.co.za/buy-a-car.
I have looked at the dev tools>network>xhr for the responses but I am trying to receive more data than from just the first page of results of vehicles. This is the code for it so far:
import json
import scrapy

class carSpider(scrapy.Spider):

    name = 'car'
    body = {"to":24,"size":24,"type":"All","filter_type":"all","subcategory":None,"q":"audi","Make":None,"Roadworthy":None,"Auctions":[],"Model":None,"Variant":None,"DealerKey":None,"FuelType":None,"BodyType":None,"Gearbox":None,"AxleConfiguration":None,"Colour":None,"FinanceGrade":None,"Priced_Amount_Gte":0,"Priced_Amount_Lte":0,"MonthlyInstallment_Amount_Gte":0,"MonthlyInstallment_Amount_Lte":0,"auctionDate":None,"auctionEndDate":None,"auctionDurationInSeconds":None,"Kilometers_Gte":0,"Kilometers_Lte":0,"Priced_Amount_Sort":"","Bid_Amount_Sort":"","Kilometers_Sort":"","Year_Sort":"","Auction_Date_Sort":"","Auction_Lot_Sort":"","Year":[],"Price_Update_Date_Sort":"","Online_Auction_Date_Sort":"","Online_Auction_In_Progress":""}

    def start_requests(self):
        yield scrapy.Request(
            url='https://website-elastic-api.webuycars.co.za/api/search',
            callback=self.parse,
            body=json.dumps(self.body),
            method="POST")

    def parse(self, response):
        response = json.loads(response.body)

        for resp in response['data']:
            yield {
                'Title': resp['OnlineDescription']
            }

This is the data I receive:
2022-05-04 22:21:42 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2020 Nissan Almera 1.5 Acenta Auto'}
2022-05-04 22:21:42 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Citroen C3 Aircross 1.2T Puretech Sine Auto'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Toyota Hilux 2.4 Gd-6 RB Raider Pick Up Double Cab'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2013 Hyundai i10 1.25 Gls/fluid Auto'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2019 SYM Symphony JET 14 200'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2019 Nissan Micra 1.2 Active Visia'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2021 Suzuki Super Carry 1.2i Pick Up Single Cab'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Suzuki AN UB 125 (burgman)'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Honda XRL XR 125l'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Toyota Hilux 2.4 Gd-6 RB Raider Pick Up Double Cab'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Land Rover Defender 110 D300 SE X-Dynamic (221 KW)'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Big Boy TSR 250'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2019 Renault Kwid 1.0 Dynamique 5-Door'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2013 Tata Indigo 1.4 Manza Ignis'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2018 Datsun GO 1.2 LUX'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2021 Renault Kiger 1.0 Energy ZEN'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2020 Crosby Adventure Bike 400cc'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2012 Jeep Compass 2.0 LTD'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2021 Crosby Adventure Bike 400cc'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Renault Kwid 1.0 Climber 5-Door'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2019 Suzuki Swift 1.2 GLX'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2022 Volkswagen Polo Classic GP 1.4 Comfortline'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2020 Renault Kwid 1.0 Climber 5-Door Auto'}
2022-05-04 22:21:43 [scrapy.core.scraper] DEBUG: Scraped from <200 https://website-elastic-api.webuycars.co.za/api/search>
{'Title': '2019 Yamaha YZ 450 FX'}

However I have been trying to query audi as seen in line 7 of the code in the body variable("q":"audi").
No matter what I try, I keep receiving the same data back which is all from the first page. I assume there is something wrong with how I parse my body in scrapy.Request but I am unsure. I have tried different formats of the body like making it a string, directly copy and pasting the payload from the response and also not parsing it as json formatted but rather a string. Any help would be appreciated.
Answer: Actually,you want to get data from more than one page meaning want to make pagination, If so, then you can follow the next working solution.
import json
import scrapy
from scrapy.crawler import CrawlerProcess

class CarsSpider(scrapy.Spider):
    name = 'car'
    body = {"to":24,"size":24,"type":"All","filter_type":"all","subcategory":None,"q":"","Make":None,"Roadworthy":None,"Auctions":[],"Model":None,"Variant":None,"DealerKey":None,"FuelType":None,"BodyType":None,"Gearbox":None,"AxleConfiguration":None,"Colour":None,"FinanceGrade":None,"Priced_Amount_Gte":0,"Priced_Amount_Lte":0,"MonthlyInstallment_Amount_Gte":0,"MonthlyInstallment_Amount_Lte":0,"auctionDate":None,"auctionEndDate":None,"auctionDurationInSeconds":None,"Kilometers_Gte":0,"Kilometers_Lte":0,"Priced_Amount_Sort":"","Bid_Amount_Sort":"","Kilometers_Sort":"","Year_Sort":"","Auction_Date_Sort":"","Auction_Lot_Sort":"","Year":[],"Price_Update_Date_Sort":"","Online_Auction_Date_Sort":"","Online_Auction_In_Progress":""}

    def start_requests(self):

        yield scrapy.Request(
            url='https://website-elastic-api.webuycars.co.za/api/search',
            callback=self.parse,
            body=json.dumps(self.body),
            method="POST",
            headers= {
                "content-type": "application/json",
                "User-Agent":"mozilla/5.0"
                }
        )

    def parse(self, response):
        response = json.loads(response.body)
        for item in range(0,6528,24):
            response['total']['value']=item

            for resp in response['data']:
                yield {
                    'Title': resp['OnlineDescription']
                }

if __name__ == "__main__":
    process =CrawlerProcess()
    process.crawl()
    process.start()

Output:
'downloader/response_status_count/200': 1,

 'item_scraped_count': 6528,

screenshot_pagination_source


How do I show that $\int _0^\infty \! \frac{x\cos^3(x)}{t^2+x^2} \, \mathrm{d}x$ converges uniformly for all t > 0?

Question: Until now, I've tried to solve by Dirichlet Criteria and Weierstrass M-test, but couldn't find an answer. Also tried to do inequalities, but didn't get anywhere.
Can somebody help me on this please?
Comment: Hint : Show that integrand is bounded for $t > 0$, then use definition of uniform continuity
Comment: How could I do this? Does integrand bounded guarantee uniform convergence for the integral? This topic is a bit new to me, sorry
Comment: You should show some of your effort.  What happened when you tried the Dirichlet test? Notice that $\int_0^x \cos^3 t \, dt$ is uniformly bounded for all $x,t$.
Comment: Actually yes! I thought I couldn't conclude anything with the Dirichlet test, but turns out that I was looking a bit wrong to it... actually I've misunderstood it because of class notes, but now it all makes sense. Thank you guys :D
Comment: It seems a bit odd that you are saying everything is clear from what you are reading here -- particularly the fact that the integrand is bounded  which is by no means sufficient for uniform convergence of an integral over an infinite interval.
Comment: Also the fact that the integral converges (pointwise)  as shown by direct evaluation does not prove uniform convergence.
Answer: Around $x=0$
$$\frac{x\cos^3(x)}{t^2+x^2}=\frac{x}{t^2}-\left(\frac{1}{t^4}+\frac{3}{2 t^2}\right) x^3+O\left(x^4\right)$$ so no problem at the lower bound.
You can also compute the antiderivative writing
$$\frac{x}{t^2+x^2}=\frac{x}{(x+it)(x-it)}=\frac{1}{2 (x+i t)}+\frac{1}{2 (x-i t)}$$ and use
$$4\cos^3(x)=\cos(3x)+3\cos(x)$$ to face rather simple integrals.
Comment: We can't use the Big O or complex functions :(
Answer: According to the Dirichlet test for uniform convergence, the improper integral $\int_0^\infty f(x,t) g(x,t) \, dx$ is uniformly convergent for $t \in D$ if $\int_0^x g(y,t) \, dy$ is uniformly bounded for all $x >0$ and $t \in D$ and $f(x,t) \searrow 0$ as $x \to \infty$ monotonically with respect to $x$ and uniformly for $t \in D$.
In this case, the first hypothesis is true for all $x > 0$ and $t \in (0,\infty)$, since
$$\left|\int_0^x \cos^3y  \, dy\right| = \left|\frac{9}{12}\sin x + \frac{1}{12}\sin 3x  \right| \leqslant \frac{10}{12}$$
Considering the behavior of $f(x,t) = \frac{x}{x^2 +t^2}$ we first note that $|f(x,t)| \leqslant \frac{1}{x}$ which gives us uniform convergence to $0$ as $x \to \infty$ for all $t \in (0,\infty)$. However, $f(x,t)$ is monotone nonincreasing only when $x \geqslant t$ and we don't fulfill the uniformity of the monotonicity condition for all $t \in (0,\infty)$.
If we restrict the domain to $t \in (0,\alpha]$ for any finite $\alpha > 0$, then we have uniform convergence because
$$\int_0^\infty \frac{x}{x^2 + t^2} \cos ^3 x \, dx = \int_0^\alpha \frac{x}{x^2 + t^2} \cos ^3 x \, dx+ \int_\alpha^\infty \frac{x}{x^2 + t^2} \cos ^3 x \, dx,$$
and the first integral on the RHS is proper and for the second we have all the conditions of the Dirichlet test fulfilled  as $x \geqslant \alpha \geqslant t$ for all $t \in (0,\alpha]$.
There remains the question of uniform convergence for all $t > 0$.


How to change image src depending on whether image exists

Question: I'm trying to load one of two different thumbnail images according to whether or not an image corresponding to a database entry and identified with an id as part of its name exists on the system.
Simplifying a bit for clarity, if the specific image, named {id}-thumb.png, exists then I want to load its name into the src of the HTML using jQuery. If the image does not exist I want to load a generic thumbnail image named thumbnail.png.
This is what I have so far:
var image_path = id + "-thumb.png";
$.ajax({
    url: image_path,
    type: "HEAD",
    error: function() {
        $("li#" + id + " .thumbnail").attr("src","thumbnail.png");
    },
    success: function() {
        $("li#" + id + " .thumbnail").attr("src",id + "-thumb.png");
    }
});

Then I generate the new HTML to insert by building up a string variable, list_item
var list_item = "
";
list_item += "
";
list_item += "";
list_item += "
";

And finally I add this new list_item variable to the existing ul:
$(".list ul").prepend(list_item);

But I get no image and looking at the generated HTML, src is empty.
Any ideas much appreciated!
Comment: Is it just me or you're sending an ajax request to the picture?
Comment: You are not closing `li` .. ``
Comment: your create dynamically your image name `attr("src",id + "-thumb.png");` but u are sure this is also the path to the image on disk. Check to see exactly your image path and add it to src attr
Comment: your using ajax I think you can solve the problem on server side, which should much more easier
Answer: If the image does not exist you can use the "onerror" parameter. Generate the image tag like this:

Comment: That works fine for me - excellent simple solution - many thanks.
Comment: That just puts the text "something_else.jpg" on the page - not the image itself.
Comment: Superb. Sorted my issue.
Answer: Load generic thumb by default, then load specific one - if it does not exist, it won't get loaded:

JS
$('img[data-src]').each(function(){

    var $self = $(this), specificSrc = $self.data('data-src');

    // create an img node, inject the real src attribute...
    $("").bind("load", function() {

      // ...when it gets loaded [and the resource is thus available],
      // set it to the actual DOM img element.
      $self.attr('src', specificSrc);

    }).attr("src", specificSrc);

});


Should I switch from learning the Violin to learn Piano Keyboard instead?

Question: I bought a violin over 2 years ago and yet I haven't learned anything since I couldn't get lessons. I was supposed to get some this summer but with the pandemic going on I couldn't. I really tried to learn the violin but no luck I can't find anything that will help me online and the violin requires precise hand movements and when I tune it, the strings keep going back to their original position and become off-tune again. No matter how much I try... I just can't, even though I really want to.
My friend said I should get a keyboard instead, so should I? Will it be easier for me to learn it online?
Comment: This would make an outstanding chatroom discussion, but not a good fit for the Q&A part of the site.
Answer: It depends on what your personal preference is. Violin is much harder to start online as a beginner, and there's a chance of you developing a posture issue an in-person instructor might have caught, but as long as you're careful it's more than possible to learn it.

I really tried to learn the violin but no luck I can't find anything
that will help me online

If you're financially able, it's best to find a private instructor.

The violin requires precise hand movements and when I tune it, the
strings keep going back to their original position and become off-tune
again.

Those hand movements will come to you with time and practice. Usually, all it takes to tune a violin is some gentle pressure into the scroll, but it could also be a technical issue. You might want to get that checked if it's not just a strength problem.
Comment: "Violin is much harder to start online as a beginner". Online piano lessons can be problematic as well. The teacher can miss something as the camera cannot show everything that a teacher can see at a "normal" piano lesson.
Comment: @andrewjohnsson online music lessons, in general, are harder than in-person lessons regardless of instrument, but violin is extra challenging because of how much of your tone and intonation depends on your posture.


How can I automatically rotate images based on EXIF data prior to image styles being applied?

Question: I have a website where users can upload pictures of themselves.  Many of these pictures are taken with  mobile phones and as a result a lot of them are shot such that the picture is vertical, but it is uploaded as horizontal because Drupal ignores the EXIF data.  This can be fixed using the Image Cache Actions module (autorotate submodule), but if I do so, this breaks the Manual Crop module, which I use to trim the pictures as necessary.
Is it possible to somehow have Drupal automatically rotate all images upon upload based on their EXIF data if available, such that image styles would be applied to the rotated image, not the original image?
Answer: Another option is to process the images before they are uploaded. I wrote a windows script to do this 5+ years ago. It still works, but I won't be offering any support for it.
http://www.autoitscript.com/forum/topic/85891-imagemagick-batch-jpg-processor/
Answer: Use the http://drupal.org/project/imagecache_actions, this module has a sub-module imagecache_autorotate. The "autorotate" image filter do what you want.
Comment: I mentioned the autorotate submodule in my question; it does not do what I want, because the autorotate module rotates the "image style" version of the image, not the original file itself.  I want to rotate the original file itself.
Comment: I see. You can still use imagecache_actions but generate the style on the upload and move the file. I will code this on
hook_node_presave but you can perhaps use a module like http://drupal.org/project/rules_image_styles.


Split rdd and access subgroup of elements

Question: I would like to split my RDD regarding commas and access a predefined set of elements.
For example, I have a RDD like that:
a, b, c, d
e, f, g, h

and I need to split then access the first and fourth element on the first line and the second and third element on the second line to get this resulting RDD:
a, d
f, g

I can't hard write "1" and "4" on my code, that's why solution like that won't work:
rdd.map{line => val words = line.split(",") (words(0),words(3)) }

Lets assume I have a second RRD with the same number of lines which contains the elements I want to get for each line
1,4
2,3

Is there a way to get my elements ?
Answer:
Lets assume I have a second RRD with the same number of lines which contains the elements I want to get for each line

1,4
2,3

Is there a way to get my elements ?

If you have a second RDD that already has the numbers of the groups you want for each line, you could zip them.
From Spark docs:
 RDD<scala.Tuple2<T,U>> zip(RDD other, scala.reflect.ClassTag evidence$13)

Zips this RDD with another one, returning key-value pairs with the first element in each RDD, second element in each RDD, etc.

So in your example, a, b, c, d would be in a key-value pair with 1,4 and e, f, g, h with 2,3 . So you could do something like:
val groupNumbers = lettersRDD zip numbersRDD

groupnumbers.map{tuple ->
val numbers: Seq[Int] = // get the numbers from tuple._2
 val words = tuple._1.split(",") (words(numbers.head),words(numbers(1) ) }
}


How to output entire git log --stat to xml

Question: I'm trying to turn this standard git log --stat output:
commit 8a3f15205922e524d59524fe89c4304849dd6c8c
Author: FooManChu <email@example.com>
Date:   Fri Jul 15 20:33:17 2016 -0400

    Some Commit Message Body

 foodir/foofile1.foo |    8 +
 foodir/foofile2.foo |   47 +
 foodir/foofile3.foo | 7049 +++++++++++++++++++++++
 foodir/foofile4.foo | 3563 ++++++++++++
 foodir/foofile5.foo |   24 +
 foodir/foofile6.foo |    0
 foodir/foofile7.foo |   41 +
 7 files changed, 10732 insertions(+)

commit c8bd4ca8d683c20f3cf206fdeb8dbec2f185536e
Author: FooGirlChu <firstname.lastname@example.com>
Date:   Fri Jul 15 00:11:24 2016 -0400

    Initial commit

 FOO       | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 README.md |   1 +
 2 files changed, 675 insertions(+)

Into the xml file structure seen below.  It doesn't have to be mapped directly like below, but still close enough to be customized if needed.
<?xml version="1.0" encoding="utf-8"?>
<stats>
    <commit sha1='8a3f15205922e524d59524fe89c4304849dd6c8c'>
        <author firstname.lastname@example.com'>FooManChu</author>
        <date>Fri Jul 15 20:33:17 2016 -0400</date>
        Some Commit Message Body
        <diff-stat>
            <filepathname insertions='8'>foodir/foofile1.foo</filepathname>
            <filepathname insertions='47'>foodir/foofile2.foo</filepathname>
            <filepathname insertions='7049'>foodir/foofile3.foo</filepathname>
            <filepathname insertions='3563'>foodir/foofile4.foo</filepathname>
            <filepathname insertions='24'>foodir/foofile5.foo</filepathname>
            <filepathname insertions='0'>foodir/foofile6.foo</filepathname>
            <filepathname insertions='41'>foodir/foofile7.foo</filepathname>
        </diff-stat>

    </commit>
    <commit sha1='c8bd4ca8d683c20f3cf206fdeb8dbec2f185536e'>
        <author firstname.lastname@example.com'>FooGirlChu</author>
        <date>Fri Jul 15 00:11:24 2016 -0400</date>
        Initial commit
        <diff-stat>
            <filepathname insertions='674'>FOO</filepathname>
            <filepathname insertions='1'>README.md</filepathname>
        </diff-stat>

    </commit>
</stats>

I've looked at Parsing Git Log Output and Understand Git Log Stat Output, but I've been unable to duplicate the --stat format.
My question is therefore can this be done in git? or should I be trying to code a parsing program instead that takes --stat as input and outputs my xml file?
Comment: You might use the --numstat flag instead of --stat so you dont have to count plusses and minuses.
Comment: https://gist.github.com/textarcana/1306223 claims to output into JSON format. Also see http://stackoverflow.com/questions/4600445/git-log-output-to-xml-json-or-yaml
Comment: I'll try that JSON format.  At least it's one step closer in the right direction.
Answer: Here is the original answer: Parse git log file names to json
Parse XML file should be similar to parse JSON file.
This is an example to export git log -stat as json.
We define a function to load the files changed in one git commit
function getcommit { \
git show --pretty="format:"  --name-only $1 | \
perl -pe's/^\n//g;' | \
sed 's/\(.*\)/"\1"/g' | \
perl -0pe 's/\n(?!\Z)/,\n/g'; \
}

export -f getcommit

Then use git log -1 to show the latest one commit info:

    git log -1 --pretty=format:'{%n  "commit": "%H",%n  "author": "%an ",%n  "date": "%ad",%n  "message": "%f",%n  "files": [ COMMIT_HASH_%H  ]%n},' | \
    perl -pe 'BEGIN{print "["}; END{print "]\n"}' | \
    perl -pe 's/},]/}]/;s/COMMIT_HASH_(\w+)/`echo -n "";getcommit $1`/e'

Sample result

    [{
    "commit": "1edcef90b42afee11fbd31dcc458ae0f15a3bb6e",
    "author": "Bertrand Martel ",
    "date": "Tue Oct 13 17:35:34 2015 +0200",
    "message": "update-readme",
    "files": [ "README.md",
        "device.png",
        "screenshot.png"
        ]
    }]


Using WCF service with SignalR SelfHost

Question: I am new to SignalR and I am sorry if this is a old question. If it is please let me know where it is. Please excuse me for my English.
I am working on following task.
I need to read MSMQ messages and publish a message to all subscribed clients. For this we want to do like below
Have a SelfHost SignalR. In this have a WCF service that continuously read MSMQ messaes. We want to pass the reply/response to various clients that subscribe via SelfHost SignalR. I googled a lot but cannot find nice and simple example of my scenario where you use SignalR SelfHost + WCF service that does something continuously and SelfHosted SignalR sends reply back to a simple clients like a Console application or WPF.
Please let me know if you know any link where I can find some information of how to do what I am trying to do
Answer: I created an Empty ASP.NET Web application. For that I added WCF Service, using Package Manager Console executed install-package Microsoft.AspNet.SignalR, then added Hub class and Startup class. External client will call a method in my service, and then service broadcasts to all other clients
Answer: If you're looking for an example of the server initiating a broadcast in response to a non-client event, see the following:
http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-server-broadcast-with-signalr-20

Using WCF service with SignalR SelfHost


Java Comparator, Comparable and TreeSet.contains

Question: edit - slightly simplified example below (any simpler and i'm not sure it contains all of the elements of the desired behavior)
Below is a code snippet that represents one thing I'm trying to do with Comparator.  I would like for contains to return true once the second time that doRSM is called:
package comparisonTest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.TreeSet;

public class ComparisonTest {

    private static class ArbitraryItem {
        String node;
        ArbitraryItem(String node) {
            this.node = node;
        }
        public String getNode() {
            return node;
        }
    }

    private static final Map<String, ResultSet> idToArbitraryItems = new HashMap<>();

    private static class ArbitraryItemComparable implements Comparable<ArbitraryItemComparable> {
        ArbitraryItem item;
        Comparator<ArbitraryItemComparable> c;
        ArbitraryItemComparable(ArbitraryItem item, Comparator<ArbitraryItemComparable> c) {
            this.item = item;
            this.c = c;
        }
        @Override
        public boolean equals(Object o) {
            if (!(o instanceof ArbitraryItemComparable)) {
                System.out.println("not a ArbitraryItemComparable="+o);
                return false;
            }
            boolean eq = this.c.compare(this, ((ArbitraryItemComparable)o)) == 0;
            System.out.println("   equality val="+eq);
            return eq;
        }
        @Override
        public int compareTo(ArbitraryItemComparable o) {
            int compVal = this.c.compare(this, ((ArbitraryItemComparable)o));
            System.out.println("   comparison val="+compVal);
            return compVal;
        }

    }

    private static class ResultSet {
        SortedSet<ArbitraryItemComparable> usedResults;
        String node;
        Comparator<ArbitraryItemComparable> comparator;
        ResultSet(String node, Comparator<ArbitraryItemComparable> comparator) {
            this.usedResults = new TreeSet<ArbitraryItemComparable>();
            this.node = node;
            this.comparator = comparator;
        }
    }

    static private void doRSM(Collection <ArbitraryItem> foobar, ResultSet set, int max, boolean close, String id) {
        Iterator<ArbitraryItem> items = foobar.iterator();
        for (;items.hasNext();) {
            ArbitraryItem item = (ArbitraryItem) items.next();
            ArbitraryItemComparable itemComparable = new ArbitraryItemComparable(item, set.comparator);
            System.out.println("*** looking at node "+itemComparable.item.getNode()+"***, sur size="+set.usedResults.size());
            if (!set.usedResults.contains(itemComparable)); {
                System.out.println("*** node "+itemComparable.item.getNode()+" not in usedResults");
            }
            set.usedResults.add(itemComparable);
        }
    }

    public static void main(String [] args)
    {
        Collection<ArbitraryItem> items = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            items.add(new ArbitraryItem(""+i));
        }

        Comparator<ArbitraryItemComparable> comparator = new Comparator<ArbitraryItemComparable>() {
            @Override
            public int compare(ArbitraryItemComparable o1, ArbitraryItemComparable o2) {
                // this is where the magic needs to happen!!
                System.out.println("calling compare: o1 node="+o1.item.getNode()+" "+o1.item.getNode().hashCode()+" o2 node="+o2.item.getNode()+" "+o2.item.getNode().hashCode());
                return o1.item.getNode().hashCode() - o2.item.getNode().hashCode();
            }
            @Override
            public boolean equals(Object o) {
                System.out.println("why is this called?");
                return false;
            }
        };
        ResultSet set = new ResultSet("3", comparator);
        idToArbitraryItems.put("q", set);
        doRSM(items, set, 1000, false, "q");
        doRSM(items, set, 1000, false, "q");
    }
}

However, the log shows this:
*** looking at node 0***, sur size=0
*** node 0 not in usedResults
calling compare: o1 node=0 48 o2 node=0 48
   comparison val=0
*** looking at node 1***, sur size=1
calling compare: o1 node=1 49 o2 node=0 48
   comparison val=1
*** node 1 not in usedResults
calling compare: o1 node=1 49 o2 node=0 48
   comparison val=1
*** looking at node 2***, sur size=2
calling compare: o1 node=2 50 o2 node=0 48
   comparison val=2
calling compare: o1 node=2 50 o2 node=1 49
   comparison val=1
*** node 2 not in usedResults
calling compare: o1 node=2 50 o2 node=0 48
   comparison val=2
calling compare: o1 node=2 50 o2 node=1 49
   comparison val=1
*** looking at node 0***, sur size=3
calling compare: o1 node=0 48 o2 node=1 49
   comparison val=-1
calling compare: o1 node=0 48 o2 node=0 48
   comparison val=0
*** node 0 not in usedResults
calling compare: o1 node=0 48 o2 node=1 49
   comparison val=-1
calling compare: o1 node=0 48 o2 node=0 48
   comparison val=0
*** looking at node 1***, sur size=3
calling compare: o1 node=1 49 o2 node=1 49
   comparison val=0
*** node 1 not in usedResults
calling compare: o1 node=1 49 o2 node=1 49
   comparison val=0
*** looking at node 2***, sur size=3
calling compare: o1 node=2 50 o2 node=1 49
   comparison val=1
calling compare: o1 node=2 50 o2 node=2 50
   comparison val=0
*** node 2 not in usedResults
calling compare: o1 node=2 50 o2 node=1 49
   comparison val=1
calling compare: o1 node=2 50 o2 node=2 50
   comparison val=0

The offending lines start here:
*** looking at node 0***, sur size=3
calling compare: o1 node=0 48 o2 node=1 49
   comparison val=-1
calling compare: o1 node=0 48 o2 node=0 48
   comparison val=0
*** node 0 not in usedResults

Meaning that the comparison value is 0 (which means they are equal) and yet the adding code is still being called, meaning that the list is not saying that it contains the value.  Why?  I thought that returning a compareTo of 0 meant equality?  Furthermore, why is equals is never being called?  The TreeSet documentation states for contains:

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Which would lead me to believe that ArbitraryItemComparable.equals would be called, but it is not?  Any ideas on how to get the usedResults.contains function to return true?
Comment: You've posted a lot of code with a lot of output using several different collections, which makes it hard to nail down exactly what's going on *and* what you're asking about. Could you reduce the example down to a much simpler one?
Comment: Don't forget to account for the overflow of the condition `o1.hashCode() - o2.hashCode()`. It creates weird bugs
Comment: Looks like there is no overflow in that it says that the subtraction returns 0.
Answer: You have this:
...
if (!set.usedResults.contains(itemComparable)); { // NOTE THE SEMICOLON!!!!

That basically means "ignore this condition and unconditionally execute the following block".
Comment: Static analysis tools will warn about this kind of problems, I use NetBeans and the IDE underlines anything "suspicious". But it is up to you not to ignore the underlines and actually check what's going on
Comment: Ugh, eclipse didn't even underline this...


How can I allow anonymous visitors to submit content?

Question: I am working on a website that displays a list of historical events.  Most of the events have been added by a small group of users that manage the site.  However, I would also like to add the ability for anonymous visitors to suggest events to be added to the site.
I could make the node/add form available to anonymous visitors however this isn't ideal for several reasons:

the standard submission form is quite complex and I would like to simplify this for anonymous visitors e.g. some fields aren't relevant I want to hide these.
anonymous visitors should be able to submit partial information about the events and for an editor to add more details later.
anonymous submissions need to be moderated before being published.
I would like to guard against spam submissions.

How would you suggest I do this?
Is it possible to have two forms to add a new event, a more complex one for site users and a simpler one for anonymous visitors?
Answer: Create another content type, say "Event Suggestion", which contains only those fields you want anonymous users to submit suggestions for. Do not include the fields you consider as not relevant (and which you want to 'hide' for such anonymous users).
When creating such extra content type, for its fields just use the same fields as for the content type that you already have, say "Event". So the fields for this new content type (Event Suggestion) will be a subset of the fields that you already have for the content type already being used by your "small group of users" (= Event).
Related to permissions: allow anonymous users to create an Event suggestion, but do not allow Event to be created by anonymous users.
For spam reduction/prevention, use modules such as Honeypot, Mollom, Captcha, reCaptcha, etc.
Use the Rules module to finetune your workflow related to nodes of type Event suggestions being created (saved). To just mention a few options (the list is virtually unlimited):

Unpublish such nodes (so that spam submissions that are not caught by spam prevention modules, never get shown without reviewing them first).
Send an eMail msg to your small group of users who manage your site (something like "a new Event suggestion is waiting your approval".
Set some kind of "confirmation message" when an Event suggestion is beiing submitted (like "Thank you for your Event suggestion, it will be reviewed soon ...").

When your small group of users who manage your site then review such Event suggestion, they should use the Node Convert module to convert an Event Suggestion into an Event. Using the Rules module you could then automatically "publish" such event also. After such node got converted, your small group of users who manage your site could then complete what you described as "add more details later on".
Other modules like Flag and/or Content Access might further enhance the various features / functionality you might be looking for. E.g. as an alternative to working wirth "unpublished" content, you could work with content that is published, but can only be accessed by authorized users.
Bottom line: Rules and Node Convert could get you pretty close, possibly further enhanced with Flag and Content Access.
Note: Adding the View unpublished module seems like an interesting improvement also, i.e. to grant access for specific user roles (such as editors or reviewers) to view unpublished nodes of a specific type.
Comment: Thank you, I've managed to get this working to do just what I need.  The node convert process is a little bit clunky but it works okay.  I used Node Convert and Rules as you suggested.  I also installed the View Unpublished module to allow editors to view the unpublished submissions.
Answer: Simple Interface for Anonymous User
Create custom form submit of what will call node_save() with values from form fields. Custom form will be simple and will have only limited fields to be shown to anonymous user.
Content Moderation by Editor.
In order to have moderation on content you can install workbench_moderation module. With help of this module you can setup different moderation states on any content type, also it will give dashboard to users with permissions so if in your case you have Editor as role to publish nodes created by anonymous user, you can setup draft as the intermediate moderation state before it gets published, now when anonymous user submits the custom form, a node is created programmatically and is in draft state, Editor role will have permission to access Draft dashboard which will be coming out of workbench_moderation module and will list all nodes in draft state, all you need is to give permission to editor role to move nodes from draft to publish.
Spam Protection
In order to avoid spam you can have captcha on your custom form, install recaptcha module. Your custom form will have field like
<code>$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);
</code>
Reference - How do I add reCaptcha to a custom form?
Answer: I see two simple options:
1) create a completely different content type for the submission, and use something like Node Block

This module allows you to specify content type(s) as being a block.
  This allows the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.

to display the submission over an edit form of the final content, so the moderators can simply copy and paste from the top of the screen to the bottom, and then make changes as they like
OR
2) Use Field Permissions

The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.
Features
Enable field permissions on any entity, not just nodes. Role-based
  field permissions allowing different viewing patterned based on what
  access the user has. Author-level permissions allow viewing and
  editing of fields based on who the entity owner is. Permissions for
  each field are not enabled by default. Instead, administrators can
  enable these permissions explicitly for the fields where this feature
  is needed.

and restrict the view and edit of the fields you don't want anonymous users to access.
Either way you could then create a flag system: a boolean value only moderators can see and change (again using Field Permissions) which tells the system if the submission has been accepted or not (for either content type)
With the Flag system you can use Views

You need Views if
You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month.

To display a list of pending submissions to moderators, based on the flag value
For the Anonymous content creation, you will want to look at some form of spam control, be it captcha, or form edit timing - but there are lots of resources available for determining what's best for your situation elsewhere.
Answer: For Drupal 8, we developed subtonode (https://github.com/owenmorrill/subtonode) to push a webform submission to a node of a specific content type (ours was "bulletin").
Permissions are such that we can't let submitters edit their submissions at this time. Once the node is created with subtonode, anonymous users have no backend/edit access to it.
Answer: You can use anonymous_posting module
https://www.drupal.org/project/anonymous_posting


MS Sharepoint 2007 - Site Deleted But Link is Still Displayed

Question: We have a site on our Sharepoint which was deleted, however the links to the site still exist. Obviously, when you click the link it just goes to a 404 error but I don't know how to delete the site from our Sharepoint.
I know at one point I fixed this same exact problem by going to a tree of our sites and deleting it from the tree. However, at the moment I can't seem to find where I did that before.
Can somebody please lend a hand?
Thanks in advance.
Comment: Figured it out, but for others in this situation it was...Site Actions > Manage Content and Structure.
Answer: Figured it out, but for others in this situation it was...Site Actions > Manage Content and Structure
Answer: At a command prompt: IISRESET /NOFORCE
Restarting IIS will often force an immediate flush of the cache that keeps this site in the navigation.  Worked for me in the same situation as yours.


How do I use OSX's Folder Actions to execute a command in Terminal when a file is added to a folder?

Question: How do I use OSX's Folder Actions to execute a command in Terminal when a file is added to a folder? My understanding is that Folder Actions can trigger AppleScripts when files are placed in them. I tried to modify a sample "added to folder" script, but it's not working.
This is the exact Terminal command I'd like to run on any zip files placed in the folder (and I know this syntax is correct):
for file in *.zip; do zip -d "$file" "__MACOSX*"; done; for file in *.zip; do zip -d "$file" "*.DS_Store"; done; unzip -l \*.zip

I tried this code in Script Editor (ver. 2.10), but it's not correct syntax:
on adding folder items to theAttachedFolder after receiving theNewItems
    tell application Terminal
        for file in *.zip; do zip -d "$file" "__MACOSX*"; done; for file in *.zip; do zip -d "$file" "*.DS_Store"; done; unzip -l \*.zip
    end tell
end adding folder items to

Here is what the script looks like in Script Editor if that helps any:

What is the correct syntax? I'm running OSX 10.13.6.
PS: I've seen Run a shell command when a file is added plus several other similar questions, but I'm too new to Folder Actions and AppleScripts to understand how to make them work in my situation.
Answer: You need to use the syntax:
set currentTab to do script ("[command]")

For example:
tell application "Terminal"
    set currentTab to do script ("ls")
end tell

Would list the current directory. Make sure you also wrap Terminal in quotes: "Terminal"
Comment: Actually, that does work for "ls", but for the long command string I was wanting to use, it doesn't work. At the first $ it says "Syntax Error: Expected "," but found unknown token." Also, is there any syntax manual I can look at? What would I google to find it? I can't find anything so far.
Comment: Instead of trying to use Terminal, just use the 'do shell script' instruction in your Applescript. It runs a shell command directly from AS. Because it seems your folder is always the same, you can hardcode this folder path into your shell command. Currently, you zip command does not specify the folder containing the .zip. Keep in mind that AS, then 'do shell script' do not know what default folder means.


Convolutional neural network Newbie

Question: I am new to CNN so I am trying to learn to code it with python by following tutorials online, and I came up to this tutorial: https://medium.com/nybles/create-your-first-image-recognition-classifier-using-cnn-keras-and-tensorflow-backend-6eaab98d14dd
I followed the code and all but I get this small error that I can't seem to know the solution:
FileNotFoundError: [Errno 2] No such file or directory: 'random.jpg'
This is the code where the error points out to:
<code>import numpy as np
from keras.preprocessing import image
test_image = image.load_img('random.jpg',target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] >= 0.5:
    prediction = 'dog'
else:
    prediction = 'cat'
    print(prediction)
</code>
I'm going to include the whole code just in case people want to see: https://drive.google.com/open?id=1ew22sJOvl5Ea9VTM_PXqVKNZJm1OuXTG
Any help is appreciated. :)
Comment: Do you have the image file `random.jpg`? If yes, is it in the same location as the file you are running?
Answer: You need to give full path to the image or put code file and the image to the same file.
Comment: Do I just put the directory of the image inside the same apostrophe as the random .jpg?
Comment: Yes, if the image and code is on the some directory code can find random.jpg
Answer: Based on what I read on the blog post, he used just a random dog image (downloaded from any web), name it as "random.jpg", and use it as a test image. You can just seek for any dog/cat image around the web, download and rename it as "random.jpg".
The point is, you know the image is a dog or cat, then test your model to predict what image it is.
Comment: Ow I see now, I just want to know how will I be able to do that? Do I just put the directory on the same apostrophe symbol of the random.jpg?
Comment: Putting the 'random.jpg' file on the same directory as your python code would be the easiest
Answer: You need to put 'random.jpg' into your working directory. That is put any file( a dog, cat, or any) with that name inside your folder :)

Convolutional neural network Newbie


Qual função javascript uso para extrair um bloco HTML de um lugar e inseri-lo em outro na mesma pagina

Question: Seguinte estou mexendo no moodle e 90% do html dele é gerado via backend, preciso mudar um
Title
 de lugar via javascript ja que não tenho acesso a esse elemento, a ideia era retirá-lo de onde está para jogá-lo dentro de um container que tenho na mesma pagina.
Qual função javascript/JQuery posso usar para isso?
Procurei no google mas não consegui expressar a dúvida de uma forma tão clara que pudesse me retornar respostas.
Espero que aqui esteja claro a dúvida, qualquer coisa edito. Obrigado.
Exemplo:

Title

 Quero retirar o h1 ali de cima e colocá-lo aqui dentro

Obs.: Eu até poderia criar um h1 novo dentro do container via JS mas gostaria de aproveitar o que já tem.
Obs2.:  Esqueci de mencionar, que eu quero que esse h1se junto aos outros elementos dentro do container e que ele se mantenha dentro da tag h1...
Comment: Um pouco pedante mas é interessante notar que o que você quer é mudar de lugar um _elemento DOM_ .
Comment: você quer uma solução usando jquery ou vanilla JS?
Comment: Na vdd gostaria de saber a função, usando jquery.   Acho até uma pergunta meio 'besta'  mas so precisava saber qual função usar ... @CaioFelipePereira
Answer: Usando jQuery, você tem várias maneiras de fazer isso. Não sei se é a mais performática ou a mais elegante, mas resolve o problema. Veja:

var _h1 = $('#courseheader').html();

var _container = $('.container');

setTimeout(function(){
  _container.append(' ' + _h1);
}, 2000);

Title

 Quero retirar o h1 ali de cima e colocá-lo aqui dentro

O setTimeout é uma perfumaria, apenas pra você ver funcionando.
EDIT
Eu propositalmente apaguei o conteúdo da div porque achei que era isso que você queria. Editei o código pra ficar de acordo com o seu comentário
Comment: Legal, e mais ou menos isso ai que eu quero, na vdd ele não poderia apagar o conteúdo que esta dentro da div e sim apenas se juntar aos outros elementos, mas vc ja deu o caminho, vou mexer no código para ver se consigo resolver ... Obrigado Caio.
Comment: Mudei de `_container.html('').append(_h1);` para `_container.append(' ' + _h1);`
Comment: Veja a resposta editada
Comment: Cara so uma duvida besta,  o que vc mudou no codigo mesmo para não apagar o conteudo que estava na div container?
Comment: haha vlw onbrigado
Answer: Você pode utilizar o código abaixo como exemplo, ele:

Captura o elemento h1 desejado através do ID
Captura o elemento container através do className
Adiciona ao textContent do container um novo elemento clone de h1 através do método cloneNode(true)

Nota: Para que não houvesse quebra de linha no container, foi necessário adicionar a propriedade display: inline;

//Recuperando elemento H1
var h1Element = document.getElementById("courseheader");

//Recuperando elemento container
var containerElement = document.getElementsByClassName('container')[0];

//Adicionando conteúdo do h1 ao container
containerElement.appendChild(h1Element.cloneNode(true));
h1{
  display: inline;
 }

Title

 Quero retirar o h1 ali de cima e colocá-lo aqui dentro

Comment: +1 por usar JS puro
Comment: A ultima linha do codigo coloquei  containerElement.insertBefore(h1Element.cloneNode(true) , containerElement.firstChild);  e o elemento ficou em primeiro lugar =D
Comment: Dei uma editada na minha pergunta acho que esqueci de mencionar que preciso que o h1 se mantenha dentro do container e que não apague os demais elementos que lá existe e sim se junte a eles.
Comment: @Erick Resposta atualizada
Comment: Legal to mexendo aqui para colocar ele no topo =D ... Mas obrigado aos dois que ajudaram, era isso ai que eu queria mesmo... vlwww


Looking for JQuery OpenViewer for PDF Files

Question: Im trying to find the location of a JavaScript Function that is being used for another site, and Im having trouble locating this function via FireBug.  I can see this in the DOM, but it doesnt provide me with the function.
Here is the site: www.williamsprofessionalpainting.com
Here is the function: OpenViewer
This is simply an onClick Method of an Anchor Tag, which opens up PDF documents.
If someone could help me locate this function, I would greatly appreciate it.
Or, if there is a better JQuery solution, I would actually prefer that option.  I've searched but can't seem to find an alternative.
Comment: chances are it's a custom function or custom plugin that someone built specifically for the site in question.
Answer: It's in the global.js file.  It just wraps window.open() using the path from the anchor as the url.
function OpenViewer(path)
{
    if(path != "")
    window.open(path,"SurveyViewer","toolbar=0,menubar=0,location=0,width=800,height=640,resizable=1");
    else
    alert("NO PATH!");
}

Answer: function OpenViewer(path)
{
    if(path != "")
    window.open(path,"SurveyViewer","toolbar=0,menubar=0,location=0,width=800,height=640,resizable=1");
    else
    alert("NO PATH!");
}

using the Chrome Javascript Console.


Water leaking out of a conical tank and water pumped in

Question:
Water is leaking out of an inverted conical tank at a rate of $0.0068\,\rm m^3/min$. At the same time water is being pumped into the tank at a constant rate. The tank has height $14\,\rm m$ and the diameter at the top is $5.5\,\rm m$. If the water level is rising at a rate of $0.24\,\rm m/min$ when the height of the water is $3\,\rm m$, find the rate at which water is being pumped into the tank.

I tried to solve, but I don't know what the appropriate symbols would be to use in this situations. I got to
$$V' = \frac{2}{3}\pi r r'h + \frac{1}{3}\pi r^2 h',$$
but I don't know what to do next. If anyone could provide a step by step explanation I'd be grateful.
Answer: You are fine up to $V'=\frac 23 \pi rhr'+\frac 13 \pi r^2h'$.  The fact that the tank is conical says that $\frac rh=\frac {2.75}{14}$ or $h=\frac {56}{11}r$, which also implies $h'=\frac {56}{11}r'$.  You can insert this to get $V'$, which is the net increase rate in volume at the given conditions.  Then if you get some units for the $0.0068$ you can add that to $V'$ to get the inflow rate.
Answer: Let $h(t)$ be the height of the water at time $t$, and let $r(t)$ be the radius of the surface of the water at time $t$; from similar triangles we know that
$$\frac{h(t)}{r(t)}=\frac{14}{2.75}=\frac{56}{11}\;.$$
We could solve this for either $r(t)$ or $h(t)$ in terms of the other, but notice that we're told $h'(t)$ at a particular moment, and we're not told anything about an specific value of $r(t)$. This suggests that we'd be better off working in terms of $h(t)$, so we'll solve for $r(t)$ and get $$r(t)=\frac{11}{56}h(t)\;.$$
At time $t$ the volume $V(t)$ of water in the tank is the volume of a right circular cone with height $h(t)$ and base radius $r(t)$, which is given by
$$V(t)=\frac13\pi r(t)^2h(t)=\frac{\pi}3\left(\frac{11}{56}h(t)\right)^2h(t)=\frac{121\pi}{9408}h(t)^3\;.$$
Then
$$V'(t)=\frac{121\pi}{3136}h(t)^2h'(t)\;.$$
We're told that $h'(t)=0.24$ when $h(t)=3$; if we call that moment time $t_0$, we have
$$V'(t_0)=\frac{121\pi}{3136}\cdot3^2\cdot0.24=\frac{3267\pi}{39200}\text{ m}^3/\text{min}\;.$$
Now let $v$ be the rate in cubic metres per minute at which water is being pumped into the tank. Taking into account both the inflow and the leakage, we know that at all times
$$V'(t)=v-0.0068\text{ m}^3/\text{min}\;.$$
In particular, at time $t_0$ we have
$$v-0.0068=\frac{3267\pi}{39200}\;,$$
which is completely straightforward to solve for $v$.
Answer: I think the simplest way to understand this problem is to recognize that
$$V^{'}_{total} = V^{'}_{in} - V^{'}_{out}$$, or in alternative notation,
$$\frac {dV_{total}}{dt} = \frac {d_{pump}}{dt}-\frac {d_{leak}}{dt}$$
Once you recognize that, everything else is straight forward.
Let's use $\frac {dp}{dt}$ for the rate of change due to the pump and $\frac {dl}{dt}$ for the rate of change due to the leak.  So,
$$\frac {dV}{dt} = \frac {dp}{dt} - \frac {dl}{dt}$$
Simplify the Volume Equation
Now, proceed in the normal way.  $V = \frac {1}{3}\pi r^2h$ and we can eliminate $r$ to simplify the equation.  $tan~\theta= \frac {r}{h}$ or $r=h~tan~\theta$.  (This comes from similar triangles and $\theta$ is constant.) Thus, our volume equation becomes $V=\frac{1}{3}\pi (h~tan~\theta)^2h$.  We know $tan~\theta$.  It is $\frac {2.75}{14} = \frac {11}{56}$.  The volume equation therefore is $V=\frac{1}{3}\pi(\frac{11h}{56})^2h = \frac {1}{3}\pi \frac {121h^2}{3136}h = \frac{121\pi h^3}{9408}$
Differentiate
$$V= \frac {121\pi h^3}{9408}$$
$$\frac {dV}{dt} = 3\cdot \frac {121\pi h^2}{9408}\frac{dh}{dt}$$
$$\frac {dV}{dt} = \frac {121\pi h^2}{3136}\frac{dh}{dt}$$
Make Substitutions
Recalling that $\frac {dV}{dt} = \frac {dp}{dt} - \frac {dl}{dt}$, our derivative becomes
$$\frac {dp}{dt} - \frac {dl}{dt} =\frac {121\pi h^2}{3136}\frac{dh}{dt}$$
We know all of the values except $\frac {dp}{dt}$ and we can solve for that:
$$\frac {dp}{dt} - 0.0068 = \frac {121\pi}{3136}\cdot3^2\cdot0.24$$
$$\frac {dp}{dt} = \frac {121\pi}{3136}\cdot3^2\cdot0.24 + 0.0068 $$
$$\frac {dp}{dt}\approx 0.2686~m^3/min$$


Embed a node form with default values in drupal 7

Question: How do I embed a node form and set some default values in that form in Drupal 7?
I understand that I can use this:
<code> $form = node_add('product_plan');
 print drupal_render($form);
</code>
That prints the form on to the page just fine, but I need help understanding how I can add default values. In Drupal 6, I would normally do this:
<code> function module_nodetype_form_embed( $property )
 {
     global $user;

    $node = new stdClass();
    $node->type = 'node_type';
    $node->uid = $user->uid;

    // Hidden through form alter
    $node->field_node_reference[0]['nid'] = $property->nid;
    node_object_prepare( $node );

    return drupal_get_form( 'node_type_node_form', $node );

 }
</code>
So how can I get the same functionality in Drupal 7
Answer: If you are using a 'select list' widget for the node reference you can do this:
<code>$form = node_add('product_plan');
$form['FIELD_NAME'][$form['language']['#value']]['#value'] = 'NID';
return drupal_render($form);
</code>
'autocomplete' widget would look like:
<code>$form = node_add('product_plan');
$element['#default_value'] = 'NID';
$form['FIELD_NAME'][$form['language']['#value']][0]['nid']['#value'] = node_reference_autocomplete_value($element, FALSE, '');
return drupal_render($form);
</code>
Answer: I got it to work with this in D7:
In your custom module write this function:
<code>function module_nodetype_form_embed( $property )
 {
 global $user;

$node = new stdClass();
$node->type = 'node_type';
$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
// Hidden through form alter
$node->field_node_reference['und'][0]['target_id'] = $property->nid;
node_object_prepare( $node );

return drupal_get_form( 'node_type_node_form', $node );

 }
</code>
When you want to embed this form in a node template, do this:
<code>/* I'm assuming that your $property argument from the function
   is the $node page that you are embedding into. */

$form = module_nodetype_form_embed($node);
print drupal_render($form);
</code>
The only problem that I'm encountering is that the validation errors are not showing up on the initial submit if the user didn't fill in the form properly...BUT if you try and submit with invalid values more than once, the error messages show up. Weird....
Comment: Thanks, this is working for me...but I am having the same problem with the error messages not showing up. I tried an embedded form with the node_add function and I still get the error message problem.


Can VI have a dominant function?

Question: On this page I found the following:
"The vi chord is used in this song as though it were a full-fledged sub-dominant (in the way it sets up the V chord) or even as a surrogate dominant — in the way it sometimes is inserted between the I chord on either side".
Is it possible for vi (or VI) to have a dominant function?
Also I'm not sure what is the "surrogate dominant" in the case of vi. In the key of C, the vi is ACE and V is GBD (no common notes), therefore I do not see the connection.
Comment: No,  but emacs can.   //rim shot  [ok I promise never again to go there]
Answer: I don't agree with that analysis. The vi chord usually has a tonic function. The reason why it cannot have a dominant function is because it misses the most important notes indicating that harmonic function: scale degrees 5 and 7 (G and B in the key of C major). Scale degrees 2 and 4 (D and F) would also help, but they're not part of the vi chord either.
If - as indicated in the analysis you quote - the I chord alternates with the vi chord, then the vi chord can be seen as a variation of the I chord to have some movement in an otherwise unchanged harmony.
You can find more information on harmonic functions on this page.
As an aside, a VI7 chord is a totally different thing because it functions as a secondary dominant leading to the ii chord. But this is not what the author of that analysis is talking about.
Answer: I'd say no, but there are those out there who are far more versed in theory than I. A dominant chord shows the need to push onto somewhere else - usually the tonic, so VI could be used as such - leading to the ii (or II) chord - reason being the leading note ( in C) of C# pushing to D/Dm.
The notes in vi (A C E) mean only the E can move one semitone to another diatonic note - F - but the mix of those three isn't powerful enough to make it a dominant of an F chord. Which is C(7) in any case.
Answer: I didn't read the link, but the provided quote is silly. In the context of being bookended by "I" chords, a "vi" shares two notes in common, the third note separated only by a whole step. A "vi" chord does not contain any members of a dominant chord. A "vi" chord is most commonly seen as an extension of "I" - with that one changed note (in this context) serving as a dutiful upper neighbor tone. It would be much more reasonable to assert the "vi" in this context as a "passing vi chord" though not a standard term.
Generally speaking, "vi" is most commonly seen as a substitute for "I", so the notion that it's being used as a "full-fledged subdominant" or even a dominant in the tonal context of the parent key is laughable.
That said, a "vi" may act like a sub-dominant as long as it is succeeded by a VII (or more correctly a V/iii) which would then resolve in any manner of ways. Similarly, as others have mentioned, it could also function as a secondary dominant, provided a raised 3rd, thus leading us to "ii" or "II". Without those conditions, however, it's really nothing more than an extension / substitution of "I".
More reasons to check your sources, folks. We live in a crazy world.
Comment: In your penultimate para., you mention V/iii. In C, that would be a B chord, wouldn't it, so would the sequence be Am>B>Em>xyz? Or would it not have to go to Em at all? I'm probably asking 'after V/x, is the chord x to follow obligatory'?
Comment: Yes, V/iii in C is a B chord. Also your sequence is correct, though it may be E major *or* E minor, *or* whatever chord the composer decides. Macro-analysis can show the intended harmonic function as well as the actual harmonic function. For example, the listener might believe that V/iii actually leads to iii or III, but it might be a deceptive cadence, leading to vi in the new intended key (C# minor) or any such chord. Up to the composer. Good question.
Answer: One could say though that vim7 is a II of V if you make the V chord into a temporary tonic which is frequent in jazz (I took a look at the page on which vi is said to precede V in the progression). In this case vim7 could be seen as a sub-dominant of G with its V of V, D7, left aside.
It's a micro II-V-I where they've ousted the V chord. It makes sense.
I don't understand the surrogate dominant thingy though
Answer: The thing with theory is that it's an attempt to explain the music that we hear and love.  In some instances, traditional interpretations don't provide the analysis we're looking for.  In those cases, theorists/analysts typically try to find interpretations to describe what's happening, which often takes the form of drawing parallels between common/traditional concepts and what's actually happening in the music.
I recall going over this in a theory/analysis class in college, where the teacher had chose to interpret an unusual chord progression within the frame of an unrelated key.  I challenged this but in the end, his interpretation was the best we could come up with.  So even though it didn't exactly make sense in the standard approach to analysis, it was the only thing that really provided us with any sort of explanation that made sense.
So I can't say that Pollack's interpretation is exactly wrong but I don't really agree with it. It's in his wording, where he says, "used...as though" and "surrogate".  If he said vi is the dominant, I'd argue he was explicitly wrong, as that, by definition, is not what the vi is.  In trying to reconcile this, I'd try to listen to the piece a few times, paying attention to how the vi chord feels and where it seems to push/pull.  If it feels like the vi prepares us for the V, it seems appropriate to say it acts as a subdominant.  If it feels like it wants to resolve back to I, then we could say it's acting as a dominant.  I don't believe I would feel that myself but you may and Pollack clearly did.
One thing to consider here is how/where/why you might be doing this analysis.  If you were taking this sort of approach to analyzing a piece of music within an academic setting, then you would want to be a bit careful with how you make your argument and possibly bring it to your teacher prior to submitting it, particularly if it is an important assignment, like a final paper.  If you're just looking to have a better understanding of a song to allow you to perform it better, or just appreciate it more when listening, then analyzing along these lines is just as valid as analyzing vi as submediant, or purple for that matter, because it's just about you at that point.  If you're trying to work with a band to play this song (and everyone happens to be familiar enough with theory), you might confuse everyone or cause an argument about the validity of the analysis but you may also find that it brings everyone to a new interpretation that allows you all to play the piece better as a group, regardless of how "correct" your analysis may be.

Can VI have a dominant function?


Why is the ossia in Wilde Jagd (Transcendental Etude 8) the same as the regular part?

Question:
In Wilde Jagd (Transcendental Etude 8) by Liszt, there is an ossia on measure 191.
The ossia and non-ossia parts only differ by where the 8va is placed. But they have the same content --- the notes which don't have a 8va are simply written one octave higher than the corresponding note in the ossia.
What is the purpose of the ossia?
Comment: There is a difference, G instead of Bb and B, in the second and third measures shown. The first of the measures indeed looks identical.
Comment: And if the question is why bother with an identical first measure, perhaps it's just that it's visually easier to start the ossia at the start of the line than to jump to it after a measure.
Answer: The two are not identical. The ossia jumps to G where the primary jumps to Bb and B in the second and third measures, respectively.
Answer: The purpose is almost certainly to avoid requiring the uppermost Bb, since at the time there were still a lot of 85-key pianos that didn't have it.
Comment: You forgot the B natural.


RewriteCond: Bad flag delimitor in my .htaccess

Question: I kinda need your help. I suddenly got website 500 error on my company's website. I have taken my complete code and put it through htaccesscheck.com.
It narrowed it down to line 290 in my .htaccess file.
The line is:
RewriteCond %{HTTP_USER_AGENT} !(android|blackberry9500|blackberry9530|cupcake|dream|incognito|iphone|ipod|mini|webOS|webmate|2.0 MMP|ASUS|AU-MIC|Alcatel|Amoi|Audiovox|AvantGo|BenQ|Bird|BlackBerry|Blazer|CDM|Cellphone|DDIPOCKET|Danger|DoCoMo|Elaine/3.0|Ericsson|EudoraWeb|Fly|HP.iPAQ|Haier|Huawei|IEMobile|J-PHONE|KDDI|KONKA|KWC|KYOCERA/WX310K|LG|LG/U990|Lenovo|MIDP-2.0|MMEF20|MOT-V|MobilePhone|Motorola|NEWGEN|NetFront|Newt|Nintendo Wii|Nitro|Nokia|Novarra|O2|Opera Mini|Opera.Mobi|PANTECH|PDXGW|PG|PPC|PT|Palm|Panasonic|Philips|Playstation Portable|ProxiNet|Proxinet|Qtek|SCH|SEC|SGH|SHARP-TQ-GX10|SIE|SPH|Sagem|Samsung|Sanyo|Sendo|Sharp|Small|Smartphone|SoftBank|SonyEricsson|Symbian|Symbian OS|SymbianOS|TS21i-10|Toshiba|Treo|UP.Browser|UP.Link|UTS|Vertu|WILLCOME|WinWAP|Windows CE|Windows.CE|Xda|ZTE|dopod|hiptop|htc|i-mobile|nokia|portalmmm|vodafone|ipad) [NC]

Which gives this error: RewriteCond: bad flag delimiters
As i am not very experienced in coding, i have not been able to detect the fault yet.
If there is anyone who can help me on this matter, it would be greatly appreciated.
-Jasper
Answer: Use:
RewriteCond %{HTTP_USER_AGENT} !"(android|blackberry9500|blackberry9530|cupcake|dream|incognito|iphone|ipod|mini|webOS|webmate|2.0 MMP|ASUS|AU-MIC|Alcatel|Amoi|Audiovox|AvantGo|BenQ|Bird|BlackBerry|Blazer|CDM|Cellphone|DDIPOCKET|Danger|DoCoMo|Elaine/3.0|Ericsson|EudoraWeb|Fly|HP.iPAQ|Haier|Huawei|IEMobile|J-PHONE|KDDI|KONKA|KWC|KYOCERA/WX310K|LG|LG/U990|Lenovo|MIDP-2.0|MMEF20|MOT-V|MobilePhone|Motorola|NEWGEN|NetFront|Newt|Nintendo Wii|Nitro|Nokia|Novarra|O2|Opera Mini|Opera.Mobi|PANTECH|PDXGW|PG|PPC|PT|Palm|Panasonic|Philips|Playstation Portable|ProxiNet|Proxinet|Qtek|SCH|SEC|SGH|SHARP-TQ-GX10|SIE|SPH|Sagem|Samsung|Sanyo|Sendo|Sharp|Small|Smartphone|SoftBank|SonyEricsson|Symbian|Symbian OS|SymbianOS|TS21i-10|Toshiba|Treo|UP.Browser|UP.Link|UTS|Vertu|WILLCOME|WinWAP|Windows CE|Windows.CE|Xda|ZTE|dopod|hiptop|htc|i-mobile|nokia|portalmmm|vodafone|ipad)" [NC]

With "
Or encode space as \. ex: 2\.0\ MMP