text
stringlengths
15
59.8k
meta
dict
Q: Code calling reverse function does not compile on either g++ or clang++ on Ubuntu 18, but mysteriously works on mac osx On Mac OSX, clang version 7.0.2 the code compiles. On Ubuntu clang version 7.0.0 it does not. Is there really a difference in some default library, this seems weird? MWE: #include <string> using namespace std; int main() { string A = "abc"; reverse(A.begin(), A.end()); } Is one really bringing in algorithm somehow, but different between the two versions? A: Yes default libraries vary on different systems with different compilers. If you use a certain function, include the respective header. On your Mac the reverse function seems to be include somewhere deep in the string header. Use #include <algorithm> and it should work on the other systems too. A: The default standard library on Mac OS is libc++. The default standard library on Ubuntu is libstdc++. You can try on Ubuntu by passing -stdlib=libc++ to the compiler, and see what happens. The difference is (I suspect, but do not know for sure) that on libc++ string::iterator is a type in namespace std, so ADL lookup occurs, but in libstdc++ the iterators are just char *, and since they don't live in namespace std, no lookup in that namespace occurs.
{ "language": "en", "url": "https://stackoverflow.com/questions/54937205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling a Fortran program within another Fortran program in Fortran 77 Say I have two programs: solve.f and plot.f . The solve program solves an equation and prints the data to a file. The plot routine reads that data and plots it. Is there a way that I can call the plot.f file in the solve.f file? I've tried compiling the plot program (the file was named plot) and tried calling it using "call plot" but that did not work. I looked through the documentation and have not been able to find anything related to this issue. The only alternative I can think of is to combine the two programs into one. A: Unless I have completely misunderstood your question, can't you use the SYSTEM() function to execute plot.f (well, its compiled executable really) from solve.f? Documentation is here.
{ "language": "en", "url": "https://stackoverflow.com/questions/22793745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActiveRecord::RecordNotFound Couldn't find Comment without an ID On my Comment view page (show.html) I have a button that, when clicked, will create a row in a different table called Repost (it has a reposts_controller and a repost model). However, when I click on the icon on the Comment show page, I get the following error: Couldn't find Comment without an ID Here's the RepostsController: class RepostsController < ApplicationController def create @comment = Comment.find(params[:id]) @repost = @comment.reposts.build(params[:comment]) @repost.user = current_user if @repost.save #flash[:success] = "Post created!" redirect_to root_url else render 'activities' end end end I know what the problem is but I'm struggling with a solution. The CommentsController easily finds the comment to display on the show page. However, how do I send that id from the show page to the RepostsController so it can create the needed relationships shown above? It's a strange situation since the button is on the actual comment page but since the button writes a row to a different table using a different controller, the button can't see/find the comment. Thanks! -b Added view: <%= link_to image_tag('star.png', :size => "16x16", :align => "right"), {:controller => 'reposts', :action => 'create', :id => @comment} %> That link_to sends me to localhost/reposts?id=1 and nothing is created on the Reposts table. A: The following code ended up working: class RepostsController < ApplicationController def index @reposts = Repost.all end def create @repost= Repost.new("comment_id" => params[:comment_id],"user_id" => params[:user_id]) @content = @repost.comments.content if @repost.save #flash[:success] = "Post created!" redirect_to root_url else render 'activities' end end end <%= link_to image_tag('purple_star.png', :size => "16x16", :align => "right"), {:controller => 'reposts', :action => 'create', :comment_id => @comment, :user_id => @comment.user}, :title=> "Pass it on!", :method=>'post' %> Thanks for the time and assistance everyone!
{ "language": "en", "url": "https://stackoverflow.com/questions/16803434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Using Recycle View on android I'm creating a app with 3 screens, first one I insert contacts info like name, address, e-mail, cellphone... Second screen I put social network links, and thir one I show all contacts info in a RecyclerView but when I click on the button to go to third screen I'm getting stuck on this error: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.person.bernardo.myperson, PID: 14891 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.person.bernardo.myperson/com.person.bernardo.myperson.RecyclerViewActivity}: java.lang.ClassCastException: com.person.bernardo.myperson.RecyclerViewActivity cannot be cast to com.person.bernardo.myperson.PessoaAdapter$ItemClickListener at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2785) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6342) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) Caused by: java.lang.ClassCastException: com.person.bernardo.myperson.RecyclerViewActivity cannot be cast to com.person.bernardo.myperson.PessoaAdapter$ItemClickListener at com.person.bernardo.myperson.RecyclerViewActivity.onCreate(RecyclerViewActivity.java:47) at android.app.Activity.performCreate(Activity.java:6847) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2785)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:163)  at android.app.ActivityThread.main(ActivityThread.java:6342)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)  My Code: /** * ---------------------------------------------- Documentacao preliminar * Pontificia Universidade Catolica de Minas Gerais * Curso de Ciencia da Computacao * LDDM * <p> * Autor: Bernardo Morais Alfredo Matricula: 565524 * Versao: 0.06 Data: 18/03/2018 * <p> * Dados: * - Ler dados de uma pessoa e criar evento no calendario. * <p> * Para funcionar: * <p> * Insira (nas dependencies de build.gradle (Module:App) : * compile fileTree(dir: 'libs', include: ['*.jar']) * compile 'com.android.support:design:22.2.0' * compile 'com.android.support:appcompat-v7:22.2.0' * <p> * Resultados: * <p> * -Funciona * <p> * Feito com ajuda de: * Luiz Braganca */ package com.person.bernardo.myperson; import android.os.Parcelable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Vibrator; import android.provider.CalendarContract; import android.provider.ContactsContract; import android.text.TextUtils; import android.support.design.widget.TextInputLayout; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import java.util.Calendar; public class MainActivity extends AppCompatActivity { static Pessoa contato = new Pessoa(); EditText nome, nasc, tel, email, endereco; // Variavel para utilizar o vibrador private Vibrator vib; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setBotoes(); } /** * Metodo para converter EditText em String. * @param txt * @return */ public String converteTexto(EditText txt) { // definir dados String resp = txt.getText().toString(); return (resp); }// end converteTexto( ) /** * Metodo para verificar cada botao. */ private void setBotoes() { // definindo botoes Button addContato = findViewById(R.id.addContato), salvaAniv = findViewById(R.id.anivesario), envWhatsapp = findViewById(R.id.whatsapp), save = findViewById(R.id.saveButton); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nome = findViewById(R.id.nome); nasc = findViewById(R.id.nascimento); tel = findViewById(R.id.phone); email = findViewById(R.id.email); endereco = findViewById(R.id.endereco); }// end onClick( ) }); // definindo os editText nome = findViewById(R.id.nome); nasc = findViewById(R.id.nascimento); tel = findViewById(R.id.phone); email = findViewById(R.id.email); endereco = findViewById(R.id.endereco); final TextInputLayout nomeInput = findViewById(R.id.input_layout_nome), nascInput = findViewById(R.id.input_layout_data), telInput = findViewById(R.id.input_layout_telefone), emailInput = findViewById(R.id.input_layout_email), endInput = findViewById(R.id.input_layout_endereco); //Inicializando a variavel vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // botao de adicionar contato addContato.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean emptyNome = TextUtils.isEmpty(converteTexto(nome)), emptyEmail = TextUtils.isEmpty(converteTexto(email)), emptytel = TextUtils.isEmpty(converteTexto(tel)), emptyAddress = TextUtils.isEmpty(converteTexto(endereco)); //Mostrar Erro se Nome Vazio if (emptyNome) { vib.vibrate(120); nomeInput.setErrorEnabled(true); nomeInput.setError(getResources().getString(R.string.erro_EditText_Nome)); }// end if //Mostrar Erro se Email Vazio if (emptyEmail) { vib.vibrate(120); emailInput.setErrorEnabled(true); emailInput.setError(getResources().getString(R.string.erro_EditText_Email)); }// end if //Mostrar Erro se Telefone Vazio if (emptytel) { vib.vibrate(120); telInput.setErrorEnabled(true); telInput.setError(getResources().getString(R.string.erro_EditText_Tel)); }// end if //Mostrar Erro se Address Vazio if (emptyAddress) { vib.vibrate(120); endInput.setErrorEnabled(true); endInput.setError(getResources().getString(R.string.erro_EditText_Endereco)); }// end if //Se os campos nao estiverem vazios: if (!emptyNome && !emptyEmail && !emptytel && !emptyAddress) { nomeInput.setErrorEnabled(false); emailInput.setErrorEnabled(false); telInput.setErrorEnabled(false); endInput.setErrorEnabled(false); contato.setNome(converteTexto(nome)); contato.setEmail((converteTexto(email))); contato.setTelefone((converteTexto(tel))); contato.setEndereco((converteTexto(endereco))); addContact(converteTexto(nome), converteTexto(email), converteTexto(tel), converteTexto(endereco)); }// end if }// end onClick( ) }); // botao de salvar aniversario salvaAniv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean emptyNome = TextUtils.isEmpty(converteTexto(nome)), emptyData = TextUtils.isEmpty(converteTexto(nasc)); //Mostrar erro se nome vazio. if (emptyNome) { vib.vibrate(120); nomeInput.setErrorEnabled(true); nomeInput.setError(getResources().getString(R.string.erro_EditText_Nome)); }// end if //Mostrar erro se data de nascimento vazia. if (emptyData) { vib.vibrate(120); nascInput.setErrorEnabled(true); nascInput.setError(getResources().getString(R.string.erro_EditText_Nasc)); }// end if if (!emptyNome && !emptyData) { nomeInput.setErrorEnabled(false); nascInput.setErrorEnabled(false); aniversario(converteTexto(nome), converteTexto(nasc)); }// end if }// end onClick }); // botao de enviar whatsapp envWhatsapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean emptyTel = TextUtils.isEmpty(converteTexto(tel)); //Mostrar erro se telefone vazio. if (emptyTel) { vib.vibrate(120); telInput.setErrorEnabled(true); telInput.setError(getResources().getString(R.string.erro_EditText_Tel)); }// end if //Mostrar erro. if (!emptyTel) { telInput.setErrorEnabled(false); whatsapp(converteTexto(tel)); }// end if }// end onClick }); }// end setBotoes( ) /** * Metodo addContact( ) - adicionar um contato. * * @Param: -Nome = nome contato * -Email = email contato * -Tel = Telefone contato * -End = endereco contato */ public void addContact(String nome, String email, String tel, String end) { //define o contato // set intent Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION); intent.setType(ContactsContract.RawContacts.CONTENT_TYPE); // set nome intent.putExtra(ContactsContract.Intents.Insert.NAME, nome); // set email intent.putExtra(ContactsContract.Intents.Insert.EMAIL, email); intent.putExtra(ContactsContract.Intents.Insert.EMAIL_TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME); // set telefone intent.putExtra(ContactsContract.Intents.Insert.PHONE, tel); intent.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME); // set endereco intent.putExtra(ContactsContract.Intents.Insert.POSTAL, end); intent.putExtra(ContactsContract.Intents.Insert.POSTAL_TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME); // set intent startActivity(intent); }// end addContact( ) /** * Metodo para adicionar data de aniversário na agenda. */ public void aniversario(String nome, String nasc) { // set data int dia, mes, year; Intent intent = new Intent(Intent.ACTION_INSERT); contato.setAniversario(nasc); // get day dia = Pessoa.getDia(nasc); contato.setDia(dia); // get month mes = Pessoa.getMes(nasc); contato.setMes(mes); // get year year = Pessoa.getYear(nasc); contato.setAno(year); // set date intent.setData(CalendarContract.Events.CONTENT_URI); // set event title intent.putExtra(CalendarContract.Events.TITLE, "Aniversário de " + nome); // set event time intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true); // set start day Calendar startTime = Calendar.getInstance(); startTime.set(2018, mes, dia, 0, 0); intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime.getTimeInMillis()); intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, startTime.getTimeInMillis()); intent.putExtra("rrule", "FREQ=YEARLY"); // iniciando a activity startActivity(intent); }// end aniversario( ) /** * Metodo que manda mensagem pelo whatsapp. * * @Param: -Numero Telefone */ public void whatsapp(String number) { contato.setTelefone(number); // send contact number Uri uri = Uri.parse("smsto:" + number); // start intent Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri); // text type sendIntent.setPackage("text/plain"); // add whatsapp package sendIntent.setPackage("com.whatsapp"); // start activity startActivity(Intent.createChooser(sendIntent, "")); }// end whatsapp( ) /** * Metodo que vai para a segunda tela. * @param view */ public void segundaTela(View view) { // criando a intent para a segunda tela Intent secondScreen = new Intent(this, MainSocial.class); Pessoa proxPessoa = new Pessoa(); proxPessoa.setNome(nome.getText().toString()); proxPessoa.setTelefone(tel.getText().toString()); proxPessoa.setEmail(email.getText().toString()); proxPessoa.setEndereco(endereco.getText().toString()); proxPessoa.setAniversario(nasc.getText().toString()); secondScreen.putExtra("proxPessoa", proxPessoa); // iniciando startActivity(secondScreen); }// end segundaTela( ) }// end class import android.content.Intent; import android.os.Parcelable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainSocial extends AppCompatActivity { Pessoa receivePessoa; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_social); Intent intent = getIntent(); receivePessoa = (Pessoa) intent.getSerializableExtra("proxPessoa"); pegarDados(); } /** * Metodo para converter EditText em String. * * @param txt * @return */ public String editTextToString(EditText txt) { // definir dados String resp = ""; if (txt != null) { resp = txt.getText().toString(); } else { resp = ""; } return (resp); }// end converteTexto( ) /** * Metodo para salvar os dados de cada rede no contato, se null = "". * * @param * @return */ public void pegarDados() { Button save = findViewById(R.id.save); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText facebook = findViewById(R.id.facebook); String face = editTextToString(facebook); receivePessoa.setFacebook(face); EditText instagram = findViewById(R.id.instagram); String insta = editTextToString(instagram); receivePessoa.setInstagram(insta); EditText linkedin = findViewById(R.id.linkedin); String link = editTextToString(linkedin); receivePessoa.setLinkedIn(link); EditText spotify = findViewById(R.id.spotify); String spot = editTextToString(spotify); receivePessoa.setSpotify(spot); EditText twitter = findViewById(R.id.twitter); String twit = editTextToString(twitter); receivePessoa.setTwitter(twit); EditText youtube = findViewById(R.id.youtube); String yout = editTextToString(youtube); receivePessoa.setYoutube(yout); }// end onClick( ) }); } /** * Metodo que vai para a segunda tela. * * @param view */ public void terceiraTela(View view) { // criando a intent para a terceira tela com RecycleView Intent terceiraTela = new Intent(this, RecyclerViewActivity.class); terceiraTela.putExtra("pessoa2", receivePessoa); System.out.println(receivePessoa.getNome()); System.out.println(receivePessoa.getTelefone()); System.out.println(receivePessoa.getEmail()); System.out.println(receivePessoa.getEndereco()); System.out.println(receivePessoa.getFacebook()); System.out.println(receivePessoa.getInstagram()); System.out.println(receivePessoa.getLinkedIn()); System.out.println(receivePessoa.getTwitter()); System.out.println(receivePessoa.getSpotify()); System.out.println(receivePessoa.getYoutube()); // iniciando startActivity(terceiraTela); }// end terceiraTela( ) } import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class PessoaAdapter extends RecyclerView.Adapter<PessoaAdapter.ViewHolder> { private List<String> mData; private LayoutInflater mInflater; private ItemClickListener mClickListener; // data is passed into the constructor PessoaAdapter(Context context, List<String> data) { this.mInflater = LayoutInflater.from(context); this.mData = data; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.recyclerview_row, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, int position) { String animal = mData.get(position); holder.myTextView.setText(animal); } // total number of rows @Override public int getItemCount() { return mData.size(); } // convenience method for getting data at click position String getItem(int id) { return mData.get(id); } // allows clicks events to be caught void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView myTextView; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.show_nome); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } } public class RecyclerViewActivity extends AppCompatActivity { PessoaAdapter adapter; Pessoa contato; private List<Pessoa> movieList = new ArrayList<>(); private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recycler_view_activity); Intent intent = getIntent(); contato = (Pessoa) intent.getSerializableExtra("pessoa2"); ArrayList<String> animalNames = new ArrayList<>(); animalNames.add(contato.getNome()); animalNames.add(contato.getTelefone()); animalNames.add(contato.getEmail()); animalNames.add(contato.getEndereco()); animalNames.add(contato.getFacebook()); animalNames.add(contato.getLinkedIn()); animalNames.add(contato.getInstagram()); animalNames.add(contato.getYoutube()); animalNames.add(contato.getSpotify()); // set up the RecyclerView RecyclerView recyclerView = (RecyclerView) findViewById(R.id.listView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new PessoaAdapter(this, animalNames); adapter.setClickListener((PessoaAdapter.ItemClickListener) this); recyclerView.setAdapter(adapter); } public void onItemClick(View view, int position) { Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show(); } } I tried using this sample here. GitHub Link For Complete Code A: Error in this line adapter.setClickListener((PessoaAdapter.ItemClickListener) this); You should do like this * *Let class RecyclerViewActivity implement interface PessoaAdapter.ItemClickListener public class RecyclerViewActivity extends AppCompatActivity implements PessoaAdapter.ItemClickListener{ *Add method to class RecyclerViewActivity void onItemClick(View view, int position){ your code } *You don't need to cast anymore adapter.setClickListener(this); Read this https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html A: You need to move out the interface out of the PessoaAdapter class. Create a new class ItemClickListener.java like the following. package com.person.bernardo.myperson; import android.view.View; public interface ItemClickListener { void onItemClick(View view, int position); } Now in your RecyclerViewActivity implement the ItemClickListener like the following and while setting the adapter to the RecyclerView, you set the listener along with the adapter. package com.person.bernardo.myperson; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; import java.util.List; public class RecyclerViewActivity extends AppCompatActivity implements ItemClickListener { PessoaAdapter adapter; Pessoa contato; private List<Pessoa> movieList = new ArrayList<>(); private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recycler_view_activity); Intent intent = getIntent(); contato = (Pessoa) intent.getSerializableExtra("pessoa2"); ArrayList<String> animalNames = new ArrayList<>(); animalNames.add(contato.getNome()); animalNames.add(contato.getTelefone()); animalNames.add(contato.getEmail()); animalNames.add(contato.getEndereco()); animalNames.add(contato.getFacebook()); animalNames.add(contato.getLinkedIn()); animalNames.add(contato.getInstagram()); animalNames.add(contato.getYoutube()); animalNames.add(contato.getSpotify()); // set up the RecyclerView RecyclerView recyclerView = (RecyclerView) findViewById(R.id.listView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // Error in the following line adapter = new PessoaAdapter(this, animalNames); adapter.setClickListener(this); recyclerView.setAdapter(adapter); } @Override public void onItemClick(View view, int position) { // Do something based on the item click in the RecyclerView } } And the modified adapter will look like the following. package com.person.bernardo.myperson; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class PessoaAdapter extends RecyclerView.Adapter<PessoaAdapter.ViewHolder> { private List<String> mData; private LayoutInflater mInflater; private ItemClickListener mClickListener; // data is passed into the constructor PessoaAdapter(Context context, List<String> data) { this.mInflater = LayoutInflater.from(context); this.mData = data; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.recyclerview_row, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, int position) { String animal = mData.get(position); holder.myTextView.setText(animal); } // total number of rows @Override public int getItemCount() { return mData.size(); } // convenience method for getting data at click position String getItem(int id) { return mData.get(id); } // allows clicks events to be caught void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView myTextView; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.show_nome); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } } I have downloaded your code from github and modified the code in a branch of mine which is locally created. Please check the pull request in the fix branch in your github repository. Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/49972627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Canvas app navigation from redirect URL I'm working on an app for work and have come to a slight roadblock. How do I navigate to a specific page in my app via redirect_uri? For example, after a user authorizes the app from the home page, I'd like to send them to a different page where they can begin to take action, rather than send them back to the root canvas URL. I'm using the ifame settup for the app located at www.onewiththem.com/facebook/ In a normal website, if I wanted to send the user to the donate page I would redirect them to www.myappurl/donate, but I have no idea how to do this inside of an iframe (other than have the user click on a link). Is there something like redirect_uri = apps.facebook.com/myapp/donate that could do this? A lot of facebook sharing features use the redirect_uri parameter to send a user someplace after they've taken action (sharing on their news feed or inviting others to use the app) and it's kindof crappy user experience to send a person back to the home page each time they do something. A: Let me know if I am not understanding you question. If you are using a Facebook application and the other page is also located in you project then you can do a simple window.location = "myLocation" or another equivalent call. If you do another kind of redirect inside of a Facebook iFrame, then the page will just appear inside that iFrame as if it was part of the app. You should not need to do anything special to navigate between pages (as long as they are part of your application) If it is not part of the application then you can still redirect, and it will appear inside of that iFrame (though it may not look as nice), though you will have to edit the redirected page so you can go back if you don't want to click the back button every time. There may be some settings that you need to edit if you are redirecting from one facebook page to another one though. If you have a separate webpage that you want to link to (without showing facebook), then you are going to have to find a different way to do so. You would have to do something like: window.open('www.yoursite.com','blank','fullscreen, yes'); A: Because a canvas app is just a website, facebook built in native navigation which means that I can redirect the canvas URL to the actual url of the website For example, since I want to redirect people to the donation page after they take a social action, I can just redirect to apps.facebook.com/myappcanvas/donation and it will go there. I guess I was a bit hasty when I asked this question. Should have tried it first. In summary: top.location.href = "apps.facebook.com/myappcanvas/secondarypage/tertiarypage/etc"; This works especially if you want to send a user back to a specific page after they invite friends or send a facebook message, or write on their wall. Hope this helps other developers out there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7032411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is there a Max width of a website of 960px instead of just making it a percentage of width? Bulma and I think Bootstrap have max widths on their media queries. Why wouldn't you just make width a percentage of the screen size and leave it at that? A: Per MDN's documentation on media queries, there are only a few features dedicated to size: width, height, device-width, and device-height. In the past, device-width and device-heigth was available for media queries, which could theoretically be sort of used for what you're attempting to do, but this has since been deprecated and must not be used in new code. That leaves width and height which takes a "length" value. Per MDN's documentation on "length", there is no length unit that corresponds to the screen/display. There are "absolute length units" which are matched to real-life lengths whenever possible, or close approximations when not. For example, 1px is 1/96th of an inch, or 1 device pixel on low-resolution screens. There are "font-relative lengths" which are relative to the size of a particular character or font attribute in the current font. For example, 1em is equal to the current font size of the element (or of the parent element when specified on the font-size property). Finally, there are "viewport-percentage lengths", which are relative to the size of the viewport. While this is sometimes confused with the size of the screen/display, this is actually the size of the visible portion of the document: the part of the browser dedicated to displaying the webpage. So, 1vw would be 1% of the width of the visible portion of the page, while 100vw would be the width of the visible portion of the page. With iframes, the "viewport" is the size of the iframe. You can see this demonstrated below: <code style="background: yellow; display: block; width: 50vw; height: 50vh"> background: yellow;<br> display: block;<br> width: 50vw;<br> height: 50vh </code> You can also use percentages in other places in CSS, but all these do are take the inherited value (parent's value) and multiply it by that percentage. That is, if the parent is 100px wide and the child sets its width to 50%, the child's width gets converted to 50px. In the case of (min|max)-(width|height) on media queries, there is no parent to compare it to, but if they faked one, it would likely be the viewport, like vw, vh, and percentages on html use. However, browsers actually just completely ignore percentages on (min|max)-(width|height) as can be seen here: @media (min-width: 1%) { * { background: yellow } } @media (max-width: 100%) { * { background: red } } <code style="display: block"> @media (min-width: 1%) { div { background: yellow } }<br> @media (max-width: 100%) { div { background: red } } </code> There are also resolution-related units you can use with media queries (with resolution), but these are limited to the number of dots per length like dpi for dots per inch, not the total number of dots on the screen. Media queries relating to the size of a screen wouldn't be all that helpful for the majority of use cases, however, as the biggest use case for (min|max)-(width|height) is for different screen sizes, such as phones, tablets, laptops, and large desktop displays. Having a max-width: 50% breakpoint on a 1920x1080 screen would mean the breakpoint would be around 960px. On an iPhone XS, that same breakpoint would be around 207px (CSS pixels, not device pixels). Most people won't be using browsers in split screen, and most (all?) phones don't support windowed mode or double split screen, so you would never hit breakpoints with both height and width set in percentages. And unless you were using percentages and items that could always wrap, you would have to specify additional information in each media query to be useful (eg, (max-width: 50%) and (min-width: 50px)). What this could be helpful for is an app that used multiple windows for a single application. Think Photoshop or GIMP in windowed mode, as opposed to all of the toolbars being in a single window. But even then, any effects are likely still achieveable with existing media queries. So, the answer to your question is we use non-percentage lengths because viewport breakpoints would never be triggered (viewport is always 100%) and resolution breakpoints (eg, percentage of screen size) don't exist. The one set of resolution breakpoint media queries available (device-width and device-height) are deprecated and must not be used in new code. Instead, we use length breakpoints to change the design when the visible portion of the page is a different size, regardless of how large or small the device is. Many libraries use absolute lengths (eg, px) instead of relative units (eg, em) due to the fact that most developers design based on pixels. Over time, there has been a shift toward relative units, but there hasn't been a tipping point. While 960px is pretty widespread, this desktop/tablet breakpoint has changed over time. For a long period of time, websites were designed to fit on a 1024x768 monitor. With the scrollbar and browser chrome (border around window) taken into account, websites were often designed at 1000px wide, and later 980px became common for reasons I can't remember, but I wouldn't be surprised if some operating system or browser came along that that had chrome and scrollbar width that added up to more than 24px, or it might be related to a popular framework at the time using it. Anyway, when mobile devices became more popular, designing sites to work in grids also did, which is why 960px is so common nowadays. A: the breakpoint values for the different display scales vary by a specific pixel depending to the fundamental that has been actually used like: Small display scales - ( min-width: 576px) and ( max-width: 575px), Medium screen scale - ( min-width: 768px) and ( max-width: 767px), Large size display dimension - ( min-width: 591px) and ( max-width: 992px), And Additional big display sizes - ( min-width: 1200px) and ( max-width: 1199px),
{ "language": "en", "url": "https://stackoverflow.com/questions/52670477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add conditional tooltip in bootstrap 3,it should be visible only when ellipses(large text) is there How to add conditional tool tip in bootstrap 3,it should be visible only when ellipses(large text) is there. A: you can add the title tag with JavaScript within your condition (if, else, or whatever) document.getElementById('myID').setAttribute('title', 'your tooltiptext'); dont Forget to set the id of your a-tag..
{ "language": "en", "url": "https://stackoverflow.com/questions/41040719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ListView items not changing text colour I've used a colouring adapter to change the text colour of my list view items but after debugging the app crashes and I get an error that I don't know how to fix. I know that the problem lies with line 77 but the reason is not clear to me. Any ideas on how to rectify this? package com.apptacularapps.exitsexpertlondonlite; import android.content.Context; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class StationChooserActivity extends ActionBarActivity { ListView list_linechooser; String[] listContent = { "Bakerloo line", "Central line", "Circle line", "District line", "Hammersmith & City line", "Jubilee line", "Metropolitan line", "Northern line", "Piccadilly line", "Victoria line", "Waterloo & City line", "Docklands Light Railway", "London Overground", "Tramlink" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stationchooser); list_linechooser = (ListView)findViewById(R.id.list_linechooser); MyColoringAdapter adapter = new MyColoringAdapter(this,listContent); list_linechooser.setAdapter(adapter); } private class MyColoringAdapter extends ArrayAdapter<String> { private final Context context; private final String[] values; public MyColoringAdapter(Context context, String[] values) { super(context, R.layout.list_item, values); this.context = context; this.values = values; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.list_item, parent, false); TextView textView = (TextView) rowView.findViewById(R.id.list_item); // Set text textView.setText(values[position]); // Set color depending on position int textColorId = R.color.white; // Default color switch (position) { case 0: textColorId = R.color.bakerloo; break; case 1: textColorId = R.color.central; break; case 2: textColorId = R.color.circle; break; case 3: textColorId = R.color.district; break; case 4: textColorId = R.color.hc; break; case 5: textColorId = R.color.jubilee; break; case 6: textColorId = R.color.metropolitan; break; case 7: textColorId = R.color.white; break; case 8: textColorId = R.color.piccadilly; break; case 9: textColorId = R.color.victoria; break; case 10: textColorId = R.color.wc; break; case 11: textColorId = R.color.dlr; break; case 12: textColorId = R.color.overground; break; case 13: textColorId = R.color.tramlink; break; } textView.setTextColor(getResources().getColor(textColorId)); return rowView; } } } A: Your list item layout file name is list_item but i think you are not giving the correct id for textview. Here TextView textView = (TextView) rowView.findViewById(R.id.list_item); Make double sure you text view id in xml file is list_item (i dont think so). In that case just change it to correct id and it will work hopefully. A: The error is a NullPointerException on Line 77 is ( Please, avoid using an image for share the error log, text is better ). That line is: textView.setText(values[position]); I assumed that you don't pass a null array to constructor, so the other possible NullExcepction problem is in textView. I would said that textView is null. Can you check that?
{ "language": "en", "url": "https://stackoverflow.com/questions/29803123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get Excel Sheet into a Deedle data frame in F# I am trying to get data in excel into a Deedle data frame. I have used Excel provider to get the data but I am not sure how to get it into a record so that it can be taken into Deedle. My code that I have is shown below. open Deedle open FSharp.Interop.Excel type TheFile = ExcelFile<"*******.xlsx","Sheet Desired"> let data = TheFile() let data = data.Data ****figuring out how to convert to record**** let df = Frame.ofRecords data I haven't figured out how to convert this data to a record in the special type sequence. A: You can use a map, for instance: data |> Seq.map (fun r -> {| a = r.a ; b = r.b |}) |> Frame.ofRecords
{ "language": "en", "url": "https://stackoverflow.com/questions/64558607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to style Google Maps with their API I'm trying to change the style of a Google Map, but I'm not sure how. Google has given me these object attributes: [ { "stylers": [ { "hue": "#ff0022" }, { "saturation": -16 }, { "lightness": -5 } ] } ] But I am unsure how to make that work with the following code, which is a generated Google map: <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script> <div style="overflow:hidden;height:500px;width:700px;"> <div id="gmap_canvas" style="height:500px;width:700px;"></div> <a class="google-map-data" href="http://www.addmap.org" id="get-map-data">google maps</a> <iframe src="http://www.embed-google-map.com/map-embed.php"></iframe> <a class="google-map-data" href="http://www.nuckelino.de" id="get-map-data">http://www.nuckelino.de</a></div> <script type="text/javascript"> function init_map(){ var myOptions = { zoom:15, center:new google.maps.LatLng(51.8476894,-1.355176799999981), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions); marker = new google.maps.Marker({ map: map,position: new google.maps.LatLng(51.8476894, -1.355176799999981)}); infowindow = new google.maps.InfoWindow({ content:"<div style='position:relative;line-height:1.34;overflow:hidden;white-space:nowrap;display:block;'><div style='margin-bottom:2px;font-weight:500;'>1 Market Street</div><span>1 Market Street <br> OX4 2JR Woodstock</span></div>" }); google.maps.event.addListener(marker, "click", function(){ infowindow.open(map,marker);});infowindow.open(map,marker);} google.maps.event.addDomListener(window, 'load', init_map); </script> I've tried adding them to the myOptions, but it's not working: var myOptions = { zoom:15, center:new google.maps.LatLng(51.8476894,-1.355176799999981), mapTypeId: google.maps.MapTypeId.ROADMAP, stylers: [ { hue: "#00ffe6" }, { saturation: -20 } ] }; And here is the link to the styling API. But I can't make heads or tails of it. Could anyone help? A: You simply add the stylers to your map options (as the links in the comments explains) : var stylers = [{ "stylers": [{ "hue": "#ff0022" }, { "saturation": -16 }, { "lightness": -5 }] }]; var myOptions = { ... styles: stylers }; Here is your code from above in a fiddle using the stylers -> http://jsfiddle.net/cKQxb/ producing this : A: From the first example in the documentation: <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script> <div style="overflow:hidden;height:500px;width:700px;"> <div id="gmap_canvas" style="height:500px;width:700px;"></div> <a class="google-map-data" href="http://www.addmap.org" id="get-map-data">google maps</a> <iframe src="http://www.embed-google-map.com/map-embed.php"></iframe> <a class="google-map-data" href="http://www.nuckelino.de" id="get-map-data">http://www.nuckelino.de</a></div> <script type="text/javascript"> function init_map(){ var styles =[ { "stylers": [ { "hue": "#ff0022" }, { "saturation": -16 }, { "lightness": -5 } ] } ] var myOptions = { zoom:15, center:new google.maps.LatLng(51.8476894,-1.355176799999981), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions); map.setOptions({styles: styles}); marker = new google.maps.Marker({ map: map,position: new google.maps.LatLng(51.8476894, -1.355176799999981)}); infowindow = new google.maps.InfoWindow({ content:"<div style='position:relative;line-height:1.34;overflow:hidden;white-space:nowrap;display:block;'><div style='margin-bottom:2px;font-weight:500;'>1 Market Street</div><span>1 Market Street <br> OX4 2JR Woodstock</span></div>" }); google.maps.event.addListener(marker, "click", function(){ infowindow.open(map,marker);});infowindow.open(map,marker);} google.maps.event.addDomListener(window, 'load', init_map); </script> Or when you create the map: <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script> <div style="overflow:hidden;height:500px;width:700px;"> <div id="gmap_canvas" style="height:500px;width:700px;"></div> <a class="google-map-data" href="http://www.addmap.org" id="get-map-data">google maps</a> <iframe src="http://www.embed-google-map.com/map-embed.php"></iframe> <a class="google-map-data" href="http://www.nuckelino.de" id="get-map-data">http://www.nuckelino.de</a></div> <script type="text/javascript"> function init_map(){ var styles =[ { "stylers": [ { "hue": "#ff0022" }, { "saturation": -16 }, { "lightness": -5 } ] } ] var myOptions = { styles: styles, zoom:15, center:new google.maps.LatLng(51.8476894,-1.355176799999981), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions); marker = new google.maps.Marker({ map: map,position: new google.maps.LatLng(51.8476894, -1.355176799999981)}); infowindow = new google.maps.InfoWindow({ content:"<div style='position:relative;line-height:1.34;overflow:hidden;white-space:nowrap;display:block;'><div style='margin-bottom:2px;font-weight:500;'>1 Market Street</div><span>1 Market Street <br> OX4 2JR Woodstock</span></div>" }); google.maps.event.addListener(marker, "click", function(){ infowindow.open(map,marker);});infowindow.open(map,marker);} google.maps.event.addDomListener(window, 'load', init_map); </script> A: You should put it on Option Object that you contruct your map. Or set this option with map.set("styles", stylesOpts). Change your code to this: var myOptions = { zoom:15, center:new google.maps.LatLng(51.8476894,-1.355176799999981), mapTypeId: google.maps.MapTypeId.ROADMAP, styles: [ // The correct is STYLES not STYLERS { hue: "#00ffe6" }, { saturation: -20 } ] }; https://developers.google.com/maps/documentation/javascript/reference#MapOptions A: The accepted answer explains how to implement styles. To generate the styles, there's a very useful styling tool which allows you to visually tweak map settings, which then spits out the JSON you need: https://mapstyle.withgoogle.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/22252632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How Session.run() chooses which sub-graph to run I was trying to understand how Session.run() works in Tensorflow flow. I know that Session.run() runs the sub-graph specified by the "fetch" argument we give it. Since depending on which part of the sub-graph is executed first we might get different results, I was trying to see if that is really the case. Suppose we compare the output of this code: import tensorflow as tf x = tf.Variable(42) assign1 = tf.assign(x, 13) assign2 = tf.assign(x, 14) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) val1, val2, val3 = sess.run([x, assign1, assign2]) print(val1, val2, val3) with this code: import tensorflow as tf x = tf.Variable(42) assign2 = tf.assign(x, 14) assign1 = tf.assign(x, 13) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) val1, val2, val3 = sess.run([x, assign1, assign2]) print(val1, val2, val3) (The only change is assigning of 14 comes first in the second code). I was expecting to see that the first code produces output 14, 14, 14 while the second one produced 13, 13, 13. However, the result is that the first produced 13, 13, 13 while the second on produced 14, 14, 14. Why does this happen? Update: Following Chosen Answer: I don't quite get what is independent and what is not. For example, in the following code: x = tf.Variable([1, 2, 3, 4, 5]) def foo(): tmp_list = [] assign = tf.assign(x[4], 100) for i in range(0, 5): tmp_list.append(x[i]) return tmp_list z = foo() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) val1, val2 = sess.run([z, assign]) print(val1, val2) In my Session.run() I have both z and assign. To get z, I need foo(). When foo() is ran, assign = tf.assign(x[4], 100) is also ran. However, the output is [1, 2, 3, 4, 5] 13 and I have no idea where the 13 comes from. A: There is no guarantee which of independent ops is performed first, so you can get 13 or 14 in both cases. Your result is pure luck. Try this: with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(100): val1, val2, val3 = sess.run([x, assign1, assign2]) print(val1, val2, val3) ... and you'll see 13 and 14 printed out. Update for the subsequent question: z = foo() (which is just list of x slices) does not depend on assign. Note that foo is called just once before the session is started. I think, the best to see it is to visualize the graph in tensorboard. If you say... sess.run(z) ... tensorflow won't run assign, because it doesn't run a python function, it evaluates tensors. And tensor x or x[i] does not depend on the op assign. Dependency is defined by operations that are performed with tensors. So if you had... y = x + 2 ... this is a dependency: in order to evaluate y, tensorflow must evaluate x. Hope this makes it more clear now.
{ "language": "en", "url": "https://stackoverflow.com/questions/48465510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting printer's "KeepPrintedDocuments" property in .NET Here's what we're trying to do: We want an unobtrusive way of taking everything a client prints on their computer (all of our clients are running POS systems and use Windows XP exclusively) and sending it to us, and we've decided the best way to do that is to create a c# app that sends us their spool files, which we can already parse easily. However, this requires setting "Keep All Printed Documents" to true. We want to do this in our app rather than manually, for the following reason: some (hundreds) of our clients are, for lack of a better word, dumb. We don't want to force them to mess around in control panel... our tech support people are busy enough as it is. Here's where I've run into a problem: string searchQuery = "SELECT * FROM Win32_Printer"; ManagementObjectSearcher searchPrinters = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection printerCollection = searchPrinters.Get(); foreach (ManagementObject printer in printerCollection) { PropertyDataCollection printerProperties = printer.Properties; foreach (PropertyData property in printerProperties) { if (property.Name == "KeepPrintedJobs") { printerProperties[property.Name].Value = true; } } } This should, as far as I can tell from several hours of WMI research, set the KeepPrintedJobs property of each printer to true... but its not working. As soon as the foreach loop ends, KeepPrintedJobs is set back to false. We'd prefer to use WMI and not mess around in the registry, but I can't spend forever trying to make this work. Any ideas on what's missing? A: Try adding a call to Put() on the ManagementObject to explicitly persist the change, like this: foreach (ManagementObject printer in printerCollection) { PropertyDataCollection printerProperties = printer.Properties; foreach (PropertyData property in printerProperties) { if (property.Name == "KeepPrintedJobs") { printerProperties[property.Name].Value = true; } } printer.Put(); } Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/12110010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: JSF 1.2 : Can I create reusable component inside JSF view Is possible to something like this in jsf? <ui:composition> <x:reusableCode id="editScreen">InnerHtml ... </x:reusableCode> code... <x:use component="editScreen"/> </ui:composition I know I can create my own component and register it in jsf tagLib, but I need reusable HTML only in on jsf view file. A: In Facelets 1.x you can create a tag file for this purpose. Here's a basic kickoff example. Create /WEB-INF/tags/some.xhtml: <ui:composition xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" > <h:outputText value="#{foo}" /> </ui:composition> Define it in /WEB-INF/my.taglib.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "http://java.sun.com/dtd/facelet-taglib_1_0.dtd"> <facelet-taglib> <namespace>http://example.com/jsf/facelets</namespace> <tag> <tag-name>some</tag-name> <source>/WEB-INF/tags/some.xhtml</source> </tag> </facelet-taglib> Register it in /WEB-INF/web.xml: <context-param> <param-name>facelets.LIBRARIES</param-name> <param-value>/WEB-INF/my.taglib.xml</param-value> </context-param> (note, when you have multiple, use semicolon ; to separate them) Finally just declare it in your main page templates. <ui:composition xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:my="http://example.com/jsf/facelets" > <my:some foo="value1" /> <my:some foo="value2" /> <my:some foo="value3" /> </ui:composition> A more advanced example can be found here: How to make a grid of JSF composite component? Note: JSF 2.0 targeted, but with minor changes based on above example it works as good on Facelets 1.x.
{ "language": "en", "url": "https://stackoverflow.com/questions/10750384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: C# array access from first element only I'm sorry if this has been asked before, but I don't even know what to search for to find an answer. I'm fairly experienced in .net/c# etc., however, I have come across something I don't understand how works. I'm working on a third party library where I do not have access to the source. My question is: How is this function able to get the whole data in the array when only the first value is being passed? Prototype: SomeClass(ref byte pByte, int length); Code example: ... byte[] bArr = new byte[100]; // fill array with some data SomeClass(ref bArr[0], bArr.Length); ... Update: Sorry I didn't include this in the post to begin with. I am en experienced embedded fw engineer but I have also worked with c#/.net/wpf/wcf etc. for many years. So I am well aware of the difference between pass-by-value/reference and the ref modifier. My initial confusion was that I have never seen any c# function calls only passing the first element in an array (like pointers in c/c++) and the function can access the whole array. So it's more the syntax that got me. :) Thanks to @jdweng's comment I used iLSpy to confirm Nicholas Carey's answer. The library is just a CLR wrapped c++ library where the dll importing and marshaling is done. Thank you all for your answers. :) A: An array is a contiguous bit of memory, calling a function like this: foo( ref bAarr[0], bArr.Length ); It passes two things: * *The address of the 1st element of the array, and *The number of elements in the array Your 3rd-party library is almost certainly a C/C++ DLL exposing a function signature along the lines of int foo( unsigned char *p, int len ); An array reference like arr[n] is [roughly] the equivalent of the following pseudocode: * *let p be the address of arr *let offset be n multiplied by the size in octets of the array's underlying type *let pElement be p + offset, the address of element n of array arr. pElement, when dereferenced, gives you the value of arr[n]. A: @Nicholas explained how it happens but if you want to do the same thing in the c# check the bellow code: I don't recommend using it, just for satisfying curiosity: void Main() { byte[] bArr = new byte[100]; // fill the entire array without passing it to method FillEntireArray(ref bArr[0], bArr.Length); // read the entire array without passing it to method ReadEntireArray(ref bArr[0], bArr.Length); } public unsafe void FillEntireArray(ref byte pByte, int length) { fixed (byte* ptr = &pByte) { byte* p = ptr; for (int i = 0; i < length; i++) { // set a new value to pointer *p = ((byte)(i)); // move pointer to next item p++; } } } public unsafe void ReadEntireArray(ref byte pByte, int length) { fixed (byte* ptr = &pByte) { byte* p = ptr; for (int i = 0; i < length; i++) { // Print the value of *p: Console.WriteLine($"Value at address 0x{(int)p:X} is {p->ToString()}"); // move pointer to next item p++; } } } A: shorter form: public unsafe void FillArray(ref byte arr, int length) { fixed (byte* ptr = &arr) { for (byte i = 0; i<length; i++) { *(ptr + i) = i; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/70944981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mapping values in dropdown 2 dependent on value selected in dropdwon 1 via php mysql I am fresher in php & mysql. I have a from where there are 2 dropdwon's. The value in dropdwon are coming via mysql. But now i am not able to get the value in 2nd dropdown dependent on value selected in 1st dropdown. Here is the code i have tried so far. Please Help! Thank You <html> <head><title>Sheet</title></head> <body> <h2 align="center">SKU Selection</h2> <?php $conn=mysqli_connect('localhost','root',''); $db="sample"; mysqli_select_db($conn,$db); $sql="SELECT DISTINCT(Site) FROM `bom`"; $result=mysqli_query($conn,$sql); echo "Site Name :"; echo "<select name='Site'>"; echo "<option value='0'>Select Site</option>"; while($row=mysqli_fetch_array($result)) { echo "<option value='".$row['Site']."'>".$row['Site']."</option>"; } echo "</select>"; $sql1="SELECT BOM Desc FROM `bom` where Site= "; $result1=mysqli_query($conn,$sql1); echo "<br>"; echo "SKU :"; echo "<select name='SKU'>"; while($row1=mysqli_fetch_array($result1)) { echo "<option value='".$row1['BOM Desc']."'>".$row1['BOM Desc']."</option>"; } echo "</select>"; ?> </body> </html> A: Hi Your fixed code here: <html> <head><title>Sheet</title></head> <body> <h2 align="center">SKU Selection</h2> <?php $conn = mysqli_connect('localhost', 'root', ''); $db = "sample"; mysqli_select_db($conn, $db); $sql = "SELECT DISTINCT(Site) FROM `bom`"; $result = mysqli_query($conn, $sql) or die(mysqli_error($conn)); // add error show info echo "Site Name :"; echo "<select name='Site'>"; echo "<option value='0'>Select Site</option>"; while ($row = mysqli_fetch_array($result)) { echo "<option value='" . $row['Site'] . "'>" . $row['Site'] . "</option>"; } echo "</select>"; $sql1 = "SELECT BOM Desc FROM `bom` where Site IS NULL "; // change the for null site $result1 = mysqli_query($conn, $sql1) or die(mysqli_error($conn)); // add error show info echo "<br>"; echo "SKU :"; echo "<select name='SKU'>"; while ($row1 = mysqli_fetch_array($result1)) { echo "<option value='" . $row1['BOM Desc'] . "'>" . $row1['BOM Desc'] . "</option>"; } echo "</select>"; ?> </body> </html> And if you need load on second select php only cant handle this because you must give time to user for check first select. I think the better way is using Ajax request for second: Auto Load Second Dropdown using AJAX A: I suggest to use in both <select> the clause selected to show the selected <option>. Then, in the first <select> add the on change event to launch a page refresh so that: * *The selected entry is recognised as selected *The SQL for the second drop-down can be filtered on the selected entry in first dropdown The first select should appear then like this: <select onChange='if(options[selectedIndex].value) { location=options[selectedIndex].value;}' size='1'> <option value='?site=Plant1'>Plant ONE</option> <option value='?site=Plant2' selected>Plant 2</option> </select> When Plant 2 is selected, the page will be refreshed with the URL containing the parameter &site=Plant2 which you can read in the variable $_REQUEST['site'] to be used in the 2nd SQL query
{ "language": "en", "url": "https://stackoverflow.com/questions/34835569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the best way to store a Delphi set in a dataset? The title pretty much says it all. I'm using a TClientDataset to store an array of objects, and one of the objects has a member defined as a set of an enumerated type. As I understand it, Delphi sets are bitfields whose size can vary from 1 to 32 bytes depending on how much data they contain, and Delphi doesn't define a TSetField. What sort of field should I use to load this value into? A: You can convert them to Byte, like this: var States : TUpdateStatusSet; // Can be any set, I took this one from DB.pas unit SetAsAInteger: Integer; dbs: Pointer; // Here's the trick begin States := [usModified, usInserted]; // Putting some content in that set dbs := @States; SetAsAInteger := PByte(dbs)^; //Once you got it, SetAsAInteger is just another ordinary integer variable. //Use it the way you like. end; To recover from anywhere: var MSG: string; Inserted, Modified: string; States: TUpdateStatusSet; MySet: Byte; begin while not ClientDataSet.Eof do begin //That's the part that interest us //Convert that integer you stored in the database or whatever //place to a Byte and, in the sequence, to your set type. iSet := Byte(ClientDatasetMyIntegerField);// Sets are one byte, so they // fit on a byte variable States := TUpdateStatusSet(iSet); //Conversion finished, below is just interface stuff if usInserted in States then Inserted := 'Yes'; if usModified in States then Modified := 'Yes'; MSG := Format('Register Num: %d. Inserted: %s. Modified:%s', [ClientDataSet.RecNo, Inserted, Alterted]); ShowMessage( MSG ); ClientDataset.Next; end; end; A: You could use a TBytesField or a TBlobField ClientDataSet1MySet: TBytesField, Size=32 var MySet: set of Byte; Bytes: array of Byte; begin MySet := [1, 2, 4, 8, 16]; // Write Assert(ClientDataSet1MySet.DataSize >= SizeOf(MySet), 'Data field is too small'); SetLength(Bytes, ClientDataSet1MySet.DataSize); Move(MySet, Bytes[0], SizeOf(MySet)); ClientDataSet1.Edit; ClientDataSet1MySet.SetData(@Bytes[0]); ClientDataSet1.Post; // Read SetLength(Bytes, ClientDataSet1MySet.DataSize); if ClientDataSet1MySet.GetData(@Bytes[0]) then Move(Bytes[0], MySet, SizeOf(MySet)) else MySet := []; // NULL end; A: Based on the example of Andreas, but made somewhat simpler and clearer IMHO. Tested on XE2 You could use a TBytesField or a TBlobField ClientDataSet1MySet: TBytesField, Size=32 1) Writing var MySet: set of Byte; Bytes: TBytes; begin MySet := [0]; // Write Assert(ClientDataSet1Test.DataSize >= SizeOf(MySet), 'Data field is too small'); SetLength(Bytes, ClientDataSet1Test.DataSize); Move(MySet, Bytes[0], SizeOf(MySet)); ClientDataSet1.Edit; ClientDataSet1Test.AsBytes := Bytes; ClientDataSet1.Post; end; 2) Reading var MyResultSet: set of Byte; begin Move(ClientDataSet1Test.AsBytes[0], MyResultSet, ClientDataSet1Test.DataSize); end;
{ "language": "en", "url": "https://stackoverflow.com/questions/347592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why parallelizing this code yields almost no performance improvement on six core machine? I am learning parallel programming in Haskell using Simon Marlow's book. In the chapter about parallelizing Sudoku solvers, I decided to write my own solver using backtracking algorithm. The problem is that there is almost no performance gain when I try to distribute 6 cases among 6 cores. When I try to do examples with more cases, I get more significant performance gains yet still far from theoretical maximum which should be between 5 and 6. I understand that some cases may run far slower, but the threadscope diagram shows no excuse for such little gain. Can someone explain me what I am doing wrong. Maybe there is something about ST threads which I am not understanding? Here is the code: Sudoku.hs {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} module Sudoku (getSudokus, solve) where import Data.Vector(Vector, (!), generate, thaw, freeze) import Data.List ( nub ) import qualified Data.Vector.Mutable as MV import Text.Trifecta import Control.Monad ( replicateM, when ) import Control.Applicative ((<|>)) import Control.Monad.ST import Control.DeepSeq (NFData) import GHC.Generics (Generic) data Cell = Given Int | Filled Int | Empty deriving (Generic, NFData) newtype Sudoku = Sudoku (Vector Cell) deriving (Generic, NFData) instance Show Cell where show Empty = " " show (Filled x) = " " ++ show x ++ " " show (Given x) = "[" ++ show x ++ "]" instance Show Sudoku where show (Sudoku vc) = "\n" ++ "+ - - - + - - - + - - - +" ++ "\n" ++ "|" ++ i 0 ++ i 1 ++ i 2 ++ "|" ++ i 3 ++ i 4 ++ i 5 ++ "|" ++ i 6 ++ i 7 ++ i 8 ++ "|" ++ "\n" ++ "|" ++ i 9 ++ i 10 ++ i 11 ++ "|" ++ i 12 ++ i 13 ++ i 14 ++ "|" ++ i 15 ++ i 16 ++ i 17 ++ "|" ++ "\n" ++ "|" ++ i 18 ++ i 19 ++ i 20 ++ "|" ++ i 21 ++ i 22 ++ i 23 ++ "|" ++ i 24 ++ i 25 ++ i 26 ++ "|" ++ "\n" ++ "+ - - - + - - - + - - - +" ++ "\n" ++ "|" ++ i 27 ++ i 28 ++ i 29 ++ "|" ++ i 30 ++ i 31 ++ i 32 ++ "|" ++ i 33 ++ i 34 ++ i 35 ++ "|" ++ "\n" ++ "|" ++ i 36 ++ i 37 ++ i 38 ++ "|" ++ i 39 ++ i 40 ++ i 41 ++ "|" ++ i 42 ++ i 43 ++ i 44 ++ "|" ++ "\n" ++ "|" ++ i 45 ++ i 46 ++ i 47 ++ "|" ++ i 48 ++ i 49 ++ i 50 ++ "|" ++ i 51 ++ i 52 ++ i 53 ++ "|" ++ "\n" ++ "+ - - - + - - - + - - - +" ++ "\n" ++ "|" ++ i 54 ++ i 55 ++ i 56 ++ "|" ++ i 57 ++ i 58 ++ i 59 ++ "|" ++ i 60 ++ i 61 ++ i 62 ++ "|" ++ "\n" ++ "|" ++ i 63 ++ i 64 ++ i 65 ++ "|" ++ i 66 ++ i 67 ++ i 68 ++ "|" ++ i 69 ++ i 70 ++ i 71 ++ "|" ++ "\n" ++ "|" ++ i 72 ++ i 73 ++ i 74 ++ "|" ++ i 75 ++ i 76 ++ i 77 ++ "|" ++ i 78 ++ i 79 ++ i 80 ++ "|" ++ "\n" ++ "+ - - - + - - - + - - - +" ++ "\n" where i x = show (vc ! x) parseSudoku :: Parser Sudoku parseSudoku = do lst <- replicateM 81 field (newline *> return ()) <|> eof return $ Sudoku $ generate 81 (lst !!) where field = (char '.' >> return Empty) <|> (Given . read . return <$> digit) getSudokus :: String -> Maybe [Sudoku] getSudokus raw = case parseString (some parseSudoku) mempty raw of Success ss -> Just ss Failure _ -> Nothing data Direction = Back | Forward solve :: Sudoku -> Maybe Sudoku solve sudoku@(Sudoku puzzle) = if isValid sudoku then Just $ runST $ do puzzle' <- thaw puzzle go puzzle' 0 Forward Sudoku <$> freeze puzzle' else Nothing where go _ 81 _ = return () go vector position direction = do cell <- MV.read vector position case (cell, direction) of (Empty, Back) -> error "Calling back Empty cell, this should not ever occur" (Empty, Forward) -> MV.write vector position (Filled 1) >> go vector position Forward (Given _, Back) -> go vector (position-1) Back (Given _, Forward) -> go vector (position+1) Forward (Filled 10, Back) -> MV.write vector position Empty >> go vector (position-1) Back (Filled 10, Forward) -> go vector position Back (Filled x, Forward) -> do let (r, c, s) = calculatePositions position row <- getRowMV r vector col <- getColumnMV c vector sqr <- getSquareMV s vector if isUnique row && isUnique col && isUnique sqr then go vector (position+1) Forward else MV.write vector position (Filled (x+1)) >> go vector position Forward (Filled x, Back) -> MV.write vector position (Filled (x+1)) >> go vector position Forward calculatePositions :: Int -> (Int, Int, Int) calculatePositions i = let (row, col) = divMod i 9 sqr = (row `div` 3)*3 + (col `div` 3) in (row, col, sqr) isValid :: Sudoku -> Bool isValid sudoku = go 0 where go 9 = True go i = isUnique (getRow i sudoku) && isUnique (getColumn i sudoku) && isUnique (getSquare i sudoku) && go (i+1) getRow :: Int -> Sudoku -> [Cell] getRow l (Sudoku vector) = go 0 where go 9 = [] go c = vector ! (l*9 + c) : go (c+1) getRowMV :: MV.PrimMonad m => Int -> MV.MVector (MV.PrimState m) Cell -> m [Cell] getRowMV l mv = go 0 where go 9 = return [] go c = do n <- MV.read mv (l*9 + c) rl <- go (c+1) return (n:rl) getColumn :: Int -> Sudoku -> [Cell] getColumn c (Sudoku vector) = go 0 where go 9 = [] go i = vector ! (c + i*9) : go (i+1) getColumnMV :: MV.PrimMonad m => Int -> MV.MVector (MV.PrimState m) Cell -> m [Cell] getColumnMV c mv = go 0 where go 9 = return [] go i = do n <- MV.read mv (c + i*9) rl <- go (i+1) return (n:rl) getSquare :: Int -> Sudoku -> [Cell] getSquare q (Sudoku vector) = let (y, x) = quotRem q 3 start = x*3 + y*3*9 in [ vector ! start, vector ! (start + 1), vector ! (start + 2) , vector ! (start + 9), vector ! (start + 10), vector ! (start + 11) , vector ! (start + 18), vector ! (start + 19), vector ! (start + 20)] getSquareMV :: MV.PrimMonad m => Int -> MV.MVector (MV.PrimState m) a -> m [a] getSquareMV q mv = let (y, x) = quotRem q 3 start = x*3 + y*3*9 in do a1 <- MV.read mv start a2 <- MV.read mv (start + 1) a3 <- MV.read mv (start + 2) b1 <- MV.read mv (start + 9) b2 <- MV.read mv (start + 10) b3 <- MV.read mv (start + 11) c1 <- MV.read mv (start + 18) c2 <- MV.read mv (start + 19) c3 <- MV.read mv (start + 20) return [a1,a2,a3,b1,b2,b3,c1,c2,c3] isUnique :: [Cell] -> Bool isUnique xs = let sv = strip xs in length sv == length (nub sv) where strip (Empty:xs) = strip xs strip ((Given x):xs) = x : strip xs strip ((Filled x):xs) = x : strip xs strip [] = [] Main.hs module Main where import Control.Parallel.Strategies import Control.Monad import Control.DeepSeq ( force ) import Sudoku import System.Environment (getArgs) main :: IO () main = do filename <- head <$> getArgs contents <- readFile filename case getSudokus contents of Just sudokus -> print $ runEval $ do start <- forM sudokus (rpar . force . solve) forM start rseq Nothing -> putStrLn "Error during parsing" I am compiling it with following flags: ghc-options: -O2 -rtsopts -threaded -eventlog Execution with following flags: cabal exec sudoku -- sudoku17.6.txt +RTS -N1 -s -l Gives following performance report and threadscope diagram: 950,178,477,200 bytes allocated in the heap 181,465,696 bytes copied during GC 121,832 bytes maximum residency (7 sample(s)) 30,144 bytes maximum slop 7 MiB total memory in use (0 MB lost due to fragmentation) Tot time (elapsed) Avg pause Max pause Gen 0 227776 colls, 0 par 1.454s 1.633s 0.0000s 0.0011s Gen 1 7 colls, 0 par 0.001s 0.001s 0.0001s 0.0002s TASKS: 4 (1 bound, 3 peak workers (3 total), using -N1) SPARKS: 6 (0 converted, 0 overflowed, 0 dud, 0 GC'd, 6 fizzled) INIT time 0.001s ( 0.001s elapsed) MUT time 220.452s (220.037s elapsed) GC time 1.455s ( 1.634s elapsed) EXIT time 0.000s ( 0.008s elapsed) Total time 221.908s (221.681s elapsed) Alloc rate 4,310,140,685 bytes per MUT second Productivity 99.3% of total user, 99.3% of total elapsed Execution with parallelization: cabal exec sudoku -- sudoku17.6.txt +RTS -N6 -s -l 950,178,549,616 bytes allocated in the heap 325,450,104 bytes copied during GC 142,704 bytes maximum residency (7 sample(s)) 82,088 bytes maximum slop 32 MiB total memory in use (0 MB lost due to fragmentation) Tot time (elapsed) Avg pause Max pause Gen 0 128677 colls, 128677 par 37.697s 30.612s 0.0002s 0.0035s Gen 1 7 colls, 6 par 0.005s 0.004s 0.0006s 0.0012s Parallel GC work balance: 11.66% (serial 0%, perfect 100%) TASKS: 14 (1 bound, 13 peak workers (13 total), using -N6) SPARKS: 6 (5 converted, 0 overflowed, 0 dud, 0 GC'd, 1 fizzled) INIT time 0.010s ( 0.009s elapsed) MUT time 355.227s (184.035s elapsed) GC time 37.702s ( 30.616s elapsed) EXIT time 0.001s ( 0.007s elapsed) Total time 392.940s (214.667s elapsed) Alloc rate 2,674,847,755 bytes per MUT second Productivity 90.4% of total user, 85.7% of total elapsed Here are the contents of sudoku17.6.txt: .......2143.......6........2.15..........637...........68...4.....23........7.... .......241..8.............3...4..5..7.....1......3.......51.6....2....5..3...7... .......24....1...........8.3.7...1..1..8..5.....2......2.4...6.5...7.3........... .......23.1..4....5........1.....4.....2...8....8.3.......5.16..4....7....3...... .......21...5...3.4..6.........21...8.......75.....6.....4..8...1..7.....3....... .......215.3......6...........1.4.6.7.....5.....2........48.3...1..7....2........ A: Believe it or not, but your problem potentially had nothing to do with parallelization. In the future I'd recommend you first look at the input to the function you are trying to parallelized. It turned out you always tried a single puzzle. Edit - @Noughtmare pointed out that according to Threadscope results posted in the question there is some parallelization going on. Which is true and it makes me believe that the file posted in question doesn't exactly match the one used for creating the results. If that's the case, then you can skip to Parallelization section for the answer about: "Why parallelizing this code yields almost no performance improvement on six core machine?" Parser Long story short there is a bug in your parser. If you ask my true opinion, it is actually a bug in trifecta package documentation, because it promises to fully consume the input parseString: Fully parse a String to a Result. but instead it consumes the first line only and successfully returns the result. However, honestly, I've never used it before, so maybe it is the expected bahavior. Lets take a look at your parser: parseSudoku :: Parser Sudoku parseSudoku = do lst <- replicateM 81 field (newline *> return ()) <|> eof return $ Sudoku $ generate 81 (lst !!) where field = (char '.' >> return Empty) <|> (Given . read . return <$> digit) At first glance it looks just fine, until input is closely examined. Every empty line between the lines with data also contain a newline character, but your parser expects one at most: .......2143.......6........2.15..........637...........68...4.....23........7.... <this is also a newline> .......241..8.............3...4..5..7.....1......3.......51.6....2....5..3...7... So you parser should instead be: many (newline *> return ()) <|> eof Side note. If it was up to me this is how I would write the parser: parseSudoku :: Parser Sudoku parseSudoku = do (Sudoku <$> V.replicateM 81 field) <* ((() <$ many newline) <|> eof) where field = (Empty <$ char '.') <|> (Given . Data.Char.digitToInt <$> digit) Parallelization When it comes to implementation of parallelization it seems to work fine, but the problem is the work load is really unbalanced. That's why there is only about x2 speed up when using 6 cores. In other words not all puzzles are created equally hard. For that reason solving 6 puzzles using 6 cores in parallel will always get the performance of the longest solution at best. Therefore to gain more from parallelization you either need more puzzles or less CPU cores ;) EDIT: Here are some benchmarks to support my explanation above. These are the results for solving each individual puzzle: And these two are the sequential and parallelized solvers using one core and six cores respectfully. As you can see solving the second puzzle with index 1 took the longest time, which on my computer took a little over a 100 seconds. This is also the time it took for the parallelized algorithm to solve all puzzles. Which makes sense, since all other 5 puzzles were solved much quicker and those cores that were freed up had no other work to do. Also as a sanity check if you sum up the individual times it took for puzzles to be solved it will match up pretty good with the total time it took to solve all of them sequentially.
{ "language": "en", "url": "https://stackoverflow.com/questions/75220688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to use jq syntax within a bash script? The following command works fine if launched in a console: /bin/lshw -quiet -json -C network|/bin/jq '.[1] | .logicalname' Please, note the 1 in square brackets. On my computer this command delivers: root@t15:/home/hmb# /bin/lshw -quiet -json -C network|/bin/jq '.[1] | .logicalname' "wlp9s0" root@t15:/home/hmb# When I tried to use this syntax within a bash script like this: #!/bin/bash # The next line works: test1=$(/bin/lshw -quiet -json -C network|/bin/jq '.[1] | .logicalname') /bin/echo "test1 = $test1" i=1 # This line doesn't: test2=$(/bin/lshw -quiet -json -C network|/bin/jq '.[$i] | .logicalname') /bin/echo "test2 = $test2" ... things don't work as expected: root@t15:/home/hmb/HPT/playground/hmbnetwatch# ./question.sh test1 = "wlp9s0" jq: error: $i is not defined at <top-level>, line 1: .[$i] | .logicalname jq: 1 compile error test2 = root@t15:/home/hmb/HPT/playground/hmbnetwatch# I've tested all methods of escaping for the single quotes which occur in the jq command, but I wasn't able to use a script variable within these squared brackets. I managed to find a way getting the needed information out of lshw by using an array, but out of curiosity and since I invested hours of trial and error without any success, I'd really like to know whether it is impossible to use a variable here or if there is a way. It is said this is a duplicate of Passing bash variable to jq, but I don't think so. The question is why one should not inject a shell variable in the square brackets of jq, which is not really answered elsewhere. A: No, don't inject shell variables into your jq filter! Rather use options provided by jq to introduce them as variables inside jq. In your case, when using a variable that holds a number, --argjson will do: i=1 test2=$(/bin/lshw -quiet -json -C network|/bin/jq --argjson i $i '.[$i] | .logicalname')
{ "language": "en", "url": "https://stackoverflow.com/questions/71394745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Getting and Setting Values for Dynamically Created HTML inputs using Javascript I created "input" elements dynamically in Javascript and am appending and "insertAfter" to a "div" already created. These "inputs" show up but I am unable to get or change their values incrementally which I would need to be using later on. "Input" elements are added for every file in the directory and "id"s are made in order to get and change the values of the input with plus and minus buttons but when I try to get the value I get this error. Uncaught TypeError: Cannot read property 'value' of null The basic code snippets used are shown below: Javascript: $.ajax({ url: "http://localhost:8888/file", success: function(data){ var filename = this.href.replace(window.location.host, "").replace("http://", "").replace("/","").replace(".csv", "");$(data).find("a:contains(" + fileextension + ")").each(function () { if(counter == 0){ $('<div class="col-md-3 ' + counter + '"></div>').appendTo('#stock_types'); $('<a href = "#" onclick="return false; onclick=removing();" class = "is_stock"> </a>').html(filename).appendTo('.'+ counter).attr('id', filename); $('<button type="button" onclick="adding()" class = "btn btn-default plus_"> + </button>').insertAfter($( "#" + filename )).attr('id','plus_'+filename); $('<input class = "stock_amount" name="input_' + filename + '" id = input_'+ filename +' value = "0" ">').insertAfter($( "#plus_" + filename )); $('<button type="button" onclick="subtracting()" class = "btn btn-default minus_"> - </button>').insertAfter($( '#input_' + filename)).attr('id','minus_'+filename); function adding(){ raw_id = ''; raw_id = raw_id + $(this).attr('id'); var new_id = raw_id.replace("plus", "input"); console.log(new_id); current_val = document.getElementById(new_id).value; current_val = current_val + 1; console.log(current_val); }; The ultimate goal for me is getting and incrementing the value of an input that is dynamically created. Thanks in advance. A: $(this).attr('id') This will not work since the function has not been attached to any object (So this will return undefined). You can pass the desired element as an argument to the function. You could do: $('<button type="button" onclick="adding(document.querySelector('.stock_amount')[0])" class = "btn btn-default plus_"> + </button>').insertAfter($( "#" + filename )).attr('id','plus_'+filename); and in the adding function: function adding(input){ raw_id = ''; raw_id = raw_id + $(input).attr('id'); ... } A: jQuery supports dynamic elements out of the box. There's no need for vanilla js with onclick attributes and etc... var btn = $('<button>', { text: ' + ', 'class':'btn btn-default plus' }); function adding(event){ // adding... } btn.on('click', adding).insertAfter($('.....whatever'));
{ "language": "en", "url": "https://stackoverflow.com/questions/36121572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CountIf not automatically calculating My countif function if not calculating automatically - am I missing something? Option Explicit Function my3CountIfs(Rng1 As Range, Criteria1 As String, Rng2 As Range, Criteria2 As String, Rng3 As Range, Criteria3 As String) As Long Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets Select Case ws.Name Case "Summary-Sheet", "Notes", "Results", "Instructions", "Template" ' do nothing Case Else my3CountIfs = my3CountIfs + Application.CountIfs(ws.Range(Rng1.Address), Criteria1, ws.Range(Rng2.Address), Criteria2) End Select Next ws End Function When I use the following command I have to manually click on it and hit return for it to bring up the updated answer =my3COUNTIFS(I49,"Yes",I7,"Yes",I1, "Active") and yes, I have excel set to automatic calculations. Thanks for your help - giving a presentation on this excel sheet tonight and just discovered its not working correctly! - yikes! A: As cyboashu mentioned in the comments, you'll need to put Application.Volatile in the function. But as Rik mentioned, this also can lead to performance issues. This particular post and its answers are relevant to your issue. Just a summary of the options available to you: Function xyz() Application.Volatile 'or Application.Volatile = True in later versions ... End Function Or some manual keypresses * *F9 Recalculates all worksheets in all open workbooks *Shift+ F9 Recalculates the active worksheet *Ctrl+Alt+ F9 Recalculates all worksheets in all open workbooks (Full recalculation) *Shift + Ctrl+Alt+ F9 Rebuilds the dependency tree and does a full recalculation Or an option that worked for me (since I only needed to have my UDFs recalculated each time I ran a specific macro) was to use SendKeys like so: Sub xyz() ... 'Recalculates all formulas by simulating keypresses for {ctrl}{alt}{shift}{F9} SendKeys "^%+{F9}" ... End Sub (Here's the MSDN page for SendKeys)
{ "language": "en", "url": "https://stackoverflow.com/questions/41765395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Grouping bar chart by filtered rows (R) I want to display time series data on a grouped bar chart. I filtered the two variables from one column (x, y). Unfortunately I can't figure out how to display them grouped. Using the code below will stack the bars: library(ggplot2) library(dplyr) target <- c("x", "y") filtered_dat <- filter(dat, column %in% target) ggplot(filtered_dat, aes(year, column)) + geom_col(position = "dodge", stat = "identity", width = 0.7) + geom_text(aes(label = column), colour = "white") Thank you very much for any help. A: The group aes() solves the problem. Therefore I had to group them with the group = column code.
{ "language": "en", "url": "https://stackoverflow.com/questions/73108038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MissingTableException in unit test with hiverunner I have a simple hiverunner tests from - https://github.com/klarna/HiveRunner/blob/master/src/test/java/com/klarna/hiverunner/ExecuteScriptIntegrationTest.java and I want to add it to my multimodule maven project. After adding tests, resources, plugins and dependencies I got an exception. I tried to create the new maven project and add the same to it. It worked successfully. I tried to execute mvn dependency:tree and comparing the result. 2020-04-13T21:11:16,626 WARN DataNucleus.Query:106 - Query for candidates of org.apache.hadoop.hive.metastore.model.MDatabase and subclasses resulted in no possible candidates org.datanucleus.store.rdbms.exceptions.MissingTableException: Required table missing : "DBS" in Catalog "" Schema "". DataNucleus requires this table to perform its persistence operations. Either your MetaData is incorrect, or you need to enable "datanucleus.autoCreateTables" Could you help me to resolve this problem: pom.xml contains <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.klarna</groupId> <artifactId>hiverunner</artifactId> <version>5.1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>provided</scope> </dependency> </dependencies> Working project contains next: +- org.apache.hive:hive-jdbc:jar:2.3.6:compile [INFO] | | +- org.apache.hive:hive-metastore:jar:2.3.6:compile [INFO] | | | +- javolution:javolution:jar:5.5.1:compile [INFO] | | | +- org.apache.hbase:hbase-client:jar:1.1.1:compile [INFO] | | | | +- org.apache.hbase:hbase-annotations:jar:1.1.1:compile [INFO] | | | | +- org.apache.hbase:hbase-protocol:jar:1.1.1:compile [INFO] | | | | +- io.netty:netty-all:jar:4.0.23.Final:compile [INFO] | | | | +- org.jruby.jcodings:jcodings:jar:1.0.8:compile [INFO] | | | | +- org.jruby.joni:joni:jar:2.1.2:compile [INFO] | | | | \- com.github.stephenc.findbugs:findbugs-annotations:jar:1.3.9-1:compile [INFO] | | | +- com.jolbox:bonecp:jar:0.8.0.RELEASE:compile And the unworking version contains | +- org.apache.hive:hive-jdbc:jar:1.2.1:compile [INFO] | | +- org.apache.hive:hive-metastore:jar:1.2.1:compile [INFO] | | | +- com.jolbox:bonecp:jar:0.8.0.RELEASE:compile [INFO] | | | +- org.apache.derby:derby:jar:10.10.2.0:compile [INFO] | | | +- org.datanucleus:datanucleus-api-jdo:jar:3.2.6:compile [INFO] | | | +- org.datanucleus:datanucleus-core:jar:3.2.10:compile [INFO] | | | +- org.datanucleus:datanucleus-rdbms:jar:3.2.9:compile [INFO] | | | +- commons-pool:commons-pool:jar:1.5.4:compile [INFO] | | | +- commons-dbcp:commons-dbcp:jar:1.4:compile [INFO] | | | +- javax.jdo:jdo-api:jar:3.0.1:compile [INFO] | | | | \- javax.transaction:jta:jar:1.1:compile A: You should run the hive schema .sql scripts mentioned in $HIVE_HOME\scripts\metastore\upgrade\mysql. NOTE: I was using MySql as the underlying db for hive.
{ "language": "en", "url": "https://stackoverflow.com/questions/61202463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rename a file with a "unknown" name in C++? A VM creates a file and a .vbs gets it's directory and name. Simply by checking for .m4a files in a directory. (there is only one at a time) and I'd like to rename the file, It says there is no such file or directory though. ifstream infile; infile.open("A:\\Spotify\\Sidifyindex\\indexchecker.txt"); The file says "Z:\Spotify\Sidify test out\01 VVS.m4a" getline(infile, VMin); infile >> VMin; infile.close(); //clear drive letter VMin.erase(0, 1); //add new drive letter VMin = "A" + VMin; //copy file dir string outpath; outpath = VMin; //get new file name outpath.erase(0, 30); outpath = "A:\\Spotify\\Sidify test out\\" + outpath; //convert to const char* const char * c = VMin.c_str(); const char * d = outpath.c_str(); //rename int result; char oldname[] = "VMin.c_str()"; char newname[] = "outpath.c_str()"; result = rename(oldname, newname); if (result == 0) puts("File successfully renamed"); else perror("Error renaming file"); cout << VMin << endl; cout << outpath << endl; I'm getting "Error remaining file: no such file or directory" Output is correct "A:\Spotify\Sidify test out\01 VVS.m4a" and "A:\Spotify\Sidify test out\VVS.m4a" I assume that the issue is hidden somewhere in the rename part A: You wrote: char oldname[] = "VMin.c_str()"; char newname[] = "outpath.c_str()"; but you probably meant to do: char oldname* = VMin.c_str(); char newname* = outpath.c_str(); The first variant will look for a file which is called "VMin.c_str()" which does not exist and thus you are getting this error. You accidentally have put C++ code into quotes. Quotes are only for verbatim strings, like messages and fixed filenames. But your filenames are determined programmatically. You can use the const char * c and d you are calculating above and pass these to rename().
{ "language": "en", "url": "https://stackoverflow.com/questions/54729016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: @ApiImplicitParams ... @Example(value) is ignored I am trying to provide custom JSON example to the body of my request. I am writing @ApiImplicitParams({ @ApiImplicitParam( paramType = "body", //dataType = "com. ... .MyClass", dataType = "java.lang.String", name="payload", examples = @Example(value = { @ExampleProperty(value = "[\"haha\"]", mediaType = MediaType.APPLICATION_JSON_VALUE) }) ) }) public OperationResponse createEntity(@RequestBody MyClass payload ... If @ApiImplicitParams annotation is absent, Swagger draws deserialization of MyClass which is incorrect. I am trying to provide predefined example (haha string). When I am adding @ApiImplicitParams only string appears in the body, hot haha. Why and how to fix?
{ "language": "en", "url": "https://stackoverflow.com/questions/72035446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EJB3/JPA entity with an aggregated attribute I wanted to know if there is a way to get in a One2Many relationship a field of the One side that is an aggregate of the Many side. Let's take the following example: @Entity public class A { @Id private Long id; @OneToMany (mappedBy="parentA") private Collection<B> allBs; // Here I don't know how to Map the latest B by date private B latestB; // Acceptable would be to have : private Date latestBDate; } @Entity public class B { @Id private Long id; private Date date; @ManyToOne (targetEntity=A.class) private A parentA; } My question is how can I make the mapping of the field latestB in the A entity object without doing any de-normalization (not keeping in sync the field with triggers/listeners)? Perhaps this question gives some answers, but really I don't understand how it can work since I still want to be able to fetch all childs objects. Thanks for reading/helping. PS: I use hibernate as ORM/JPA provider, so an Hibernate solution can be provided if no JPA solution exists. PS2: Or just tell me that I should not do this (with arguments of course) ;-) A: I use hibernate as ORM/JPA provider, so an Hibernate solution can be provided if no JPA solution exists. Implementing the acceptable solution (i.e. fetching a Date for the latest B) would be possible using a @Formula. @Entity public class A { @Id private Long id; @OneToMany (mappedBy="parentA") private Collection<B> allBs; @Formula("(select max(b.some_date) from B b where b.a_id = id)") private Date latestBDate; } References * *Hibernate Annotations Reference Guide * *2.4.3.1. Formula Resources * *Hibernate Derived Properties - Performance and Portability A: See, http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Filtering.2C_Complex_Joins Basically JPA does not support this, but some JPA providers do. You could also, - Make the variable transient and lazy initialize it from the OneToMany, or just provide a get method that searches the OneToMany. - Define another foreign key to the latest. - Remove the relationship and just query for the latest.
{ "language": "en", "url": "https://stackoverflow.com/questions/3709010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: react-pose flip animation e.g thumbnail goes full screen want to create a portfolio/projects page where user click on thumbnail it goes full screen and other page comes in i guess i can achieve this using pose-flip https://codesandbox.io/s/fourth-react-pose-example-qj92p problem is how i can do it with multiple elements on page this is the sample site i'm new to react, when i click the thumbnail how to remove all others ( fade ), we can do it simply in jquery not selector
{ "language": "en", "url": "https://stackoverflow.com/questions/59580354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Docker postgres doesn't start at build I want do use a docker container to simulate my production environment, so I installed the db and the server in the same container, and not each in his own. This is my dockerfile: FROM debian RUN apt update RUN apt install postgresql-9.6 tomcat8 tomcat8-admin -y RUN service postgresql start RUN service postgresql status # says postgres is down RUN su - postgres ; RUN createdb db_example # fails !!! RUN psql -c "CREATE USER springuser WITH PASSWORD 'test123';" RUN exit RUN service tomcat8 start COPY target/App-1.0.war /var/lib/tomcat8/webapps/ CMD ["/bin/bash"] The problem is that the database is down so I am uable to create the user and the database. If I start the a debian docker container and do this steps per hand everything works fine. Thanks for your help A: All the recommendations in the comments are correct, it's better to keep services in different containers. Nevertheless and just to let you know, the problem in the Dockerfile is that starting services in RUN statements is useless. For every line in the Dockerfile, docker creates a new image. For example RUN service postgresql start, it may start postgresql during docker build, but it doesn't persist in the final image. Only the filesystem persist from one step to another, not the processes. Every process need to be started in the entrypoint, this is the only command that's called when you exec docker run: FROM debian RUN apt update RUN apt install postgresql-9.6 tomcat8 tomcat8-admin -y COPY target/App-1.0.war /var/lib/tomcat8/webapps/ ENTRYPOINT["/bin/bash", "-c", "service postgresql start && service postgresql status && createdb db_example && psql -c \"CREATE USER springuser WITH PASSWORD 'test123';\" && service tomcat8 start && sleep infinity"] (It may have problems with quotes on psql command) A: I have the problem hat in the war file the localhost for the database war hard coded. Thanks to Light.G, he suggested me to use --net=host for the container, so now there is one container with the database and one with the tomcat server. This are the steps I followed. Build the docker image docker build -t $USER/App . Start a postgres database We are using the host namespace it is not possible to run another programm on the post 5432. Start the postgres container like this: docker run -it --rm --net=host -e POSTGRES_USER='springuser' -e POSTGRES_DB='db_example' -e POSTGRES_PASSWORD='test123' postgres Start the tomcat Start the App container, with this command: docker run -it --net=host --rm $USER/App
{ "language": "en", "url": "https://stackoverflow.com/questions/52493726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plotting a chart from nested JSON list I am trying to plot the price data I took from the CoinGecko API. To get the data itself, I used this command: mbrp = coingecko.get_coin_market_chart_range_by_id("bitcoin","usd","1577836800","1609459200")["prices"] The output of that command looks like this: [[1577836800000, 7195.153895430029],[1577923200000, 7193.7546679601],...,[1609459200000, 29022.41839530417]] Where the first column (1577836800000) is the UNIX date of the data and the second column is the price (7195.153895430029). I didn't know what to do to make this data plottable, so I tried to plot the data directly like this: mbrpdf = pandas.DataFrame(mbrp) mbrpdf.plot() As I expected this approach did not work. I suspect this is because I haven't removed the outer brackets of the output and the UNIX time column. My question is, how do I remove the outer brackets and the first column? Thank you in advance. A: pd.Series's index can be the x axis, and it's values show as y axis . alist = [[1577836800000, 7195.153895430029],[1577923200000, 7193.7546679601],[1609459200000, 29022.41839530417]] df = pd.DataFrame(alist, columns=['ts', 'price']) df['date'] = pd.to_datetime(df['ts'], unit='ms') obj = df.set_index('date')['price'] obj.plot()
{ "language": "en", "url": "https://stackoverflow.com/questions/65714229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When will managed container services (AKS) be available on Azure Government? This article from January 2018 states that AKS will be coming to Azure Government soon. Do we know of a target delivery date? An older post references a target of Q3, but the newer post was more vague. A: The latest and most accurate update on timing of feature availability in Azure Government is always the Azure Government feedback forum. As such, you should go by the date posted in the Azure Container Service (ACS/AKS) in Azure Government feedback entry which at this point in time is preview in CY18Q3. Vote for the feedback entry so that you get updates as they become available. Side note: The Trends in Government Software Developers article dates back to January 2018 whereas the latest response to the dates back to February 2018.
{ "language": "en", "url": "https://stackoverflow.com/questions/50361047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to save image names for multiple arrays? I am trying to save image names in cellImageName in CitySelectViewController (shown as a comment above the line with the error). ViewController.swift var selectedImages = [String : UIImage ]() let cityImages: [String : UIImage] = [ "City00" : UIImage(named: "city_00")! , "City01" :UIImage(named: "city_01")!, "City02" : UIImage(named: "city_02")!] let townImages: [String : UIImage] = [ "Town00" : UIImage(named: "town_00")! , "Town01" :UIImage(named: "town_01")!, "Town02" : UIImage(named: "town_02")!] let cityBImages: [String : UIImage] = [ "CityB00" : UIImage(named: "city_B00")! , "CityB01" :UIImage(named: "city_B01")!, "CityB02" : UIImage(named: "city_B02")!] let townBImages: [String : UIImage] = [ "TownB00" : UIImage(named: "town_B00")! , "TownB01" :UIImage(named: "town_B01")!, "TownB02" : UIImage(named: "town_B02")!] func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell // Ambiguous reference to member 'subscript' cell.imageView?.image = self.selectedImages[(indexPath as NSIndexPath).item] return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showOptions" { let indexPaths = self.collectionView!.indexPathsForSelectedItems! var indexPath = indexPaths[0] as IndexPath let CityVC = segue.destination as! CitySelectViewController if (indexPath.row == 2) { if self.areas == city { CityVC.imageSelected = cityBImages } else if self.areas == town { CityVC.imageSelected = townBImages } else // Ambiguous reference to member 'subscript' CityVC.imageSelected = self.selectedImages[(indexPath as NSIndexPath).item] } How do I get rid of these errors? This is `CitySelectViewController.swift` func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.imageSelected.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CityCollectionViewCell cell.imageView?.image = imageSelected[(indexPath as NSIndexPath).row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) cellImage = imageSelected[(indexPath as NSIndexPath).row] cellImageName = imageSelected[(indexPath as NSIndexPath).row] } A: Based on the code in my answer to your previous question You can simply create an array of arrays and put each array into its own section in the collection view: struct City { var name: String var imageName: String } class firstViewController: UIViewController // Or UICollectionViewController let cities = [City(name:"City00", imageName:"city_00"), City(name:"City01", imageName:"city_01"), City(name:"City02", imageName:"city_02")] let towns = [City(name:"Town00", imageName:"town_00"), City(name:"Town01", imageName:"town_01"), City(name:"Town02", imageName:"town_02")] let villages = [City(name:"Village00", imageName:"village_00"), City(name:"Village01", imageName:"village_01"), City(name:"Village02", imageName:"village_02")] let allPlaces = [cities, towns, villages] func numberOfSections(in collectionView: UICollectionView) -> Int { return self.allPlaces.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let places = self.allPlaces[section] return places.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell let places = self.allCities[indexPath.section] let city = places[indexPath.item] cell.imageView?.image = UIImage(named:city.imageName) return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showOptions" { if let indexPaths = self.collectionView!.indexPathsForSelectedItems { if let cityVC = segue.destination as? CitySelectViewController { var selectedCities = [City]() for indexPath in indexPaths { let places = self.allPlaces[indexPath.section] selectedCities.append(places[indexPath.item]) } cityVC.selectedCities = selectedCities } } } } A: first of all your selectedImage is never filled (or at least in the code you provide) so its always an empty dictionary. secondly why you downcast IndexPath to NSIndexpath in cellForItemAt? cell.imageView?.image = imageSelected[(indexPath as NSIndexPath).row] also your dictionary is type of [String : UIImage] and you're treating it as [Int : UIImage]. also when you are going to use indexpath you can use array instead of [Int, UIImage].
{ "language": "en", "url": "https://stackoverflow.com/questions/41115241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access the .csv file directory through array I have created save button which I guess going to create a .csv file to store x,y and name of the object on screen since I can't check it because I can't access the file its created @IBAction func saveButton(_ sender: Any) { let objectsName = stringObjectName.joined(separator: ",") let coX = stringObjectX.joined(separator: ",") let coY = stringObjectY.joined(separator: ",") let fileName = getDocumentsDirectory().appendingPathComponent("output.csv") CSVFilesName.append(fileName) var csvText = "Name, Data X, Data Y\n" let count = stringObjectName.count if count > 0 { for _ in 0..<(stringObjectName.count-1) { let newLine = "\(objectsName),\(coX),\(coY)\n" csvText.append(contentsOf: newLine) } } do { try csvText.write(to: fileName, atomically: true, encoding: String.Encoding.utf8) } catch { print("error") } print(fileName) } after this I try to access the file call "output.csv" which it is suppose to store in document directory in another viewport. So, I created the method to pass the method from another view controller to current view controller by using and store CSVFile var CSVFileName = [URL]() func assignArray() { let cameraVC = CameraViewController() CSVFileName = cameraVC.CSVFilesName print(CSVFileName) } and the problem start here since I have array which suppose to store file name in String let fileNames = ["sth1.csv", "sth2.csv"] but I can't find the convert CSVFileName from saving button to String, and replace "static array" into "dynamic array" and change the method below to get URL from FileManager().default.url instead of fileURL to give TableViewController data to show and accessible private func prepareFileURLS() { for file in fileNames { let fileParts = file.components(separatedBy: ".") print(fileParts[0]) if let fileURL = Bundle.main.url(forResource: fileParts[0], withExtension: fileParts[1]) { if FileManager.default.fileExists(atPath: fileURL.path) { print(fileURL) fileURLs.append(fileURL as NSURL) } } } print(fileURLs) } A: Here is the way you can read Your CSV file : func filterMenuCsvData() { do { // This solution assumes you've got the file in your bundle if let path = Bundle.main.path(forResource: "products_category", ofType: "csv"){ // STORE CONTENT OF FILE IN VARIABLE let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8) var rows : [String] = [] var readData = [String]() rows = data.components(separatedBy: "\n") for data in 0..<rows.count - 1{ if data == 0 || rows[data].contains(""){ continue } readData = rows[data].components(separatedBy: ",") Category.append(readData[0]) if readData[2] != ""{ Occassions.append(readData[2]) } selectedOccassionsRadioButtonIndex = Array(repeating: false, count: Occassions.count) selectedCategoryRadioButtonIndex = Array(repeating: false, count: Category.count) } } } catch let err as NSError { // do something with Error} print(err) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/46061564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProcessFrameUsingD3D11() vs ProcessFrameUsingXVP() in DX11VideoRenderer? I'm attempting to render video using using the Microsoft sample DX11VideoRenderer found at: https://github.com/Microsoft/Windows-classic-samples/tree/master/Samples/DX11VideoRenderer From my extensive research it seems that using DirectX 11 with hardware-acceleration is the most up-to-date method (least likely to be deprecated) and offers the best performance solution. There are 2 similar functions within Presenter.cpp that process frames but I cannot figure out what the difference is between them. ProcessFrameUsingD3D11()uses VideoProcessorBlt() to actually do the render. The mystery is that ProcessFrameUsingXVP() does not use this function so how does it actually do the render? Or is it doing something else entirely? Also it appears that my implementation is using ProcessFrameUsingXVP()based in the value of the variable m_useXVP which is by default set to '1'. Here is the code sample: if (m_useXVP) { BOOL bInputFrameUsed = FALSE; hr = ProcessFrameUsingXVP( pCurrentType, pSample, pTexture2D, rcDest, ppOutputSample, &bInputFrameUsed ); if (SUCCEEDED(hr) && !bInputFrameUsed) { *pbProcessAgain = TRUE; } } else { hr = ProcessFrameUsingD3D11( pTexture2D, pEVTexture2D, dwViewIndex, dwEVViewIndex, rcDest, *punInterlaceMode, ppOutputSample ); LONGLONG hnsDuration = 0; LONGLONG hnsTime = 0; DWORD dwSampleFlags = 0; if (ppOutputSample != NULL && *ppOutputSample != NULL) { if (SUCCEEDED(pSample->GetSampleDuration(&hnsDuration))) { (*ppOutputSample)->SetSampleDuration(hnsDuration); } if (SUCCEEDED(pSample->GetSampleTime(&hnsTime))) { (*ppOutputSample)->SetSampleTime(hnsTime); } if (SUCCEEDED(pSample->GetSampleFlags(&dwSampleFlags))) { (*ppOutputSample)->SetSampleFlags(dwSampleFlags); } } } The reason for setting m_useXVP is also a mystery to me and I cannot find an answer in my research. It uses a registry key that does not exist on my particular Windows10 PC so the value is not modified. const TCHAR* lpcszInVP = TEXT("XVP"); const TCHAR* lpcszREGKEY = TEXT("SOFTWARE\\Microsoft\\Scrunch\\CodecPack\\MSDVD"); if(0 == RegOpenKeyEx(HKEY_CURRENT_USER, lpcszREGKEY, 0, KEY_READ, &hk)) { dwData = 0; cbData = sizeof(DWORD); if (0 == RegQueryValueEx(hk, lpcszInVP, 0, &cbType, (LPBYTE)&dwData, &cbData)) { m_useXVP = dwData; } } So since my PC does not have this key, the code is defaulting to using ProcessFrameUsingXVP(). Here is the definition: HRESULT DX11VideoRenderer::CPresenter::ProcessFrameUsingXVP(IMFMediaType* pCurrentType, IMFSample* pVideoFrame, ID3D11Texture2D* pTexture2D, RECT rcDest, IMFSample** ppVideoOutFrame, BOOL* pbInputFrameUsed) { HRESULT hr = S_OK; ID3D11VideoContext* pVideoContext = NULL; ID3D11Texture2D* pDXGIBackBuffer = NULL; IMFSample* pRTSample = NULL; IMFMediaBuffer* pBuffer = NULL; IMFAttributes* pAttributes = NULL; D3D11_VIDEO_PROCESSOR_CAPS vpCaps = { 0 }; do { if (!m_pDX11VideoDevice) { hr = m_pD3D11Device->QueryInterface(__uuidof(ID3D11VideoDevice), (void**)&m_pDX11VideoDevice); if (FAILED(hr)) { break; } } hr = m_pD3DImmediateContext->QueryInterface(__uuidof(ID3D11VideoContext), (void**)&pVideoContext); if (FAILED(hr)) { break; } // remember the original rectangles RECT TRectOld = m_rcDstApp; RECT SRectOld = m_rcSrcApp; UpdateRectangles(&TRectOld, &SRectOld); //Update destination rect with current client rect m_rcDstApp = rcDest; D3D11_TEXTURE2D_DESC surfaceDesc; pTexture2D->GetDesc(&surfaceDesc); BOOL fTypeChanged = FALSE; if (!m_pVideoProcessorEnum || !m_pSwapChain1 || m_imageWidthInPixels != surfaceDesc.Width || m_imageHeightInPixels != surfaceDesc.Height) { SafeRelease(m_pVideoProcessorEnum); SafeRelease(m_pSwapChain1); m_imageWidthInPixels = surfaceDesc.Width; m_imageHeightInPixels = surfaceDesc.Height; fTypeChanged = TRUE; D3D11_VIDEO_PROCESSOR_CONTENT_DESC ContentDesc; ZeroMemory(&ContentDesc, sizeof(ContentDesc)); ContentDesc.InputFrameFormat = D3D11_VIDEO_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST; ContentDesc.InputWidth = surfaceDesc.Width; ContentDesc.InputHeight = surfaceDesc.Height; ContentDesc.OutputWidth = surfaceDesc.Width; ContentDesc.OutputHeight = surfaceDesc.Height; ContentDesc.Usage = D3D11_VIDEO_USAGE_PLAYBACK_NORMAL; hr = m_pDX11VideoDevice->CreateVideoProcessorEnumerator(&ContentDesc, &m_pVideoProcessorEnum); if (FAILED(hr)) { break; } m_rcSrcApp.left = 0; m_rcSrcApp.top = 0; m_rcSrcApp.right = m_uiRealDisplayWidth; m_rcSrcApp.bottom = m_uiRealDisplayHeight; if (m_b3DVideo) { hr = m_pVideoProcessorEnum->GetVideoProcessorCaps(&vpCaps); if (FAILED(hr)) { break; } if (vpCaps.FeatureCaps & D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_STEREO) { m_bStereoEnabled = TRUE; } DXGI_MODE_DESC1 modeFilter = { 0 }; modeFilter.Format = DXGI_FORMAT_B8G8R8A8_UNORM; modeFilter.Width = surfaceDesc.Width; modeFilter.Height = surfaceDesc.Height; modeFilter.Stereo = m_bStereoEnabled; DXGI_MODE_DESC1 matchedMode; if (m_bFullScreenState) { hr = m_pDXGIOutput1->FindClosestMatchingMode1(&modeFilter, &matchedMode, m_pD3D11Device); if (FAILED(hr)) { break; } } hr = m_pXVP->GetAttributes(&pAttributes); if (FAILED(hr)) { break; } hr = pAttributes->SetUINT32(MF_ENABLE_3DVIDEO_OUTPUT, (0 != m_vp3DOutput) ? MF3DVideoOutputType_Stereo : MF3DVideoOutputType_BaseView); if (FAILED(hr)) { break; } } } // now create the input and output media types - these need to reflect // the src and destination rectangles that we have been given. RECT TRect = m_rcDstApp; RECT SRect = m_rcSrcApp; UpdateRectangles(&TRect, &SRect); const BOOL fDestRectChanged = !EqualRect(&TRect, &TRectOld); const BOOL fSrcRectChanged = !EqualRect(&SRect, &SRectOld); if (!m_pSwapChain1 || fDestRectChanged) { hr = UpdateDXGISwapChain(); if (FAILED(hr)) { break; } } if (fTypeChanged || fSrcRectChanged || fDestRectChanged) { // stop streaming to avoid multiple start\stop calls internally in XVP hr = m_pXVP->ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0); if (FAILED(hr)) { break; } if (fTypeChanged) { hr = SetXVPOutputMediaType(pCurrentType, DXGI_FORMAT_B8G8R8A8_UNORM); if (FAILED(hr)) { break; } } if (fDestRectChanged) { hr = m_pXVPControl->SetDestinationRectangle(&m_rcDstApp); if (FAILED(hr)) { break; } } if (fSrcRectChanged) { hr = m_pXVPControl->SetSourceRectangle(&SRect); if (FAILED(hr)) { break; } } hr = m_pXVP->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0); if (FAILED(hr)) { break; } } m_bCanProcessNextSample = FALSE; // Get Backbuffer hr = m_pSwapChain1->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pDXGIBackBuffer); if (FAILED(hr)) { break; } // create the output media sample hr = MFCreateSample(&pRTSample); if (FAILED(hr)) { break; } hr = MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pDXGIBackBuffer, 0, FALSE, &pBuffer); if (FAILED(hr)) { break; } hr = pRTSample->AddBuffer(pBuffer); if (FAILED(hr)) { break; } if (m_b3DVideo && 0 != m_vp3DOutput) { SafeRelease(pBuffer); hr = MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pDXGIBackBuffer, 1, FALSE, &pBuffer); if (FAILED(hr)) { break; } hr = pRTSample->AddBuffer(pBuffer); if (FAILED(hr)) { break; } } DWORD dwStatus = 0; MFT_OUTPUT_DATA_BUFFER outputDataBuffer = {}; outputDataBuffer.pSample = pRTSample; hr = m_pXVP->ProcessOutput(0, 1, &outputDataBuffer, &dwStatus); if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) { //call process input on the MFT to deliver the YUV video sample // and the call process output to extract of newly processed frame hr = m_pXVP->ProcessInput(0, pVideoFrame, 0); if (FAILED(hr)) { break; } *pbInputFrameUsed = TRUE; hr = m_pXVP->ProcessOutput(0, 1, &outputDataBuffer, &dwStatus); if (FAILED(hr)) { break; } } else { *pbInputFrameUsed = FALSE; } if (ppVideoOutFrame != NULL) { *ppVideoOutFrame = pRTSample; (*ppVideoOutFrame)->AddRef(); } } while (FALSE); SafeRelease(pAttributes); SafeRelease(pBuffer); SafeRelease(pRTSample); SafeRelease(pDXGIBackBuffer); SafeRelease(pVideoContext); return hr; } And here is the definition of ProcessFrameUsingD3D11() : HRESULT DX11VideoRenderer::CPresenter::ProcessFrameUsingD3D11( ID3D11Texture2D* pLeftTexture2D, ID3D11Texture2D* pRightTexture2D, UINT dwLeftViewIndex, UINT dwRightViewIndex, RECT rcDest, UINT32 unInterlaceMode, IMFSample** ppVideoOutFrame ) { HRESULT hr = S_OK; ID3D11VideoContext* pVideoContext = NULL; ID3D11VideoProcessorInputView* pLeftInputView = NULL; ID3D11VideoProcessorInputView* pRightInputView = NULL; ID3D11VideoProcessorOutputView* pOutputView = NULL; ID3D11Texture2D* pDXGIBackBuffer = NULL; ID3D11RenderTargetView* pRTView = NULL; IMFSample* pRTSample = NULL; IMFMediaBuffer* pBuffer = NULL; D3D11_VIDEO_PROCESSOR_CAPS vpCaps = {0}; LARGE_INTEGER lpcStart,lpcEnd; do { if (!m_pDX11VideoDevice) { hr = m_pD3D11Device->QueryInterface(__uuidof(ID3D11VideoDevice), (void**)&m_pDX11VideoDevice); if (FAILED(hr)) { break; } } hr = m_pD3DImmediateContext->QueryInterface(__uuidof( ID3D11VideoContext ), (void**)&pVideoContext); if (FAILED(hr)) { break; } // remember the original rectangles RECT TRectOld = m_rcDstApp; RECT SRectOld = m_rcSrcApp; UpdateRectangles(&TRectOld, &SRectOld); //Update destination rect with current client rect m_rcDstApp = rcDest; D3D11_TEXTURE2D_DESC surfaceDesc; pLeftTexture2D->GetDesc(&surfaceDesc); if (!m_pVideoProcessorEnum || !m_pVideoProcessor || m_imageWidthInPixels != surfaceDesc.Width || m_imageHeightInPixels != surfaceDesc.Height) { SafeRelease(m_pVideoProcessorEnum); SafeRelease(m_pVideoProcessor); m_imageWidthInPixels = surfaceDesc.Width; m_imageHeightInPixels = surfaceDesc.Height; D3D11_VIDEO_PROCESSOR_CONTENT_DESC ContentDesc; ZeroMemory( &ContentDesc, sizeof( ContentDesc ) ); ContentDesc.InputFrameFormat = D3D11_VIDEO_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST; ContentDesc.InputWidth = surfaceDesc.Width; ContentDesc.InputHeight = surfaceDesc.Height; ContentDesc.OutputWidth = surfaceDesc.Width; ContentDesc.OutputHeight = surfaceDesc.Height; ContentDesc.Usage = D3D11_VIDEO_USAGE_PLAYBACK_NORMAL; hr = m_pDX11VideoDevice->CreateVideoProcessorEnumerator(&ContentDesc, &m_pVideoProcessorEnum); if (FAILED(hr)) { break; } UINT uiFlags; DXGI_FORMAT VP_Output_Format = DXGI_FORMAT_B8G8R8A8_UNORM; hr = m_pVideoProcessorEnum->CheckVideoProcessorFormat(VP_Output_Format, &uiFlags); if (FAILED(hr) || 0 == (uiFlags & D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_OUTPUT)) { hr = MF_E_UNSUPPORTED_D3D_TYPE; break; } m_rcSrcApp.left = 0; m_rcSrcApp.top = 0; m_rcSrcApp.right = m_uiRealDisplayWidth; m_rcSrcApp.bottom = m_uiRealDisplayHeight; DWORD index; hr = FindBOBProcessorIndex(&index); // GG This may not be needed. BOB is something to do with deinterlacing. if (FAILED(hr)) { break; } hr = m_pDX11VideoDevice->CreateVideoProcessor(m_pVideoProcessorEnum, index, &m_pVideoProcessor); if (FAILED(hr)) { break; } if (m_b3DVideo) { hr = m_pVideoProcessorEnum->GetVideoProcessorCaps(&vpCaps); if (FAILED(hr)) { break; } if (vpCaps.FeatureCaps & D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_STEREO) { m_bStereoEnabled = TRUE; } DXGI_MODE_DESC1 modeFilter = { 0 }; modeFilter.Format = DXGI_FORMAT_B8G8R8A8_UNORM; modeFilter.Width = surfaceDesc.Width; modeFilter.Height = surfaceDesc.Height; modeFilter.Stereo = m_bStereoEnabled; DXGI_MODE_DESC1 matchedMode; if (m_bFullScreenState) { hr = m_pDXGIOutput1->FindClosestMatchingMode1(&modeFilter, &matchedMode, m_pD3D11Device); if (FAILED(hr)) { break; } } } } // now create the input and output media types - these need to reflect // the src and destination rectangles that we have been given. RECT TRect = m_rcDstApp; RECT SRect = m_rcSrcApp; UpdateRectangles(&TRect, &SRect); const BOOL fDestRectChanged = !EqualRect(&TRect, &TRectOld); if (!m_pSwapChain1 || fDestRectChanged) { hr = UpdateDXGISwapChain(); if (FAILED(hr)) { break; } } m_bCanProcessNextSample = FALSE; // Get Backbuffer hr = m_pSwapChain1->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pDXGIBackBuffer); if (FAILED(hr)) { break; } // create the output media sample hr = MFCreateSample(&pRTSample); if (FAILED(hr)) { break; } hr = MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pDXGIBackBuffer, 0, FALSE, &pBuffer); if (FAILED(hr)) { break; } hr = pRTSample->AddBuffer(pBuffer); if (FAILED(hr)) { break; } // GG For 3D - don't need. if (m_b3DVideo && 0 != m_vp3DOutput) { SafeRelease(pBuffer); hr = MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pDXGIBackBuffer, 1, FALSE, &pBuffer); if (FAILED(hr)) { break; } hr = pRTSample->AddBuffer(pBuffer); if (FAILED(hr)) { break; } } QueryPerformanceCounter(&lpcStart); QueryPerformanceCounter(&lpcEnd); // // Create Output View of Output Surfaces. // D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC OutputViewDesc; ZeroMemory( &OutputViewDesc, sizeof( OutputViewDesc ) ); if (m_b3DVideo && m_bStereoEnabled) { OutputViewDesc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2DARRAY; } else { OutputViewDesc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D; } OutputViewDesc.Texture2D.MipSlice = 0; OutputViewDesc.Texture2DArray.MipSlice = 0; OutputViewDesc.Texture2DArray.FirstArraySlice = 0; if (m_b3DVideo && 0 != m_vp3DOutput) { OutputViewDesc.Texture2DArray.ArraySize = 2; // STEREO } QueryPerformanceCounter(&lpcStart); hr = m_pDX11VideoDevice->CreateVideoProcessorOutputView(pDXGIBackBuffer, m_pVideoProcessorEnum, &OutputViewDesc, &pOutputView); if (FAILED(hr)) { break; } D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC InputLeftViewDesc; ZeroMemory( &InputLeftViewDesc, sizeof( InputLeftViewDesc ) ); InputLeftViewDesc.FourCC = 0; InputLeftViewDesc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D; InputLeftViewDesc.Texture2D.MipSlice = 0; InputLeftViewDesc.Texture2D.ArraySlice = dwLeftViewIndex; hr = m_pDX11VideoDevice->CreateVideoProcessorInputView(pLeftTexture2D, m_pVideoProcessorEnum, &InputLeftViewDesc, &pLeftInputView); if (FAILED(hr)) { break; } if (m_b3DVideo && MFVideo3DSampleFormat_MultiView == m_vp3DOutput && pRightTexture2D) { D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC InputRightViewDesc; ZeroMemory( &InputRightViewDesc, sizeof( InputRightViewDesc ) ); InputRightViewDesc.FourCC = 0; InputRightViewDesc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D; InputRightViewDesc.Texture2D.MipSlice = 0; InputRightViewDesc.Texture2D.ArraySlice = dwRightViewIndex; hr = m_pDX11VideoDevice->CreateVideoProcessorInputView(pRightTexture2D, m_pVideoProcessorEnum, &InputRightViewDesc, &pRightInputView); if (FAILED(hr)) { break; } } QueryPerformanceCounter(&lpcEnd); QueryPerformanceCounter(&lpcStart); SetVideoContextParameters(pVideoContext, &SRect, &TRect, unInterlaceMode); // Enable/Disable Stereo if (m_b3DVideo) { pVideoContext->VideoProcessorSetOutputStereoMode(m_pVideoProcessor, m_bStereoEnabled); D3D11_VIDEO_PROCESSOR_STEREO_FORMAT vpStereoFormat = D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_SEPARATE; if (MFVideo3DSampleFormat_Packed_LeftRight == m_vp3DOutput) { vpStereoFormat = D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_HORIZONTAL; } else if (MFVideo3DSampleFormat_Packed_TopBottom == m_vp3DOutput) { vpStereoFormat = D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_VERTICAL; } pVideoContext->VideoProcessorSetStreamStereoFormat(m_pVideoProcessor, 0, m_bStereoEnabled, vpStereoFormat, TRUE, TRUE, D3D11_VIDEO_PROCESSOR_STEREO_FLIP_NONE, 0); } QueryPerformanceCounter(&lpcEnd); QueryPerformanceCounter(&lpcStart); D3D11_VIDEO_PROCESSOR_STREAM StreamData; ZeroMemory( &StreamData, sizeof( StreamData ) ); StreamData.Enable = TRUE; StreamData.OutputIndex = 0; StreamData.InputFrameOrField = 0; StreamData.PastFrames = 0; StreamData.FutureFrames = 0; StreamData.ppPastSurfaces = NULL; StreamData.ppFutureSurfaces = NULL; StreamData.pInputSurface = pLeftInputView; StreamData.ppPastSurfacesRight = NULL; StreamData.ppFutureSurfacesRight = NULL; if (m_b3DVideo && MFVideo3DSampleFormat_MultiView == m_vp3DOutput && pRightTexture2D) { StreamData.pInputSurfaceRight = pRightInputView; } hr = pVideoContext->VideoProcessorBlt(m_pVideoProcessor, pOutputView, 0, 1, &StreamData ); if (FAILED(hr)) { break; } QueryPerformanceCounter(&lpcEnd); if (ppVideoOutFrame != NULL) { *ppVideoOutFrame = pRTSample; (*ppVideoOutFrame)->AddRef(); } } while (FALSE); SafeRelease(pBuffer); SafeRelease(pRTSample); SafeRelease(pDXGIBackBuffer); SafeRelease(pOutputView); SafeRelease(pLeftInputView); SafeRelease(pRightInputView); SafeRelease(pVideoContext); return hr; } One last note, the documentation states that: Specifically, this sample shows how to: * *Decode the video using the Media Foundation APIs *Render the decoded video using the DirectX 11 APIs *Output the video stream to multi-monitor displays I cannot find anything that does decoding unless by some MF magic chant phrase that I haven't stumbled across yet. But it's not a showstopper because I can stick an H.264 decoder MFT in front no problem. I would just like to clarify the documentation. Any help would be much appreciated. Thank you! A: There are 2 similar functions within Presenter.cpp that process frames but I cannot figure out what the difference is between them. ProcessFrameUsingD3D11()uses VideoProcessorBlt() to actually do the render. The functions are not rendering - they are two ways to scale video frames. Scaling might be done with a readily available Media Foundation transform internally managed by the renderer's presenter, or scaling might be done with the help of Direct3D 11 processor. Actually both utilize Direct3D 11, so the two methods are close one to another and are just one step in the rendering process. I cannot find anything that does decoding unless by some MF magic chant phrase that I haven't stumbled across yet. There is no decoding and the list of sink video formats in StreamSink.cpp suggests that by only listing uncompressed video formats. The renderer presents frames carried by Direct3D 11 textures, which in turn assumes that a decode, esp. hardware decoder such as DXVA2 based already supplies the decoded textures on the renderer input.
{ "language": "en", "url": "https://stackoverflow.com/questions/50136565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to get a listing of attributes and ranges for an NSMutableAttributedString? I've created a method that takes a NSAttributedString and I'm looking to dynamically create a subview and label to put the string into. Because attributes like font and size need to be determined to correctly determine the size of the label, I need to determine if it is possible to iterate through values and ranges that have been applied to the attributed string? I understand that I could pass the attributes separately, but for sake of reusability, i'd like to be able to pass as few parameters to the method as possible. A: Swift 3: // in case, that you have defined `attributedText` of label var attributes = attributedText.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, attributedText.length)) ... A: Swift 4: If you want to get the attributes for NSTextAttachment (just change the attribute value if you want font) commentTextView.attributedText.enumerateAttribute(NSAttachmentAttributeName, in:NSMakeRange(0, commentTextView.attributedText.length), options:.longestEffectiveRangeNotRequired) { value, range, stop in if let attachment = value as? NSTextAttachment { print("GOT AN ATTACHMENT! for comment at \(indexPath.row)") } } A: Apple expects you to use enumerateAttributesInRange:options:usingBlock:. The block you supply will receive ranges and the attributes applicable for that range. I've used that in my code to create invisible buttons that are placed behind text so that it acts as a hyperlink. You could also use enumerateAttribute:inRange:options:usingBlock: if there's only one you're interested in, but no halfway house is provided where you might be interested in, say, two attributes but not every attribute. A: Apple's Docs have a number of methods to access attributes: To retrieve attribute values from either type of attributed string, use any of these methods: attributesAtIndex:effectiveRange: attributesAtIndex:longestEffectiveRange:inRange: attribute:atIndex:effectiveRange: attribute:atIndex:longestEffectiveRange:inRange: fontAttributesInRange: rulerAttributesInRange: A: If you need all of the attributes from the string in the entire range, use this code: NSDictionary *attributesFromString = [stringWithAttributes attributesAtIndex:0 longestEffectiveRange:nil inRange:NSMakeRange(0, stringWithAttributes.length)]; A: Swift 5 – 4 let attributedText = NSAttributedString(string: "Hello, playground", attributes: [ .foregroundColor: UIColor.red, .backgroundColor: UIColor.green, .ligature: 1, .strikethroughStyle: 1 ]) // retrieve attributes let attributes = attributedText.attributes(at: 0, effectiveRange: nil) // iterate each attribute for attr in attributes { print(attr.key, attr.value) } In case, that you have defined attributedText of label. Swift 3 var attributes = attributedText.attributes( at: 0, longestEffectiveRange: nil, in: NSRange(location: 0, length: attributedText.length) ) Swift 2.2 var attributes = attributedText.attributesAtIndex(0, longestEffectiveRange: nil, inRange: NSMakeRange(0, attributedText.length) ) A: I have modified one of the answers with suggested fixes to prevent infinite recursion and application crashes. @IBDesignable extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor { return color } return nil } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[.foregroundColor: newValue!]) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/19844336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "68" }
Q: how to remove active record object from array I have set of active record object in array. I just want to delete on object from array not in database a = Model.limit(2) b = Model.first a.delete(b) returning nil value Its not deleting is there anyway? A: This is what you need: objects_in_db = Model.all objects_in_array = Model.first(2) objects_in_array.delete_if { |obj| !objects_in_db.include?(obj)} In your case, Model.limit(2) may not return the first two object and so the array a may not contain b and hence, it returns nil. A: a.to_a - [b] Background: a.to_a convertrs the relation into an array in in memory. [b] is an array whith just the element, you want to delete (in memory). a.to_a - [b] does an array substraction. (In Rails 3.2 .to_a was applied automatically to a relation when it was accessed. I agree with gregates: It's better to convert the relation to an array explicitly) A: There's potentially some confusion here because in ActiveRecord, Model.limit(2) does not return an array. Model.limit(2).class #=> ActiveRecordRelation So when you call a.delete(b), you may not be calling Array#delete. Try this instead: a = Model.limit(2).to_a # Executes the query and returns an array b = Model.first a.delete(b)
{ "language": "en", "url": "https://stackoverflow.com/questions/16883709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Sort by date but group similar fields I am new to Stack Overflow and to ASP, but this site has bailed me out many times! I am very unfamiliar with ASP and VBS but more familiar with PHP, so if there is a PHP solution to my problem, that will be okay too. A little background - My access DB has two tables (that are relevant to this query) one is called SignUpLog and the other Notes. The SignUpLog.FirstNoteAddr field corresponds to the Notes.NoteKey field in the other table. I've been successful in showing all the entries in the DB, but what I'd like to do is group all entries for a specific patient together in one row, while still ordering by date (newest at top). Here's my code: Set DataConn = Server.CreateObject("ADODB.Connection") Set RS = Server.CreateObject("ADODB.RecordSet") DataConn.Open "DBQ=" & Server.Mappath("/path/to/mydb") & ";Driver={Microsoft Access Driver (*.mdb)};Uid=user;Pwd=pass;" Set rsDsp = DataConn.Execute("SELECT SignUpLog.PatientFileNumber, SignUpLog.ArrivalDateTime, Notes.Note, SignUpLog.Called, SignUpLog.DrName FROM SignUpLog, Notes WHERE (((Notes.NoteKey)=[SignUpLog].[FirstNoteAddr])) ORDER BY SignUpLog.ArrivalDateTime DESC;") If rsDsp.EOF Then Response.Write "Sorry, no entries in the database!" Else %> <div align="center"><center> <table BORDER="0" width="700"> <tr> <th width="105">Name</th> <th width="105">Arrival Time</th> <th width="105">Doctor</th> <th width="105">Notes</th> </tr> <% While Not rsDsp.EOF x = x + 1 If x = 1 Then Response.Write "<TR><TD>" & rsDsp.Fields.Item("PatientFileNumber").Value & "</TD>" Response.Write "<TD>" & rsDsp("ArrivalDateTime").Value & "</TD>" Response.Write "<TD>" & rsDsp("DrName").Value & "</TD>" Response.Write "<TD>" & rsDsp("Note").Value & "</TD></TR>" Else Response.Write "<TR><TD BGCOLOR=E4E4E4>" & rsDsp.Fields.Item("PatientFileNumber").Value & "</TD>" Response.Write "<TD BGCOLOR=E4E4E4>" & rsDsp("ArrivalDateTime").Value & "</TD>" Response.Write "<TD BGCOLOR=E4E4E4>" & rsDsp("DrName").Value & "</TD>" Response.Write "<TD BGCOLOR=E4E4E4>" & rsDsp("Note").Value & "</TD></TR>" x = 0 End If rsDsp.MoveNext Wend Response.Write "</TABLE>" DataConn.Close End If %> </table> </center></div> This gives me an output similar to this: Patient A | 9/18/2012 12:56:21 PM | Appt | Note1 Patient A | 9/18/2012 12:56:21 PM | Appt | Note2 Patient A | 9/18/2012 12:56:21 PM | Appt | Note3 Patient B | 9/18/2012 1:56:21 PM | WalkIn | Note1 Patient B | 9/18/2012 1:56:21 PM | WalkIn | Note2 What i would like is this : Patient A | 9/18/2012 12:56:21 PM | Appt | Note1, Note2, Note3 Patient B | 9/18/2012 1:56:21 PM | WalkIn | Note1, Note2 I've tried playing around with Group By and keep getting hung up on Aggregate functions, which is confusing because I'm not trying to do anything mathematical. Like said I am a complete ASP noob, and I'm not a programmer by no means. A: I believe there already is a solution for your problem here on SO, try looking at THIS question. You will just need to define (a bit complicated) function and use it as in example. A: This is really a SQL query issue that has little to do with ASP. Since you're using MDB you may find it easier to model your queries using MS Access, then paste the generated SQL statement back into your ASP code. The following question can help: SQL Group with Order by A: Serious fails in the HTML. Anyway, here's a quick solution by making a few mods to the logic for looping through the result set and displaying it. <% Set DataConn = Server.CreateObject("ADODB.Connection") Set RS = Server.CreateObject("ADODB.RecordSet") DataConn.Open "DBQ=" & Server.Mappath("/path/to/mydb") & ";Driver={Microsoft Access Driver (*.mdb)};Uid=user;Pwd=pass;" Set rsDsp = DataConn.Execute("SELECT SignUpLog.PatientFileNumber, SignUpLog.ArrivalDateTime, Notes.Note, SignUpLog.Called, SignUpLog.DrName FROM SignUpLog, Notes WHERE (((Notes.NoteKey)=[SignUpLog].[FirstNoteAddr])) ORDER BY SignUpLog.ArrivalDateTime DESC;") If rsDsp.EOF Then Response.Write "Sorry, no entries in the database!" Else %> <div align="center"> <table BORDER="0" width="700"> <tr> <th width="105">Name</th> <th width="105">Arrival Time</th> <th width="105">Doctor</th> <th width="105">Notes</th> </tr> <% Dim LastPatient; Dim Notes = ""; Dim x = 0; While Not rsDsp.EOF If LastPatient = rsDsp.Field.Item("PatientFileNumber").Value Then Response.Write "<br />" & rsDsp("Note").Value Else If LastPatient <> NULL Then Response.Write "</td></tr>" If x Mod 2 = 0 Then Response.Write "<tr><td>" & rsDsp.Fields.Item("PatientFileNumber").Value & "</td>" Response.Write "<td>" & rsDsp("ArrivalDateTime").Value & "</td>" Response.Write "<td>" & rsDsp("DrName").Value & "</td>" Response.Write "<td>" & rsDsp("Note").Value Else Response.Write "<tr><td bgcolor=""E4E4E4"">" & rsDsp.Fields.Item("PatientFileNumber").Value & "</td>" Response.Write "<td bgcolor=""E4E4E4"">" & rsDsp("ArrivalDateTime").Value & "</td>" Response.Write "<td bgcolor=""E4E4E4"">" & rsDsp("DrName").Value & "</td" Response.Write "<td bgcolor=""E4E4E4"">" & rsDsp("Note").Value End If x = x + 1 End If LastPatient = rsDsp.Fields.Item("PatientFileNumber").Value rsDsp.MoveNext Wend Response.Write "</td></tr>" DataConn.Close End If %> </table> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/12482614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mouse.get_pressed() inconsistent/returning (0, 0, 0) edit (solved): using event.button seems to have done the trick. When it returns 0, 0, 0 it returns the correct mouse button (1 = left, 3 = right) I've tried looking up solutions to this but in every answer it seems the person didn't know about or forgot to include for event in pg.event.get() .. the mouse detection in pygame has stopped working reliably and I'm not sure if it's a hardware error, my code is bad or something else. Here is a simplified version of my game loop for the mouse: while running: for event in pg.event.get(): pos = pg.mouse.get_pos() if event.type == pg.MOUSEBUTTONDOWN: if grid_space.get_rect(x=(adj_x), y=(adj_y)).collidepoint(pos): if pg.mouse.get_pressed()[2]: do_thing() elif event.button == 4: do_thing() elif event.button == 5: do_thing() else: print(pg.mouse.get_pressed()) do_thing() I moved the primary mouse button in to the else because it's the only way to make the most important action more reliable at the moment, but by printing the else result I also found that one in every 4 or 5 clicks returns (0, 0, 0) rather than (1, 0, 0). I've tried different ways of writing the expression, simplifying the structure, increasing the Pygame clock and nothing is working. Has anyone encountered this and is there a solution? edit: I've run another test saving the get_pressed result to a variable immediately and it still returns 0, 0, 0 so I'm pretty sure its state hasn't changed from MOUESBUTTONDOWN to the time its called. A: pygame.mouse.get_pressed() get the current state of the mouse buttons. The state of the buttons may have been changed, since the mouse event occurred. Note that the events are stored in a queue and you will receive the stored events later in the application by pygame.event.get(). Meanwhile the state of the button may have been changed because of this he button which causes the MOUSEBUTTONDOWN event is stored in the button attribute of the pygame.event.Event object immediately. In the event loop, whn you get the event the state of event.button and pygame.mouse.get_pressed() may be different. The same goes for pygame.mouse.get_pos(). The position of the mouse is stored in the attribute pos Use event.button and event.pos rather than pygame.mouse.get_pressed() and pygame.mouse.get_pos(): while running: for event in pg.event.get(): if event.type == pg.MOUSEBUTTONDOWN: print(event.button) if grid_space.get_rect(topleft=(adj_x, adj_y)).collidepoint(event.pos): if event.button == 2: do_thing() elif event.button == 4: do_thing() elif event.button == 5: do_thing() else: do_thing() pygame.mouse.get_pos() and pygame.mouse.get_pressed() are not intended to be used in the event loop. The functions should be used directly in the application loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/63970977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Leaflet sidebar not opening on load I'm using the leaflet-sidebarv2 plugin to create a sidebar for a cartodb/leaflet map. I'm running into problems that I a.) can't get the options to work – close button, autoPan, etc) and b.) can't use setContent to dynamically set data. The sidebar functions as expected. The problem is modifying it seems to have no effect. I also get an error "Uncaught TypeError: undefined is not a function" on the setTimeout and setContent lines. cartodb.createLayer(map, { user_name: {{user_name}}, type: 'cartodb', sublayers: [{ sql: 'select * from {{table_name}}', cartocss: '#layer', interactivity: 'cartodb_id, name', auto_bound: true }] }) .addTo(map) .done(function(layer) { var barData; barData = layer.createSubLayer({ sql: 'select * from {{table_name}}', cartocss: '#layer {marker-fill: #bababa; marker-opacity: 0.3; marker-width: 4px; }', interactivity: 'name, location' }); //on click barData.on('featureClick', function(e, pos, pixel, data) { //log active data console.log("Name: " + data.name + " @ " + data.location); $('#map').css('cursor', 'pointer'); }); barData.setInteraction(true); //hover pop-up var infobox = new cdb.geo.ui.InfoBox({ width: 100, layer: layer, template: '<p class="cartodb-infobox">{{name}}</p></br><p>{{location}}</p>', position: 'top|right' // top, bottom, left and right are available }); $("body").append(infobox.render().el); // leaflet-sidebar> closeButton not engaging var sidebar = L.control.sidebar('sidebar', {closeButton: true}); map.addControl(sidebar); //content not showing up anywhere sidebar.setContent('test <b>test</b> test'); // sidebar still collapsed at reload setTimeout(function () { sidebar.show(); }, 500); }); } window.onload = main; Any suggestions on what I might be doing wrong? I've got all the right pieces loaded in the head. A: You seem to be using the wrong API. The setContent() method and the options hash is part of the leaflet-sidebar library API, but not of sidebar-v2.
{ "language": "en", "url": "https://stackoverflow.com/questions/29519394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: caused by java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/Module in spring starter project in IntelIj In my spring starter project, I am trying to do API calls using the JPA. My pom.xml look like this: 4.0.0 <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> When I try to run it is getting error as java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/Module A: spring-boot-starter-web already includes Jackson. You should not override the managed version, otherwise the versions can be different between different Jackson libraries, causing ClassNotFoundException. Remove this from the pom: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.5</version> </dependency> and let the transitive dependency with the correct version be used. Or when you add Jackson to your pom, just don't use any version number, since parent project dependency management already includes all jackson libraries with a consistent version. A: Try 2 options : <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> or <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.3</version> A: If you are using SpringBoot you should know that Jackson is added by default. so remove to avoid conflicting versions and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/47511572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can i add a field to my Django model to dynamically filter a dropdown on another field? I have a created Django-CMS Plugin with a ManytoManyField to another model. When creating the Plugin on the Front-End, i want the user to be able to filter the ManytoManyField list (which might be too long). By the way this future is already on Django admin: class ModelAdmin(admin.ModelAdmin): list_filter = ('field_name', ) form = PartnerLogoTableForm Is it possible to have something similar like that on my cms_plugins.py: class PartnerLogoTablePlugin(CMSPluginBase): model = LogoTablePlugin form = LogoTablePluginForm name = _('LogoTable Plugin') render_template = False search_fields = ('description',) def render(self, context, instance, placeholder): self.render_template = 'aldryn_logo_tables/plugins/%s/logotable.html' % instance.style context.update({ 'object': instance, 'placeholder': placeholder, }) return context plugin_pool.register_plugin(PartnerLogoTablePlugin) models.py: class PartnerLogoTable(models.Model): name = models.CharField(_('Partner name'), max_length=255) image = FilerImageField(verbose_name=_('Image'), null=True, blank=True, on_delete=models.SET_NULL) partner_url = models.TextField(_('Partner url'), null=True, blank=True, validators=[URLValidator()]) is_active = models.BooleanField(_('Is active'), blank=True, default=True) created_at = models.DateTimeField(_('Created at'), auto_now_add=True) updated_at = models.DateTimeField(_('Updated at'), auto_now=True) order = models.IntegerField(_('Order'), null=True, blank=True) class Meta: verbose_name = _('Partner Logo') verbose_name_plural = _('Partner Logos') ordering = ['order'] def __str__(self): return self.name class LogoTablePlugin(CMSPlugin): DEFAULT = 'default' LOGOTABLE_CHOICES = [ (DEFAULT, _('Default')), ] description = models.CharField(_('Description'), max_length=255, null=True, blank=True) partner = models.ManyToManyField(PartnerLogoTable, verbose_name=_('Partner')) logo_per_row = models.IntegerField(_('Logo per line'), default=1, null=True, blank=True, validators=[MaxValueValidator(4), MinValueValidator(1)], help_text=_('Number of logos to be displayed per row')) style = models.CharField(_('Style'), choices=LOGOTABLE_CHOICES + get_additional_styles(), default=DEFAULT, max_length=50, blank=True, null=True, ) class Meta: verbose_name = _('Partner Logo Plugin') verbose_name_plural = _('Partner Logo Plugins') def __unicode__(self): return u'%s' % self.description forms.py class LogoTablePluginForm(forms.ModelForm): model = LogoTablePlugin def clean_style(self): ..... return style class PartnerLogoTableForm(forms.ModelForm): model = PartnerLogoTable def clean(self): .... return self.cleaned_data This is how the plugin looks now A: ModelSelect2Multiple from django-autocomplete-light seems perfect for your use case.
{ "language": "en", "url": "https://stackoverflow.com/questions/55615478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linking to OpenGL from a DLL: glew functions are null when running I'm building a DLL that links to OpenGL. But I get a problem when calling some functions such as glGenBuffers, because apparently __glewGenBuffers (and other glew buffer functions) are null. Everything compiles properly, and the same code works in the executable, but not in my DLL. I'm using VS 2010. Any ideas about linking to OpenGL from a DLL? Edit: I forgot to mention, I'm actually trying to link an engine (static library) to the DLL, and the exe file uses it too (it does almost everything, except a small part that I want to put in my DLL). I would definitely be fine with using just OpenGL calls from the DLL though, instead of linking the engine, if I could get it to work better. A: GLEW must do some tricks in order to deal with the context dependent function pointers on some plattforms. One of these plattforms is Windows. A foolproof way to make things working is to * *Test if there's actually a OpenGL context bound *call glewInit() everytime a function in the DLL is called that uses extended OpenGL functionality. I.e. … some_DLL_exported_function(…) { if( NULL == wglGetCurrentContext() || GLEW_OK == glewInit() ) { return …; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/14131083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Populating RecyclerView with two sets of data from Firebase I have Firebase set up as so... { "items" : { "-LDJak_gdBhZQ0NSB-7B" : { //item "name" : "Test123", ... }, ... }, "likes" : { "YoTjkR2ORlcr5hGedzQs5xOK2VE3" : { //user "-LDJiY0YSraa_RhxVWXL" : true //whether or not the item is liked }, ... } } And I'm populating a RecyclerView with items, but I need to know if each item has been liked by the current user. I know I could store each user who has liked an item in the item itself, but that seems like too much repetition. But even if done that way, I'd have to check through a list of users who liked an item for that specific user, for each item added. Should I just live with all of this repetition or is there an easy way to deal with this? Here's the code I have that uses FirebaseRecyclerAdapter: private fun setUpFirebaseAdapter() { val ref = FirebaseDatabase.getInstance().reference val itemQuery = ref .child("items") .limitToLast(20) val itemOptions = FirebaseRecyclerOptions.Builder<Item>() .setQuery(itemQuery, Item::class.java) .build() firebaseAdapter = object : FirebaseRecyclerAdapter<Item, FirebaseViewHolder>(itemOptions) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FirebaseViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_row, parent, false) return FirebaseViewHolder(view) } override fun onBindViewHolder(holder: FirebaseViewHolder, position: Int, model: Item) { holder.bindItems(model) //... } } } I know there's index support, but I think that would only allow me to only return liked items. A: But that seems like too much repetition. Yes, it is. Should I just live with all of this repetition or is there an easy way to deal with this? Yes, you should! In such cases as yours, you should use this tehnique which is named in Firebase denormalization, and for that I recomend you see this tutorial, Denormalization is normal with the Firebase Database, for a better understanding. So, there is nothing wrong in what you are doing, besides that is a common practice when it comes to Firebase.
{ "language": "en", "url": "https://stackoverflow.com/questions/50574906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tomcat 8 Unicode filename war file deploy issue On Linux(openSUSE) machine I'm trying to deploy on Tomcat 8 application(war file) that contains a files with names with Unicode characters. Inside of the war file the name looks like: бжк-природний-1496336830201.xml but after deploy the file looks like: ???-?????????????-1496336830201.xml How to tell Tomcat to properly deploy the file names ? UPDATED This is a sample war file with Unicode file name inside: war file What is wrong with the file name of the file inside in this war ? UPDATED I have installed unzip-rcc as it was suggested here https://superuser.com/questions/1215670/opensuse-unzip-unicode-issue and now unzip(console command) on the WAR file is working fine but Tomcat still deploy the files with the same issue. A: Try putting these settings in Tomcat startup script: export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 export LANGUAGE=en_US.UTF-8 From experience, Java will print up-side-down question mark for characters it does not know how to encode. A: The filename is indeed in UTF-8 in the zip .war file. try (ZipFile zipFile = new ZipFile(path, StandardCharsets.UTF_8)) { zipFile.stream() .forEachOrdered(entry -> System.out.printf("- %s%n", entry.getName())); } catch (IOException e) { e.printStackTrace(); } However the zip does not has added the encoding (as bytes[] extra information). Three solutions would be imaginable: * *One short solution might be to run TomCat under a UTF-8 locale. *The best would be to have maven build a war with UTF-8 encoding. (<onfiguration><encoding>UTF-8</encoding></configuration>) *Repairing the war by converting it. With the first two solutions I have no experience. A quick search didn't yield anything ("encoding" is a bit ubiquitous). The repair code is simple: Path path = Paths.get(".../api.war").toAbsolutePath().normalize(); Path path2 = Paths.get(".../api2.war").toAbsolutePath().normalize(); URI uri = URI.create("jar:file://" + path.toString()); Map<String,String> env = new HashMap<String,String>(); env.put("create", "false"); env.put("encoding", "UTF-8"); URI uri2 = URI.create("jar:file://" + path2.toString()); Map<String,String> env2 = new HashMap<String,String>(); env2.put("create", "true"); env2.put("encoding", "UTF-8"); try (FileSystem zipFS = FileSystems.newFileSystem(uri, env); FileSystem zipFS2 = FileSystems.newFileSystem(uri2, env2)) { Files.walkFileTree(zipFS.getPath("/"), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("* File: " + file); Path file2 = zipFS2.getPath(file.toString()); Files.createDirectories(file2.getParent()); Files.copy(file, file2); return FileVisitResult.CONTINUE; } }); } catch(IOException e) { e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/44343502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UWP Kinect V2 keep frame rate constant (30fps) I am processing frames received from Kinect v2 (Color and IR) in UWP. The program runs on remote machine (XBOX One S). The main goal is to get frames and write them to the disk with 30 fps for Color and IR to later process them further. I am using the following code to check the frame rate: public MainPage() { this.InitialiseFrameReader(); // initialises MediaCapture for IR and Color } const int COLOR_SOURCE = 0; const int IR_SOURCE = 1; private async void InitialiseFrameReader() { await CleanupMediaCaptureAsync(); var allGroups = await MediaFrameSourceGroup.FindAllAsync(); if (allGroups.Count == 0) { return; } _groupSelectionIndex = (_groupSelectionIndex + 1) % allGroups.Count; var selectedGroup = allGroups[_groupSelectionIndex]; var kinectGroup = selectedGroup; try { await InitializeMediaCaptureAsync(kinectGroup); } catch (Exception exception) { _logger.Log($"MediaCapture initialization error: {exception.Message}"); await CleanupMediaCaptureAsync(); return; } // Set up frame readers, register event handlers and start streaming. var startedKinds = new HashSet<MediaFrameSourceKind>(); foreach (MediaFrameSource source in _mediaCapture.FrameSources.Values.Where(x => x.Info.SourceKind == MediaFrameSourceKind.Color || x.Info.SourceKind == MediaFrameSourceKind.Infrared)) // { MediaFrameSourceKind kind = source.Info.SourceKind; MediaFrameSource frameSource = null; int frameindex = COLOR_SOURCE; if (kind == MediaFrameSourceKind.Infrared) { frameindex = IR_SOURCE; } // Ignore this source if we already have a source of this kind. if (startedKinds.Contains(kind)) { continue; } MediaFrameSourceInfo frameInfo = kinectGroup.SourceInfos[frameindex]; if (_mediaCapture.FrameSources.TryGetValue(frameInfo.Id, out frameSource)) { // Create a frameReader based on the source stream MediaFrameReader frameReader = await _mediaCapture.CreateFrameReaderAsync(frameSource); frameReader.FrameArrived += FrameReader_FrameArrived; _sourceReaders.Add(frameReader); MediaFrameReaderStartStatus status = await frameReader.StartAsync(); if (status == MediaFrameReaderStartStatus.Success) { startedKinds.Add(kind); } } } } private async Task InitializeMediaCaptureAsync(MediaFrameSourceGroup sourceGroup) { if (_mediaCapture != null) { return; } // Initialize mediacapture with the source group. _mediaCapture = new MediaCapture(); var settings = new MediaCaptureInitializationSettings { SourceGroup = sourceGroup, SharingMode = MediaCaptureSharingMode.SharedReadOnly, StreamingCaptureMode = StreamingCaptureMode.Video, MemoryPreference = MediaCaptureMemoryPreference.Cpu }; await _mediaCapture.InitializeAsync(settings); } private void FrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args) { using (var frame = sender.TryAcquireLatestFrame()) { if (frame != null) { //Settings.cameraframeQueue.Enqueue(null, frame.SourceKind.ToString(), frame.SystemRelativeTime.Value); //Add to Queue to process frame Debug.WriteLine(frame.SourceKind.ToString() + " : " + frame.SystemRelativeTime.ToString()); } } } I am trying to debug the application to check the frame rate so I have removed further processing. I am not sure if I am not calculating it properly or something else is wrong. For example, System Relative Time from 04:37:06 to 04:37:48 gives : IR: Fps(Occurrence) 31(1) 30(36) 29(18) 28(4) Color: Fps(Occurrence) 30(38) 29(18) 28(3) I want this frame rate to be constant (30 fps) and aligned so IR and Color and same number of frames for that time. This does not include any additional code. As soon as I have a process queue or any sort of code, the fps decreases and ranges from 15 to 30. Can anyone please help me with this? Thank you. UPDATE: After some testing and working around, it has come to my notice that PC produces 30fps but XBOX One (remote device) on debug mode produces very low fps. This does however improve when running it on release mode but the memory allocated for UWP apps is quite low. https://learn.microsoft.com/en-us/windows/uwp/xbox-apps/system-resource-allocation A: XBOX One has maximum available memory of 1 GB for Apps and 5 for Games. https://learn.microsoft.com/en-us/windows/uwp/xbox-apps/system-resource-allocation While in PC the fps is 30 (as the memory has no such restrictions). This causes the frame rate to drop. However, the fps did improve when running it on release mode or published to MS Store.
{ "language": "en", "url": "https://stackoverflow.com/questions/66046498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: LESS css compile error I am not super proficient with LESS (I use SCSS/SASS) but am working on someone else's code that appears to have been compiled successfully in the past. The ONLY thing that's spitting out an error is this: background: url(@theme-images-dir + 'bx_loader.gif') center center no-repeat #fff; specifically this error: SyntaxError: expected ')' got '+' in /Users/rwboyer/2fish/grpin/wp-content/themes/lawyers-attorneys/wpv_theme/assets/css/bxslider.less on line 40, column 36: @theme-images-dir appears to be defined and included in another less file before this statement is reached. Any hints as to what is happening here? Thanks. A: Like Zar's saying you cant use +, you have to do it like this: background: url("@{theme-images-dir}bx_loader.gif") center center no-repeat #fff; A: It's a parsing error that's saying that you can't put a '+' in your URL, you need to have a closing parenthesis. I'm betting that string concatenation is not supported. See this to get an alternative to string concatenation: Concatenate strings in Less
{ "language": "en", "url": "https://stackoverflow.com/questions/32148246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ModuleNotFoundError: No module named 'utils': How do I change the parent directory looked at by Import I think I know what the issue is here but I don't know how to approach fixing it. This is the current structure I have in my project directory: └── src ├── utils └── utils.py ├── comparator └── comparatorclass.py In my comparatorclass.py I have the following import statements: from utils.logging_service import LoggingService from utils.utils import Utils When I run comparatorclass.py, I get the error Traceback (most recent call last): File "comparator_gui.py", line 11, in <module> import comparatorclass File "/Users/sidu/Desktop/aaababa/src/comparator/comparatorclass.py", line 16, in <module> from utils.logging_service import LoggingService ModuleNotFoundError: No module named 'utils' Of course, I'm pretty sure what's happening is that the comparatorclass.py is looking for the utils directory within the comparator directory when in fact it is one layer above that. The code works when I have a structure like this: └── src ├── utils └── utils.py ├── comparatorclass.py This makes sense because now it is able to find the utils directory within the same parent, src. My question is how do I get it to work with the first scenario? I need a way to change what parent directory the import statement looks at. A: I fixed the problem by adding the following line before importing the utilities: sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')) from utilities.logging_service import LoggingService from utilities.comparator_utils import Utils I don't know if this is the correct solution, but it did solve the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/65159240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hashtable "default" getter? A particular class has a Hashtable containing 1..N elements. I'm wondering if there are generic getter/setter methods for the Hashtable used in a class. I'm looking to make the hashtable values behave more like regular object properties: public class foo { private HashTable _stuff; public HashTable stuff { get; set; } public foo() {} } I was wondering if something like this can happen: foo bar = new foo(); bar.stuff.name; //returns the data in the 'name' index if it exists bar.stuff.name = "Me"; //sets the stuff[name] value = "me" A: There's nothing like that in the current version of C#. The dynamic stuff in C# 4.0 will make this easier. In the meantime, why not just make Name (and other values) simple properties? While you're at it, you'll find the generic Dictionary<K,V> easier to work with than HashTable. A: You can't do this with C#, at least not in the current version. What you'd need is the equivalent of method_missing in ruby. If this was C# 4.0 you could do something similar to this with anonymous types and the dynamic keyword, however you'd need to know the keys up front. A: Apparently you can do that in .NET 4.0 by implementing the IDynamicMetaObjectProvider interface... doesn't seem trivial though ! A: Depending on how you are rendering the HTML there might be a few ways to solve your problem. The code above is as noted not possible at current in c#. First of all I assume there's a reason why you don't use ADO objects, that usually solve the rendering problems you mention (together with GridView or similar). If you want to generate a class with "dynamic" properties you can create a propertybag it will not make the above code possible though but will work with a rendering engine based on TypeDescriptor using custom descriptors. A: Take a look at ExpandoObject in c# 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/963131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to ensure the same static pybind11:dict defined in one module is accessed by other modules using that library I'm trying to build some python modules using pybind11 and Bazel. The key thing is that I need a central dictionary to store information on all modules of a certain type (Foo, Bar in code below). However, the static pybind11::dict that I use to store this information seems to be initialized multiple times, with each module (Foo/Bar) receiving it's own copy of it. Hence below when I run Registration::register() in the Foo module, and Bar module, I get a different pointer to dict in each instance as shown in the print statement in Registration::register(). I suspected my issue has something to do with how I'm linking the libraries, or how I'm ensuring that the library is shared. In project_name/registration/registration.h: class Registration { public: static pybind11::dict dict; static pybind11::dict& registrations(); template <typename BaseClass> static void register(const char* name); }; template <typename BaseClass> void Registration::register(const char* name) { pybind11::dict& dict = Registration::registrations(); pybind11::print(&dict); **// This prints a different pointer in each module!** dict[name] = WrapInPyCapsule(some_function<BaseClass>); }; In project_name/registration/registration.cc: pybind11::dict Registration::dict = pybind11::dict(); pybind11::dict& Registration::registrations() { return Registration::dict; } In project_name/foo/foo.cc and project_name/bar/bar.cc include "project_name/registration/registration.h" PYBIND11_MODULE(foo, m) { Registration::register("foo") // or "bar" in bar.cc } BAZEL Build File For Registration: pybind_library( name = "registration", hdrs = ["registration.h"], srcs = ["registration.cc"], ) BAZEL Build File For Foo: pybind_extension( name = "foo", srcs = [ "foo.cc", ], linkopts = [ "-ldl", ], deps = [ "//project_name/registration/registration", ], ) BAZEL Build File For Bar: pybind_extension( name = "bar", srcs = [ "bar.cc", ], linkopts = [ "-ldl", ], deps = [ "//project_name/registration/registration", ], )
{ "language": "en", "url": "https://stackoverflow.com/questions/71079308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get different behaviour based on the value that comes from the GUI component? I have text box on a GUI app where user might set two values "productsupport" or "productLocal" in my service class I am checking if the type is productSupport do something otherwise do something else Is there a better way of checking these values that come from the GUI component? class ProductService{ void handle(String type){ if(type.equals("productSupport"){ // //do something } else if(type.equals("productLocal"){ //do something else } } } A: You did not specify what kind of UI it is, but in general I would not use a textbox in case a user can choose between two things. It would make more sense to use a drop-down or combo box. As items in the boxes I would use the values of an enum: enum Type { PRODUCT_SUPPORT("Product support"), PRODUCT_LOCAL("Product local"); final String label; Type(String label) { this.label = label; } } class ProductService { void handle(Type type) { switch(type) { case PRODUCT_LOCAL: //do somethinf break; case PRODUCT_SUPPORT: //do something els3 } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/60084838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to pass multiple bundles from an activity/class through multiple successive classes so the data ends up at a final class? how to pass multiple bundles from an activity/class through multiple successive classes to all end up at a final activity (final activity = email client from android app)? I was able to pass one bundle of strings from one activity/class to the immediate following final activity /class (the in-app email client) ? can you point me to a good resource? I was able to pass 1 bundle of strings like this: btnSend.setOnClickListener(this); btnAttachment.setOnClickListener(this); //create a bundle object to store //the bundle we added to the intent Bundle bundle1=getIntent().getExtras(); //get the values out by key String Medicx1=bundle1.getString("Medicx1"); String Medicx2=bundle1.getString("Medicx2"); String Medicx3=bundle1.getString("Medicx3"); String Medicx4=bundle1.getString("Medicx4"); String Medicx5=bundle1.getString("Medicx5"); String Medicx6=bundle1.getString("Medicx6"); //get the textview controls EditText medication1=(EditText)findViewById(R.id.editTextMessage); //set the text values of the text controls medication1.setText("To whom it may concern \n\n " + "On this trip, different travelers will be taking the following medications: \n \n"+ "-"+ Medicx1 + "\n \n" + "-"+ Medicx2 + "\n \n" + "-"+ Medicx3 + "\n \n" + "-"+ Medicx4 + "\n \n" + "-"+ Medicx5 + "\n \n" + "-"+ Medicx6 + "\n \n" + "i would like you to know this before the trip"); * I successfully got the above code to work because this information comes from the immediately previous class/activity* but i want more data, from classes that are even farther away, to show up also in the final activity/class. A: You can work with a local database (SQLite) to store and retrieve things to use throughout the classes or you can create a class that would store all the data and have an instance of that class live in an interface that you would implement on all those classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/35148510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Referencing a checkbox value from HTML to C# I have a checkbox on my .cshtml page that when it is checked I want it to NOT send and e-mail to the user. Below is the various pages of code that I have to transfer the boolean value from the .cshtml page to the .cs mailer code but somewhere the value is not transferring. Please help. In View.cshtml I put the checkbox in: <input class="checkbox_priority" id="no_emails" name="no_emails" type="checkbox" value="true" title="This only applies to the 'Complete' button"/>Do not send e-mail to requestor. In Notification.cs I get/set the value: public virtual Boolean no_emails { get; set; } //Used to not send an e-mail to the creator of a request. And then finally I put the IF statement into the mailer code on RequestService.cs: [Spring.Transaction.Interceptor.Transaction] public int Create(int requestId, Policy.Models.Review newReview) { Policy.Models.Request request; Policy.Models.Review review; request = RequestDao.Get(requestId); newReview.Id = ReviewDao.Save(newReview); //Refresh review object review = ReviewDao.Get(newReview.Id); request.Review = review; //Associate review to request RequestDao.Update(request); //Notify request's author of a response string message = "The response to your <a href=\"{0}\">request</a> has been started"; if (!review.Status.IsActive && !no_emails) message = "The response to your <a href=\"{0}\">request</a> has been completed"; Helpers.Notifier.CreateNotification(request.Author, request, string.Format(message, Helpers.Link.RequestLink(request.Id))); return newReview.Id; } CreateNotification is defined in a seperate file titled Notifier.cs public static void CreateNotification(IList<Policy.Models.User> recipients, Policy.Models.AAuditable subject, string message) { if (recipients != null && recipients.Count > 0) { for (int i = 0; i < recipients.Count; ++i) { CreateNotification(recipients[i], subject, message); } } } public static Policy.Models.Notification CreateNotification(Policy.Models.User recipient, Policy.Models.AAuditable subject, string message) { Policy.Models.Notification note = new Policy.Models.Notification(); note.Description = message; note.IsRead = false; note.User = recipient; However, it is saying that no_emails does not exist in the current context. How do I get the code to recognize no_emails has a boolean value from the .cshtml page? A: This sounds like a scope issue to me. I would need to see more of your code to be sure but let's assume that there is an instance of Notification that is created in RequestService. You can't directly access the variable no_emails. You would access like this: // here is the instance of notification Notification someNotifacation = new Notification(); // call the getter method to get the value if(!someNotification.no_emails) { ... } A: If this is ASP.NET MVC, you can put the no_emails variable in the Action parameter list, and MVC will bind it for you to the POSTed form value. However, the parameter name and the name attribute on the form must match. Here, you have name="emails", so you will need to change it to match the parameter name you use. but you have a Spring attribute which makes me think this is not ASP.NET MVC?
{ "language": "en", "url": "https://stackoverflow.com/questions/31593039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: C# Limit Calls Per Second I am calling a service that only allows 10 calls per second. I am using Stopwatch and Thread.Sleep to limit my calls. Are these the correct tools for this job, or should I be using Timers or some other tool. public void SomeFunction() { Stopwatch stopwatch = new Stopwatch(); int numCallsThisSecond = 0; foreach(MyEvent changedEvent in changedEvents) { stopwatch.Start(); service.ChangeEvent(changedEvent); numCallsThisSecond += 1; stopwatch.Stop(); if(numCallsThisSecond==10 && stopwatch.ElapsedMilliseconds<=1000) Thread.Sleep((int)(1100-stopwatch.ElapsedMilliseconds)); if(stopwatch.ElapsedMilliseconds>1000) { stopwatch.Reset(); numCallsThisSecond = 0; } } } Thank you in advance for any help! A: As you already know it can be 10 calls / sec. Code can be simple as follows : public void SomeFunction() { foreach(MyEvent changedEvent in changedEvents) { service.ChangeEvent(changedEvent); Thread.Sleep(100);//you already know it can be only 10 calls / sec } } Edit : Ok got it, please see if following alternative will be helpful, it only allows 10 or less calls per second depending on how its performing : public void SomeFunction() { DateTime lastRunTime = DateTime.MinValue; foreach(MyEvent changedEvent in changedEvents) { lastRunTime = DateTime.Now; for (int index = 0; index < 10; index++) { if (lastRunTime.Second == DateTime.Now.Second) { service.ChangeEvent(changedEvent); } else { break;//it took longer than 1 sec for 10 calls, so break for next second } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/31347104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "TypeError: 'list' object is not callable" for keywords= inside a list I am going to put a very easy example of what I'm trying to do before posting my code example 1: This is what I want to accomplish(but with the keywords inside a list) print("hi", end="****") output: hi **** example 2: This is as far as I can make it work keyword = end="****" print("hi", keyword) output: hi **** example 2: This is where it fails keywords = ['spam', end="****"] print("hi", keywords[1]) output: keywords = ['spam', end="****"] ^ SyntaxError: invalid syntax example 2.1: This is where it fails (on a similar but different approach) although, this works keyword = end="****" keywords = ['spam', keyword] print("hi", keywords[1]) output: hi **** this one doesn't work: keyword = sep="^^^^", end="****" keywords = ['spam', keyword] print("hi", keywords[1]) output: keyword = sep="^^^^", end="****" ^ SyntaxError: can't assign to literal and this is my code: from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier LogisticRegression_args = None KNeighborsClassifier_args = n_neighbors=5 GaussianNB_args = None DecisionTreeClassifier_args = criterion='entropy' SVC_args = kernel='linear' SVC_non_linear_args = kernel='rgb' RandomForestClassifier_args = criterion='entropy', n_estimators=10, random_state=0 basic_classifier_models = [[[LogisticRegression], [LogisticRegression_args], ['LogisticRegression:']], [[KNeighborsClassifier], [KNeighborsClassifier_args], ['KNeighborsClassifier:']], [[GaussianNB], [GaussianNB_args], ['GaussianNB:']], [[DecisionTreeClassifier], [DecisionTreeClassifier_args], ['DecisionTreeClassifier:']], [[SVC], [SVC_args], ['SVC:']], [[SVC], [SVC_non_linear_args], ['Non_linear SVC:']], [[RandomForestClassifier], [RandomForestClassifier_args], ['RandomForestClassifier:']]] output: RandomForestClassifier_args = criterion='entropy', n_estimators=10, random_state=0 ^ SyntaxError: can't assign to literal A: keyword = end="****" sets two variables. keyword = "****" and end = "****". It does not do what you think it does. Your second example prints what it does because it is equivalent to calling print("hi", "****") To specify arguments without actually writing them in the function call, you can do it by argument unpacking. You specify positional arguments by unpacking a list like so: args = ['a', 'b', 'c'] print(*args) # Output: a b c Or, for keyword args, you unpack a dict like so: kwargs = { "end": "****\n" } print("abc", **kwargs) Output: abc**** You can even do both: args = ["hello", "world"] kwargs = { "sep": "|", "end": "***\n" } print(*args, **kwargs) # Equivalent to print("hello", "world", sep="|", end="***\n") # Output: hello|world*** A: You can't define a variable in a list. Here's how you could make this function work (assuming I read the question right) keywords = ['spam', "****"] print("hi", keywords[1]) if you're trying to find a word in a sequence, which is what I'm assuming this is trying to accomplish, you can do so easily by doing the following for loop: check = "hi" for item in keywords: if check.find(item) != -1: print("keyword found in input")
{ "language": "en", "url": "https://stackoverflow.com/questions/69318668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Semaphore and Critical Section issue on multiple threads I am having an issue with my multithreaded code and hope someone can help me out. I wish to print on the console all files and folder starting from a folder given as an argument. I use this function for the enumeration: void enumerate(char* path) { HANDLE hFind; WIN32_FIND_DATA data; char *fullpath = new char[strlen(path) - 1]; strcpy(fullpath, path); fullpath[strlen(fullpath) - 1] = '\0'; hFind = FindFirstFile(path, &data); do { if (hFind != INVALID_HANDLE_VALUE) { if (strcmp(data.cFileName, ".") != 0 && strcmp(data.cFileName, "..")) { EnterCriticalSection(&crit); queue.push(data.cFileName); LeaveCriticalSection(&crit); ReleaseSemaphore(semaphore, 1, NULL); if (data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) { strcat(fullpath, data.cFileName); strcat(fullpath, "\\*"); enumerate(fullpath); } } } } while (FindNextFile(hFind, &data)); FindClose(hFind); return; } When I find a file or a folder, I want to add it to a global queue and have my worker threads print it to the console. My worker threads function is: DWORD WINAPI print_queue(LPVOID param) { while (1) { WaitForSingleObject(semaphore, INFINITE); EnterCriticalSection(&crit); char *rez = queue.front(); queue.pop(); LeaveCriticalSection(&crit); if (strcmp(rez, "DONE") == 0) break; else std::cout << rez << std::endl; } return 1; } In main, I initialize the semaphore and critical section, both variables declared globally: semaphore = CreateSemaphore(NULL, 0,1, NULL); InitializeCriticalSection(&crit); Then create 4 threads: thread1 = CreateThread(NULL, 0, print_queue, NULL, 0, &tId1); thread2 = CreateThread(NULL, 0, print_queue, NULL, 0, &tId2); thread3 = CreateThread(NULL, 0, print_queue, NULL, 0, &tId3); thread4 = CreateThread(NULL, 0, print_queue, NULL, 0, &tId4); I then call the enumerate() function and for strings to the queue that will signal my threads to stop when those strings are reached: for (int p = 0; p<4; p++) { EnterCriticalSection(&crit); queue.push(done); LeaveCriticalSection(&crit); ReleaseSemaphore(semaphore, 1, NULL); } Those 4 strings are the stop condition for my threads. I then wait for the threads: HANDLE * threadArray = new HANDLE[4]; threadArray[0] = thread1; threadArray[1] = thread2; threadArray[2] = thread3; threadArray[3] = thread4; WaitForMultipleObjects(4, threadArray, TRUE, INFINITE); And close the semaphore and critical section: CloseHandle(semaphore); DeleteCriticalSection(&crit); For some reason, the output is random garbage and I can't figure out why. This is an example output: te(L┤(L ┤(L ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠°┐*╧wM3╧weµFC4 ╠╠╠╠╠ My logic was to start the semaphore on 0, enter the critical section whenever operations happened on a queue to protect my data, increment the semaphore in the enumerate() function and decrease it in print_queue(). What might be the problem? A: enumerate() has MANY problems: * *you are not using strcpy() and strcat() correctly, so you are trashing memory. You are not allocating enough memory to hold the result of strcpy(), which copies characters until it reaches a null terminator. You are allocating memory for 2 fewer characters than needed (the last char in the path, and the null terminator). You should be allocating strlen+1 characters instead of strlen-1 characters. And worse, you are using strcat() to concatenate a filename onto the allocated string without first reallocating the string to make room for the filename. *you are leaking the allocated string, as you never call delete[] for it. *the if inside the loop is missing != 0 when checking strcmp(".."). *you are pushing pointers into queue to data that is local to enumerate() and gets overwritten on each loop iteration, and goes out of scope when enumerate() exits. Your threads are expecting pointers to data that are stable and do not disappear behind their backs. This is the root of your garbage output. Consider yourself lucky that your code is simply outputting garbage and not just crashing outright. *you are not testing the data.dwFileAttributes field correctly. You need to use the & (bitwise AND) operator instead of the == (equals) operator. Folders and files can have multiple attributes, but you are only interested in checking for one, so you have to test that specific bit by itself and ignore the rest. You really should be using std::string instead for string management, and let it handle memory allocations for you. Also, consider using std::filesystem or boost::filesystem to handle the enumeration. Also, there is no need to push "DONE" strings into the queue after enumerating. When a thread is signaled and goes to extract a string and sees the queue is empty, just exit the thread. Try something more like this instead: #include <windows.h> #include <iostream> #include <string> #include <queue> #include <thread> #include <mutex> #include <conditional_variable> std::queue<std::string> paths; std::mutex mtx; std::conditional_variable cv; bool done = false; void enumerate(const std::string &path) { std::string searchPath = path; if ((!searchPath.empty()) && (searchPath[searchPath.length()-1] != '\\')) searchPath += '\\'; WIN32_FIND_DATA data; HANDLE hFind = FindFirstFileA((searchPath + "*").c_str(), &data); if (hFind != INVALID_HANDLE_VALUE) { do { if ((strcmp(data.cFileName, ".") != 0) && (strcmp(data.cFileName, "..") != 0)) { string fullpath = searchPath + data.cFileName; { std::lock_guard<std::mutex> lock(mtx); paths.push(fullpath); cv.notify_one(); } if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) enumerate(fullpath); } } while (FindNextFileA(hFind, &data)); FindClose(hFind); } } void print_queue() { std::unique_lock<std::mutex> lock(mtx); while (true) { cv.wait(lock, [](){ return (!paths.empty()) || done; }); if (paths.empty()) return; std::string rez = paths.front(); paths.pop(); std::cout << rez << std::endl; } } int main() { std::thread thread1(print_queue); std::thread thread2(print_queue); std::thread thread3(print_queue); std::thread thread4(print_queue); enumerate("C:\\"); done = true; cv.notify_all(); thread1.join(); thread2.join(); thread3.join(); thread4.join(); return 0; } A: You nowhere have written which kind of queue you use, but I guess it's a queue<char*>. This means it stores only pointers to memory which is owned somewhere else. When you now do queue.push(data.cFileName); you write a pointer to the queue which is not valid after the next iteration, since data changes there. After enumerate exists the data pointers (and thereby queue elements) will even point to undefined memory, which would explain the output. To fix this store copies of the file names inside the queue, e.g. by using a queue<std::string>
{ "language": "en", "url": "https://stackoverflow.com/questions/49581223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Github.com issues with TFS source control, is it possible? Is it possible to use Github for the issues, TFS for source control, and reference the github issue ids on the TFS checkins? We use TFS and there's no plan to switch to Git in the near future. The product owner is out of our network and we can't allow them VPN access so they can't see the issues on TFS. A: No, it is not supported to add issues in Github when check in code at TFS. It could only add workitems in TFS. If they couldn't see those workitem, you could export those workitems from TFS to Excel and send to them. Or like Daniel said in the comment, you could use VSTS instead of using TFS.
{ "language": "en", "url": "https://stackoverflow.com/questions/43120529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run time for insertion sort with different size, how do I calculate? If I have n random int, it takes x time to run it Now, I have 6n random int, how long does it take? I use insertion sort. Last question, if i choose different sort (same size n), how do I calculate it? A: There's no way to know exactly, but there are rules of thumb that will allow you to obtain a very rough approximation of the running time. Insertion sort is an O(n2) algorithm. What that means in the real world is that, all other things being equal, increasing the size of n by some number, x, will increase the running time by approximately n2. So if you double the size of n, running time will increase by approximately 4 times. If you multiply n by 6, running time will increase by approximately 36 times. Unfortunately, you can't always keep other things equal. You have to think about the effects of cache misses, virtual memory, other things running on the computer, etc. Asymptotic analysis isn't really a tool for computing real-world running times, but it can serve as a very rough approximation: a "ball park estimate," if you will. Other sorting algorithms have different orders of complexity. Merge sort, for example, has computational complexity of O(n log n), meaning that running time increases with the logarithm of the number of items. That increases much more slowly than does n^2. For example, sorting 1,024 items (2^10) requires on the order of (2^10 * 10) comparisons. Sorting 2^20 items will require on the order of (2^20 * 20) comparisons. I can't stress strongly enough that those calculations are very rough approximations. They'll get you in the area--probably within an order of magnitude--but you'll never get an exact number that way. What you can't do with any degree of certainty is say that if insertion sort takes x time, then merge sort will take y time. Asymptotic analysis ignores constant factors. So you can't even approximate the running time of merge sort based on the running time of insertion sort. Nor, for that matter, can you approximate bubble sort (another O(n^2) algorithm) based on the running time of insertion sort. The whole idea of using asymptotic analysis to estimate the real world running time of an algorithm is fraught with error. It often works when estimating the running time of one implementation of one algorithm on specific hardware, but beyond that it's useless. Update You asked: for n = 2^20, M seconds for merge sort, and B seconds for bubble sort, If I have a different size that takes 4B for bubble sort, how do i know the run time of merge sort? As I pointed out above, you cannot estimate the time for merge sort based on the time for bubble sort. What you can do, is estimate the running time of merge sort for the new size based on the running time for merge sort at size n=2^20. For example, at n=2^20, merge sort requires on the order of (2^20 * 20) comparisons. At n=2^21, it requires on the order of (2^21 * 21) comparisons. At n=2^32, (2^32 * 32) comparisons. What you can do then, is take the expected number of comparisons for your new n, compute the expected number of comparisons, and divide that by (2^20 * 20). So, for example, when n=2^22, the expected number of comparisons is approximately 92,274,688. Divide that by 20,971,520 (2^20 * 20), and you get 4.4. So, if sorting 2^20 items with merge sort takes time x, then sorting 2^22 items will take approximately 4.4*x. Again, let me point out that these are very rough approximations that assume everything else remains equal.
{ "language": "en", "url": "https://stackoverflow.com/questions/50165548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Jenkins Consolidate Email Notifications with all upstream job status in a single mail Is there any way to get build number, build status and build url information of all upstream jobs of a build pipeline at last job. I have many jobs connected to each other. A triggers B, B triggers C. I do not want to send success email for every project but want to send email on last downstream build. But email should contains links to logs for all upstream builds. The Mail content would like to be as below: Job A: Build number #1 SUCCESS Console output: <console link> Job B: Build number #1 FAILED Console output: <console link> Job C: Build number #1 SUCCESS Console output: <console link> A: You can use Email-ext plugin for sending emails. The advantage of this plugin is we can write our own mail templates using groovy. You can find some examples here and also some more examples from plugin source itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/44730089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Recursively read a directories with a folder I've been trying to request a recursively read a directory with fs module. I had problems along the way, its only giving me a file name. Here's how I need it to be: * *File name. *And also a directory of that file. This results may be as an object or bulked into an array. Anyone please help. Thanks. A: Here is a recursive solution. You can test it, save it in a file, run node yourfile.js /the/path/to/traverse. const fs = require('fs'); const path = require('path'); const util = require('util'); const traverse = function(dir, result = []) { // list files in directory and loop through fs.readdirSync(dir).forEach((file) => { // builds full path of file const fPath = path.resolve(dir, file); // prepare stats obj const fileStats = { file, path: fPath }; // is the file a directory ? // if yes, traverse it also, if no just add it to the result if (fs.statSync(fPath).isDirectory()) { fileStats.type = 'dir'; fileStats.files = []; result.push(fileStats); return traverse(fPath, fileStats.files) } fileStats.type = 'file'; result.push(fileStats); }); return result; }; console.log(util.inspect(traverse(process.argv[2]), false, null)); Output looks like this : [ { file: 'index.js', path: '/stackoverflow/test-class/index.js', type: 'file' }, { file: 'message.js', path: '/stackoverflow/test-class/message.js', type: 'file' }, { file: 'somefolder', path: '/stackoverflow/test-class/somefolder', type: 'dir', files: [{ file: 'somefile.js', path: '/stackoverflow/test-class/somefolder/somefile.js', type: 'file' }] }, { file: 'test', path: '/stackoverflow/test-class/test', type: 'file' }, { file: 'test.c', path: '/stackoverflow/test-class/test.c', type: 'file' } ]
{ "language": "en", "url": "https://stackoverflow.com/questions/46390733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Pod not compiling for simulator Out of a sudden my project stopped compiling for simulator - everything works on real device but when I try to install to simulator it fails to compile two pods which were there a long time ago and used to work. Another pod is M13ProgressSuite which also can't fine NSNumberFormatter though all the dependencies are there. I suspect it started after I've removed master repo and inited pods over again as per other issue and this SO answer: pod repo remove master pod setup I've never noticed any issues since I was working with device but now it appeared that I can't compile my project to test on simulator. I've spent quite some hours trying to revert code in git to previous commit when it was working for sure, reinint pods, remove/add the problematic pods, revert to previous versions of pods, clean/build project, restarting xcode, recreating simulator - still the same error. Does anyone now why it may stuck with simulator though it used to work and keep working on real device? How can this issue be fixed? I'm out of ideas but I need to be able to test in simulator since I'm developing for watch. Any clue is much appreciated. I'm using Xcode 8.1, iOS 10 target, cocoapod version 1.1.1 Let me know if any additional information may help A: Ok finally I'm able to keep working with simulator. I've just redownloaded Xcode and reinstalled it (moved to 8.2 actually) - as long as it solved the issue I'm fine with this solution but I'm still curious what went wrong and how should I've fixed it in a good way. After spending more time I can add that copying the mentioned pods' sources into the project directly and removing them from pod file so they compile directly from sources in case there are any issues with the compiled frameworks still brought the same error - NSNumberFormatter.h was invisible though import is there - this again work on device but fails to compile for simulator. This is where simulator became the main suspect but installing new one (by downloading a new simulator runtime) didn't solve the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/41336666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Сustomize R plotly plots colors in subplots I have a dataframe, which you can get with this code: x = data.frame(metrics=c("type1", "type1", "type1","type1", "type1", "type1", "orders", "orders", "orders","orders", "orders", "orders", "mean","mean","mean","mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8,6,7,8,6,7,8,6,7,8), actual=c(14,20,34,22,24,27,56,12,34,11,15,45,56,78,89,111,123,156), time_pos=c("today", "yesterday", "today", "yesterday", "today", "yesterday")) Based on a previous question I ended up with the following: plot <- function(df) { subplotList <- list() for(metric in unique(df$metrics)){ subplotList[[metric]] <- df[df$metrics == metric,] %>% plot_ly( x = ~ hr, y = ~ actual, name = ~ paste(metrics, " - ", time_pos), colors = ~ time_pos, hoverinfo = "text", hovertemplate = paste( "<b>%{text}</b><br>", "%{xaxis.title.text}: %{x:+.1f}<br>", "%{yaxis.title.text}: %{y:+.1f}<br>", "<extra></extra>" ), type = "scatter", mode = "lines+markers", marker = list( size = 7, color = "white", line = list(width = 1.5) ), width = 700, height = 620 ) %>% layout(autosize = T,legend = list(font = list(size = 8))) } subplot(subplotList, nrows = length(subplotList), margin = 0.05) } and plot(x) gives me this: As you see it builded subplots for each type of values in column "metrics" and also, on each subplot there are two scatterplots for each type of value in column "time" (today, yesterday). But they are different colours. How to make "today" and "yesterday" values same colour in each subplot? So there be only two types: "today" and "yesterday" in legend and each subplot be titled as "type1", "orders", "mean" A: This could be achieved like so: * *To get the same colors in all plots map time_pos on color instead of colors, .i.e color = ~time_pos. Using colors I set the color palette to the default colors (otherwise I get a bunch of warnings). *The tricky part is to get only two legend entries for today and yesterday. First map time_pos on legendgroup so that the traces in all subplots get linked. Second use showlegend to show the legend only for one of the plots, e.g. the first metric. *To add titles to the subplots I make use of add_annotations following this post library(plotly) plot <- function(df) { .pal <- RColorBrewer::brewer.pal(3, "Set2")[c(1, 3)] subplotList <- list() for(metric in unique(df$metrics)){ showlegend <- metric == unique(df$metrics)[1] subplotList[[metric]] <- df[df$metrics == metric,] %>% plot_ly( x = ~ hr, y = ~ actual, color = ~ time_pos, colors = .pal, legendgroup = ~time_pos, showlegend = showlegend, hoverinfo = "text", hovertemplate = paste( "<b>%{text}</b><br>", "%{xaxis.title.text}: %{x:+.1f}<br>", "%{yaxis.title.text}: %{y:+.1f}<br>", "<extra></extra>" ), type = "scatter", mode = "lines+markers", marker = list( size = 7, color = "white", line = list(width = 1.5) ), width = 700, height = 620 ) %>% add_annotations( text = ~metrics, x = 0.5, y = 1, yref = "paper", xref = "paper", xanchor = "center", yanchor = "bottom", showarrow = FALSE, font = list(size = 15) ) %>% layout(autosize = T, legend = list(font = list(size = 8))) } subplot(subplotList, nrows = length(subplotList), margin = 0.05) } plot(x)
{ "language": "en", "url": "https://stackoverflow.com/questions/63555242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Populate Combo box with INI file in VB.NET I'm a new leaner with Vb.NET and trying to populate a combo box with a particular section from the INI file. For example, my INI file contains: [Month] Jan Feb Mar [Date] 1 2 3 I've a form with two combo boxes. I want to populate one of them with the values under Month section and other with Date section values from the specified single INI file when form loads. I'm using VS Express 2013 for Windows and using VB.NET as the language. Thanks in advance for any pointers. Edit: I've checked related posts on reading/writing INI/Text files but most of them either point to using different INI/TEXT files, read all lines or set up the INI/TEXT in a desired format/structure which is not something I can do sue to requirements. -Deepak A: There is no direct way for manipulating with INI files in .NET. Also INI files consist of key/value pairs, for example like this: [Month] Jan = 1 Feb = 2 Mar = 3 In case you can use the appropriate INI structure then I can suggest you to use my library to accomplish INI files processing: https://github.com/MarioZ/MadMilkman.Ini Here is how you would achieve your task for the above provided INI content: Dim ini As New IniFile ini.Load("path to your INI file") For Each key In ini.Sections("Month").Keys ' Jan, Feb and Mar Me.ComboBox1.Items.Add(key.Name) ' 1, 2 and 3 Me.ComboBox2.Items.Add(key.Value) Next
{ "language": "en", "url": "https://stackoverflow.com/questions/30028304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove table name prefix from aspnetboilerplate Core 2 I am trying to use aspnetboilerplate Core 2 in MVC (not Angular version). After running Add-Migration and Update-Database, all of the created tables have Abp prefix. Such as: AbpUsers, AbpRoles, AbpFeatures, ... How can I remove Abp from table names? I see some instructions but all of them are related to MVC5 version of aspnetboilerplate. A: Answered in this issue: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2382 For Entity Framework Core Override OnModelCreating and call modelBuilder.ChangeAbpTablePrefix. Example: protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ChangeAbpTablePrefix<Tenant, Role, User>(""); // Removes table prefixes. You can specify another prefix. } Remember to add using Abp.Zero.EntityFrameworkCore; to your code file in order to access ChangeAbpTablePrefix extension method.
{ "language": "en", "url": "https://stackoverflow.com/questions/47157706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove a specific file name using htaccess I have not enough experience in writing rules in .htaccess. My site url is like http://exampletest.com/detail.php?i=my-url I want to rewrite that url to http://exampletest.com/my-url What I have tried so far: RewriteEngine on RewriteBase / RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC] RewriteRule ^ detail %1? [R=302,L] That makes me able to access my site using: http://exampletest.com/detail/my-url But I want to omit detail from url as well. A: You should redirect internally as well so your code should looks like this : RewriteEngine on RewriteBase / RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC] RewriteRule ^ %1? [R=302,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ /detail.php?i=$1 [L] A: Try this: RewriteEngine on RewriteBase / RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC] RewriteRule ^ %1? [R=302,L]
{ "language": "en", "url": "https://stackoverflow.com/questions/49229880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: db2 for zos - prohibit changes in columns I would like to ask if there is a way to prohibit programs to change data in certain columns, at db2 level. The problem is that I have some programs that change data in a group of tables but now I must not change data in some columns and I would like to know if there is a way that db2 can make that restriction. I could change all the programs but would like to know if there is an easier way to block changes in a column. A: You may create, let's say, BEFORE UPDATE OF COL1, ..., COLx trigger on this table with a SIGNAL statement inside. Alternatively you may revoke the update privilege on this table from everyone and grant update on a subset of columns needed only. A: Another option is to create a view with a subset of the columns you need to update. It may be a little more complex in case you need to rebind your program(s)
{ "language": "en", "url": "https://stackoverflow.com/questions/61619342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Maxscript - align selection of meshs pivots perpendicular to mesh I have a 3D Globe and each of the countries are seperate meshes. I am in the process of writing a script in 3D Max that automates centring the pivots. for all in selection do(all.pivot = all.center) This part is fine. However I am bringing this into Unity and want to position a gameobject to each of these pivots. To have this looking aesthetically pleasing the pivots of each mesh should be perpendicular. Now I have been looking online for direction of solutions and I've been struggling - perhaps down to misunderstanding. I thought getting numFaces and dividing it by 2 would give an appropriate position and rotation alignment but unfortunately the halfway polygon is not close enough to the mesh centre. I was wondering is there a way to do this by selecting the closest polygon in the mesh to the overall pivot or maybe by selecting the centre polygon through an intersection with a newly created mesh. Perhaps I am complicating this. Would anyone have any input that could set me in the right direction? Thank you. A: Ok I figured it out after some headbutting. The solution 'for me' was provided by the pivot point of the spherical globe's ocean. By finding a question provided by Joker Martini to design a lookAt for each pivot of every mesh to look at a target (the pivot of the spherical world water that is centered) and then flipping through rotation the pivot by learning about objectoffsetrot. Here it is as it may be useful for someone. for all in selection do( one = all target = $'Globe Sea' pivotLookAt one two RotatePivotOnly one ((eulerangles 0 180 0) as quat) ) fn pivotLookAt obj target = ( ResetXForm obj old_tm = obj.transform obj.dir = normalize (target.pos - obj.pos) obj.objectOffsetRot = old_tm * (inverse obj.transform) ) fn RotatePivotOnly obj rotation = ( local rotValInv = inverse (rotation as quat) animate off in coordsys local obj.rotation *= RotValInv obj.objectoffsetrot*=RotValInv obj.objectoffsetpos*=RotValInv ) Happy to hear of any opinions out there on this for optimising or constructive improving. Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/43542343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Update and Select in one statement I am attempting to do an UPDATE and a SELECT in the same sql statement. For some reason, the below code is failing. $sql = "UPDATE mytable SET last_activity=CURRENT_TIMESTAMP, info1=:info1, info2=:info2 WHERE id = {$id};"; $sql .= "SELECT id, info1, info2 FROM myTable WHERE info1 >=:valueA AND info2>:valueB;" $stmt = $conn->prepare($sql); $stmt->bindParam(":info1", $info1); $stmt->bindParam(":info2", $info2); $stmt->bindParam(":valueA", $valueA); $stmt->bindParam(":valueB", $valueB); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($result); QUESTION: what might I be doing wrong? I have been spending hours on this issue knowing that it's probably a small error right under my nose. Edited: I obtained this error message when loading the page that contains the php code: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error' in ajaxCall.php:89 Stack trace: #0 ajaxCall.php(89): PDOStatement->fetchAll(2) #1 {main} thrown in ajaxCall.php on line 89 I am using ajax to call the php page that contains the above code, and when I load the php page from the browser, I get the above error message. Line 89 is: $result = $stmt->fetchAll(PDO::FETCH_ASSOC); A: Since you are running two queries, you need to call nextRowset to access the results from the second one. So, do it like this: // code $stmt->execute(); $stmt->nextRowset(); // code When you run two or more queries, you get a multi-rowset result. That means that you get something like this (representation only, not really this): Array( [0] => rowset1, [1] => rowset2, ... ) Since you want the second set -the result from the SELECT-, you can consume the first one by calling nextRowset. That way, you'll be able to fetch the results from the 'important' set. (Even though 'consume' might not be the right word for this, it fits for understanding purposes) A: Executing two queries with one call is only allowed when you are using mysqlnd. Even then, you must have PDO::ATTR_EMULATE_PREPARES set to 1 when using prepared statements. You can set this using: $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1); Alternatively, you can use $conn->exec($sql), which works regardless. However, it will not allow you to bind any data to the executed SQL. All in all, don't execute multiple queries with one call.
{ "language": "en", "url": "https://stackoverflow.com/questions/38553892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Form-Select saving more than 1 value I want to save two values to the DB (user id and user name) with only one form selection field. Is that even possible? This is what I got so far: <%= f.collection_select(:user_id, User.where(brand: current_user.brand), :id, :name, {prompt:true}, {class: 'form-control'}) %> That only saves the user_id (from :id) to the DB. How would you extend this to save also the user_name (from :name) to the DB? <%= f.collection_select(:user_id, :user_name, User.where(brand: current_user.brand), :id, :name, {prompt:true}, {class: 'form-control'}) %> does not work. Many thanks in advance! A: You really only need to save the user_id in order to reference all of the other attributes. I like to use options_for_select and pass it a two dimensional array when I'm saving an id. The first value will be what the user sees. The second value will be what I actually save. In this case, I'm guessing that you'd like the user to see a username but you'd like to actually save the user_id. That would look something like: <%= f.select :user_id, options_for_select(User.choices) %> and then in user.rb: def self.choices choices = [] User.find_each { |u| choices << [u.username, u.id] } choices end You don't need to save both values because you can always access any attribute saved on user with the id. EDIT: per your comment, you actually don't need a select box at all. Just set them in your orders controller create action: @order.username = current_user.username @order.user_id = current_user.id if @order.save # etc Again, though, you don't really need to save the username if you have the user_id as a foreign key. With a foreign key you'll always be able to take an instance of order and say order.user.username and get the appropriate username for that user_id.
{ "language": "en", "url": "https://stackoverflow.com/questions/36308234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Group array of object nesting some of the keys with specific names I have this array of objects, that I need to modify to make it easier the rendering. const items = [ { tab: 'Results', section: '2017', title: 'Full year Results', description: 'Something here', }, { tab: 'Results', section: '2017', title: 'Half year Results', description: 'Something here', }, { tab: 'Reports', section: 'Marketing', title: 'First Report', description: 'Something here', }, ... ]; and I'm trying to modify it, grouping them by specific keys. The idea is to have this output. As you can see the names of the keys could be different than the actual names in the items. I think that makes a bit different from previous posts. const output = [ { tab: 'Results', sections: [ { section: '2017', items: [ { 'item that belongs here' }, { ... } ], }, }, { tab: 'Reports', sections: [ { section: 'Marketing', items: [ { ... }, { ... } ], }, }, ... ] I tried using lodash.groupby, but it doesn't do exactly what i'm looking for. Any idea about how to approach it? Many thanks!! A: This can be done with a clever combinartion of _.map and _.groupBy. const items = [ { tab: 'Results', section: '2017', title: 'Full year Results', description: 'Something here', }, { tab: 'Results', section: '2017', title: 'Half year Results', description: 'Something here', }, { tab: 'Reports', section: 'Marketing', title: 'First Report', description: 'Something here', } ]; function groupAndMap(items, itemKey, childKey, predic){ return _.map(_.groupBy(items,itemKey), (obj,key) => ({ [itemKey]: key, [childKey]: (predic && predic(obj)) || obj })); } var result = groupAndMap(items,"tab","sections", arr => groupAndMap(arr,"section", "items")); console.log(result); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> A: You could use an object without additional libraries. The object contains a property _ which keeps the nested arrays of the given nested group. var items = [{ tab: 'Results', section: '2017', title: 'Full year Results', description: 'Something here' }, { tab: 'Results', section: '2017', title: 'Half year Results', description: 'Something here' }, { tab: 'Reports', section: 'Marketing', title: 'First Report', description: 'Something here' }], keys = { tab: 'sections', section: 'items' }, // or more if required result = [], temp = { _: result }; items.forEach(function (object) { Object.keys(keys).reduce(function (level, key) { if (!level[object[key]]) { level[object[key]] = { _: [] }; level._.push({ [key]: object[key], [keys[key]]: level[object[key]]._ }); } return level[object[key]]; }, temp)._.push({ title: object.title, description: object.description }); }); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/48425797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using JOIN (?) to intentionally return more results than rows Sorry for the length of detail required to ask the question. There are four tables (related to research, not really having anything to do with a sporting facility). They're as follows: 1) Let's say the first table is a list of tennis courts, and let's say there are hundreds of possibilities (not just indoor and outdoor). ------------- TENNIS_COURTS ID Type ------------- 1 Indoor 2 Outdoor … 2) We want to note which day of the year they're available for rental. To prevent redundant rows, we can list individual days (e.g., just the 2nd day of the year, entered as "From:2", "To:2") or blocks (e.g., from the 24th day through the 25th day, entered as "From:24", "To:25"). In this example, the indoor court is the most available while the outdoor court has only two date ranges (obviously unrealistic for winter). --------------------------- DAYS_AVAILABLE ID ProductID From To --------------------------- 1 1 2 2 《 Indoor 2 2 24 25 《 Outdoor 3 2 140 170 《 Outdoor 4 1 280 300 《 Indoor 5 1 340 345 《 Indoor … 3) We also want to add a list of attributes which will grow quite long over time. So rather than incorporating these in a field rule, there's an Attributes table. ----------------------- ATTRIBUTES ID Attribute ----------------------- 1 Age of Player 2 Time of Day 3 Outside Temperature … 4) Lastly, we want to add a list of Considerations (or factors) to consider when renting a court. In this example, risk of injury applies to both indoor and outdoor courts, but visibility and temperature only applies to outdoor. -------------------------------------------------- CONSIDERATIONS ID ProductID AttributeID Effect Link -------------------------------------------------- 1 1 1 Risk of injury www… 《 Indoor 2 2 1 Risk of injury www… 《 Outdoor 3 2 2 Hard to see www… 《 Outdoor 4 2 3 Gets cold www… 《 Outdoor … Utilizing the individual tables above, we'd like to create a consolidated saved view that contains at least one row for each date in the range, starting from the first day of the year (in which a court is available) through the last day of the year (for which a court is available). We also want to repeat the applicable considerations for each day listed. Based on the data shown above, it would look like this: ---------------------------------------- CONSOLIDATED VIEW Day Court Consideration Link ---------------------------------------- 2 Indoor 《 from DAYS_AVAILABLE 2 Indoor Risk of injury www… 《 from CONSIDERATIONS 24 Outdoor 《 from DAYS_AVAILABLE 24 Outdoor Risk of injury www… 《 from CONSIDERATIONS 24 Outdoor Hard to see www… 《 from CONSIDERATIONS 24 Outdoor Gets cold www… 《 from CONSIDERATIONS 25 Outdoor 《 from DAYS_AVAILABLE 25 Outdoor Risk of injury www… 《 from CONSIDERATIONS 25 Outdoor Hard to see www… 《 from CONSIDERATIONS 25 Outdoor Gets cold www… 《 from CONSIDERATIONS … We can then query the consolidated view (e.g., "SELECT * FROM CONSOLIDATED_VIEW where Day = 24") to produce a simple output like: Court: Indoor Available: 24th day Note: Risk of injury (www…) Hard to see (www…) Gets cold (www…) We want to produce the above shown example from a consolidated view because once the data is stored, it won't be changing frequently, and we very likely will not be querying single days at a time anyhow. It's more likely that a web client will fetch all of the rows into a large array (TBD based on determining the total size), and will then present it to users without further server interaction. Can we produce the CONSLIDATED_TABLE solely with an SQL query or do we need to perform some other coding (e.g., PHP or NodeJS)? A: The real deal in your question is: how can I get a list of the available days so I can join my other tables and produce my output, right? I mean, having a list of days, all you need to is JOIN the other tables. As you have a limited list (days of the year), I'd suggest creating a table with a single column containing the 365 (or 366) days (1, 2, 3, ...) and JOIN it with your other tables. The query would be smtg similar to: SELECT ... -- fields u want FROM YOUR_NEW_TABLE n JOIN DAYS_AVAILABLE D on (n.DAY between D.From and D.To) JOIN ... -- other tables that you need info
{ "language": "en", "url": "https://stackoverflow.com/questions/42657301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bootstrap navbar stopping ng-view I'm trying to build a angular application with node.js and jade. Here's the relevant code block body div(ng-controller='AppCtrl') .navbar.navbar-default.navbar-fixed-top(role='navigation') .container .navbar-header button.navbar-toggle(type='button', data-toggle='collapse', data-target='.navbar-collapse') span.sr-only Toggle navigation span.icon-bar span.icon-bar span.icon-bar a.navbar-brand(href='/') Halló {{name}} .navbar-collapse.collapse ul.nav.navbar-nav li.active a(href='/frettir') Fréttir li a(href='/dagskra') Dagskrá li a(href='/skaramuss') Skaramúss div(ng-view) And then ng-view doesn't work. But when I comment out the navbar the ng-view works. What am I doing wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/29883678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unity 2D: Gravitational Pull I'm working on a small game: I want all GameObjects to be pulled into the middle of the screen where they should collide with another GameObject. I tried this attempt: using UnityEngine; using System.Collections; public class Planet : MonoBehaviour { public Transform bird; private float gravitationalForce = 5; private Vector3 directionOfBirdFromPlanet; void Start () { directionOfGameObjectFromMiddle = Vector3.zero; } void FixedUpdate () { directionOfGameObjectFromMiddle = (transform.position-bird.position).normalized; bird.rigidbody2D.AddForce (directionOfGameObjectFromMiddle * gravitationalForce); } } sadly I can't get it to work. I've been told that I have to give the object that is being pulled another script but is it possible to do this just with one script that is used on the object that pulls? A: So first you have a lot of typos / code that doesn't even compile. You use e.g. once directionOfBirdFromPlanet but later call it directionOfGameObjectFromMiddle ;) Your Start is quite redundant. As said bird.rigidbody2D is deprecaded and you should rather use GetComponent<Rigidbody2D>() or even better directly make your field of type public Rigidbody2D bird; For having multiple objects you could simply assign them to a List and do public class Planet : MonoBehaviour { // Directly use the correct field type public List<Rigidbody2D> birds; // Make this field adjustable via the Inspector for fine tuning [SerializeField] private float gravitationalForce = 5; // Your start was redundant private void FixedUpdate() { // iterate through all birds foreach (var bird in birds) { // Since transform.position is a Vector3 but bird.position is a Vector2 you now have to cast var directionOfBirdFromPlanet = ((Vector2) transform.position - bird.position).normalized; // Adds the force towards the center bird.AddForce(directionOfBirdFromPlanet * gravitationalForce); } } } Then on the planet you reference all the bird objects On the birds' Rigidbody2D component make sure to set Gravity Scale -> 0 you also can play with the Linear Drag so in simple words how much should the object slow down itself while moving E.g. this is how it looks like with Linear Drag = 0 so your objects will continue to move away from the center with the same "energy" this is what happens with Linear Drag = 0.3 so your objects lose "energy" over time
{ "language": "en", "url": "https://stackoverflow.com/questions/63723724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I get 'NoneType' object is not callable when try to scale dataframe I have dataframe training_x like this: >>> print(training_x) Pregnancies Glucose BloodPressure 762 9 89 62 127 1 118 58 564 0 91 80 375 12 140 82 663 9 145 80 .. ... ... ... 763 10 101 76 192 7 159 66 629 4 94 65 559 11 85 74 684 5 136 82 [576 rows x 3 columns] When I run the following code on training_x dataframe to do StandardScale its values with below code: from sklearn.preprocessing import StandardScaler s_c = StandardScaler(with_mean=False) testing_x = s_c.fit_transform(training_x) test_x = s_c.transform(testing_x, dt) I get below exception at the step when doing fit_transform 'NoneType' object is not callable I don't know what is the issue, the dataframe doesn't had any none or empty values.
{ "language": "en", "url": "https://stackoverflow.com/questions/74623700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modal to interrupt form submission I have a form that I'm using to execute an account cancellation. I'm trying to display a pure CSS modal form to interrupt the form post so that the user can confirm the submission. So far, to achieve this, I have triggered the modal on form submission. Using the code below however the modal appears but does not interrupt the post, i.e. the post occurs. Does anyone know how to get the modal to interrupt the submission until a further button within the modal is pressed to confirm the post? Form: <form method='post' action='' onsubmit='return validate();'> <fieldset> <input type='hidden' id='cancel' name='cancel' value='cancel'> <input type='submit' id='submit' name='submit' value='submit'> </fieldset> </form> Modal Javascript Trigger: <script> function validate() { var result = document.getElementById('myLink').click(); // var result = confirm("Do you want to submit!"); return result; } </script> A: Change <input type='submit' id='submit' name='submit' value='submit'> to a type button <input type='button' id='submit' name='submit' value='submit'> Handle button click so it opens confirm or whatever confirmation thing you will be using. And then, based on the result yes or no submit the form http://www.w3schools.com/jsref/met_form_submit.asp The problem with your implementation it that document.getElementById('myLink').click(); doesn't really return true or false, at least the result cannot be interpreted as what you expect
{ "language": "en", "url": "https://stackoverflow.com/questions/37848271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java.lang.NoClassDefFoundError: com.google.firebase.FirebaseOptions after updating to Firebase on Play Store I updated my app to use Firebase, it was working perfectly on my device. However its crashing on many of my users devices java.lang.NoClassDefFoundError: com.google.firebase.FirebaseOptions at com.google.firebase.FirebaseApp.zzbu(Unknown Source) at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source) at android.content.ContentProvider.attachInfo(ContentProvider.java:1058) at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source) at android.app.ActivityThread.installProvider(ActivityThread.java:5021) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4633) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4573) at android.app.ActivityThread.access$1400(ActivityThread.java:157) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5319) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at dalvik.system.NativeStart.main(Native Method) This is the crash. dependencies { compile 'com.android.support:multidex:1.0.0' compile 'com.splunk.mint:mint:4.0' compile 'com.android.support:appcompat-v7:24.0.0' compile 'com.android.support:support-v4:24.0.0' compile 'com.google.android.gms:play-services:9.0.2' compile 'com.google.firebase:firebase-core:9.0.2' compile "com.mixpanel.android:mixpanel-android:4.+" compile('com.crashlytics.sdk.android:crashlytics:2.6.3@aar') { transitive = true; } } This is my build.gradle. Any pointers here? A: It looks like the problem is with google play services version of your users. You can try: private boolean checkGooglePlayServices() { final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (status != ConnectionResult.SUCCESS) { Log.e(TAG, GooglePlayServicesUtil.getErrorString(status)); // ask user to update google play services. Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1); dialog.show(); return false; } else { Log.i(TAG, GooglePlayServicesUtil.getErrorString(status)); // google play services is updated. //your code goes here... return true; } } To verify google play services is available. A: You need to lower the firebase version you have, they have some problems with the new versions on some devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/39597144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: InvalidClientTokenId error aws when trying to get caller identity hi I am unable to run this command aws sts get-caller-identity. when I do sudo nano ~/.aws/credentials I can only locate this [default] aws_access_key_id = my_id aws_secret_access_key = my_secret_id and after doing successful steps of command aws configure when I am doing aws sts get-caller-identity I am getting this error An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid. any reason which could cause this ? A: Sometimes this kind of issues are caused by another credential configuration. Environment variables credential configuration takes prority over credentials config file. So in case there are present the environment variables "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY" or "AWS_SESSION_TOKEN" these could generate issues if it were missconfigured or have been expired. Try checking the env vars associated to AWS Credentials and removing them using the 'unset' command in linux. Additionally, to remove env vars permanently you need to remove the lines related on configuration files like: * */etc/environment */etc/profile *~/.profile *~/.bashrc Reference: Configuration settings and precedence A: I had my default region disabled by default (eu-south-1), so I had to enable it via the Web console at first, then it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/70276512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to show column from another table in list_display without foreign key relation? I have these database relationships: Now in my admin.py in the list_display I want to display the orders table plus the quantity row from order_items. To do so, I would use this sql query: SELECT order_id, quantity FROM orders INNER JOIN order_items ON orders.order_id = order_items.order_id; Now I don't know how to do this in the correct way with django without using a raw query. So what do I add in the line list_display = ('order_id') in order to show the quantity row? A: In order to get the quantity for order_items for a particular related order write the following code - >>> from django.db.models import Sum >>> order.order_items_set.aggregate(quantity=Sum('quantity')) It will return you a dictionary like - {'quantity': 3} Refer to here for more information about aggregations In order to show it in your Admin for Order model - class OrderAdmin(admin.ModelAdmin): list_display = ('id', 'user_id', 'status', 'created_at', 'get_quantity') class Meta: model = Order def get_quantity(self, obj): result = obj.order_items_set.aggregate(quantity=Sum('quantity')) return result.get('quantity',0) get_quantity.short_description = 'Quantity' admin.site.register(Order, OrderAdmin) Refer to here to know more about django-admin customizations.
{ "language": "en", "url": "https://stackoverflow.com/questions/55891917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cert Revoked when calling API to my server with self signed cert I'm using Axios in ReactJS to call my API that is hosted on the cloud with a self-signed certificate. The error for the request returns net::ERR_CERT_REVOKED. I've added the self-signed code to my login keychain on MacOS running reactjs. But the cert is still getting revoked when I view the error on the logs on Chrome. On safari, the error is Failed to load resource: The certificate for this server is invalid. try { const response = await axios.post( 'https://1.1.1.1:3000/login', { withCredentials: true }, { auth: apiAuth }, { data: bodyFormData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ) return response.data; } catch (error) { console.log(error); } IP address has been changed for the question. I've tried to use the following code in the Axios request but it doesn't help const agent = new https.Agent({ rejectUnauthorized: false }); Expected the server to give a response but getting cert revoked as response. A: self-signed certificate ... net::ERR_CERT_REVOKED ... MacOS You probably run into the new requirements for certificates in MacOS 10.15 and iOS 13 which seem to be enforced also for self-signed certificates. While you don't provide any details about your specific certificate I guess it is valid for more than 825 days. It might of course also be any other of the new requirements - see Requirements for trusted certificates in iOS 13 and macOS 10.15 for the details.
{ "language": "en", "url": "https://stackoverflow.com/questions/58474007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Angular animations not working on Firefox due to CSP (with web-animations-js in polyfills.ts) I have issue applying Angular animations on Firefox (and Safari). Yes I know that there are a lot of answers out there saying you can simply adding web-animations-js in polyfills.ts and it should do the trick. Unfortunately, it's not working in my case. For your context, this is the CSP policy that we're using default-src 'self'; img-src: *. This is the animation code: animations: [ trigger('toggleCommunicationPanel', [ state('close', style({ maxWidth: '64px', width: '4vw' })), state('open', style({ width: '25vw', minWidth: '480px' })), transition('open=>close', animate('250ms')), transition('close=>open', animate('250ms')) ]) ] This is a chunk of polyfills.ts /** IE10 and IE11 requires the following for NgClass support on SVG elements */ import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). */ import 'web-animations-js'; // Run `npm install --save web-animations-js`. I have configured Angular to extract scss into a single big .css file (to avoid CSP issue). Because by default, Angular CLI will not extract your styles into a stylesheet file, instead it will inject the styles into the DOM using <style> element, this is done for each component style. Hence, you will end up having a lot of <style> element in the <head> element. This of course violates the CSP rule above. I've noticed that, in Chrome, IE and Edge, the css of the animation is extracted as expected, so it's working fine. However, in Firefox, it is injected using <style> element. <style>@keyframes gen_css_kf_2 { 0% { width: 492px; min-Width: 0px; max-Width: none; } 100% { width: 4vw; min-Width: 0px; max-Width: 64px; } } </style> So I suspect it is because of this, the animation will not work on Firefox. The solution might be to change configuration so that Angular CLI will extract css for animations (even we're using Firefox or Safari). This is the configuration for production, as you can see extractCss has been turned on. "configurations": { "production": { "fileReplacements": [{ "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" }], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [{ "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] }, "es5": { "tsConfig": "./tsconfig.es5.json" } } A: For the moment, I see no way of working around this issue. The only solution is to not to use Angular animation if CSP is set to prohibit inline style. Simply translating Angular animation code to css and use ngClass to achieve the same effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/61571057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc radiobuttonfor in editortemplate keyboard navigation does not set model Context: Model generating some RadioButtonFor groupings as input to answer questions. What is happening: Case 1. When mouse click on a radio option the display looks correct. When the [HttpPost] ActionResult(model) for the page is triggered the Model.Answer comes through with the correct value. Which is good and desired. Case 2. When navigating with the keyboard to the radio group and selecting one with arrow keys the display looks correct. But when the [HttpPost] ActionResult (model) is triggered the Model.Answer value is unchanged from what it was loaded as on page load. Here is the code that makes the radio group: @model NexusPWI.ViewModels.Wizard.QuestionModel @* Dynamically generate and model bind controls for QuestionModel *@ @{ <div class="row d-contents"> <div class="form-group"> <div class="question"> <div class="col-lg-2 d-contents"> <div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons"> <label class="btn QuestionRadio btn-default @(Model.Answer == YesNoNAOptions.Yes ? "active" : "")" for="@Model.Answer"> @YesNoNAOptions.Yes.ToString().ToUpper() @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes, new { @onfocus = "radiofocus(event)", @onblur = "radioblur(event)" }) </label> <label class="btn QuestionRadio btn-default @(Model.Answer == YesNoNAOptions.No ? "active" : "")" for="@Model.Answer"> @YesNoNAOptions.No.ToString().ToUpper() @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No, new { @onfocus = "radiofocus(event)", @onblur = "radioblur(event)" }) </label> @if (!Model.NaInvalid) { <label class="btn QuestionRadio btn-default @(Model.Answer == YesNoNAOptions.NA ? "active" : "")" for="@Model.Answer"> N/A @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA, new { @onfocus = "radiofocus(event)", @onblur = "radioblur(event)" }) </label> } </div> </div> <div class="col-lg-9 d-contents"> <div class="row"> <p> <strong>@Model.Question</strong> </p> </div> @Html.HiddenFor(x => Model.Question_IdentityMarker, new { @class = "Question_IdentityMarker" }) </div> </div> </div> </div> } Here is an example of the html that is generated: <div class="form-group"> <div class="question"> <div class="col-lg-2 d-contents"> <div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons"> <label class="btn QuestionRadio btn-default " for="No"> YES <input data-val="true" data-val-required="The Answer field is required." id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="Yes" type="radio"> </label> <label class="btn QuestionRadio btn-default active" for="No"> NO <input checked="checked" id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="No" type="radio"> </label> <label class="btn QuestionRadio btn-default " for="No"> N/A <input id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="NA" type="radio"> </label> </div> </div> <div class="col-lg-9 d-contents"> <div class="row"> <p> <strong>Do you charge sales tax?</strong> </p> </div> <input class="Question_IdentityMarker" id="Questions_0__Question_IdentityMarker" name="Questions[0].Question_IdentityMarker" value="CUSTOMERSALESTAX" type="hidden"> </div> </div> </div> EDIT Adding onFocus & onBlur at request: onFocus & onBlur are css highlighting for the keyboard navigation to make it more clear for the user where they are in the page. function radiofocus(event) { // Get event object if using Internet Explorer var e = event || window.event; // Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element if (e.target) { var addClass = focusClass(e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r"); e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass; } else { var addClass = focusClass(e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r"); e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass; } }; function radioblur(event) { // Get event object if using Internet Explorer var e = event || window.event; var removeClass = focusClass("", "r").trim(); // Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element if (e.target) { e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, ""); } else { e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, ""); } }; Why do the keyboard navigated changes not get back to the controller? Anything to add to make this clearer? Side note: For some reason before a value is chosen in the radio group the keyboard tab navigation is stopping for each radio answer for a question.
{ "language": "en", "url": "https://stackoverflow.com/questions/48551001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Syntax error: missing : after property (jQuery validate) I am building a set of jQuery validate rules to be used for a form prototype. I am getting a JS error with my code. Chromes complains with the error [14:30:27.722] SyntaxError: missing : after property id at the location specified in the code comments. here is the code: $.validator.addMethod("regex", function(value, element, regexpr) { return regexpr.test(value); }, "Entree invalide"); $('#mainform').validate({ rules: { form-nocivique: { //Chrome complains here required: true, digits: true }, form-rue: "required", form-province: "required", form-codepostal: { required: true, regex: /([ABCEGHJKLMNPRSTVWXYZ]\d){3}/i } }, }); Any idea why? A: Your property names (some of them) are invalid identifiers. You can quote it to fix the problem: rules: { "form-nocivique": { //Chrome complains here required: true, digits: true }, You can't use - in an identifier in JavaScript; it's a token (the "minus" operator).
{ "language": "en", "url": "https://stackoverflow.com/questions/22542183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing @Retryable and @Recover methods in Spring Boot + Mockito For one class e.g. called Class A, I call an external api (with exceptions and I have mocked the class). In Class B, I have a method that calls Class A's method with the potential exceptions that could occur. Class B has the @Retryable and @Recover method. I have Class A as a mock object and Class B as a spy. When I mock Class A to throw an exception and I verify the times it has been called - I get the correct maxAttempts called. However, when I try to check and verify the method for recover or retryable I get: UnfinishedVerificationException .. Missing method call for verify.... Does anyone know if it is possible to verify these method calls? A: Those methods can't be mocked because they they are final methods created by spring-retry using a CGLIB proxy.
{ "language": "en", "url": "https://stackoverflow.com/questions/66804651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AttributeError 'module' object has no attribute 'decodebytes' I'm doing some processing on an image using OpenCV. Now I need to convert the base64 string to bytes. In Python-3.6 I could use base64.decodebytes but I can't find the alternate module in Python-2.7 . Is there any other alternative present in Python-2.7 ? cvimg = cv2.imdecode(np_img_array, cv2.IMREAD_COLOR) tmp_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = base64.b64encode(cv2.imencode('.jpg', tmp_img)[1]) img = base64.decodebytes(img) NOTE: I'm using Python-2.7 as one of the module I'm using has not been converted to Python-3.6 A: Python 2 still has the base64 module built in. Using base64.standard_b64encode(s) #and base64.standard_b64decode(s) #Where 's' is an encoded string Should still work.
{ "language": "en", "url": "https://stackoverflow.com/questions/56149779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Live local coding in IntelliJ Can I make IntelliJ re-compile and run when I change the code? All I could find was this infinitest plugin that specifically runs all tests. Maybe something similar to http://www.romaniancoder.com/spring-boot-live-reload-with-intellij/
{ "language": "en", "url": "https://stackoverflow.com/questions/47664069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: default constructor for POCO entity in EF6 Code first approach I'm new in EF. I'm making an app with EF6 Code First approach, I've made all my POCO entities to derive from a base class which define an Id. What I don't know is how to declare the constructor for an entity that handles many to many relatioship. For example: I've got this entity: public partial class ArqAppRole { [Key] [Column(Order = 0)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ApplicationId { get; set; } [Key] [Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int RoleId { get; set; } public DateTime SinceDate { get; set; } public DateTime? UntilDate { get; set; } public bool IsActive { get; set; } public virtual ArqApplication ArqApplication { get; set; } public virtual ArqRole ArqRole { get; set; } } this was auto-generated by EF, what I want is to set it superclass to BaseEntity class that has a default constructor which sets it Id and I don't know how to handle ArqApplication and ArqRole properties and their propper Ids My base class is: public abstract class BaseEntity { private object _id; [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public object Id { get { return _id; } protected set { _id = value; } } protected BaseEntity() : this(null) { } protected BaseEntity(object id) { _id = id; } } A: You can leave the Id on the base class and in this use case you have to configure your one-to-one releshinship with Fluent API. protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<ArqAppRole>() .HasRequired(s => s.Application) .WithRequiredPrincipal(ad => ad.ArqAppRole); } Fluent API will override your code first. But putting the Id in the base class is a bad practice and you have to find tricks everywhere. Just use the conventional way and use the EF as should be used. More info: Code first self referencing foreign key (more than one)
{ "language": "en", "url": "https://stackoverflow.com/questions/37905651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove 'spaces' between html tags in text from Excel In MsExcel/LibreOfficeCalc I have text like this: <h3><strong>Ways to stretch your budget</strong> <p>passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? </p> <p>passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it?</p> <ul> <li><strong>Instrument Rentals</strong> &nbsp;passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it?</li> <li><strong>passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it?</li> </ul> How do I remove the text between html tags ? Example: <p>content<p><ul><li>content></li></ul> A: Just use regular expressions: import re result = re.sub('>\s*<', '><', text, 0, re.M)
{ "language": "en", "url": "https://stackoverflow.com/questions/52791146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is there a way to see if a statement is True during a give time? I have been playing around with the raspberry pi for a bit now and was trying to do a small project. I want my program to recognize when a button is pressed during a given time, i.e 1 seconds, then light up an LED. My attempt was to see if the button was pressed (True), then make the program sleep for 2 seconds, and see if it is still true. This did work but not as efficiently I wanted it to. Is there a way to see if a statement remains True for a given time? edit: more information about my setup and code. I've dissembled an old flashlight, and taken the button from it. The Button does have a two metal pieces on the sides, that i have connected to one GND cable and the other the a 1k ohm resistor and a gpio cable. When i tried the following code: import RPi.GPIO as gpio from time import sleep gpio.setmode(gpio.BOARD) gpio.setup(19, gpio.IN) gpio.setup(11, gpio.OUT) try: while True: if gpio.input(19) == 1: sleep(0.05) if gpio.input(19) == 1: sleep(0.05) if gpio.input(19) == 1: print("on") gpio.output(11, True) else: print("off") gpio.output(11, False) sleep(0.1) finally: print("\nInterrupted.\nCleaning code") gpio.cleanup() Im aware of how gross this code looks, i'm terribly sorry. The reason for the triple if statement was to see if the code returns "on" in 3 different lines after another. This is because for some reason when the input value of the button "is set to" 0, it is actually jumping around 1 and 0 for some reason. This leads to it returning "On \nOff \nOn etc". My thought was if this prints "on" 3 times in a row then this must be on the stable side, so turn the LED on, else turn it off. This works but i'm not really happy with the code. If there was a way for me to see if it is "on" for a second or two then this must be the stable side and i can turn the LED on. And it would make my code in the future of making something similar, include a lot less if statements for a cleaner looking code.
{ "language": "en", "url": "https://stackoverflow.com/questions/68628908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zend Framework 3 AJAX responding data I try to do async contact form validation in ZF3 by using ajax. Thats my ContactController public function contactAction() { $form = $this->form; $request = $this->getRequest(); $response = $this->getResponse(); $vm = new ViewModel(['form' => $this->form]); $form->setInputFilter(new ContactFormFilter()); if (!$this->getRequest()->isPost()) return new ViewModel(['form' => $this->form]); $data = $request->getPost(); $form->setData($data); if (!$form->isValid()) { $vm->setTerminal(true); return $response->setContent(\Zend\Json\Json::encode($form->getMessages())); } } and below is contact.phtml with jquery script. $(function(){ $("#foo").submit(function(event){ event.preventDefault(); $.ajax({ url: '/kontakt', type: 'POST', dataType: 'json', contentType: "application/json; charset=utf-8", async: true, data: ($("#foo").serialize()), success: function (data) { console.log(data); alert(data); }, error: function (data) { console.log(data); } }); }) }) Form has "foo" id; The problem is, that when I submit I get respond like this each time: (its from console) Object -email :Object -message :Object -subject :Object -personal-data :Object and when I open for exmaple "message Object" it shows me : isEmpty :" Field is required" even when the message field isn't empty! Could anyone know what I am doing wrong? A: Remove contentType: "application/json; charset=utf-8", to send the data as url encoded
{ "language": "en", "url": "https://stackoverflow.com/questions/40505196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: String variable is not returning properly in C I have been trying to make a function, is_isogram, return a value that is an alphabetized string. When I pass the value through the function from main, the variable to be returned is set to the correct value. However, when I return the variable from the function, it does not return anything in main. Along with this, I get an error for unable to read memory when I initialize the variable to hold the return value in main. #include <stdbool.h> #include <ctype.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <stdio.h> #include <Windows.h> #include "isogram.h" char is_isogram(char phrase[]) { int i; for (i = 0; phrase[i]; i++) { tolower(phrase[i]); } if (phrase == NULL) { return false; } char temp; int count1; int count2; char *alphabet = (char *)malloc(sizeof(char) * (strlen(phrase) + 1)); int n = strlen(phrase); for (count1 = 0; count1 < n - 1; count1++) { for (count2 = count1 + 1; count2 < n; count2++) { if (phrase[count1] > phrase[count2]) { temp = phrase[count1]; phrase[count1] = phrase[count2]; phrase[count2] = temp; alphabet = phrase; break; } } } return alphabet; } This function does not return the variable alphabet. I have been trying to use malloc and other techniques to return this local variable as a value. I wanted to use every character string as an array with "[]," however I would get errors about needing to initialize an array. The value returned is currently just a sizeable garbage value, however, when I step through the process of debugging, the variable alphabet is 'abb.' int main() { char *bet = is_isogram("bab\0"); if (bet == 'abb\0') { return 0; } else { return -1; } } The variable bet is throwing an error before even accessing the function. It tells me it was unable to read the memory and the value for bet is close to NULL for the remainder of the program. In conclusion, the program is not giving returning a value of 'abb' when from the function locally, nor is it saving the variable in memory. It throws garbage into the variable, but the variable is killed, and a new variable cannot be adequately initialized in main. A: There are multiple problems in your code: * *Function is_isogram() is defined as returning a char, it should instead return a string, hence type char *. *is_isogram() attempts to modify the string pointed to by its argument. Since it is called with a string literal from main, this has undefined behavior, potentially a program crash. *You allocate memory for alphabet, but you reset this pointer to phrase in the sorting loop. *The comparison bet == 'abb\0' does not do what you think it does. bet should be a char * and you should use strcmp() to compare the string values. Here is a modified version: #include <ctype.h> #include <string.h> #include <stdio.h> char *is_isogram(const char *phrase) { char *alphabet; int count1, count2, n; if (phrase == NULL) return NULL; alphabet = strdup(phrase); n = strlen(alphabet); for (count1 = 0; count1 < n; count1++) alphabet[count1] = tolower((unsigned char)alphabet[count1]); for (count1 = 0; count1 < n - 1; count1++) { for (count2 = count1 + 1; count2 < n; count2++) { if (alphabet[count1] > alphabet[count2]) { char temp = alphabet[count1]; alphabet[count1] = alphabet[count2]; alphabet[count2] = temp; } } } return alphabet; } int main(void) { char *bet = is_isogram("bab"); if (strcmp(bet, "abb") == 0) { return 0; } else { return -1; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/51584871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update JTable programmatically I have this code to edit contents of already existing JTable: DefaultTableModel items = new DefaultTableModel(); items.addColumn("qwe1"); items.addColumn("qwe2"); items.addColumn("qwe3"); items.addRow(new Object[]{1,2,3}); jTable1.setModel(items); But nothing is displayed in the jTable... I can't quite figure out what I am doing wrong. PS: I know about these: Updating JTable Updating a JTable JTable not updating But that's not exactly what I am trying to do...
{ "language": "en", "url": "https://stackoverflow.com/questions/20301904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Runtime error 462 when saving word file from excel I have an excel sheet that is to create numerous word files while looping through the code. After pasting data från excel, the word files are to be named and saved to the hard drive. The first iteration goes perfect, but on the second I get a Runtime error 462 just before saving the word file. Any suggestions? Thanks in advance! Sub Kopiera_Excel_Till_Word(FilVag As String) Selection.Copy Dim appWord As Word.Application Set appWord = New Word.Application Dim FilNamnVag As String With appWord .Visible = True .Activate End With appWord.Documents.Add appWord.Activate appWord.Selection.Paste Application.CutCopyMode = False With appWord .Visible = True .Activate End With '****It runs this far the second iteration, then I get Runtime error 462***** ActiveDocument.SaveAs2 filename:= _ FilVag, FileFormat:= _ wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _ :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _ :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _ SaveAsAOCELetter:=False, CompatibilityMode:=15 Application.CutCopyMode = False ActiveDocument.Close SaveChanges:=False appWord.Quit A: When working in VBA it pays to be specific rather than rely on objects such as ActiveDocument Sub Kopiera_Excel_Till_Word(FilVag As String) Selection.Copy Dim appWord As Word.Application Set appWord = New Word.Application Dim FilNamnVag As String Dim docWord As Word.Document Set docWord = appWord.Documents.Add docWord.Range.Paste Application.CutCopyMode = False docWord.SaveAs2 Filename:= _ FilVag, FileFormat:= _ wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _ :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _ :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _ SaveAsAOCELetter:=False, CompatibilityMode:=15 docWord.Close SaveChanges:=False appWord.Quit Application.CutCopyMode = False End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/72111400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reload content blockers while they are active? I have an app with several content blockers extension. Their configuration is fine and they act as they are supposed to. However I need to call reloadContentBlocker(withIdentifier:completionHandler:) from SFContentBlockerManager when I've updated the filter lists for example. Here is a code example (with NSLog for timestamp purposes below): func reload(_ callback: @escaping((Bool) -> Void)) { NSLog("Reload start") let contentBlockersIdentifiers = ["com.aaa.bbb.ContentBlocker.ExampleA", "com.aaa.bbb.ContentBlocker.ExampleB", "com.aaa.bbb.ContentBlocker.ExampleC", "com.aaa.bbb.ContentBlocker.ExampleD", "com.aaa.bbb.ContentBlocker.ExampleE"] var failures: [String] = [String]() let dispatchSemaphore = DispatchSemaphore(value: 0) let dispatchQueue = DispatchQueue(label: "reload-queue", qos: .userInitiated) dispatchQueue.async { NSLog("Reloading content blockers") for aContentBlockerIdentifier in contentBlockersIdentifiers { NSLog("Reloading '\(aContentBlockerIdentifier)'") SFContentBlockerManager.reloadContentBlocker(withIdentifier: aContentBlockerIdentifier) { (error) in if let error = error?.localizedDescription { NSLog("Failed to reload '\(aContentBlockerIdentifier)': \(error)") failures.append(aContentBlockerIdentifier) } else { NSLog("Successfully reloaded '\(aContentBlockerIdentifier)'") } dispatchSemaphore.signal() } dispatchSemaphore.wait() } callback(failures.isEmpty) NSLog("Reload end") } } This is what is prints: 16:41:43.391543+0200 Reload start 16:41:43.392003+0200 Reloading content blockers 16:41:43.392125+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleA' 16:41:50.010102+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleA' 16:41:50.010299+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleB' 16:41:50.351554+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleB': The operation couldn’t be completed. (WKErrorDomain error 2.) 16:41:50.351676+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleC' 16:41:50.493327+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleC': The operation couldn’t be completed. (WKErrorDomain error 2.) 16:41:50.493429+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleD' 16:41:50.631578+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleD': The operation couldn’t be completed. (WKErrorDomain error 2.) 16:41:50.631681+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleE' 16:41:50.718466+0200 Failed to reload 'com.aaa.bbb.ContentBlocker.ExampleE': The operation couldn’t be completed. (WKErrorDomain error 2.) 16:41:50.718600+0200 Reload end It apparently tries to do the reload one content blocker after another (as I wanted to do with the DispatchSemaphore). However after the first one succeeded the following are failures. Now let's go and disable the Content Blockers in Setting App > Safari > Content Blockers and try again: 16:55:05.699392+0200 Reload start 16:55:05.700171+0200 Reloading content blockers 16:55:05.700564+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleA' 16:55:05.714444+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleB' 16:55:05.714909+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleB' 16:55:05.723056+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleB' 16:55:05.723343+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleC' 16:55:05.730565+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleC' 16:55:05.730775+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleD' 16:55:05.735733+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleD' 16:55:05.735841+0200 Reloading 'com.aaa.bbb.ContentBlocker.ExampleE' 16:55:05.740758+0200 Successfully reloaded 'com.aaa.bbb.ContentBlocker.ExampleE' 16:55:05.740865+0200 Reload end Surprise... it works. But I would rather not ask my users to : * *go manually disable the Content Blockers in the Settings *perform the update manually (while waiting to develop automatic refresh) *go manually re-enable the Content Blockers in the Settings I'm missing something somewhere (maybe a thread issue). Hopefully someone will be able to help! A: Most likely, it means that you have rules that contains incorrect syntax or rules file have more the 50 000 rules. Also the error can happened when you fill returningItems with nil context.completeRequest(returningItems: nil, completionHandler: nil) in your NSExtensionRequestHandling where context is NSExtensionContext
{ "language": "en", "url": "https://stackoverflow.com/questions/61411329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: BeautifulSoup: how to get all article links from this link? I want to get all article link from "https://www.cnnindonesia.com/search?query=covid" Here is my code: links = [] base_url = requests.get(f"https://www.cnnindonesia.com/search?query=covid") soup = bs(base_url.text, 'html.parser') cont = soup.find_all('div', class_='container') for l in cont: l_cont = l.find_all('div', class_='l_content') for bf in l_cont: bf_cont = bf.find_all('div', class_='box feed') for lm in bf_cont: lm_cont = lm.find('div', class_='list media_rows middle') for article in lm_cont.find_all('article'): a_cont = article.find('a', href=True) if url: link = a['href'] links.append(link) and result is as follows: links [] A: Each article has this structure: <article class="col_4"> <a href="https://www.cnnindonesia.com/..."> <span>...</span> <h2 class="title">...</h2> </a> </article> Simpler to iterate over the article elements then look for a elements. Try: from bs4 import BeautifulSoup import requests links = [] response = requests.get(f"https://www.cnnindonesia.com/search?query=covid") soup = BeautifulSoup(response.text, 'html.parser') for article in soup.find_all('article'): url = article.find('a', href=True) if url: link = url['href'] print(link) links.append(link) print(links) Output: https://www.cnnindonesia.com/nasional/...pola-sawah-di-laut-natuna-utara ... ['https://www.cnnindonesia.com/nasional/...pola-sawah-di-laut-natuna-utara', ... 'https://www.cnnindonesia.com/gaya-hidup/...ikut-penerbangan-gravitasi-nol'] Update: If want to extract the URLs that are dynamically added by JavaScript inside the <div class="list media_rows middle"> element then you must use something like Selenium that can extract the content after the full page is rendered in the web browser. from selenium import webdriver from selenium.webdriver.common.by import By url = 'https://www.cnnindonesia.com/search?query=covid' links = [] options = webdriver.ChromeOptions() pathToChromeDriver = "chromedriver.exe" browser = webdriver.Chrome(executable_path=pathToChromeDriver, options=options) try: browser.get(url) browser.implicitly_wait(10) html = browser.page_source content = browser.find_element(By.CLASS_NAME, 'media_rows') for elt in content.find_elements(By.TAG_NAME, 'article'): link = elt.find_element(By.TAG_NAME, 'a') href = link.get_attribute('href') if href: print(href) links.append(href) finally: browser.quit() A: Sorry, can't add comments not enough reputation. I think this line: for url in lm_row_cont.find_all('a'): Should have the a tag as '<a>' Or you could use regex (skipping the above) to match the relevant items after grabbing a div.
{ "language": "en", "url": "https://stackoverflow.com/questions/69458471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I install only install_requires but not the lib with setup.py I want to make a docker image for my OpenERP. I have modified OpenERP source code and I want to use the image to run it. So the image should be "libs ready" but have no OpenERP pre-installed on it. The OpenERP project has a setup.py. I'd like to install all the libs specified by install_requires. In other words, I'd like to run pip install -r requirements.txt if there it is. Unfortunately, the pip and apt-get just install quite different versions of libs. So it would be quite a lot of work to make the requirements.txt file myself, nor to maintain it. What choices do I have?
{ "language": "en", "url": "https://stackoverflow.com/questions/27266626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: strcpy segfault copying file content to array This is my code char url[MAX_WORD + 1]; char *urls[MAX_WORD + 1]; //char word[MAX_WORD + 1]; while(fscanf(fp, "%100s", url) == 1) { strcpy(urls[index], url); index++; } This is the error I'm getting on valgrind: ==43177== Process terminating with default action of signal 11 (SIGSEGV) ==43177== Access not within mapped region at address 0x4844000 ==43177== at 0x4838DC8: strcpy (vg_replace_strmem.c:512) ==43177== by 0x109898: generateInvertedIndex (invertedIndex.c:102) ==43177== by 0x1092B4: test1 (testInvertedIndex.c:36) ==43177== by 0x109244: main (testInvertedIndex.c:23) This is the content of the file it is copying from nasa.txt news1.txt file11.txt mixed.txt planets.txt file21.txt info31.txt I don't know how I am getting this error. I just want to copy the content of the file to an array of Urls. But it doesn't work. A: You have an array of uninitialized pointers or null pointers if the array is declared in the file scope char *urls[MAX_WORD + 1]; So this call strcpy(urls[index], url); invokes undefined behavior. It seems what you need is to declare a two-dimensional array like for example char urls[MAX_WORD + 1][MAX_WORD + 1]; Or in the original array allocate dynamically memory for the stored string. Something like urls[index] = malloc( strlen( url ) + 1 ); if ( urls[index] != NULL ) strcpy(urls[index], url); else /* some error processing */;
{ "language": "en", "url": "https://stackoverflow.com/questions/71335369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Unable to login in Wordpress Admin on Local I am currently doing work for a live wordpress site and created a local installation using local by flywheel. When I use the admin credentials on the live site it logs in fine. However when I try to login on the local installation using the same credentials it says invalid username or password. I checked the users table in the sql database file and the username is in the table. How do i change the password on the local installation? Edit: I created the local version of the website using the wp-content folder and a sql file of the exported databases from the live website. This was how I was instructed per local by flywheel's tutorial A: https://wordpress.org/support/article/resetting-your-password/ This article will probably be your best bet. While it holds all the information. I highly recommend either going down the route of wp-cli or direct to the database. For MySQL this will effectively change the password for you UPDATE wp_options SET user_pass=MD5('newpass') WHERE user_login = <username>; However, for wp-cli you can run this wp-cli user update <username> --user_pass=<newpass> Overall wp-cli is the best option because it has tooling to solve so many other problems too! Good luck out there. A: Below article will set a resetting your password, and you can go to wp_users and edit your account pass https://wordpress.org/support/article/resetting-your-password/
{ "language": "en", "url": "https://stackoverflow.com/questions/58142709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How use BufferList with SocketAsyncEventArgs and not get SocketError InvalidArgument? I can use SetBuffer with SocketAsyncEventArgs just fine. If I try to use BufferList (after doing SetBuffer(null, 0, 0)) I always and immediately get SocketError InvalidArgument (10022) when I do SendAsync on the socket. There are NO examples or documentation on how to use BufferList and what I am doing makes sense (to me anyway). Can someone point out an example program or code snippet? I'm tearing my hair out over this and don't have much left ... Here is basically what I am doing (e is SocketAsyncEventArgs and lSocket is the same socket I use for SetBuffer which works) // null the buffer since we will use a buffer list e.SetBuffer(null, 0, 0); // create a bufferlist e.BufferList = new List<ArraySegment<byte>>(); // create the bufferlist with the network header and the response bytes e.BufferList.Add(new ArraySegment<byte>(lTxBytes)); // add the 4 character total length e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); // echo back the incoming sequence number e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse))); // *** the SendAsync always completes IMMEDIATELY (returns false) gets SocketError InvalidArgument (10022) if (lSocket.SendAsync(e) == false) { // data was already sent back to the client. AppSupport.WriteLog(LogLevel.Flow, "ProcessReceive had SendAsync complete synchronously (bytes transferred {0}).", e.BytesTransferred); ProcessSend(e); } A: The reason you are getting an exception is that under the hood the SocketAsyncEventArgs only uses the buffers present in the list at the time of setting the BufferList property. Basically you are trying to send en empty buffer with the code : e.BufferList = new List<ArraySegment<byte>>(); e.BufferList.Add(new ArraySegment<byte>(lTxBytes)); e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse))); Instead try to do : var list = new List<ArraySegment<byte>>(); list.Add(new ArraySegment<byte>(lTxBytes)); list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse))); e.BufferList = list; This behavior is not well documented at all and can only be understood by looking at the BufferList setter code in detail. Behind the scenes the SocketAsyncEventArgs has a WSABuffer array field(for interop with native code) where it copies and pins the byte arrays references when you set the BufferList. Since it is this WSABuffer[] that is sent to native code, that explains why your code throws an exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/11820677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using Dictionaries for DataGridView in c# WPF I have a Dictionary that I want to display in DataGridView in a WPF App. I have another list with the column headers that I want. The list of doubles is 200 items long, and the headers 201 items long. Im wondering if there is an way of displaying them all in a table ? Dictionary<string, List<double>> properties = new Dictionary<string, List<double>>(); List<string> gPropertyNames = new List<string>(); propertiesDataGrid.ItemsSource = properties; Trying the ToArray() and Values.ToList() after the dictionary name are not helping me. All I see in the datagrid is two columns, Key and Value, with the value column saying (Collection). I can manually set the column headers in XAML, but if there is an automated way, that would be awesome, especially if I need to change the headers. A: do you need to use some methods specific to the dictionaries ? If not, here is my suggestion : * *Create a class which has a string and a double properties *Create an ObservableCollection of that class *Set that collection as the items source of your datagrid. And that's it ! The headers will be the the name of the properties specified in your class, so easy to change afterward. Hope it's help A: Can bind rows to a collection but not columns Create a class with 200 properties like Jacques answer For the get you would return Value[0], Value[1], ... And it can be List Or you could could build up the columns in code being and in the case you can bind to Value[0], Value[1], ...
{ "language": "en", "url": "https://stackoverflow.com/questions/31996307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reset postgres password I am on Windows 10 using WAMP, I added PostgreSQL and PhpPgAdmin, everything was working fine. Today I can not log in to PostgreSQL through PhpPgAdmin or a php_pdo web app. I tried editing pg_hba.conf in 2 locations c:\PostgreSQL\pg96\init\ and c:\PostgreSQL\data\pg96\ and changed the 'method' to trust as per many answers here, none of the CLI answers worked either. I also restarted "WAMP" and even the whole computer, but no luck. The default password worked before postgres and root but not now. How do I reset the postgre password? UPDATE runing psql -U postgres returns; psql: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? contents of pg_hba.conf # TYPE DATABASE USER CIDR-ADDRESS METHOD # IPv4 local & remote connections: host all all 127.0.0.1/32 trust host all all 0.0.0.0/0 trust # IPv6 local connections: host all all ::1/128 trust A: so after a lot more diging, it was not that the password was wrong, but for whatever reason PostgreSQL was not even running. Windows is such a PITA! in the end, running pg_ctl -D "C:\PostgreSQL\data\pg96" start from CMD got it going. Now we will see if it starts tomorrow.... I miss my Unix Environment. ----- UPDATE ----- While the above code works, it is moving in the wrong direction. goto Control Panel->Administrative Tools->Services and find 'PostgreSQL ...' in the list. Right click and open Properties. My Startup type: was set to 'Automatic' but it was not starting, I set it to 'Automatic (Delayed Start)' and now it is working, automagically!
{ "language": "en", "url": "https://stackoverflow.com/questions/46223116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Same API returns different results I need some advice. I need to get data from API to display it on my application. The API is working both through Postman or through the browser, but when I upload the same code to the server, my API response returns NULL. Here is the response I am getting with POSTMAN: And here is the code I am using: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www.instagram.com/myexcellentuser/?__a=1'); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_VERBOSE, 1); $file_data = json_decode(curl_exec($ch)); curl_close($ch); var_dump($file_data); And here is what this same code returns on the app hosted on a server: I would be extremely grateful for the advice! Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/58838727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to populate an html page using data from a SQL table I want to populate an html page using data from a SQL table... data will be categorized based the year Table will look something like this: Year Month article ----------------------- 2010 Jan   Sql101 2010 Feb   Html101 2010 Mar   Smsht101 2011 jan   test101 I want the output to look something like this 2010 Jan sql101 Feb html101 Mar smsht101 2011 Jan test101 What is the easiest method to do this? I'm fairly new to ASP.NET. Maybe using a repeater?
{ "language": "en", "url": "https://stackoverflow.com/questions/66517936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div "jumping" over page I made chat, and I am using ajax to refresh messages function loadlink(){ $('#porukice').load('messages.php',function () { $(this).unwrap(); }); } loadlink(); // This will run on page load setInterval(function(){ loadlink() // this will run after every 5 seconds }, 2000); The div <div id="porukice" style=""></div> Is moving over a page three times, then it stops but in odd place. The first time element appear on page everything is fine, but after 2 ajax reloads it change place and stops, ajax still works. I really can't figure out why is this happening. That is how it moves with ajax reload. A: You guys wont believe what was problem. I just realized that because text input box had size="150"set, div element above jumped like insane. It's fixed now.
{ "language": "en", "url": "https://stackoverflow.com/questions/42402689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }