text
stringlengths
175
47.7k
meta
dict
Q: How to deal with a coworker who wants to be the expert even though he has no expertise? I am a junior developer and there is a more senior dev on our team (but certainly not the most senior) who, while being a valuable and productive member, occasionally goes on a power trip and decides that he's going to "optimize" something. These events usually go like this: him: "We should do A,B,C because it will increase our productivity for D,E,F reasons. I'll start this work now. Everyone can adopt the new system when I'm done" me or someone else: "Wait. That doesn't make any sense and will introduce problems H,I,J." him: "Oh, I didn't know that, thanks for informing me. So I'll do K,L,M instead." me or someone else: "That's still overly complicated and doesn't gain us anything, can we just keep what we have?" him: "Oh, I guess so. I was just trying to learn and help." Maybe 1/5 times his idea has merit and he proceeds with it, the rest of the time it causes confusion, wasted time, and aggravation on the team. Sometimes the exchanges can get fairly heated with multiple people wasting an entire day replying to this thread. For example, this week's issue is that he's appointed himself the team expert on designing our migration to git. Nevermind the fact that he has never used git once in his life, and that we have an in-house team dedicated to helping with git transitions. I assume that this is an effect of his own frustration at lack of career advancement or something. Either way, this happens once or twice a month to the point that it is affecting my own job satisfaction. By stepping in like I (and my other teammates) do, I feel that I am accomplishing two things: Curbing ridiculous ideas before he sinks to much time into them, or causes more confusion than necessary. By taking an adversarial tone, I am definitely contributing (or causing?) interpersonal conflict on the team. My question is: I am under no delusion that I can change his habits, so what can I, as a junior member of the team, do to reduce the amount of conflict, and ultimately increase my own happiness? A: In a team project everyone has right to contribute or voice their opinion. One of your concern probably is how he is declaring his idea as next execution step instead of asking your opinion on it. However, complaining on just how he presents his idea may not be the right thing to do. Curbing ridiculous ideas before he sinks to much time into them This is very subjective. Lot of ideas which sound ridiculous at first are actually very good ideas. Like you said 1 out of 5 idea is actually good. I do not think you will ever be able to objectively decide on the quality of the idea just by listening to it once. By taking an adversarial tone, I do not think that is your job either. If anyone, it should be your team leader or manager who is responsible for the project management. If it is a genuine concern, you and your other team members can discuss this to the project manager and let them decide how to handle it. You can try to give some examples from past on how it created confusion in the team but in my experience it is very difficult to make a convincing and conclusive argument that he is responsible for loss of productivity. There will be always another side to it which will contradict yours. Finally, I am surprised that behavior of a team member towards a project is causing you unhappiness and threatening your job satisfaction. You will never have a perfect team in any company or any project. Part of the challenge and maturity process is to learn to work with all kinds of people. You may like some and you may not like others. You are obviously posting this question here to get this learning but I think you are already making a conclusion in your question about him and about the effect it will have on you. Keep an open mind and enjoy the work. Worst case is you would have listen to some "ridiculous" ideas in your meetings and spend some time on that. Is it really that bad? You will have to deal with lot bigger challenges than this.
{ "pile_set_name": "StackExchange" }
Q: Reverse turning of Stepper motor I have a stepper motor connected to my Arduino like this using the ULN2003A Darlington Array: (Ignore the potentiometer) And I have programmed it with the following code: #include <Stepper.h> int in1Pin = 22; int in2Pin = 23; int in3Pin = 24; int in4Pin = 25; Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin); void setup() { pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); motor.setSpeed(25); } void loop() { int steps = 360; motor.step(steps); delay(500); } At the moment the motor rotates clockwise, how could I have it so it rotates in the opposite direction? My code was copied and edited from here. The problem was that I had the two middle wires the wrong way round as said here: http://forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&topic=143276.msg‌​ A: The answer is simple. Just pass a negative number of steps as an argument to motor.step();. Another note: You forgot a semicolon on your second to last line. IIRC this doesn't matter in C, but it's just bad practice to do this. If you add a line of code below that, then it won't work. Example code: #include <Stepper.h> int in1Pin = 22; int in2Pin = 23; int in3Pin = 24; int in4Pin = 25; Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin); void setup() { pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); motor.setSpeed(25); } void loop() { int steps = 360; motor.step(steps); delay(100); steps = -360; motor.step(steps); delay(500); //Semicolon added }
{ "pile_set_name": "StackExchange" }
Q: How to clear all the textbox fields in a parent page using jquery Is their any way to clear all the textbox values in a parent form using jquery or javascript. Now i am clearing each fields using var parentDoc1 = window.opener.document; parentDoc1.getElementById(id).value=""; A: To clear the all textboxes , you can use this: $(parentDoc1).find('input[type=text]').val(''); If some of textboxes (e.g. textboxes with mytextboxclass class, with mytextboxid id,etc...) mustn't be cleaned, then you can use :not in your selector for excluding those: $(parentDoc1).find('input[type=text]:not(.mytextboxclass,#mytextboxid)').val('');
{ "pile_set_name": "StackExchange" }
Q: Maven artefact licensing I was asking why Google doesn't upload android artefacts into the maven central repository. Apparently the answer is that user has to accept license before download. I know that it is possible (and required) to include a license to the artefact. But is it possible to force user to accept it before downloading and usage? A: It's simply not possible cause Maven has no such mechanism. Apart from that it's interactive during the download of artifacts.
{ "pile_set_name": "StackExchange" }
Q: How do I make my store private in React reflux How do I enforce my store functions and model private. If my store is var employeeActions = Reflux.createActions(['addEmployee']); var empStore = Reflux.createstore({ listenables: [employeeActions], model: { Total:0, employees:[] } onAddEmployee: function(employee){ this.model.employees.push(employee); } }); Even though flux says Actions->Store. The current object structure doesnt stop a developer in the team from calling empStore.OnAddEmployee ? A: Your store should be in a module, assuming you are using browserify or webpack or something similar and you require your modules. So any variable / object / function you declare in the module but don't include in the object sent to the Reflux.createStore() is private. So something like this: var employeeActions = Reflux.createActions(['addEmployee']); var model: { Total:0, employees:[] } var empStore = Reflux.createstore({ listenables: [employeeActions], onAddEmployee: function(employee){ model.employees.push(employee); } }); I would suggest keeping the onAddEmployee function on the object and rely on reflux to wire everything up if you're using the listenables mixin. Otherwise, just follow the examples on github: https://github.com/reflux/refluxjs#creating-data-stores and using the same principle, keep the function private, outside the object you are passing to the factory method.
{ "pile_set_name": "StackExchange" }
Q: How to using the loop and bulk load tasks to insert the name of the csv files being looped? Description I have created an SSIS package imports data from hundreds of csv files on a daily bases I have used the bulk load and foreach loop container Problem I have created a column on a database table and wanted to know if it is possible to add the source file name on each row of data. A: If you have the filename in a variable (which you could do in the for each loop) then you just use the variable as the data source for the column. Or ther may be a system variable that contains the file name, pole around a bit inthe system varaibles available to you and see.
{ "pile_set_name": "StackExchange" }
Q: Живой поиск имени клиента при добавлении заказа Есть две базы. Клиенты Заказы При добавлении заказа, есть поле Имя клиента (client_name), которое нужно брать из первой базы (также же client_name). При введении первых букв имени клиента, выводится список. Выбираю нужное имя и оно вставляется в мой input (referal), но почему-то при добавлении в базу что-то идет не так и оно остается пустым в MySQL, другие поля нормально добавляются. Где моя ошибка? Input <label>Имя и Фамилия Клиента</label> <input type="text" name="referal" class="who form-control" autocomplete="off"> <ul class="search_result"></ul> search.js $(function(){ //Живой поиск $('.who').bind("change keyup input click", function() { if(this.value.length >= 2){ $.ajax({ type: 'post', url: "search.php", //Путь к обработчику data: {'referal':this.value}, response: 'text', success: function(data){ $(".search_result").html(data).fadeIn(); //Выводим полученые данные в списке } }) } }) $(".search_result").hover(function(){ $(".who").blur(); //Убираем фокус с input }) //При выборе результата поиска, прячем список и заносим выбранный результат в input $(".search_result").on("click", "li", function(){ s_user = $(this).text(); $(".who").val(s_user).attr('disabled', 'disabled'); //деактивируем input, если нужно $(".search_result").fadeOut(); }) }) search.php $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $mysqli -> query("SET NAMES 'utf8'") or die ("Ошибка соединения с базой!"); if(!empty($_POST["referal"])){ $db_table = "clients"; $referal = trim(strip_tags(stripcslashes(htmlspecialchars($_POST["referal"])))); $db_referal = $mysqli -> query("SELECT * from ".$db_table." search WHERE client_name LIKE '%$referal%'") or die('Ошибка №'.__LINE__.'<br>Обратитесь к администратору сайта пожалуйста, сообщив номер ошибки.'); while ($row = $db_referal -> fetch_array()) { echo "\n<li>".$row["client_name"]."</li>"; } } Обработчик добавления заказов, то есть после выбора нужного клиента $client_name = $_POST["referal"]; $db_table = "orders"; // Имя Таблицы БД // Подключение к базе данных $db = mysql_connect($host,$user,$password) OR DIE("Не могу создать соединение "); // Выборка базы mysql_select_db("crm",$db); // Установка кодировки соединения mysql_query("SET NAMES 'utf8'",$db); $result = mysql_query ("INSERT INTO ".$db_table." (client_name,status,date) VALUES ('$client_name','$status','$date')"); A: Заменил $(".who").val(s_user).attr('disabled', 'disabled'); на $(".who").val(s_user)
{ "pile_set_name": "StackExchange" }
Q: NestJS - Use service inside Interceptor (not global interceptor) I have a controller that uses custom interceptor: Controller: @UseInterceptors(SignInterceptor) @Get('users') async findOne(@Query() getUserDto: GetUser) { return await this.userService.findByUsername(getUserDto.username) } I have also I SignService, which is wrapper around NestJwt: SignService module: @Module({ imports: [ JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ privateKey: configService.get('PRIVATE_KEY'), publicKey: configService.get('PUBLIC_KEY'), signOptions: { expiresIn: configService.get('JWT_EXP_TIME_IN_SECONDS'), algorithm: 'RS256', }, }), inject: [ConfigService], }), ], providers: [SignService], exports: [SignService], }) export class SignModule {} And Finally SignInterceptor: @Injectable() export class SignInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe(map(data => this.sign(data))) } sign(data) { const signed = { ...data, _signed: 'signedContent', } return signed } } SignService works properly and I use it. I would like to use this as an interceptor How can I inject SignService in to SignInterceptor, so I can use the functions it provides? A: I assume that SignInterceptor is part of the ApiModule: @Module({ imports: [SignModule], // Import the SignModule into the ApiModule. controllers: [UsersController], providers: [SignInterceptor], }) export class ApiModule {} Then inject the SignService into the SignInterceptor: @Injectable() export class SignInterceptor implements NestInterceptor { constructor(private signService: SignService) {} //... } Because you use @UseInterceptors(SignInterceptor) to use the interceptor in your controller Nestjs will instantiate the SignInterceptor for you and handle the injection of dependencies.
{ "pile_set_name": "StackExchange" }
Q: How do I write equations with sin in .NET Math class? I know how to solve this using a calculator, but how do I solve it using the Math class in .NET? (15/sin(v))=(10/sin(37)) A: Math doesn't offer a solver; it simply provides a few tools for common math operations. You would have to solve it manually, or fine a solver lib. But anecdotally: var v = 180 * Math.Asin(15 * Math.Sin(37 * Math.PI / 180) / 10) / Math.PI; // ~= 64.518 degrees assuming you want your units in degrees.
{ "pile_set_name": "StackExchange" }
Q: What is better: select duplicates check OR making a unique index? I have a table like this: `id` int(11) NOT NULL AUTO_INCREMENT, `torderid` int(11) DEFAULT NULL, `tuid` int(11) DEFAULT NULL, `tcontid` int(11) DEFAULT NULL, `tstatus` varchar(10) DEFAULT 'pending', the rule here is that the same user UID can't have more than one pending order with the same contid. so the first thing i could do is to check if there is a pending order like this: select count(id) into @cnt from tblorders where tuid = 1 and tcontid=5 and tstatus like 'pending'; and if it is > 0 then can't insert. or i can just make a unique index for the three columns and that way the table won't accept new records of the duplicates. the question is: WHICH WAY IS FASTER? because thats gonna be a large database... A: Few suggestions. use tstatus = 'pending'; instead of tstatus like 'pending'; Creating composite primary keys for tid, tcontid, tstatus may not work if you are considering only for 'pending' status. What about other statuses? If you decide to index the columns, I would recommend you create a separate table for tstatus and use the foreign key reference here. So it will save the space for the indexed columns and also your query will always run on the indexed fields.
{ "pile_set_name": "StackExchange" }
Q: Can I have applications using Java 1.4.2_12 and Java 1.5 on the same windows server I have a couple of applications running on Java 1.4.2_12 and now need to add an new application that uses Java 1.5. Can I have both java versions on a windows server? A: Yes. You just need to make sure that each has the correct version of Java/the JRE on its CLASSPATH, PATH and JAVA_HOME environment variables. A: Yes: actually JDK or JRE can be just "copied" wherever you want, not "installed" (avoiding putting anything in c:\Windows\System32) I would also recommend not using global environment variables. That way, your applications depend entirely on local settings (local to the application), and not on external Java installation side-effects
{ "pile_set_name": "StackExchange" }
Q: Erro ao abrir nova Activity Estou apanhando aqui para conseguir fazer com que ao clicar em um botão, seja aberta uma nova Activity. Olhei a documentação do Android sobre Activity, Intent, os métodos para criar e ainda sim, não funciona. Basicamente, fiz os seguintes passos: Criei um novo Android XML Layout File com a estrutura da nova Activity Criei uma nova classe para controlar essa nova Activity Fui no AndroidManifest.xml e add essa nova Activity lá. Fui no Main.java e configurei o .onClickListener para disparar a Intent e abrir a tela. Mas, ao clicar no botão que dispara a chamada da 'segunda Activity', o emulador dá pau. Onde está o problema? Segue arquivos para análise: MainActivity.java package com.emanuel.teste; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.Button; public class MainActivity extends Activity { TextView lblSaldo; Button btSoma; Button btSub; Button btAjuda; int saldo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lblSaldo = (TextView) findViewById(R.id.tvSaldo); btSoma = (Button) findViewById(R.id.btSoma); btSub = (Button) findViewById(R.id.btSub); btAjuda = (Button) findViewById(R.id.btAjuda); btSoma.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { saldo++; lblSaldo.setText("O saldo é: " +saldo); } }); btSub.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { saldo--; lblSaldo.setText("O saldo é: " +saldo); } }); btAjuda.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent itAjuda = new Intent("com.emanuel.teste.ajuda"); startActivity(itAjuda); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } ajuda.java Essa é a classe que controla a tela que desejo abrir package com.emanuel.teste; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class ajuda extends Activity{ Button btAjudaVoltar; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.ajuda); btAjudaVoltar = (Button) findViewById(R.id.btAjudaVoltar); btAjudaVoltar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.emanuel.teste" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.emanuel.teste.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ajuda" android:label="@string/app_name"> <intent-filter> <action android:name="com.emanuel.teste.AJUDA"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> </application> </manifest> Logcat 05-30 01:24:11.402: D/AndroidRuntime(333): Shutting down VM 05-30 01:24:11.402: W/dalvikvm(333): threadid=1: thread exiting with uncaught exception (group=0x40015560) 05-30 01:24:11.423: E/AndroidRuntime(333): FATAL EXCEPTION: main 05-30 01:24:11.423: E/AndroidRuntime(333): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.emanuel.teste.ajuda } 05-30 01:24:11.423: E/AndroidRuntime(333): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1409) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1379) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.app.Activity.startActivityForResult(Activity.java:2827) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.app.Activity.startActivity(Activity.java:2933) 05-30 01:24:11.423: E/AndroidRuntime(333): at com.emanuel.teste.MainActivity$3.onClick(MainActivity.java:53) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.view.View.performClick(View.java:2485) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.view.View$PerformClick.run(View.java:9080) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.os.Handler.handleCallback(Handler.java:587) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.os.Handler.dispatchMessage(Handler.java:92) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.os.Looper.loop(Looper.java:123) 05-30 01:24:11.423: E/AndroidRuntime(333): at android.app.ActivityThread.main(ActivityThread.java:3683) 05-30 01:24:11.423: E/AndroidRuntime(333): at java.lang.reflect.Method.invokeNative(Native Method) 05-30 01:24:11.423: E/AndroidRuntime(333): at java.lang.reflect.Method.invoke(Method.java:507) 05-30 01:24:11.423: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 05-30 01:24:11.423: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 05-30 01:24:11.423: E/AndroidRuntime(333): at dalvik.system.NativeStart.main(Native Method) A: Tente alterar a linha: Intent itAjuda = new Intent("com.emanuel.teste.ajuda"); para Intent itAjuda = new Intent("com.emanuel.teste.AJUDA"); OU entao chame assim: Intent openStartingPoint = new Intent(MainActivity.this, AJUDA.class);
{ "pile_set_name": "StackExchange" }
Q: Is there a way to return a value with async/await instead of a Promise ? As a synchronous function do Firstly I am familiar with the concept of asynchronous/synchronous function. There is also a lot of questions related to mine. But I can't find my answer anywhere. So the question is: Is there a way to return a value instead of a Promise using async/await ? As a synchronous function do. For example: async doStuff(param) { return await new Promise((resolve, reject) => { setTimeout(() => { console.log('doStuff after a while.'); resolve('mystuffisdone'+param); }, 2000); }); } console.log(doStuff('1')); The only way to get the value of this function is by using the .then function. doStuff('1').then(response => { console.log(response); // output: mystuffisdone1 doOtherStuffWithMyResponse(response); // ... }); Now, what I want is: const one = doStuff('1'); console.log(one) // mystuffisdone1 const two = doStuff('2'); console.log(two) // mystuffisdone2 To explain myself, I have an asynchronous library full of callbacks. I can turn this asynchronous behavior to a synchronous behavior by using Promises and async/await to faking a synchronous behavior. But there is still a problem, it is still asynchronous in the end; outside of the scope of the async function. doStuff('1').then((r) => {console.log(r)}; console.log('Hello wolrd'); It will result in: Hello world then mystuffisdone1. This is the expected behavior when using async/await functions. But that's not what I want. Now my question would be: Is there a way to do the same thing as await do without the keyword async ? To make the code being synchronous ? And if not possible, why ? Edit: Thank you for all you answers, I think my question is not obsvious for all. To clear up what I think here is my comment to @Nikita Isaev answer. "I understand why all I/O operations are asynchronously done; or done in parallel. But my question is more about the fact that why the engine doesn't block the caller of the sync function in an asynchronous manner ? I mean const a = doStuff(...) is a Promise. We need to call .then to get the result of this function. But why JavaScript or Node engine does not block the caller (just the block where the call is made). If this is possible, we could do const a = doStuff(...), wait and get the result in a without blocking the main thread. As async/await does, why there is no place for sync/wait ?" Hope this is more clear now, feel free to comment or ask anything :) Edit 2: All precisions of the why of the answer are in the comments of the accepted answer. A: No, going from promise to async/await will not get you from async code to sync code. Why? Because both are just different wrapping for the same thing. Async function returns immediately just like a promise does. You would need to prevent the Event Loop from going to next call. Simple while(!isMyPromiseResolved){} will not work either because it will also block callback from promises so the isMyPromiseResolved flag will never be set. BUT... There are ways to achieve what you have described without async/await. For example: OPTION 1: using deasync approach. Example: function runSync(value) { let isDone = false; let result = null; runAsync(value) .then(res => { result = res; isDone = true; }) .catch(err => { result = err; isDone = true; }) //magic happens here require('deasync').loopWhile(function(){return !isDone;}); return result; } runAsync = (value) => { return new Promise((resolve, reject) => { setTimeout(() => { // if passed value is 1 then it is a success if(value == 1){ resolve('**success**'); }else if (value == 2){ reject('**error**'); } }, 1000); }); } console.log('runSync(2): ', runSync(2)); console.log('runSync(1): ', runSync(1)); OR OPTION 2: calling execFileSync('node yourScript.js') Example: const {execFileSync} = require('child_process'); execFileSync('node',['yourScript.js']); Both approaches will block the user thread so they should be used only for automation scripts or similar purposes. A: There are some hacky ways to do what is desired, but that would be an anti-pattern. I’ll try to explain. Callbacks is one of the core concepts in javascript. When your code launches, you may set up event listeners, timers, etc. You just tell the engine to schedule some tasks: “when A happens, do B”. This is what asynchrony is. But callbacks are ugly and difficult to debug, that’s why promises and async-await were introduced. It is important to understand that this is just a syntax sugar, your code still is asynchronous when using async-await. As there are no threads in javascript, waiting for some events to fire or some complicated operations to finish in a synchronous way would block your entire application. The UI or the server would just stop responding to any other user interactions and would keep waiting for a single event to fire. Real world cases: Example 1. Let’s say we have a web UI. We have a button that downloads the latest information from the server on click. Imagine we do it synchronously. What happens? myButton.onclick = function () { const data = loadSomeDataSync(); // 0 useDataSomehow(data); } Everything’s synchronous, the code is flat and we are happy. But the user is not. A javascript process can only ever execute a single line of code in a particular moment. User will not be able to click other buttons, see any animations etc, the app is stuck waiting for loadSomeDataSync() to finish. Even if this lasts 3 seconds, it’s a terrible user experience, you can neither cancel nor see the progress nor do something else. Example 2. We have a node.js http server which has over 1 million users. For each user, we need to execute a heavy operation that lasts 5 seconds and return the result. We can do it in a synchronous or asynchronous manner. What happens if we do it in async? User 1 connects We start execution of heavy operation for user 1 User 2 connects We return data for user 1 We start execution of heavy operation for user 2 … I.e we do everything in parallel and asap. Now imagine we do the heavy operation in a sync manner. User 1 connects We start execution of heavy operation for user 1, everyone else is waiting for it to accomplish We return data for user 1 User 2 connects … Now imagine the heavy operation takes 5 seconds to accomplish, and our server is under high load, it has over 1 million users. The last one will have to wait for nearly 5 million seconds, which is definitely not ok. That’s why: In browser and server API, most of the i/o operations are asynchronous Developers strive to make all heavy calculation asynchronous, even React renders in an asynchronous manner.
{ "pile_set_name": "StackExchange" }
Q: SkyDrive is now OneDrive OneDrive for Everything in Your Life Today we are pleased to announce that SkyDrive will soon become OneDrive. We have more than a handful of questions about skydrive. Please re-tag them as onedrive and make "skydrive" a synonym. A: The simplest solution would be for someone to retag one question with onedrive then we can merge the tags. This will have the effect of retagging the rest of the questions tagged skydrive and automatically convert "skydrive" to "onedrive" when anyone uses it on a new question. This has now been done.
{ "pile_set_name": "StackExchange" }
Q: ruby: fix mostly-utf8 strings I have input data (via File.popen) that is mostly utf8, but occasionally there are iso8859-1 characters in them. I want everything that is not a valid utf8 sequence interpreted as iso8859-1 and replaced with the corresponding (two-byte) utf-8 sequence (and the result as an UTF-8 encoded string). What is an efficient way to do this in ruby? This will treat an entire git log output, so it should be reasonably fast. A: since ruby 2.1.0 (afaik) you can use scrub to do this kind of ugly encoding stuff: https://ruby-doc.org/core-2.1.0/String.html#method-i-scrub If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block. "abc\u3042\x81".scrub #=> "abc\u3042\uFFFD" "abc\u3042\x81".scrub("*") #=> "abc\u3042*" "abc\u3042\xE3\x80".scrub{|bytes| '<'+bytes.unpack('H*')[0]+'>' } #=> "abc\u3042<e380>"
{ "pile_set_name": "StackExchange" }
Q: how to solve this error with lambda and sorted method when i try to make sentiment analysis (POS or NEG text)? Input code: best = sorted(word_scores.items(), key=lambda w, s: s, reverse=True)[:10000] Result: Traceback (most recent call last): File "C:\Users\Sarah\Desktop\python\test.py", line 78, in <module> best = sorted(word_scores.items(), key=lambda w, s: s, reverse=True)[:10000] TypeError: <lambda>() missing 1 required positional argument: 's' How do I solve it? A: If I've understood the format of your word_scores dictionary correctly (that the keys are words and the values are integers representing scores), and you're simply looking to get an ordered list of words with the highest scores, it's as simple as this: best = sorted(word_scores, key=word_scores.get, reverse=True)[:10000] If you want to use a lambda to get an ordered list of tuples, where each tuple is a word and a score, and they are ordered by score, you can do the following: best = sorted(word_scores.items(), key=lambda x: x[1], reverse=True)[:10000] The difference between this and your original attempt is that I have passed one argument (x) to the lambda, and x is a tuple of length 2 - x[0] is the word and x[1] is the score. Since we want to sort by score, we use x[1].
{ "pile_set_name": "StackExchange" }
Q: Do I get the Class Feats at level 1 in D&D 4E? I'm a bit confused about Class Feats. PHB says characters gain one Feat on first level. However, it seems reasonable for me that characters get these on first level. So, do I get them then, or do I have to "buy" them separately? A: Each Class Feat (Feats with a prerequisite of that class) must be taken using your feats. Each Class Feature (Features listed in the class description) are gained automatically at first level.
{ "pile_set_name": "StackExchange" }
Q: If I compile Java app at another location it can not read from any folder I have an app. Which is in RC state. I've started finalizing works by splitting the classes to separate files with appropriate import sets at another location but suddenly I've found that cleaner version cannot read from any folder. So I investigated that if I compile the code in another location except the actual (original) app cannot read from any folder. Strange is that from folders from those cannot be read can be obtained path (subdirectories included). I have packed this app to executable jar file before started this works. Maybe somewhere in JVM is something stuck? Note: New files are compiled without error. I've tried both original source and new sources. Failure is in methods File.list() or File.listFiles(). The same using directory stream. Used packages: import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.table.DefaultTableModel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.LineNumberReader; import java.io.FileReader; import java.io.File; import java.io.FileInputStream; import java.io.DataInputStream; import java.io.FilenameFilter; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.UnsupportedLookAndFeelException; For sure at this part: private void loadFiles(){ cesta=folderPicker.getSelectedFile(); if(folder==null||loadedCesta!=cesta||(cesta==folderPicker.getSelectedFile()&vetsiPismoVisible==true)){ folder=new File(cesta.getName()); String datFiles[]=folder.list(new FilenameFilter() { public boolean accept(File folder, String fileName) { return fileName.endsWith(".dat");}}); If I try: folder.canRead() on every folder on my PC and also e.g.on my workstation these new compilations get false as a result. Variable: folderPicker is reffering to JFileChooser that is limited to folders and folders are obtained via actionListener of special JButton (not classic Open and Cancel). You can try it from Karolina_RC.jar from link provided in commentary under conditions said. A: Problem solved. For some reason is no longer possible to use only folder name to make File type (folder). Now it is required to use path. E.g. File folder=new File(path.getName()); File folder=new File(path.getPath()); Former no longer working. Latter does. I am guessing some JVM-compile issue.
{ "pile_set_name": "StackExchange" }
Q: Direct proof for angular velocity from direction cosine matrix I am trying to work through the math of what should be a relatively simple proof of a direct definition of the angular velocity matrix starting from the direction cosine matrix. The reference for this problem is example 490 from: Jazar, Reza (2011) Advanced Dynamics: Rigid Body, Mulitbody and Aerospace Applications. Hobboken, New Jersey: John Wiley & Sons, Inc. Pg. 717. Let {I, J, K} denote the orthonormal triad of unit vectors that characterize the Cartesian representation of the inertial frame (G-frame). Let {i, j, k} denote the orthonormal triad of unit vectors that characterize the Cartesian representation of the body frame (B-frame) that is rotating in the G-frame. The direction cosine matrix that transforms coordinates from the B-frame to the G-frame is: $$^G R_B = \begin{pmatrix} I \cdot i & I \cdot j & I\cdot k\\J \cdot i & J \cdot j & J \cdot k\\ K \cdot i & K \cdot j & K \cdot k\end{pmatrix}$$ The direction cosine matrix that transforms coordinates from the G-frame to the B-frame is the transpose of $^G R_B$: $$ ^B R_G = (^G R_B)^T =\begin{pmatrix} i \cdot I & i \cdot J & i\cdot K\\j \cdot I & j \cdot J & j \cdot K\\ k \cdot I & k \cdot J & k \cdot K\end{pmatrix}$$ The angular velocity matrix representing the rotation of B about G, expressed in the B-frame, $^B_G \omega_B$, is defined as: $$^B_G \omega_B = (^B R_G) \cdot (^G\dot R_B)$$ The direction cosine matrix should be (is) a matrix of scalars. However, when expressed as the dot product of unit vectors of the two coordinate frames, it would appear that the designation of the frame of reference in which time derivatives are being taken (i.e. $\frac{^G d}{dt}$ or $\frac{^B d}{dt}$). The derivation uses the G-derivative such that: $$^B_G \omega_B =\begin{pmatrix} i \cdot I & i \cdot J & i\cdot K\\j \cdot I & j \cdot J & j \cdot K\\ k \cdot I & k \cdot J & k \cdot K\end{pmatrix} \cdot \frac{^G d}{dt} \begin{pmatrix} I \cdot i & I \cdot j & I\cdot k\\J \cdot i & J \cdot j & J \cdot k\\ K \cdot i & K \cdot j & K \cdot k\end{pmatrix}$$ The result that is shown is: $$\begin{pmatrix} i \cdot \frac{^G di}{dt} & i \cdot \frac{^G dj}{dt} & i \cdot \frac{^G dk}{dt} \\ j \cdot \frac{^G di}{dt} & j \cdot \frac{^G dj}{dt} & j \cdot \frac{^G dk}{dt}\\ k \cdot \frac{^G di}{dt} & k \cdot \frac{^G dj}{dt} & k \cdot \frac{^G dk}{dt}\end{pmatrix}$$ The unit vector relationships of $e_i \cdot e_j = 0, e_i \cdot e_i = 1, e_i \cdot de_i = 0$ and $e_i \cdot de_j = -e_j \cdot de_i$ show that the result shown above produces the correct skew-symmetric form of the angular velocity matrix. The problem that I am having is with what should be the simple intermediate step in getting to the last step. Because the unit vectors for each frame are fixed in their own frame of reference, the G derivative of any $E_i \cdot e_j$ should be $E_i \cdot \frac{^G de_j}{dt}$. If this holds, the G-derivative of $^G R_B$ should reduce to the following: $$\frac{^G d}{dt} \begin{pmatrix} I \cdot i & I \cdot j & I\cdot k\\J \cdot i & J \cdot j & J \cdot k\\ K \cdot i & K \cdot j & K \cdot k\end{pmatrix}=\begin{pmatrix} I \cdot \frac{^G di}{dt} & I\cdot \frac{^G dj}{dt} & I\cdot \frac{^G dk}{dt}\\J \cdot \frac{^G di}{dt} & J \cdot \frac{^G dj}{dt} & J \cdot \frac{^G dk}{dt}\\ K \cdot \frac{^G di}{dt} & K \cdot \frac{^G dj}{dt} & K \cdot \frac{^G dk}{dt}\end{pmatrix}$$ If this holds then the result is: $$^B_G \omega_B =\begin{pmatrix} i \cdot I & i \cdot J & i\cdot K\\j \cdot I & j \cdot J & j \cdot K\\ k \cdot I & k \cdot J & k \cdot K\end{pmatrix} \cdot \begin{pmatrix} I \cdot \frac{^G di}{dt} & I\cdot \frac{^G dj}{dt} & I\cdot \frac{^G dk}{dt}\\J \cdot \frac{^G di}{dt} & J \cdot \frac{^G dj}{dt} & J \cdot \frac{^G dk}{dt}\\ K \cdot \frac{^G di}{dt} & K \cdot \frac{^G dj}{dt} & K \cdot \frac{^G dk}{dt}\end{pmatrix}$$ Taking element 2-3 of the resulting matrix multiplication as an example: $$j\cdot I\cdot I\cdot \frac{^G dk}{dt}+j\cdot J\cdot J\cdot \frac{^G dk}{dt}+j\cdot K\cdot K\cdot \frac{^G dk}{dt} =j\cdot \frac{^G dk}{dt}+j\cdot \frac{^G dk}{dt}+j\cdot \frac{^G dk}{dt}=3j\cdot \frac{^G dk}{dt} $$ I am unsure as to where I am going wrong such that every term has an extraneous multiplicative factor of three. Any help would be appreciated. A: Unless I am missing something, it seems you are using a false identity of the form $$(a\cdot b)(c \cdot d) = (b\cdot c)(a \cdot d)$$ To see that this equation does not hold in general, notice that $(i \cdot j) (j \cdot i) = 0 \cdot 0 = 0$, but $(j \cdot j)(i \cdot i) = 1 \cdot 1 = 1$. Remember that the dot product takes in two vectors and spits out a scalar. There is no way to take the dot product of three or more vectors at the same time. With that in mind, I think the computation should look something like this: \begin{align} (j\cdot I) \left(I\cdot \frac{^G dk}{dt}\right) &+ (j\cdot J) \left(J\cdot \frac{^G dk}{dt}\right) + (j\cdot K) \left(K\cdot \frac{^G dk}{dt}\right) \\&= j \cdot \left[I \left(I\cdot \frac{^G dk}{dt}\right) + J\left(J\cdot \frac{^G dk}{dt}\right) + K\left(K\cdot \frac{^G dk}{dt}\right)\right] \\&= j \cdot \left[\left(I\cdot \frac{^G dk}{dt}\right) I + \left(J\cdot \frac{^G dk}{dt}\right) J + \left(K\cdot \frac{^G dk}{dt}\right) K\right] \\&= j \cdot \left[ \frac{^G dk}{dt} \right] \\&= j \cdot \frac{^G dk}{dt} \end{align} The last equality follows from the fact that $$ a = (I \cdot a)I + (J \cdot a)J + (K\cdot a)K $$ for all vectors $a$. This is a fundamental fact about dot products (or metrics, or dual spaces -- it depends on context) known as the resolution of the identity. In words, $I \cdot a$ is the component of $a$ along $I$. The vector $(I \cdot a)I$ is then the vector part of $a$ along $I$. By adding all such vectors up, we get the original vector. This is probably something you've seen before, albeit in less abstract terms. This wikipedia article should bridge the gap.
{ "pile_set_name": "StackExchange" }
Q: Фрагменты в Андроид Android работа с Fragment. Создаю и добавляю фрагменты в программно: fragmenttransaction = fragmentmanager.beginTransaction(); fragmenttransaction.setCustomAnimations(R.anim.slide_up, R.anim.slide_down); if (fragmentmanager.findFragmentByTag(LoginFragment.TAG) != null) { fragmenttransaction.remove(fragment_login); } if (fragmentmanager.findFragmentByTag(RegistrationFragment.TAG) == null) { fragmenttransaction.add(R.id.layout_login_window, fragment_registration, RegistrationFragment.TAG); } fragmenttransaction.commit(); Главный класс Активити унаследован от AppCompatActivity. Каким образом мне перехватить onCreateView у добавляемого фрагмента, чтобы понять что я могу инициализировать View относящиеся фрагменту? A: Методы жизненного цмкла будут вызваны автоматически после fragmenttransaction.commit(); Всё, что вам нужно - в вашем классе фрагмента их переопределить: public class LoginFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("onCreateView called"); return inflater.inflate(R.layout.article_view, container, false); } }
{ "pile_set_name": "StackExchange" }
Q: What should a student do, when a professor delays submitting his letter of recommendation? I'm applying to Stanford, which requires 2 letters of recommendation from teachers, due in 2 days. Both teachers have known about this since mid-September, but one of them hasn't submitted his letter. I've asked him, and he tells me that he has one prepared, but he hasn't submitted it yet. I can't add a third letter that would qualify because of the way that the common application works. Should I wait for the deadline to pass, hoping that he turns his letter in at the last minute? Or should I ask someone else to write a letter in his place? I'm mainly considering the first option, because I have no reason not to trust him, but I'm not sure what will happen if he doesn't pull through. Turns out that they do accept letters of recommendation after the deadline, so long as the application is in on time. A: Politely and very gently remind the professor that the letter of recommendation is due. That's really all you can do. If your professors says they will submit it on time, try to believe them. As you have found out after posting the question, to the extent that it doesn't hold up other parts of their process, people on admissions committees understand that your flakey letter writers don't mean that you are flakey and will usually do what they can to accept or consider late letters. Often, departments will remind students or letter writers that their letters are missing, at, or even after, a deadline.
{ "pile_set_name": "StackExchange" }
Q: How do I pronounce Emacs? I struggle to pronounce many computer terms, and to this day still mispronounce latex in my head - it just sounds better rhyming with flex. How would I pronounce Emacs? A: Just think of E-max. The letter E is pronounced like the name of the letter is pronounced. I has the same sound as in need, clean, feel, green etc. Also, I recommend this video: How to Say or Pronounce Emacs
{ "pile_set_name": "StackExchange" }
Q: How to monitor what Ubuntu One is doing? Is there a way to monitor what Ubuntu One is doing when it seems to be chewing up so much network bandwidth? I'd like to see what files it's syncing. I looked in ~/.cache/ubuntuone/log but can't find anything that shows this. A: Install Magicicada. It will allow you to see what Ubuntu One is doing with a nice interface. sudo apt-get install magicicada
{ "pile_set_name": "StackExchange" }
Q: Avoiding Nagios commands.cfg I want to call a command directly from a Nagios service file, instead of passing arguments clumsily to commands.cfg. For example I want do this: define service { service_description footest check_command $USER1$/check_http example.com -u http://example.com/index.html use generic-service host_name example } But I get a: Error: Service check command '/usr/share/nagios/libexec/check_http example.com -u http://example.com/index.html' specified in service 'footest' for host 'example' not defined anywhere! A: If you absolutely insist on doing this, which is a really, really terrible idea, this snippet should work: define command { command_name check_by_arbitrary_path check_command /bin/sh -c "$ARG1$" } define service { use remote-service host_name example service_description This is a bad idea, seriously check_command check_by_arbitrary_path!$USER1$/check_http example.com -u http://example.com/index.html } Seriously, though, please don't.
{ "pile_set_name": "StackExchange" }
Q: Parse.com IOS, cannot fetch a pointer to PFUser I am following the tutorials on Parse.com but I don't seem to get it working properly. Here is my issue. I have a class called Questions and a class named _User of type PFUser (it has a picture icon next to the class name). User logins via FB and is registered as a _User. I can see myself in the _User class. I make a question and I have a field in the Question class named qOwner, which is the owner of the Question. This is being set when saving a new question via the ios app like this : QuestionCard[@"qOwner"] = [PFUser currentUser]; I can see the objectId of myself in _User to be the value inside the qOwner column, at the row for the current question made. Problem is that I cannot retrieve the values inside my app. If I place in the correct place the below: PFQuery *query = [PFQuery queryWithClassName:@"Questions"]; [query addAscendingOrder:@"createdAt"]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (!error) { // The find succeeded. NSLog(@"@@@ : Successfully retrieved %lu questions ", (unsigned long)objects.count); // Do something with the found objects NSLog(@"%@",objects); // fetched data are PFObjects // we need to convert that into a YesOrNo object // and then add it to _cards array for (PFObject *object in objects) { NSLog(@"currentUser : %@",[PFUser currentUser]); PFUser *qOwnerUser = [object objectForKey:@"qOwner"]; NSLog(@"Question Made by : %@",qOwnerUser); } ..... The following is being printed: 1) @@@ : Successfully retrieved 1 cards 2) ( "<Questions: 0x17011f5c0, objectId: zZWGsfciEU, localId: (null)> {\n CardId = 999;\n qOwner = \"<PFUser: 0x17037e000, objectId: LtdxP5K0n6>\";\n type = 0;\n }" ) 3) currentUser : <PFUser: 0x174375e40, objectId: LtdxP5K0n6, localId: (null)> { facebookId = 10153480462518901; thumbnail = "<PFFile: 0x174479a80>"; username = UYRRmfbXDHqr1Ws4VwJcAy2wx; } 4) Question Made by : <PFUser: 0x17037e000, objectId: LtdxP5K0n6, localId: (null)> { } 1-2-3 seem correct, I can see the pointer relation. But why in 4 inside {} I see nothing? I would have expected to see the same user details as in 3. Am I missing something? A: Parse does not fetch the pointer values by default in a query. You have to tell the query to include the pointer data using includeKey:. Do this: PFQuery *query = [PFQuery queryWithClassName:@"Questions"]; [query addAscendingOrder:@"createdAt"]; [query includeKey:@"qOwner"]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { ... }];
{ "pile_set_name": "StackExchange" }
Q: How to Deploy "SQL Server Express + EF" Application It's my first time to Deploy an Application which uses SQL Server Express Database. I'm Using Entity Framework Model First to contact Database. and i created a Setup wizard with Install Shield to Install the App. These are Steps that I'v done to Install The Application in Destination Computer : Installing MS SQL Server Express (DEST) Installing The Program using Setup file (DEST) Detach Database from SQL server and Copy Related .mdf ,.ldf file to the Destination Computer. Attach database file in destination computer using SQL Server Management Studio. I know server names and SQL name Instances are different and my program can't run correctly with the Old Connection String. I'm Beginner at this, and I want to know what should I do in the Destination Computer to make the program run? should I find a way to change the connection string on runtime?! or is there any way to modify installshield project and it do this work for me? (installshield is professional edition) could you suggest me what to do? in my searches I saw that WiX can do this, but I find it complicated, and i don't have enough time to learn it. i need to deploy the app ASAP. Thanks alot. A: Few hints for using LocalDB in your project: Download SQL Express LocalDB 2014 here. You can install it silently with single command like this msiexec /i SqlLocalDB.msi /qn IACCEPTSQLLOCALDBLICENSETERMS=YES Include your .MDF in your VS project and set in properties to Copy if newer so that it gets copied to your bin folder during build so that it is automatically included in the installer. At your app startup (in app.cs) check, if database file exists in desired location (e.g. %PUBLIC%\YourApp\Data) (WPF Desktop Application with MDF used locally for all local users). If not, copy the .mdf file from your app install dir to your data dir. Modify app.config so that your connection string looks like: <add name="MyContextLocalDB" connectionString="Server=(localdb)\MSSQLLocalDB; Integrated Security=True; AttachDBFilename=|DataDirectory|\MyDatabase.mdf; Connection Timeout = 30" providerName="System.Data.SqlClient" /> Connection timeout should be increased, since LocalDB exe is launched when you first try to connect to it. You can also use Database.CreateIfNotExists, but I have never tried it.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to toggle different divs by clicking on different elements using the same function? Say I have 50 div, like this: <div class="btn1"></div> //Toggles the first container to appear <div class="btn2"></div> //Toggles the second container to appear <div class="btn3"></div> //Toggles the third container to appear And another 50 div that contain information, like this: <div class="container-1"><h1>This is the first container</h1></div> <div class="container-2"><h1>This is the second container</h1></div> <div class="container-3"><h1>This is the third container</h1></div> Is it possible to make the corresponding div toggle when each button is clicked with just one function? I have read a little about delegation and operating on parents/siblings but it only seems to work on multiple buttons opening the same container, rather than each button opening each container. Somehow I don't think writing a function for every div is the way to go. A: yes it is possible. Basically you need to add a reference to clicked object so click event will know what to show/hide $(function() { $('.btn').on('click', function(e) { var $dataTarget = $($(this).data('target')); $dataTarget.show().siblings('.container').hide(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="btn btn1" data-target=".container-1"></div> //Toggles the first container to appear <div class="btn btn2" data-target=".container-2"></div> //Toggles the second container to appear <div class="btn btn3" data-target=".container-3"></div> //Toggles the third container to appear <div class="container container-1"> <h1>This is the first container</h1> </div> <div class="container container-2"> <h1>This is the second container</h1> </div> <div class="container container-3"> <h1>This is the third container</h1> </div> This will show the container targeted, then will hide other containers.
{ "pile_set_name": "StackExchange" }
Q: Eslint: no-duplicates Resolve error: unable to load resolver "node" I just updated my project(SPA with VueJS and Quasar Framework) today with npm update and I can't now run it. I am getting error no-duplicates Resolve error: unable to load resolver "node" in many different modules. It is always pointing 1:1 I have no idea what is going on as it was all working fine before... Any suggestions? A: Had the same issue, I think some dependancies have been removed to fix I did npm install eslint-plugin-import --save-dev npm install babel-preset-env --save-dev Then I edited .eslintrs.js modify extends to look like this extends: [ 'standard', 'plugin:import/errors', 'plugin:import/warnings', ], add the import plugin like plugins: [ 'html', 'import' ], then add the following rules 'import/named': 2, 'import/namespace': 2, 'import/default': 2, 'import/export': 2, You then also have to modify where you import quasar for example it looked like this before import Quasar from 'quasar' Now you have to do import Quasar from 'quasar-framework'
{ "pile_set_name": "StackExchange" }
Q: RecycleView adapter data show wrong when scrolling too fast I have a custom Recycle View adapter that list my items. in each Item I check database and draw some circles with colors. when I scroll listview very fast every drawed data ( not title and texts) show wrongs! how I can manage dynamic View creation without showing wrong data?! @Override public void onBindViewHolder(final ItemViewHolder itemViewHolder, int i) { itemViewHolder.date.setText(items.get(i).getData()); // set the title itemViewHolder.relative_layout_tag_place.addView(generateTagImages(items.get(i).getServerId())); // had to generate a Relativelaout with } and this is importMenuTags(): private RelativeLayout generateTagImages(String serverId) { List<String> color_list = new ArrayList<>(); RelativeLayout result = new RelativeLayout(context); List<String> list = db.getCardTags(serverId); int i = 0; for (String string : list) { RelativeLayout rl = new RelativeLayout(context); color_list.add(get_the_proper_color); Drawable drawable = context.getResources().getDrawable(R.drawable.color_shape); drawable.setColorFilter(Color.parseColor(dao.getTagColor(string)), PorterDuff.Mode.SRC_ATOP); RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lparams.addRule(RelativeLayout.ALIGN_PARENT_START); lparams.setMargins(i, 0, 0, 0); lparams.width = 35; lparams.height = 35; rl.setLayoutParams(lparams); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { rl.setBackground(drawable); } else { rl.setBackgroundDrawable(drawable); } result.addView(rl); i = i + 25; } return result; } I also had the same problem in simple custom adapter that it's solved by moving my function place out of if (convertView == null) { this is the link. A: As per seeing in your code, I found your relative layout must be showing some extra data while scrolling. And thats because of recycling of views. Here public void onBindViewHolder(final ItemViewHolder itemViewHolder, int i) { itemViewHolder.date.setText(items.get(i).getData()); // set the title itemViewHolder.relative_layout_tag_place.addView(generateTagImages(items.get(i).getServerId())); // had to generate a Relativelaout with //Problem is here. Suppose you added some child views in above holde.relative_layout , and this ViewHodler is recyclerd and provided to another item view, It already have all previously added views in it. and you are adding new child view with them. Hope you understand your problem. Solution: Very easy one. remove all previsousley added view in onBindViewHolder public void onBindViewHolder(final ItemViewHolder itemViewHolder, int i) { itemViewHolder.date.setText(items.get(i).getData()); // set the title itemViewHolder.relative_layout_tag_place.removeAllViews(); itemViewHolder.relative_layout_tag_place.addView(generateTagImages(items.get(i).getServerId())); // had to generate a Relativelaout with
{ "pile_set_name": "StackExchange" }
Q: Create cartesian product expansion of two variadic, non-type template parameter packs Lets say, I have two lists of non-type template parameteres (which might have a different type) a template foo that takes one value of each of those lists as a parameter How can I create a variadic parameter pack of foos, parameterized with the cartesian product of the two list elements? Here is what I mean: template<int ...> struct u_list {}; template<char ...> struct c_list {}; template<int, char > struct foo {}; template<class ...> struct bar {}; using int_vals = u_list<1, 5, 7>; using char_vals = c_list<-3, 3>; using result_t = /* magic happens*/ using ref_t = bar< foo<1, -3>, foo<1, 3>, foo<5, -3>, foo<5, 3>, foo<7, -3>, foo<7, 3> >; static_assert(std::is_same<result_t, ref_t >::value, ""); I'm looking for a solution that works in c++11 and doesn't use any libraries except the c++11 standard library. I also have my handroled version of c++14's index_sequence / make_index_sequence and can provide the non-type parameter lists as arrays if that simplifies the code. The closest I've found so far is this: How to create the Cartesian product of a type list?. So in principle (I haven't tested it) it should be possible to turn the non-type parameter packs into type parameter packs and then apply the solution in the linked post, but I was hoping that there is a simpler / shorter solution along the lines of this: template<int... Ints, char ... Chars> auto magic(u_list<Ints...>, c_list<Chars...>) { //Doesn't work, as it tries to expand the parameter packs in lock step return bar<foo<Ints,Chars>...>{}; } using result_t = decltype(magic(int_vals{}, char_vals{})); A: You may do something like the following: template <int... Is> using u_list = std::integer_sequence<int, Is...>; template <char... Cs> using c_list = std::integer_sequence<char, Cs...>; template<int, char> struct foo {}; template<class ...> struct bar {}; template <std::size_t I, typename T, template <typename, T...> class C, T ... Is> constexpr T get(C<T, Is...> c) { constexpr T values[] = {Is...}; return values[I]; } template <std::size_t I, typename T> constexpr auto get_v = get<I>(T{}); template<int... Ints, char ... Chars, std::size_t ... Is> auto cartesian_product(u_list<Ints...>, c_list<Chars...>, std::index_sequence<Is...>) -> bar<foo< get_v<Is / sizeof...(Chars), u_list<Ints...> >, get_v<Is % sizeof...(Chars), c_list<Chars...> > >... >; template<int... Ints, char ... Chars> auto cartesian_product(u_list<Ints...> u, c_list<Chars...> c) -> decltype(cartesian_product(u, c, std::make_index_sequence<sizeof...(Ints) * sizeof...(Chars)>())); using int_vals = u_list<1, 5, 7>; using char_vals = c_list<-3, 3>; using result_t = decltype(cartesian_product(int_vals{}, char_vals{})); Demo Possible implementation of std part: template <typename T, T ... Is> struct integer_sequence{}; template <std::size_t ... Is> using index_sequence = integer_sequence<std::size_t, Is...>; template <std::size_t N, std::size_t... Is> struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> {}; template <std::size_t... Is> struct make_index_sequence<0u, Is...> : index_sequence<Is...> {}; And change in answer: template <std::size_t I, typename T, template <typename, T...> class C, T ... Is> constexpr T get(C<T, Is...> c) { using array = T[]; return array{Is...}[I]; } template<int... Ints, char ... Chars, std::size_t ... Is> auto cartesian_product(u_list<Ints...>, c_list<Chars...>, index_sequence<Is...>) -> bar<foo< get<Is / sizeof...(Chars)>(u_list<Ints...>{}), get<Is % sizeof...(Chars)>(c_list<Chars...>{}) >... >; Demo C++11
{ "pile_set_name": "StackExchange" }
Q: Hibernate validator doesn't work Im trying to use hibernate validator in my spring mvc project with a html form. It compiles correctly but when I put put the wrong text in the form input, hibernate doesn't detect that, the BindingResult has no erros. Im using java 8 with Tomcat 9.0. Here is my code: The class that I want to validate: private int id; private String jugador; @NotNull(message = "No puede estar vacio") @Size(min = 1, max = 16, message = "...") private String contra; @NotNull(message = "No puede estar vacio") @Size(min = 1, max = 16, message = "...") @Email private String email; The controller: @RequestMapping("/procesarRegistro") public String procesarRegistro(@Valid @ModelAttribute("Cuenta") Cuenta cuenta, BindingResult bindingResult){ //This is allways false (idk why) if(bindingResult.hasErrors()){ return "registrarse"; } } The html form: <form:form action="procesarRegistro" name="reg" modelAttribute="Cuenta" cssClass="login" cssStyle="margin-top: 4%; margin-left: 40%; margin-right: 40%; border-radius: 3%; background: #fff;"> <div class = "contenedorLogin"> <div class = "input-contenedor"> <form:input path="jugador" placeHolder = "Nombre de minecraft" value = "" cssClass="textLog" cssStyle="text-align: left;"></form:input><br> <form:input path= "id" placeHolder = "Numero de cuenta" cssClass="textLog" cssStyle="text-align: left;"></form:input><br> <form:input path="email" placeHolder = "email" cssClass="textLog" cssStyle="text-align: left;"></form:input><br> <form:errors path = "email"></form:errors> <form:password path="contra" placeHolder = "Tu contraseña" value = "" cssClass="textLog" cssStyle="text-align: left;"></form:password><br> <form:errors path = "contra"></form:errors> <input type="text" value="confirmar"> <input type="password" name="contra2" placeholder="Confirmar" value = "" class = "textLog" style="text-align: left;"><br><br> </div> <input type="submit" value = "Registrarse" class = "botonLog"> <p style="text-align: center; color: gray;">Si tienes alguna duda entra al servidor de minecraft y pon /cuenta</p> </div> </form:form> Im using the 5.4.3 version of hibernate validator (I have tried 7.0, 6.1 and 6.0). Here is a photo of my jar files: Thanks for reading, i would be so pleased if someone can help me :) A: prueba de utilizar el validador @NotBlank. Es probable que te esté llegando un valor "" en vez de nulo. Para mayor control utiliza los dos validador es juntos @NotNull y @NotBlank. Espero te ayude
{ "pile_set_name": "StackExchange" }
Q: Mechanical energy of a body is relative? Since, the potential energy of a body is relative and depends on the point we choose as having zero potential. Does this mean that the mechanical energy (potential energy + kinetic energy) of the body is also relative? A: As Vladimir said, the answer is yes, although you are not talking about the same thing as he is. Kinetic energy is relative, because it depends on velocity, which is not the same for every frame of reference. Easiest example is this : say you and your friend are sitting on a train. From your perspective, your friend has zero kinetic energy, since he is not moving relatively to you. But if I stand on the ground and I see the train passing by, I will see your friend going foward with a certain velocity $v$ (the same as the train), and his (classical) kinetic energy will be $\frac{1}{2}mv^2$. Thus we both measure a different energy. Potential energy is also "relative", but for another reason. It does not depend on the reference frame like kinetic energy. Instead, it depends on a reference point chosen arbitrarily. John Taylor (Classical Mechanics) defines potential energy $U(\overrightarrow{r})$ as (minus) the work done by a conservative force $\overrightarrow{F}$ that acts on a body that goes from a reference point $\overrightarrow{r_0}$ to the point $\overrightarrow{r}$ (where the potential energy is calculated). Mathematically, we write: $$ U(\overrightarrow{r})=-W(\overrightarrow{r_0}\rightarrow\overrightarrow{r})= -\int_\overrightarrow{r0}^\overrightarrow{r}\overrightarrow{F}\cdot d\overrightarrow{r} $$ As you might have noted, since this reference point is arbitrary, different values could be calculated for the potential energy of the same object in the same situation. However, the value of this potential is of no interest. What really matters is its variation, ie its gradient. If you know a bit about calculus, you might know that, for a conservative force $\overrightarrow{F}$ : $$ \overrightarrow{F}=-\vec{\nabla} U $$ Which means that (minus) the variation of the potential energy must be equal to the force applied. But, you can add any constant $C$ to this potential $U$ and define a new potential energy $U'(\overrightarrow{r})=U(\overrightarrow{r})+C$ and get the same result, since the derivative of the constant is zero. For example, the gravitational potential energy on the surface of the Earth is approximately $U(\overrightarrow{r})=U(h)=mgh$. Common sense invites us to use the ground as a reference point for $h=0$, but you could use the top of a building without any problem : would the object go below that point, its potential energy would be negative, which has little significance since its value is arbitrary. Whichever point of reference you choose, if say the object drops 10 m from it initial position, you will always measure a loss of potential energy $\Delta U = mg\Delta h=mg\times(-10 \;\mathrm{m})$. So, really we don't care how much mechanical energy an object has. What really is important is that, as long as you are in an inertial reference frame and that all forces are conservative, this value is constant, whatever it is. This is exactly what the law of conservation of energy is about! And if there are non-conservative forces, then the change of potential energy will be minus the variation of the kinetic energy (again, you see that we don't really care about the value of the PE, only how it changes). Also note that this doesn't apply to the "rest mass energy" introduced in special relativity ($E=mc^2$), which is characteristic for a given particle and which is always measured in the same reference frame as the object (at rest, no velocity). In other words, it is not relative nor arbitrary.
{ "pile_set_name": "StackExchange" }
Q: android error: Could not read input channel file descriptors from parcel I've made an application for Android that works more or less like this: Application communicates with the Web service and transfers information (not files) I can navigate to a different screen using Intent and startActivity Unfortunately, sometimes the application crashes with the following error in different activity: java.lang.RuntimeException: Could not read input channel file descriptors from parcel. at android.view.InputChannel.nativeReadFromParcel(Native Method) at android.view.InputChannel.readFromParcel(InputChannel.java:135) at android.view.IWindowSession$Stub$Proxy.add(IWindowSession.java:523) at android.view.ViewRootImpl.setView(ViewRootImpl.java:481) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215) at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140) at android.view.Window$LocalWindowManager.addView(Window.java:537) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2507) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986) at android.app.ActivityThread.access$600(ActivityThread.java:123) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4424) 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:784) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) at dalvik.system.NativeStart.main(Native Method) But I don't know what does this error mean because I don't work with files. Any idea? A: This question appears to be the same as Could not read input channel file descriptors from parcel, which was (incorrectly) closed as off-topic. It is also more or less same as Could not read input channel file descriptors from parcel crash report. Unfortunately those questions haven't gotten a satisfactory (and sufficiently general) answer, so I am going to try anyway. File descriptors are used in multiple places in Android: Sockets (yes, open network connections are "files" too); Actual files (not necessarily files on disks, may as well be android.os.MemoryFile instances); Pipes—Linux uses them everywhere, for example the attempt to open pipe, that resulted in your exception, was likely required to send input events between IME (keyboard) process and your application. All descriptors are subject to shared maximum limit; when that count is exceeded, your app begins to experience serious problems. Having the process die is the best scenario in such case, because otherwise the kernel would have run out of memory (file descriptors are stored in kernel memory). You may have issues with descriptors (files, network connections) not being closed. You must close them ASAP. You may also have issues with memory leaks—objects not being garbage-collected when they should (and some of leaked objects may in turn hold onto file descriptors). Your own code does not have to be guilty, libraries you use and even some system components may have bugs, leading to memory leaks and file descriptor leaks. I recommend you to use Square's Leak Canary—a simple, easy to use library for automatic detection of leaks (well, at least memory leaks, which are most frequent).
{ "pile_set_name": "StackExchange" }
Q: CodeIgniter Production and Developpement server on the same domain. (no subdomain) I googled this many times but now I have to ask it here. I want to make a workflow for a website for Developpement/Production. My constraint is that I use Facebook Connect (Facebook Graph now) so I need to have the dev and prod on the same domain and server. (to be able to log in and test the features) I thought I will edit the CodeIgniter Index.php to redirect if I have a specific user agent (I can edit the one of my firefox) You think it's a good Idea or you have a better one ? And now comes the eternal question : how can I deploy this the easy way ? should I use Capistrano or Phing ? or simply a script with SVN ? Please help me, I'm totally new to this Deployment thing. I used to work directly in production for my little websites or on other domains. but now it's not possible anymore. A: For me, I'll have something like two application folders. One called "production", one called "development". Then in your index.php file, where you set your application folder, you can use php to determine which one to use for whatever reason. Just set your $application_folder variable to whichever one you need. (You could do this based on anything. A cookie, IP address or something.)
{ "pile_set_name": "StackExchange" }
Q: Calling .NET Web Services Asynchronically from Java I need to make asynchronous calls to .NET web services from java since synchronous calls are too slow. I know in .NET this is easily done since the stub (proxy) class created by wsdl.exe also generates methods for asynchronous calls(BeginMethod()/EndMethod()). I created the service stub using eclipse Ganymede but no asynchronous method call were generated. How do you do this in java? Thanks in advance A: Since you are using Eclipse, you are probably using Axis2 to generate the Web Services client. Axis2 is capable of generating an asynchronous client. Have a look at the instructions here. You need to select the "Generate async" or "Generate both sync and async" option. This is an article for asynchronous web services with Axis2. It refers mainly to the service (not the client), but the client code isn't much different. All Java Web Services Framework support asynchronous operations. You just need to configure the generator properly.
{ "pile_set_name": "StackExchange" }
Q: Using mock objects without tying down unit tests I'm currently writing a set of unit tests for a Python microblogging library, and following advice received here have begun to use mock objects to return data as if from the service (identi.ca in this case). However, surely by mocking httplib2 - the module I am using to request data - I am tying the unit tests to a specific implementation of my library, and removing the ability for them to function after refactoring (which is obviously one primary benefit of unit testing in the firt place). Is there a best of both worlds scenario? The only one I can think of is to set up a microblogging server to use only for testing, but this would clearly be a large amount of work. A: You are right that if you refactor your library to use something other than httplib2, then your unit tests will break. That isn't such a horrible dependency, since when that time comes it will be a simple matter to change your tests to mock out the new library. If you want to avoid that, then write a very minimal wrapper around httplib2, and your tests can mock that. Then if you ever shift away from httplib2, you only have to change your wrapper. But notice the number of lines you have to change is the same either way, all that changes is whether they are in "test code" or "non-test code".
{ "pile_set_name": "StackExchange" }
Q: NSString allocation and initializing What is the difference between: NSString *string1 = @"This is string 1."; and NSString *string2 = [[NSString alloc]initWithString:@"This is string 2.]; Why am I not allocating and initializing the first string, yet it still works? I thought I was supposed to allocate NSString since it is an object? In Cocoa Touch, -(IBAction) clicked: (id)sender{ NSString *titleOfButton = [sender titleForState:UIControlStateNormal]; NSString *newLabelText = [[NSString alloc]initWithFormat:@"%@", titleOfButton]; labelsText.text=newLabelText; [newLabelText release]; } Why do I not allocate and initialize for the titleOfButton string? Does the method I call do that for me? Also, I'm using XCode 4, but I dislike iOS 5, and such, so I do not use ARC if that matters. Please don't say I should, I am just here to find out why this is so. Thanks! A: The variable string1 is an NSString string literal. The compiler allocates space for it in your executable file. It is loaded into memory and initialized when your program is run. It lives as long as the app runs. You don't need to retain or release it. The lifespan of variable string2 is as long as you dictate, up to the point when you release its last reference. You allocate space for it, so you're responsible for cleaning up after it. The lifespan of variable titleOfButton is the life of the method -clicked:. That's because the method -titleForState: returns an autorelease-d NSString. That string will be released automatically, once you leave the scope of the method. You don't need to create newLabelText. That step is redundant and messy. Simply set the labelsText.text property to titleOfButton: labelsText.text = titleOfButton; Why use properties? Because setting this retain property will increase the reference count of titleOfButton by one (that's why it's called a retain property), and so the string that is pointed to by titleOfButton will live past the end of -clicked:. Another way to think about the use of retain in this example is that labelsText.text is "taking ownership" of the string pointed to by titleOfButton. That string will now last as long as labelsText lives (unless some other variable also takes ownership of the string).
{ "pile_set_name": "StackExchange" }
Q: how can i insert no more than 5 sentences and no more than 50 letters per each sentence in C before each sentence it needs to say the number of the sentence im writing. starting the count from one. what i mean is: How many sentences you want to enter [1-5]? 2 sentence 1: write what you want sentence 2: here as long as its less then 50 letters my problem is that i dont know how to limit the number of letters, without needing to insert them all. if i write for(i=0; i<50; i++) i will need to enter all the 50 letters, but if i want i need to be able to write even only 1. so that is what i have done so far: (note that i dont need to ask the user how many letters he wants to enter) char text[5][50]={0}; int x=0, i=0, n=0, m=0; printf("How many sentences you want to enter [1-5]?\n"); scanf("%d", &n); printf("how many letters [1-50]?\n"); scanf("%d", &m); for (x=1; x<=n; x++)// will print max of 5 sentences { printf("Sentence %d: \n", x); for(i=0; i<m; i++)// will print max of 50 letters { scanf(" %c", &text[x][i]); } } thanks a lot for the help! A: for(i=0;i<n;i++) { if(fgets(text,50,stdin) != NULL) /* Read just 50 character */ { // Do your stuff } } PS: fgets() comes with a newline character
{ "pile_set_name": "StackExchange" }
Q: Python Bokeh dependencies not found This question has been asked but not answered. The only difference is I am on a Arch Linux 64 bit. I am using python 2.7 and the package that got installed of bokeh is 0.10.0 I followed the conda install bokeh instructions from here and did the conda update conda and conda update anaconda Still it does not work. Not only is bokeh.plotting not working, but neither is bokeh.sampledata which leads me to believe none of it is working. Has any one else had this problem with this or any package and successfully solved it? I do not know if this helps, but there are three versions of bokeh in my pkgs folder. Two of them are bokeh 0.9.0 and one of them is bokeh 0.10.0 which is the one that comes up when I call conda. In the site-packages/bokeh folder there is a plotting.py. I tried to install it in python 3.4 and this is what the terminal returned (py34)[bob@bob anaconda]$ conda install bokeh Fetching package metadata: .... Solving package specifications: . Package plan for installation in environment /home/bob/anaconda/envs/py34: The following packages will be downloaded: package | build ---------------------------|----------------- numpy-1.9.3 | py34_0 5.7 MB pytz-2015.6 | py34_0 173 KB setuptools-18.3.2 | py34_0 346 KB tornado-4.2.1 | py34_0 557 KB wheel-0.26.0 | py34_1 77 KB jinja2-2.8 | py34_0 301 KB bokeh-0.10.0 | py34_0 3.9 MB ------------------------------------------------------------ Total: 10.9 MB The following NEW packages will be INSTALLED: libgfortran: 1.0-0 openblas: 0.2.14-3 wheel: 0.26.0-py34_1 The following packages will be UPDATED: bokeh: 0.9.0-np19py34_0 --> 0.10.0-py34_0 jinja2: 2.7.3-py34_1 --> 2.8-py34_0 numpy: 1.9.2-py34_0 --> 1.9.3-py34_0 pip: 7.0.3-py34_0 --> 7.1.2-py34_0 pytz: 2015.4-py34_0 --> 2015.6-py34_0 setuptools: 17.1.1-py34_0 --> 18.3.2-py34_0 tornado: 4.2-py34_0 --> 4.2.1-py34_0 Proceed ([y]/n)? y Fetching packages ... numpy-1.9.3-py 100% |##########################| Time: 0:00:00 6.21 MB/s pytz-2015.6-py 100% |##########################| Time: 0:00:00 1.44 MB/s setuptools-18. 100% |##########################| Time: 0:00:00 2.63 MB/s tornado-4.2.1- 100% |##########################| Time: 0:00:00 3.57 MB/s wheel-0.26.0-p 100% |##########################| Time: 0:00:00 1.28 MB/s jinja2-2.8-py3 100% |##########################| Time: 0:00:00 2.19 MB/s bokeh-0.10.0-p 100% |##########################| Time: 0:00:00 5.74 MB/s Extracting packages ... [ COMPLETE ]|#############################################| 100% Unlinking packages ... [ COMPLETE ]|#############################################| 100% Linking packages ... [ COMPLETE ]|#############################################| 100% (py34)[bob@bob anaconda]$ python bokeh.py Traceback (most recent call last): File "bokeh.py", line 1, in <module> from bokeh import plotting File "/home/bob/anaconda/bokeh.py", line 1, in <module> from bokeh import plotting ImportError: cannot import name 'plotting' A: You have a file /home/bob/anaconda/bokeh.py in your current directory, which is being imported instead of bokeh. You might look at what that file is, if it is really needed. If it's a file you made, it's not recommended to put things in the anaconda directory (some subdirectory of your Documents directory is a better place). It's also not really a good idea to have anaconda be your current directory.
{ "pile_set_name": "StackExchange" }
Q: Upload document : Default value not applied on choice column if baseFieldControl.ControlMode = SPControlMode.Display I created a new site column, a choice column with 5 values to pick from in a drop down list : 1, 2, 3, 4 (default value), 5 I then created a document content type using this column. The problem I am currently having is that when uploading a new document, I programmatically set the ControlMode of the baseFieldControl to SPControlMode.Display for certain users that should not be able to modify this column's value but should still be able to upload new document to the library. On the edit form, the value that is displayed is "4" which is normal as it is the defalut value, but once you save, if you go have a look the items properties, the saved value is "1". If you do the same test but using radio buttons it doesn't even save a value, not even the first one. So basically all I want is to be able to set a field "readonly" on the edit form when adding a new document but I want the default value to be saved properly. Thanks for any help you can provide on that issue. Alex A: If you want to use your BaseFieldControl with the Display Mode and set a value, you must set the value before setting the ControlMode. You may find a different workaround Here
{ "pile_set_name": "StackExchange" }
Q: WordPress: Change main width based on active sidebar I'm writing a WP theme, and I want the main content area to change width based on whether there's an active sidebar or not. To make this easier, I'm using bootstrap. The problem is that the output is blank. Here's the code I'm trying to use to do the calculations: <!-- Calculate content width based on sidebars --> <?php if ( is_active_sidebar( 'left_sidebar' ) && !is_active_sidebar( 'right_sidebar' ) ) { $mainspan = "9"; } ?> <?php if ( !is_active_sidebar( 'left_sidebar' ) && is_active_sidebar( 'right_sidebar' ) ) { $mainspan = "span9"; } ?> <?php if ( is_active_sidebar( 'left_sidebar' ) && is_active_sidebar( 'right_sidebar' ) ) { $mainspan = "span6"; } ?> <?php if ( !is_active_sidebar( 'left_sidebar' ) && !is_active_sidebar( 'right_sidebar' ) ) { $mainspan = "span12"; } ?> The result should be loaded here, but I get a blank value: <main class="<?php echo $mainspan; ?>"> A: Andrewsi asked if there were any includes in the file. That lead me to realize that the code itself was functional, but was not working because one was being included into the other. The IF statements were written in the Header.php, which was included into the Index.php where the variable call was located. Placing the IF statements into the Index.php fixed the issue.
{ "pile_set_name": "StackExchange" }
Q: whats the standard way to setup a casperjs for travis-ci testing surprisingly enough, when thinking about js tremendous popularity in GitHub repos, there is no "offical" guide to testing frontend js with Travis-ci (only node.js, a very specific subset). from my research I found out a lot of big js projects don't have Travis-ci integration (e.g jQuery) or have a very minimal travis setup (see backbone) which uses the default npm test. I know travis-ci runs npm testas default and runs the test named scripts from package.json. and I found a few examples running phantomjs for headless testing (which the docs don't give any details about setting up) but couldn't find canonical examples for how to setup casper.js integration tests with travis-ci. I'll be help for help and guidance with this A: Seems the canonical way is hiding the tests behind the default npm test which usually triggers a script (or a grunt task) running the test suite. you can look at the .travis.yml in a small project I coded to see how to install casperjs for the testing.
{ "pile_set_name": "StackExchange" }
Q: GWT showing low disk space I am new to GWT. Iam using eclipse Indigo along with GWT. The moment I open eclipse and start running a simple program I have created , my system shows low disk space. I can understand it is something related to cache. But dont know how to proceed. The system becomes very slow and not allowing me to work. Again If I close my eclipse and browser , things become normal. Before starting my eclipse I have 2 GB in C. But after some time it become 100 mb and forcing me to clean or close. What I need to do? A: This is a known issue of the Google Plugin for Eclipse. Workaround: avoid relaunching the DevMode too much (you can launch it once and then reload the app at will) clean your temporary directory regularly
{ "pile_set_name": "StackExchange" }
Q: How to set an image in imageview swift 3? So I have an image view titled cashOrCredit and have am trying to set it's image programatically but somehow not able to. First I set the image like this cell.cashOrCredit.image = UIImage(named: "cash1.png") and I get an error saying a separator of "," is needed. Then I tried it this way var cashImage: UIImage? cashImage = "cash1.png" cell.cashOrCredit.image = cashImage But I get a THREAD 1 EXC BAD INSTRUCTION error. I can't seem to understand what is going wrong ? Here is the error A: Try this: cell.cashOrCredit.image = UIImage(named: "cash1") and check "cash1.png" image is available in Assets.xcassets or not. If you get solution, then give upvote to my answer. A: Updated for Swift 3: use below simple code, to set the image to UIImageView; class YourViewControllerName: UIViewController { var mYourImageViewOutlet: UIImageView? func addImageToUIImageView{ var yourImage: UIImage = UIImage(named: "Birthday_logo")! mYourImageViewOutlet.image = yourImage } // call this function where you want to set image. } Note: "Birthday_logo" type of image must be present in your Assets.xcassets of your project. I attached the screenshot if you want any help please refer it. ****// used anywhere you want to add an image to UIImageView. [Here I used one function & in that function, I write a code to set image to UIImageView]**** Enjoy..!
{ "pile_set_name": "StackExchange" }
Q: How can I use google.visualization typings with Angular CLI? I'm trying to use Google Charts in an Angular CLI (7.2.3) project but am running into an issue getting the typings to work. First, I installed the typings with this command (both with and without the -dev flag): npm install --save-dev @types/google.visualization After doing this, intellisense starts working immediately in Visual Studio Code and I don't get any highlighted errors when I create a simple test like this: const chartBoxStyle: google.visualization.ChartBoxStyle = {}; However, when I try to build by running ng build, I get this error: error TS2503: Cannot find namespace 'google'. I have tried adding this to my file with no luck: declare const google: any; My tsconfig.json file has the following for typeRoots and I see the google.visualization folder in there: "typeRoots": ["node_modules/@types"] Any help would be greatly appreciated as I'm out of ideas on how to progress past this. A: Summary The problem is the "types" property in the ./src/tsconfig.app.json file. Even though the root ./tsconfig.json file sets "typeRoots" to ["node_modules/@types"], the ./src/tsconfig.app.json file disables inclusion of those types by setting its own types property to an empty array. Solution Open ./src/tsconfig.app.json and make one of two changes: Delete the "types": []" property; that will tell the compiler to include all typeRoots packages. Alternatively, add the types that you want to use into the "types": []" array. The latter option would look like this: "types": [ "google.visualization" ] Details ng build reads its configuration from the ./angular.json file. That ./angular.json file sets "tsConfig" to "src/tsconfig.app.json". That ./src/tsconfig.app.json file sets its "types" property to an empty array. { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/app", "types": [] <------------------------------- empty array }, "exclude": [ "test.ts", "**/*.spec.ts" ] } That's the problem, because as the TypeScript documentation says: "If types is specified, only packages listed will be included."
{ "pile_set_name": "StackExchange" }
Q: How to iterate over a char pointer array returned by a function in cpp I create a function that creates a 28 array from random chars from a-z. When I try to iterate over the pointer array from main I get the wrong values. What do I'm missing? I know array are passed by reference to function, does are returned by reference too? #include <iostream> #include <ctime> #define MAX 28 // Generate random char array with a-z values char* generateRandomString(int length) { char random[length]; for (int i = 0; i < length; i++) { // Minimun a ascii = 97 // Maximun z ascii = 122 srand(int(time(NULL))); // Timestamp seed generator int randomInt = 97 + (rand() % 25); char randomChar = randomInt; random[i] = randomChar; } return random; } int main() { char* random = generateRandomString(MAX); for (int i = 0; i < MAX; i++) { std::cout << random[i] << std::endl; // (*random)[i] Does not work neither } return 0; } A: You are returning a pointer to a local variable that goes out of scope before the caller can use it. Just use std::string instead. And don't call srand() multiple times, call it only once.1 1: Even better, don't use srand() at all, use a C++ random number generator from the <random> library instead. #include <iostream> #include <string> #include <ctime> #define MAX 28 // Generate random char array with a-z values std::string generateRandomString(int length) { std::string random; random.resize(length); for (int i = 0; i < length; i++) { // Minimun a ascii = 97 // Maximun z ascii = 122 int randomInt = 97 + (rand() % 25); char randomChar = randomInt; random[i] = randomChar; } return random; } int main() { srand(int(time(NULL))); // Timestamp seed generator std::string random = generateRandomString(MAX); for (int i = 0; i < MAX; i++) { std::cout << random[i] << std::endl; // (*random)[i] Does not work neither } return 0; }
{ "pile_set_name": "StackExchange" }
Q: Using STL containers in GNU Assembler Is it possible to "link" the STL to an assembly program, e.g. similar to linking the glibc to use functions like strlen, etc.? Specifically, I want to write an assembly function which takes as an argument a std::vector and will be part of a lib. If this is possible, is there any documentation on this? A: Any use of C++ templates will require the compiler to generate instantiations of those templates. So you don't really "link" something like the STL into a program; the compiler generates object code based upon your use of templates in the library. However, if you can write some C++ code that forces the templates to be instantiated for whatever types and other arguments you need to use, then write some C-linkage functions to wrap the uses of those template instantiations, then you should be able to call those from your assembly code.
{ "pile_set_name": "StackExchange" }
Q: How to let ogr/gdal CreateLayer() create a `geom` field instead of `wkb_geometry`? When creating a new table (PostGIS) using OGR/GDAL (2.1+), is there a way to select a specific name for the geometry field (such as geom), rather than using the default name? I created a new table via python3 ogr/grdal liek this: ds = gdal.OpenEx(connection_string, gdal.OF_VECTOR | gdal.OF_UPDATE) lyr = ds.CreateLayer( "mylayer", XXX, ogr.wkbLineString) The problem is that I can't find a parameter to specify the name of the geometry field, only its type. In the table created, the geometry field seems to be called wkb_geometry by default: wkb_geometry geometry(LineString,26945) Is there a parameter or option to let CreateLayer() use a different name such as geom? Related question: Use Postgis to convert wkb_geometry data type to geom datatype A: As you can see from http://gdal.org/python/osgeo.ogr.DataSource-class.html#CreateLayer, CreateLayer support also "options" which are "None" by default. The papszOptions argument can be used to control driver specific creation options. These options are normally documented in the format specific documentation. Usage example for PostgeSQL and Python can be found from the GDAL autotest script https://trac.osgeo.org/gdal/browser/trunk/autotest/ogr/ogr_pg.py See for example row 5191: lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_82', geom_type = ogr.wkbNone, options = ['GEOMETRY_NAME=another_name'])
{ "pile_set_name": "StackExchange" }
Q: Determining the difference between odd and even numbers I have code that converts each character of a String to an int and returns the difference between odd and even numbers. Can this code be simplified? int compareSumOfDigits(String N) { int e=0,o=0; for (int i =0;i<N.length();i++){ int t = Character.getNumericValue(N.charAt(i)); if(t%2==0) e+=t; else o+=t; } return o-e ; } A: Combining some of the existing answers, you can do s.chars() // get the char stream .map(Character::getNumericValue) // convert to ints .map(n -> n%2==0 ? -n : n) // negate the even ones .sum() // sum it all up This will give you the sum of the odds and the negative evens, which is the same as the sum of the odds minus the sum of the evens. edit In response to @kai, for absolute max readability, I'd probably do (pseudocode) List<int> ints = s.chars().map(Character::getNumericValue) Map<Boolean, List<int>> intsEven = ints.partitioningBy(n -> n%2==0) return intsEven.get(false).sum() - intsEven.get(true).sum() or with isEven from the other answers and not defined here List<int> ints = s.chars().map(Character::getNumericValue) List<int> evens = ints.filter(isEven) List<int> odds = ints.filter(not(isEven)) return odds.sum() - evens.sum() A: Instead of counting two sums (of odd and even digits) and returning their difference, you could use a single sum value, subtracting a digit's value if it's even and adding if it's odd. An added benefit of this approach is that you are more protected from integer overflows: if odd and even digits are interleaved, the two-sum approach will be much less likely to overflow. Building on @m0nhawk's version, with further improving the variable names and a few other tidbits: boolean isEven(int number) { return (number % 2) == 0; } int compareSumOfDigits(String numericString) { int sum = 0; for (Character ch : numericString.toCharArray()) { int digit = Character.getNumericValue(ch); if (isEven(digit)) { sum -= digit; } else { sum += digit; } } return sum; } Or as @tobias_k proposed, the if-else can be flattened for a more compact form, but this is less readable so it goes away from "simple", and I don't recommend it, but here you go anyway: int compareSumOfDigits(String numericString) { int sum = 0; for (Character ch : numericString.toCharArray()) { int digit = Character.getNumericValue(ch); sum += digit * (isEven(digit) ? -1 : 1); } return sum; } Nothing to do with simplicity, but when playing with an implementation, it helps to have some JUnit tests handy to verify that the code still works. A few examples to get you started: @Test public void test_compareSumOfDigits_11111111() { assertEquals(8, compareSumOfDigits("11111111")); } @Test public void test_compareSumOfDigits_22222222() { assertEquals(-16, compareSumOfDigits("22222222")); } @Test public void test_compareSumOfDigits_12345678() { assertEquals(-4, compareSumOfDigits("12345678")); } A: It depend on you definition of a "more simple code". From my point of view it can be extend with the next stuff: Formatting, obviously. Using foreach loop, instead of indexing (notice, that you use index once in the for, only to get a character), this will greatly simplify the code. Introduce function isEven for check. Java compiler is smart enough to reduce to zero all overhead on calling this function, but from reader view it's clearer now. Put more expressible variable names, instead of one letter. I can hardly recall any situation where it impossible to seek for a better, explanatory name. So, my simplier code looks like this. Boolean isEven(int number) { return (number % 2) == 0; } int compareSumOfDigits(String numbers) { int sumEvens = 0, sumOdds = 0; for (Character ch : numbers.toCharArray()) { int number = Character.getNumericValue(ch); if (isEven(number)) { sumEvens += number; } else { sumOdds += number; } } return sumOdds - sumEvens; }
{ "pile_set_name": "StackExchange" }
Q: What airplane does this vintage instrument panel come from? Can anyone please tell me what this is from? It looks like it's military. I have a few panels that came with this and gauges (not if it's a b-16) A: The shape makes it clear that this is from a single seater or tandem aircraft. This makes a glider very likely, which is supported by the "Vario" engraving over the column of small holes on the bottom right. A little googling then brings me to this page and the assumption that this panel is from a Schempp-Hirth Standard Cirrus, Serial No. 176. The plane was badly damaged at Minisink, NY on October 23, 1976 in a botched landing and consequently written off. At that time it was registered as N11JY. Schempp-Hirth Standard Cirrus (picture source) Standard Cirrus instrument panel (picture source) A: It has the legend "Vario", short for variometer stenciled on it and it looks very much like the panel from a Cirrus sailplane. Source. Standard Cirrus
{ "pile_set_name": "StackExchange" }
Q: Extend TTPhotoViewController with custom TTPhotoView I have successfully integrated the three20 framework in my project, and I have extended the TTPhotoViewController to add some further functionality. Now I need to add some subviews to the TTPhotoView loaded by the TTPhotoViewController. In particular I would like to add that subviews after every TTPhotoView as been loaded. These subviews represents sensible area over the image so they should scale proportionally with the image. The user can tap a subview to get extra info about the image. I don't know how to implement this behavior. Should I extend the TTPhotoView and make sure that the TTPhotoViewController use this extended version instead of its TTPhotoView? Could someone point me to the right direction? Thank you A: Solved subclassing the TTPhotoView (TapDetectingPhotoView) and then adding all my subviews to that subclass. The main problem was represented by the photo switching, because the TTPhotoViewController (in particular its inner TTScrollView) reuse the TTPhotoView during switching operation. So for example if you add your subview to your TTPhotoView subclass and try to switch to the next photo, your subview will probably be here, because the TTPhotoView is reused. To solve this problem I decided to add and remove all my subviews every time a photo switch occur (see TTPhotoViewController::didMoveToPhoto). In this way I'm sure that every photoview has its subviews. Here my implementation (only remarkable methods) Hope these help! PhotoViewController.h: #import "TapDetectingPhotoView.h" @interface PhotoGalleryController : TTPhotoViewController <TTScrollViewDelegate, TapDetectingPhotoViewDelegate> { NSArray *images; } @property (nonatomic, retain) NSArray *images; @end PhotoViewController.m: #import "PhotoGalleryController.h" @implementation PhotoGalleryController @synthesize images; - (void)viewDidLoad { // fill self.images = ... } - (TTPhotoView*)createPhotoView { TapDetectingPhotoView *photoView = [[TapDetectingPhotoView alloc] init]; photoView.tappableAreaDelegate = self; return [photoView autorelease]; } #pragma mark - #pragma mark TTPhotoViewController - (void)didMoveToPhoto:(id<TTPhoto>)photo fromPhoto:(id<TTPhoto>)fromPhoto { [super didMoveToPhoto:photo fromPhoto:fromPhoto]; TapDetectingPhotoView *previousPhotoView = (TapDetectingPhotoView *)[_scrollView pageAtIndex:fromPhoto.index]; TapDetectingPhotoView *currentPhotoView = (TapDetectingPhotoView *)[_scrollView pageAtIndex:photo.index]; // destroy the sensible areas from the previous photoview, because the photo could be reused by the TTPhotoViewController! if (previousPhotoView) previousPhotoView.sensibleAreas = nil; // if sensible areas has not been already created, create new if (currentPhotoView && currentPhotoView.sensibleAreas == nil) { currentPhotoView.sensibleAreas = [[self.images objectAtIndex:photo.index] valueForKey:@"aMap"]; [self showSensibleAreas:YES animated:YES]; } } #pragma mark - #pragma mark TappablePhotoViewDelegate // show a detail view when a sensible area is tapped - (void)tapDidOccurOnSensibleAreaWithId:(NSUInteger)ids { NSLog(@"SENSIBLE AREA TAPPED ids:%d", ids); // ..push new view controller... } TapDetectingPhotoView.h: #import "SensibleAreaView.h" @protocol TapDetectingPhotoViewDelegate; @interface TapDetectingPhotoView : TTPhotoView <SensibleAreaViewDelegate> { NSArray *sensibleAreas; id <TapDetectingPhotoViewDelegate> tappableAreaDelegate; } @property (nonatomic, retain) NSArray *sensibleAreas; @property (nonatomic, assign) id <TapDetectingPhotoViewDelegate> tappableAreaDelegate; @end @protocol TapDetectingPhotoViewDelegate <NSObject> @required - (void)tapDidOccurOnSensibleAreaWithId:(NSUInteger)ids; @end TapDetectingPhotoView.m: #import "TapDetectingPhotoView.h" @interface TapDetectingPhotoView (Private) - (void)createSensibleAreas; @end @implementation TapDetectingPhotoView @synthesize sensibleAreas, tappableAreaDelegate; - (id)init { return [self initWithSensibleAreas:nil]; } - (id)initWithFrame:(CGRect)frame { return [self initWithSensibleAreas:nil]; } // designated initializer - (id)initWithSensibleAreas:(NSArray *)areasList { if (self = [super initWithFrame:CGRectZero]) { self.sensibleAreas = areasList; [self createSensibleAreas]; } return self; } - (void)setSensibleAreas:(NSArray *)newSensibleAreas { if (newSensibleAreas != self.sensibleAreas) { // destroy previous sensible area and ensure that only sensible area's subviews are removed for (UIView *subview in self.subviews) if ([subview isMemberOfClass:[SensibleAreaView class]]) [subview removeFromSuperview]; [newSensibleAreas retain]; [sensibleAreas release]; sensibleAreas = newSensibleAreas; [self createSensibleAreas]; } } - (void)createSensibleAreas { SensibleAreaView *area; NSNumber *areaID; for (NSDictionary *sensibleArea in self.sensibleAreas) { CGFloat x1 = [[sensibleArea objectForKey:@"nX1"] floatValue]; CGFloat y1 = [[sensibleArea objectForKey:@"nY1"] floatValue]; area = [[SensibleAreaView alloc] initWithFrame: CGRectMake( x1, y1, [[sensibleArea objectForKey:@"nX2"] floatValue]-x1, [[sensibleArea objectForKey:@"nY2"] floatValue]-y1 ) ]; areaID = [sensibleArea objectForKey:@"sId"]; area.ids = [areaID unsignedIntegerValue]; // sensible area internal ID area.tag = [areaID integerValue]; area.delegate = self; [self addSubview:area]; [area release]; } } // to make sure that if the zoom factor of the TTScrollView is > than 1.0 the subviews continue to respond to the tap events - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *result = nil; for (UIView *child in self.subviews) { CGPoint convertedPoint = [self convertPoint:point toView:child]; if ([child pointInside:convertedPoint withEvent:event]) { result = child; } } return result; } #pragma mark - #pragma mark TapDetectingPhotoViewDelegate methods - (void)tapDidOccur:(SensibleAreaView *)aView { NSLog(@"tapDidOccur ids:%d tag:%d", aView.ids, aView.tag); [tappableAreaDelegate tapDidOccurOnSensibleAreaWithId:aView.ids]; } SensibleAreaView.h: @protocol SensibleAreaViewDelegate; @interface SensibleAreaView : UIView { id <SensibleAreaViewDelegate> delegate; NSUInteger ids; UIButton *disclosureButton; } @property (nonatomic, assign) id <SensibleAreaViewDelegate> delegate; @property (nonatomic, assign) NSUInteger ids; @property (nonatomic, retain) UIButton *disclosureButton; @end @protocol SensibleAreaViewDelegate <NSObject> @required - (void)tapDidOccur:(SensibleAreaView *)aView; @end SensibleAreaView.m: #import "SensibleAreaView.h" @implementation SensibleAreaView @synthesize delegate, ids, disclosureButton; - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.userInteractionEnabled = YES; UIColor *color = [[UIColor alloc] initWithWhite:0.4 alpha:1.0]; self.backgroundColor = color; [color release]; UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; [button addTarget:self action:@selector(buttonTouched) forControlEvents:UIControlEventTouchUpInside]; CGRect buttonFrame = button.frame; // set the button position over the right edge of the sensible area buttonFrame.origin.x = frame.size.width - buttonFrame.size.width + 5.0f; buttonFrame.origin.y = frame.size.height/2 - 10.0f; button.frame = buttonFrame; button.autoresizingMask = UIViewAutoresizingFlexibleTopMargin |UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight; self.disclosureButton = button; [self addSubview:button]; // notification used to make sure that the button is properly scaled together with the photoview. I do not want the button looks bigger if the photoview is zoomed, I want to preserve its default dimensions [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoomFactorChanged:) name:@"zoomFactorChanged" object:nil]; } return self; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; if ([[touches anyObject] tapCount] == 1) [delegate tapDidOccur:self]; } - (void)buttonTouched { [delegate tapDidOccur:self]; } - (void)zoomFactorChanged:(NSNotification *)message { NSDictionary *userInfo = [message userInfo]; CGFloat factor = [[userInfo valueForKey:@"zoomFactor"] floatValue]; BOOL withAnimation = [[userInfo valueForKey:@"useAnimation"] boolValue]; if (withAnimation) { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.18]; } disclosureButton.transform = CGAffineTransformMake(1/factor, 0.0, 0.0, 1/factor, 0.0, 0.0); if (withAnimation) [UIView commitAnimations]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:@"zoomFactorChanged" object:nil]; [disclosureButton release]; [super dealloc]; }
{ "pile_set_name": "StackExchange" }
Q: Pasting text into a webview in the default android browser, when you long-press on a textbox inside of a webpage you get a context menu showing several options, such as the ability to paste text into the textbox. How do I replicate this functionality with my own webview? I looked in the android source code, specifically the code that handles context menu creation and found this: @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { ... WebView.HitTestResult result = webview.getHitTestResult(); int type = result.getType(); if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { // let TextView handles context menu return; } ... } What the code means is that when the user long-presses on a "EDIT_TEXT_TYPE" ie. a textbox, the webview does nothing. Some magical "TextView" handles the context menu. Now I'm lost, how do I get this context menu to appear in my webview? A: Have you tried using registerForContextMenu(). I know it works on ListView for sure but it also works on other views. It should go something like this: registerForContextMenu(yourWebView); @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { //Code for "Paste"; } Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Should I mention teaching experience in my cover letter? I am applying for tenure-track positions in R1 (say, top 50) universities in Computer Science in the US. When writing the cover letter, should I mention teaching experience and competence? Or should I leave it for the teaching statement? A: I've been on the faculty recruiting committee of my American R1 top-whatever computer science department for more than 15 years, including three years as committee chair. (But my experience is only in one department, so take this with a grain of salt.) To first approximation, nobody will read your cover letter. It's quite common to get faculty applications that have no cover letter at all, or that include a plain-text email "cover letter" that reads "I'm applying for an assistant professor position; I've uploaded the requested documents and the contact info for my references. Kthxbye!" I have never seen this affect discussions about who to interview or who to hire. Nobody ever notices. Nobody ever cares. All the information we care about is already in your other application materials, your recommendation letters, and your papers. In particular, recruiting committees already expect to see a detailed description of your teaching experience in your CV and in your teaching statement. That's where everyone puts it, so that's where we look. And we'll look there regardless of whether you mention it in your cover letter. So why would we look at your cover letter? In my experience, cover letters are only useful if they contain information that potentially changes the hiring process — like "I am applying for a tenured position at the rank of full professor." or "Please keep my application confidential." or "My spouse is also applying to your chemistry department." Cover letters do play a more important role in some departments, because they want convincing evidence that you are seriously interested in a job there. After all, if you're just shotgunning your application to every ivy-colored building in the country, then interviewing you is probably a waste of their time and money. But this is much less likely to be a concern in a top-50 R1 department. It's never been a concern at mine. A: At an R1 university you will still need to teach. Mentioning teaching in the cover letter is certainly appropriate, but a few words will do. It needn't even be as much as a full sentence since you get to expand in a teaching statement here. But a sentence that simply says you have wide experience in both research and teaching is probably enough for the cover letter. For a different sort of university teaching would be the most important thing to mention, but for almost any academic job, don't try to seem too focused on any one thing. The job has multiple facets. Your application will be evaluated by people with different viewpoints in most cases.
{ "pile_set_name": "StackExchange" }
Q: Resources describing Somerset English Can anyone suggest any good resources describing the grammar of traditional Somerset English (not accented standard English)? The Wikipedia article for the West Country dialects provides a good introduction, but I am looking for sources that go into greater depth regarding the grammatical differences between Somerset and standard English. A: The first two books on this Amazon UK page are popular guides to the Somerset dialect. The third is an academic account of English dialects by Peter Trudgill, a prominent linguist who has written on regional dialects and on socioliguistics. The index has an entry for Somerset, and there may be some pointers to more specific works in the Further Reading section.
{ "pile_set_name": "StackExchange" }
Q: How to read .runsettings test parameter in xUnit fixture I'm writing xUnit unit test cases for a dotnet core application which uses DocumentDB (CosmosDB) as storage. The unit test are written to execute against the local cosmos db emulator. On the Azure DevOps build environment, I've setup the Azure Cosmos DB CI/CD task which internally creates a container to install the emulator. However, I'm not able to figure out that how the endpoint of emulator can be passed to xUnit fixture? Is there any way through which xUnit fixture can read the .runsettings test parameters or parameters can be passed via other source? Update Currently, I implemented the scenario using Environment Variable but still not happy to define the connection string as a environment variable using powershell in build task and read it in through code during unit test execution. I was thinking if there could be another way of achieving it.. Below snapshot shows how the build tasks are configured currently as workaround to achieve the desired: And code to read the value as var serviceEndpoint = Environment.GetEnvironmentVariable("CosmosDbEmulatorEndpointEnvironmentVariable"); Since, UnitTest task provides the option to pass .runsettings/.testsettings with option to override the test run parameters so was thinking it something can be achieved using those options. A: This is not supported in xUnit. See SO answers here and here, and this github issue indicating that it is not something that will be supported in xUnit. A: Currently, I implemented the scenario using Environment Variable but still not happy to define the connection string as a environment variable using powershell in build task and read it in through code during unit test execution. I was thinking if there could be another way of achieving it.. Below snapshot shows how the build tasks are configured currently as workaround to achieve the desired: And code to read the value as var serviceEndpoint = Environment.GetEnvironmentVariable("CosmosDbEmulatorEndpointEnvironmentVariable"); Since, UnitTest task provides the option to pass .runsettings/.testsettings with option to override the test run parameters so was thinking it something can be achieved using those options.
{ "pile_set_name": "StackExchange" }
Q: When is the adjoint to a monoidal functor monoidal? Let $\mathcal C,\mathcal D$ be monoidal categories. Recall that a functor $F : \mathcal C \to \mathcal D$ is lax monoidal if it is equipped with maps $1_{\mathcal D} \to F(1_{\mathcal C})$ and $F(X) \otimes_{\mathcal D} F(Y) \to F(X \otimes_{\mathcal C} Y)$, the latter natural in $X,Y\in \mathcal C$, compatible with associators and unitors. It is oplax monoidal if it is instead equipped with maps in the other direction, and strong monoidal if it is equipped with isomorphisms. For each choice of lax/oplax/strong, there is a bicategory of monoidal categories, lax/oplax/strong monoidal functors, and monoidal natural transformations. Suppose that $F : \mathcal C \to \mathcal D$ is one of lax/oplax/strong monoidal, and also admits a left adjoint $F^L$ in the bicategory of all functors. Under what circumstances is $F^L$ naturally lax/oplax/strong monoidal? Under what circumstances does this adjunction come from an adjunction in the bicategory of monoidal categories and lax/oplax/strong monoidal functors? A: If $L$ and $R$ are a left and right adjoint, then doctrinal adjunction asserts that $L$ is oplax monoidal iff $R$ is lax monoidal. (I'm being a bit imprecise here, treating monoidality as if it were a property instead of a structure, but hopefully the meaning is clear.)
{ "pile_set_name": "StackExchange" }
Q: How to prevent ServiceStackVS to add ApiResponse attribute on generated DTOs? How to prevent ServiceStackVS to add ApiResponse attribute on generated DTOs? A: You can choose which attributes are exported by either adding or removing them from the NativeTypesFeature plugin, e.g The Swagger API attributes can be removed in AppHost.Configure() with: var feature = this.GetPlugin<NativeTypesFeature>(); feature.MetadataTypesConfig.ExportAttributes.RemoveWhere( x => x is ApiAttribute || x is ApiMemberAttribute || x is ApiResponseAttribute);
{ "pile_set_name": "StackExchange" }
Q: Symfony 3 unit tests pass locally but not at Travis I have a Symfony 3 project with tests that pass in php 5.5 & 5.6 but fail in 7.0 and 7.1. All the same tests pass when using Symfony 2.8. All tests pass locally but some fail on travis. shows failing tests: https://travis-ci.org/zikula/core/builds/257745627 travis file: https://github.com/zikula/core/blob/master/.travis.yml#L40 I’m hoping someone here will have some insight. I’m pretty much at a complete loss. originally in the Travis file I just ran phpunit and it was passing until very recently where I started to get errors like reported here (https://github.com/symfony/symfony/issues/19532) e.g. YamlFileLoader - Undefined class constant 'PARSE_CONSTANT' so I tried both ./src/vendor/symfony/symfony/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit and bin/pnpunit (current setting) and they both fail (but differently!) as it is currently set up I get these errors before the tests fail: $ ./bin/phpunit PHP Warning: PHP Startup: Unable to load dynamic library '/home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/apc.so' - /home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/apc.so: cannot open shared object file: No such file or directory in Unknown on line 0 Warning: PHP Startup: Unable to load dynamic library '/home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/apc.so' - /home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/apc.so: cannot open shared object file: No such file or directory in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library '/home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/memcache.so' - /home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/memcache.so: cannot open shared object file: No such file or directory in Unknown on line 0 Warning: PHP Startup: Unable to load dynamic library '/home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/memcache.so' - /home/travis/.phpenv/versions/7.0.7/lib/php/extensions/no-debug-zts-20151012/memcache.so: cannot open shared object file: No such file or directory in Unknown on line 0 So I am guessing this is related because I do not get those errors locally or in php 5.5/5.6 any ideas how to solve this? Thanks in advance! A: Firstly, composer run on PHP 7 might bring different versions of dependencies than if it was run on PHP 5. This is because many packages are dropping PHP 5 support these days. Perhaps you're fetching a dependency that behaves differently on PHP 7. Another option is that your code behaves differently on PHP 7. For example, if failures you're getting are related to sorting, it might be that your algorithm sorts in a slightly different way depending on a PHP version it's run on.
{ "pile_set_name": "StackExchange" }
Q: How to treat a return value from method as a class type - Itcl Suppose I have the following code implemented in Itcl. package require Itcl itcl::class A { constructor {} { puts $this } destructor {} public method Print {} { puts "ok" } } itcl::class B { constructor {} { } destructor {} public method returnA {} { return [A #auto] } } B b ;# create an instance of class B set obj [b returnA] ; #assign return value to obj $obj Print ;# should treat obj as an A type and print ok Now, I get the following error: invalid command name "0" while executing "$obj Print" I understood that I need to add scopes to my variable or to the Print command in order to invoke Print method that associated to class A. But I don't really know how. I also read the following post: How to get a reference on the Itcl class member variable? But it doesn't says there how to treat the return value as a specific class type variable A: You have to qualify the name of the yet to be created instance of class A: A [namespace current]::#auto Otherwise, the name of the created object is returned in an unqualified manner (0, a0, ...), which cannot be resolved to a Tcl command for the scope of the caller of returnA.
{ "pile_set_name": "StackExchange" }
Q: Count ngram word frequency using text collocations I would like to count the frequency of three words preceding and following a specific word from a text file which has been converted into tokens. from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize from nltk.util import ngrams with open('dracula.txt', 'r', encoding="ISO-8859-1") as textfile: text_data = textfile.read().replace('\n', ' ').lower() tokens = nltk.word_tokenize(text_data) text = nltk.Text(tokens) grams = nltk.ngrams(tokens, 4) freq = Counter(grams) freq.most_common(20) I don't know how to search for the string 'dracula' as a filter word. I also tried: text.collocations(num=100) text.concordance('dracula') The desired output would look something like this with counts: Three words preceding 'dracula', sorted count (('and', 'he', 'saw', 'dracula'), 4), (('one', 'cannot', 'see', 'dracula'), 2) Three words following 'dracula', sorted count (('dracula', 'and', 'he', 'saw'), 4), (('dracula', 'one', 'cannot', 'see'), 2) The trigram containing 'dracula' in the middle, sorted count (('count', 'dracula', 'saw'), 4), (('count', 'dracula', 'cannot'), 2) Thank you in advance for any help. A: Once you get the frequency information in tuple format, as you've done, you can simply filter out the word you're looking for with if statements. This is using Python's list comprehension syntax: from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize from nltk.util import ngrams with open('dracula.txt', 'r', encoding="ISO-8859-1") as textfile: text_data = textfile.read().replace('\n', ' ').lower() # pulled text from here: https://archive.org/details/draculabr00stokuoft/page/n6 tokens = nltk.word_tokenize(text_data) text = nltk.Text(tokens) grams = nltk.ngrams(tokens, 4) freq = nltk.Counter(grams) dracula_last = [item for item in freq.most_common() if item[0][3] == 'dracula'] dracula_first = [item for item in freq.most_common() if item[0][0] == 'dracula'] dracula_second = [item for item in freq.most_common() if item[0][1] == 'dracula'] # etc. This produces lists with "dracula" in different positions. Here is what dracula_last looks like: [(('the', 'castle', 'of', 'dracula'), 3), (("'s", 'journal', '243', 'dracula'), 1), (('carpathian', 'moun-', '2', 'dracula'), 1), (('of', 'the', 'castle', 'dracula'), 1), (('named', 'by', 'count', 'dracula'), 1), (('disease', '.', 'count', 'dracula'), 1), ...]
{ "pile_set_name": "StackExchange" }
Q: How to calculate secondary RMS current of each winding in multiplre output flyback converter? As I am designing multiple output flyback converter and I have confusion in selection of wire gauge of the secondary winding. There are 4 secondary windings and one bias winding. Mode of operation is CCM. V_out1 48 V I_out1 1.5 A V_out2 48 V I_out2 0.15A V_out3 25 V I_out3 0.7 A V_out4 25 V I_out4 0.3 A V_bias 16 V I_bias 0.05 A 280 V dc input voltage. D_max=0.47, Lprimary=3.1mH, Fsw=65KHz A: Wire gauge is determined by the required output current. Estimate the wire length from the core size and number of turns, the calculate the resistance. Remember that the resistance of copper is a function of temperature, so you can use the wire resistance at your expected transformer temperature. The wire resistance is in series with your output, and you can perform the R*I^2 calculation to determine the power you will be generating which will be both a transformer loss and a heat source for your design. Remember that you will be supplying pulsed current, so your voltage drop will be greatest immediately after switching off the primary, and the voltage must be high enough immediately after switching. You will have to do some math. When your power supply is fully loaded, what is the duty cycle? It depends on whether you are in discontinuous mode or continuous mode and the duty cycle, but the peak current on the output winding will be much higher than the average current. It should be relatively easy to draw a theoretical waveform, and then calculate the result of adding the expected winding resistance.
{ "pile_set_name": "StackExchange" }
Q: AirPlay button on custom view 4.3 finally :) I am searching right now how to add air play button to custom view. I have MPMoviePlayer that load movie. I disabled standard controls and added overlay view with my custom play, pause, stop, volume buttons. If anybody know how to add button that will be air play please share knowledge? I cant't find what notification to send, what to listen...:( A: If you want just the AirPlay button without the volume slider follow the instructions in Jilouc's answer and then set the following properties on the myVolumeView: [myVolumeView setShowsVolumeSlider:NO]; [myVolumeView setShowsRouteButton:YES]; That will hide the volume slider but keep the route button. A: EDIT It seems I've been misguided in my previous answer because the device was not running the released version iOS 4.3. There is a way to provide the AirPlay button on a custom interface. Use a MPVolumeView and add it to your view hierarchy MPVolumeView *myVolumeView = [[MPVolumeView alloc] initWithFrame: overlayView.bounds]; [overlayView addSubview: myVolumeView]; [myVolumeView release]; The MPVolumeView provides the volume slider and the route button (see image below). But I don't think it's possible to only display the button.
{ "pile_set_name": "StackExchange" }
Q: LeetCode: Prison Cells After N Days Stack, I can't quite wrap my head around this oddity. I'm evaluating the positions within the array, each time. How is it that by initializing the array each time I receive different results... I would appreciate if someone can explain this. In While Loop: Correct 0,1,0,1,1,0,0,1 0,1,1,0,0,0,0,0 0,0,0,0,1,1,1,0 0,1,1,0,0,1,0,0 0,0,0,0,0,1,0,0 0,1,1,1,0,1,0,0 0,0,1,0,1,1,0,0 0,0,1,1,0,0,0,0 Outside While Loop (Initialized Once): Incorrect 0,1,0,1,1,0,0,1 0,1,1,0,0,0,0,0 0,0,1,0,1,0,1,0 0,0,1,1,0,0,1,0 0,0,0,1,0,0,1,0 0,1,1,0,1,1,0,0 0,0,1,1,1,0,1,0 0,0,0,0,1,1,0,0 Question Details There are 8 prison cells in a row, and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. Otherwise, it becomes vacant. (Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.) We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0. Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.) Example 1: Expected Output Input: cells = [0,1,0,1,1,0,0,1], N = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day 4: [0, 0, 0, 0, 0, 1, 0, 0] Day 5: [0, 1, 1, 1, 0, 1, 0, 0] Day 6: [0, 0, 1, 0, 1, 1, 0, 0] Day 7: [0, 0, 1, 1, 0, 0, 0, 0] Method static public int[] PrisonAfterNDays(int[] cells, int N) { int counter = 0; //Doesn't work if it's here //int[] temp = new int[8]; while(counter < N) { Console.WriteLine(String.Join(",",cells)); //Works if it's here ?!?!?! int[] temp = new int[8]; for(int j = 1; j < 8-1; j++) { if(cells[j-1] == cells[j+1]) { temp[j] = 1; } else { temp[j] = 0; } } cells = temp; counter++; } return cells; } A: Remember that even though int is a value type, arrays are reference types, so int[] is a reference type. (See What is the difference between a reference type and value type in c#?) When you execute cells = temp;, you point cells and temp at the exact same array! You can test this with the following code: int[] a = new int[2]; int[] b = a; b[0] = 85; b[1] = 3; Console.WriteLine(a[0]); // prints 85 Console.WriteLine(a[1]); // prints 3 So this means that on the second iteration of the outer loop, the following code changes both cells[j] and temp[j]: temp[j] = 1; Which, clearly, means you will get strange results. For this reason, I'd argue that you should define temp within the loop.
{ "pile_set_name": "StackExchange" }
Q: Minkowski functional of a open set Given $X$ is a topological vector space and $V$ is a convex, balanced neighbourhood of $0$ in X. Then for $x \in V$, the Minkowski functional $\mu_{V}(x)$ = inf $\{t>0: t^{-1}x\in V\}$ $<$ $1$. The reason given for strict inequality is "$V$ is open". But I dont get it. I can observe the following. Since $x\in V$, $\mu_{V}(x)$ $\leq 1$ and since $V$ is balanced $tV$ $\subseteq V$ for all $0<t<1$. Let $x\in V$. As $V$ is open, there exists a neighbourhood $U$ of $x$ such that $x\in U \subset V$. I dont know how to proceed with this. Please help! A: Using continuity of the map $M\colon X\times \mathbf R\to x$ defined by $M(x,\lambda):=\lambda x$ (continuity for the product topology), we have that the map $t\mapsto tx$ is continuous, hence the set $$S:=\{t>0,t^{-1}x\in V\}$$ is an open subset of $(0,+\infty)$. Since $1$ belongs to $S$, the infimum of $S$ is necessarily strictly smaller than $1$.
{ "pile_set_name": "StackExchange" }
Q: Auto update docker image if exist new version of images on DockerHub I want to update and restart my application ( docker container ) when I push new version of this app to Docker Hub. Can You tell any solution for auto update an image and restart them on server? P.S I hear about kubernetes, but its very hard to understanding how use it A: There are lots of possibilities: Write a poll service to look if a new version is uploaded and let it trigger a redeploy if you have a private registry you might be able to add a trigger (notifications) to a new push. The trigger might trigger a new build. if you let e.g. jenkins do the whole build it can also take care of the build and redeploy. You can trigger ansible to do a redeploy based on a new version. etc. etc.
{ "pile_set_name": "StackExchange" }
Q: Primary source for WoW lua API? I've been looking for first-hand information on the World of Warcraft addon API. There are a couple wikis that are pretty good, but their reference links only point internally. Surely there is some information published by Blizzard on the topic. Can all of their information really be gleaned from reverse-engineering and forums? That would be hard for me to believe. A: Its not all necessarily gleaned from inspection or trial and error. Some is provided, but randomly, from "heads up" posts in the forums from "the source", as in Blizzard employees. They are usually pretty good about it, though is almost always provided in a "just the essentials to save you some pain" sort of way. Here's an example: http://blue.mmo-champion.com/topic/233590-mop-changes/ Watching for the "Blue" posts goes a long way, and its been this way for a long time. If you look at someting like this (old 3.1.0 end user patch notes) http://us.battle.net/wow/en/game/patch-notes/3-1-0 , and then scan to near the bottom there will be a note and link for API changes, so its easy to glean their intent on this, and that they intend to provide some "unofficial" support about API changes there whilenot burdening the actual product readme with them. In general, I'd say that due to the very open nature of the materials, the source for the UI, very little is hidden and most is pretty self-evident, so it sort of barely qualifies as reverse engineering. Once you understand the Lua relationship to the general design of the WoW UI and supporting API, it's much easier. As for the implied question about "why", the "hard to believe" part. They are doing, in my estimation, what they believe is the best balance between fully supporting without "officially" suporting, and not wasting cycles trying to document a huge amount of available facilites thats ever changing. I think they belive it makes a better product, having the ability to customize, so its intheir interest, however is frought with problems and even legal issues from many angles to be expressly "official" about it or to try to maintain coherent docs. ---- Toward the question "git hub" below, here is the "blue" post in context, which can be found by clicking the "blizz" link icon on the mmo-champion link provided before: http://us.battle.net/wow/en/forum/topic/6413172918#1 I was trying to give an example of a Blue post that had detail, but I accidentally gave one for the Web API not the Game API. However the principle is the same, and provides more Blizzard to Community context for dev support. So basically that particular post was in reference to changes in the Web API, and the Git remark has no relevance to the game UI Customization and Macro thing. There is no hidden or official doc source for game UI Customization and Macro. Mostly its because it simply doesnt exist for anyone. :)
{ "pile_set_name": "StackExchange" }
Q: Can an estate be forced to sell real estate to cover debt if the home was bequeathed to an adult child? My mother died in West Virginia. I am her son and the executor of her will, in which the home was bequeathed to me. The estate has insufficient funds to pay medical and other debts. Can WV probate court force me to sell the home to pay the medical and other debts? Can liens be placed on the home prior to, or after probate closes (and the home, I presume, will become mine)? A: I am sorry for your loss, and that you have to deal with bills on top of everything else. The quick answer is yes, you might have to sell the house to pay your mother's bills. As you probably know, the estate includes both your mother's assets (cash, house, car, and so on) and her debts. In general, to "settle the estate," the executor must pay all debts before she gives away any of the assets. Legal Aid of West Virginia has a helpful website about West Virginia probate law. Here is what it says about this issue: If you can’t pay all of your family member’s creditors from the person’s available money, you must sell off the family member’s property and pay the creditors in the order listed in W. Va. Code § 44-2-21; W. Va. Code §§ 44-1-18 to -20. You may have to sell the family member’s land or home in order to pay creditors. W. Va. Code § 44-8-7. Added after comments Under WV law, it does not matter that you were bequeathed your mother’s house. The law gives debtors priority over heirs. This means debtors are paid before any heir. Heirs are “paid” from whatever is left in the estate after the debts are paid. So if the estate is underwater, if it owes more than it is worth, there will be nothing left in the estate to give to the heirs. As executor, your job is to carry out West Virginia law. The nuts and bolts of what happens if you refuse to the sell the house depends on WV law. You might be able to find the details by searching on line, but your best bet is to probably to talk to an attorney who specializes in WV probate law. An attorney will know both the law on the books, and how that law is implemented. They will be able to advise you on what options you really have, and the costs and benefits of those options. If the estate is underwater, you could buy the house from the estate. If you do that, you will not be liable for any of your mother’s debts; those are owed by the estate. Depending on how the sale is handled, this may be your (financially) best option. (Depending on whether the price covers the debt, and on what other heirs are bequeathed, the court might worry about you selling yourself the house at a discount price, and thus look at the sale very carefully.) A: You have to pay the debts from the assets that comprise the estate, to the extent that it is possible, but the executor has some discretion in how that happens. This law determines what order debts are to be paid in: funeral expenses are high on the list, last-illness debts are lower but still ahead of "everything else". §44-1-17 though -21 cover assets to be sold or not sold, but except for the family food and fuel exemption, anything can be sold, and debts must be paid. There will not be any debts of the estate after the estate is closed, more or less by definition. There is a Final Settlement form where you say what was in the estate and what claims there were, and how the property was disbursed and the claims satisfied. If there are still debts, you have to pay those debts and can't e.g. sell the house and divide the procedes without paying those debts. (By "can't", I mean that as executor you get in legal trouble). You will know what those debts are because creditors have 60 days to file a claim. You have to publish a notice, in a form prescribed by law, that basically says "X died, send your claims here" (read the statute to get it right). If somebody comes along a year later and demands payment, they are out of luck. A creditor can't just "put a lien on a house", although a contractor who did work on the house could put a mechanic's lien on the house if they were not paid for their work. The IRS can put a lien on your house for non-payment of taxes. But if a bank lends someone money to run a business and they don't pay off the loan—unless the loan was secured with the property as collateral—they can't just put a lien on the house. Nevertheless, as executor, you have to pay that debt at least to the extent that there is any property at all in the estate. A: Yes, in theory, but pursue other options too Yes, in theory, the estate would have to liquidate property to cover those debts. In theory. First, it doesn't necessarily need to be the house. If other assets are saleable, that will suffice. Second, the estate does not necessarily need to sell the house. It could, for instance, mortgage the house to obtain cash to settle the debts. Who would write such a mortgage? Someone friendly - a family member - maybe even the person to whom the house is bequeathed. It also may be possible to structure a deal with a commercial mortgage wherein the estate takes the mortgage (with you as co-party) and then you take possession of the house with assent of the mortgage writer. Now you own a house, albeit with a mortgage. Haggle those debts mercilessly - especially medical debt. Many firms, especially those who function in the elder-care/end of life business, "know the drill". For instance my grandparents both got medicines from a company which is a darling of nursing homes. So most of their business is geriatric. When my grandmother passed, they cheerfully settled her outstanding invoice for half, without even putting up a fight - the estate was fully attachable, they didn't even try. When her husband passed, they just walked away and settled for $0. This is old-hat for them. Many other medical bills are insanely "puffed up" for business reasons. Hospitals' bread-and-butter business is in-network insurance work, where they are locked down by contract to "Reasonable, Usual & Customary" industry rates, such as $47 for a blood test series or $70 for a COVID-19 test. However, when dealing out-of-network or with the uninsured, the prices suddenly puff up to $320 (happened to me) for a blood test or $2,315 for a COVID-19 test. The hospitals have no realistic expectation that a cash patient will pay this. They do it a) to profiteer off medical tourism (wealthy people in the third world think America has a wonderful healthcare system; and they can and do pay those crazy numbers). Many people who can pay won't put up a fight, and it's easy money - like taking candy from babies. (think about that before you scream "morals"). For those who do fight, it gives them a ridiculously highball number to start with; "I'll knock it down from $2315 to $1000 if you pay today for that $70 COVID test". (again, anyone care to argue a moral duty to pay $2315?) For the vast majority of customers who can never pay, it allows the hospital to puff up their paper losses for fundraising reasons. "We donated $1.2 billion of services to those who couldn't pay" (read: after we burned their credit rating to the ground trying to collect). All of that to say, you must look at those medical bills not at all like a real number, but as an absurd highball number from which you start negotiating. But you have to handle that creditor by creditor: I saw $105 bills for a doctor's visit with an independent doctor; that guy was clearly not profiteering, so I paid that in full). And you can haggle down any creditor, and be ruthless! The creditor cannot simply attach a lein on the estate; they have to go through a huge rigmarole of dunning, filing suit, battling with your lawyer... they know perfectly well that if you dig in your heels, they will probably spend $5000 and possibly $10,000 just getting to a judge's verdict, and that only allows them to start another long road: the collections process, and they have to grind through all of that (possibly another $5000) to finally attach that lein on the house. So figure that into your offers: if the estate owes a credit card $7000, offer to settle the debt for $500. It's lowball, but you may both find a happy number in the $1000-3000 range. Creditors do this all the time. A hospital could take their outlandish bill down 75% or more if you are extremely persistent. To be clear: They cannot sue you or attach debt to you, in any way whatsoever. So they can scream and howl all they want; they cannot do anything to you; they can only target the estate. And that's a long, long road to payback, for them. Never assent to take on the estate's debt personally - that's just suicide. Well, there might be a case for personally accepting some estate debt as part of a plan to eliminate all the estate's debt and leave you in a good position, but that is so complex and dangerous you must only do it on advice of your lawyer who is fully in the loop. The asset protection questions are too complex - will this house be homesteaded, will you be converting secured debt to unsecured, etc. You need a pro.
{ "pile_set_name": "StackExchange" }
Q: Fody, propertychanged and setting same value? Is there any way to configure fody to not check the value which is set to property - I have situations when value is the same and I want property to be set because I have additional logic in property setter that is not invoked. A: This is clearly literally years after the original question but for future reference: This is indeed possible by modifying the options in the FodyWeavers.xml file. As is shown on the PropertyChanged.Fody wiki, one of the options is called CheckForEquality and can be set to false (it defaults to true). This will prevent Fody from injecting equality checking code. The FodyWeavers.xml file could now look as follows: <?xml version="1.0" encoding="utf-8" ?> <Weavers> <PropertyChanged CheckForEquality='false'/> </Weavers> As noted in the comments there is also the possibility to do this per property via the DoNotCheckEquality attribute e.g. [ImplementPropertyChanged] public class Person { [DoNotCheckEquality] public string Name { get; set; } } See wiki/Attributes
{ "pile_set_name": "StackExchange" }
Q: add all user ids for one product For adding to cart customer has to logg in,in cart table I have a column for user_id but in user_id column all of user_id in database add!for example for product1 all user1,user2,user3 ides add not just the one logged in cart table: Schema::create('cart', function (Blueprint $table) { $table->increments('id'); $table->integer('product_id'); $table->char('user_id'); $table->string('session_id'); $table->string('product_name'); $table->string('user_email'); $table->integer('qty'); $table->integer('product_price'); $table->timestamps(); }); addToCart method in controller: public function addtocart(Request $request){ $data = $request->all(); if (empty($data['user_email'])){ $data['user_email'] = ' '; } $user_id = User::get('id'); if (empty($user_id)){ $user_id = Auth::user()->id; } $session_id = Session::get('session_id'); if (empty($session_id)){ $session_id = Str::random(40); Session::put('session_id' , $session_id); } DB::table('cart')->insert(['product_id' => $data['product_id'] , 'product_name' => $data['product_name'], 'user_id'=>$user_id, 'product_price' => $data['product_price'], 'qty' => $data['qty'], 'user_email' => $data['user_email'] , 'session_id' => $session_id ]); return redirect('cart'); } what is the problem? A: You are currently requesting all the user ids by doing $user_id = User::get('id'); so if you want to set user_id as your authenticated user id you need to replace: $user_id = User::get('id'); if (empty($user_id)){ $user_id = Auth::user()->id; } by: $user_id = Auth::user()->id; or shorter version: $user_id = Auth::id();
{ "pile_set_name": "StackExchange" }
Q: Datetime colum to float type conversion is getting issue in sql server I'd like alter a column type from Datetime to float. Hence, I executed the below query but it was getting a issue alter table dbo.purchasedate alter column supp_dt float null Error :: Implicit conversion from data type datetime to float is not allowed. Use the CONVERT function to run this query. A: Without knowing your desired output, you could just: Add Float column, populate, drop date column. To my knowledge you cannot add a CONVERT to an ALTER statement, anyone know otherwise?
{ "pile_set_name": "StackExchange" }
Q: SQL Stored Proc Executing Select before gettting values from other procs Got a strange problem created a little stored proc which need to execute a couple of other stored procs to get some values before executing the main select statement see below, set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[usp_get_ApplicationUserServiceRoles] @UserId int, @ApplicationName varchar(50), @ServiceName varchar(50) AS BEGIN ----------------------------------------- SET NOCOUNT ON ----------------------------------------- DECLARE @ApplicationId INT exec @ApplicationId = dbo.usp_get_AppIdFromName @ApplicationName DECLARE @ServiceId INT exec @ServiceId = dbo.usp_get_ServiceIdFromName @ServiceName SELECT [RoleName] FROM [ServiceRoles] s INNER JOIN [ApplicationUserServiceRoles] r ON s.ServiceRoleId = r.ServiceRoleId INNER JOIN [ApplicationServices] p ON s.ServiceId = p.ServiceId WHERE r.UserId = @UserID AND r.ApplicationId = @ApplicationId AND s.ServiceId = @ServiceId END When I run this stored proc it returns me the two values from the two procs with this proc but not the actual select value. However when I run the select statement on its own with the values the secondary stored procs return it returns the correct data. Any idea what's going on, is the select statement running before the two secondary stored procs so the select statement hasn't got the correct values? Running in SQL 2005 A: A stored procedure returns a number indicating the execution status of the stored procedure. In order to capture the select statement's output you'll have to use INSERT...EXECUTE (see here for details) What happens in your case is that each sub-procedure executes but your main procedure fails. Check your output window, it should tell you the error. A: The only way to capture the result set of a stored procedure is INSERT ... EXEC: declare @applicationId int; declare @tableApplicationId table (ApplicationId ind); insert into @tableApplicationId exec dbo.usp_get_AppIdFromName @ApplicationName; select @applicationId = ApplicationId from @tableApplicationId; You may want to consider changing dbo.usp_get_AppIdFromName into a function instead, or a procedure that returns @applicationId as OUTPUT parameter. INSERT ... EXEC has all sort of side effect problems, like nesting issues: http://www.sommarskog.se/share_data.html#INSERTEXEC The Hidden Costs of INSERT EXEC
{ "pile_set_name": "StackExchange" }
Q: find a universe for variables x, y, and z for which this statement is true and another universe in which it is false Im solving a practice quesitons on quantifiers and I'm stuck with this questions im trying to solve this question for few hours now and I really don't have a clue what to do... The question is Find a universe for variables $x$, $y$, and $z$ for which the statement $$\forall x∀y((x\ne y) → ∀z((z = x) ∨ (z = y)))$$ is true and another universe in which it is false Detailed explanation will be really much appreciated. Thanks in advance guys! A: Hint: The logical negation of $$ x\ne y\to (z=x\lor z=y)$$ is $$x\ne y \land z\ne x\land z\ne y$$ or $$x,y,z\text{ are three distinct objects}$$
{ "pile_set_name": "StackExchange" }
Q: Why does Moshe tell Hashem that he is 'heavy of mouth and heavy of tongue' - twice? Shemot 4:10-15 is a dialogue between Hashem and Moshe where Moshe tells Hashem that he is 'heavy of mouth and heavy of tongue'. In pssukim 14-15 Hashem tells Moshe that he will tell Aharon what to say, and that he will be Moshe's interpreter, because of his speech impediment. [see Rashi there] So why then does Moshe say the same claim in Shemot 6:12 ... How then will Pharaoh hearken to me, seeing that I am of closed lips?" to which Hashem answers seemingly the same answer in Shemot 7:1-2 (ie that Aharon will act as interperetor) A: Moshe repeats that he has a speech impediment in Shemos 6,12 because it is part of his argument to Hashem that Pharaoh would not hearken to him, as it says: "And Moshe spoke before Hashem, saying: Behold, Yisrael did not hearken to me, how then will Pharaoh hearken to me, seeing that I am of closed lips?". The sefer Binyan Ariel explains Moshe's argument was as follows: When Hashem told Moshe to go together with Aharon because he was "heavy of tongue" and also to accord honor to his older brother, Moshe understood that they were supposed to speak together, as it says in the Mechilta on the posuk in Shemos 12,3: "Moshe accorded honor to Aharon, and Aharon accorded honor to Moshe, and it seemed as if the speech came from both of them". But the gemara in Rosh Hashanah 27a says that two voices speaking simultaneously cannot be heard very well, unless it is something that the person listening really wants to hear. This was Moshe's argument, that if Yisrael were not able to hear us because we were speaking together, even though we were telling something that they really wanted to hear, how is it possible that Pharaoh will hear us, "seeing that I am of closed lips". That is, since Moshe had a speech impediment and thus always spoke together with Aharon as per his understanding of Hashem's instructions, if Yisrael were not able to hear them, all the more so Pharaoh would not be able to hear them. Therefore, Hashem now clarified to Moshe that he was to speak first and then Aharon by himself. Full text in English can be found here. A: [A friend of mine suggested this answer to me and it seems right: (no source though)] The dialogue in Shemot 4:10-15 deals with Moshe's apprehension in speaking with the Jewish people. Similarly Hashem tells Moshe in Passuk 16 that Aharon will be his interpreter- to the Jewish people. Shemot 4:16: And he will speak for you to the people, and it will be that he will be your speaker, and you will be his leader. So , until instructed explicitly, it would follow that Moshe would be speaking straight to Pharoh ( without Aharon as interpreter) which is why Moshe tells Hashem in Shemot 6:12 that he is "of closed lips".
{ "pile_set_name": "StackExchange" }
Q: How to query by embedded example containing null values using hibernate? I have a problem with a query using hibernate. The entity class EntityClass has an embedded property embedded of type EmbeddedClass and this property has a nullable property optional. When all properties are set, i can do a very simpel HQL query as: Query query = getSession().createQuery( "FROM EntityClass t WHERE t.embedded = :embedded"); query.setParameter("embedded", embedded); return (EntityClass) query.uniqueResult(); But when the property optional is null, this does not work, because hibernate creates a SQL query like t.optional=? but =NULL should be IS NULL in SQL. The WHERE clause never matches, the query returns no rows. Some further reading pointed to Example which is handling null properly. Now my code looks like: Criteria query = getSession().createCriteria(EntityClass.class); query.createCriteria("embedded").add(Example.create(embedded)); return (EntityClass) query.uniqueResult(); When running the code I get a ClassCastException: java.lang.ClassCastException: EmbeddedClass at org.hibernate.criterion.Example.getEntityMode(Example.java:279) at org.hibernate.criterion.Example.toSqlString(Example.java:209) at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:357) at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:113) at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:82) at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:91) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1577) at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306) at org.hibernate.impl.CriteriaImpl.uniqueResult(CriteriaImpl.java:328) It has something to do with EntityPersister.guessEntityMode() returning null, because hibernate looks for the mapping of the entity class, not the embedded one. It seems that org.hibernate.criterion.Example can not be used for an embedded class. Any idea how to to this? Is there an ohter approach? The classes look like: @Entity public class EntityClass { ... @Embedded private EmbeddedClass embedded; ... } @Embeddable public class EmbeddedClass { private String name; private String optional; ... } I use hibernate 3.3.1 and an oracle 10g if that helps. A: Uh, I got it: After debugging the hibernate code, I discovered you need to build the example on the entity class. So I created an example instance of the entity, set the embedded value and excluded the unused properties on the Example criterion: Criteria query = getSession().createCriteria(EntityClass.class); EntityClass example = new EntityClass(); example.setEmbedded(embedded); query.add(Example.create(example).excludeNone() .excludeProperty("id").excludeProperty("other")); return (EntityClass) query.uniqueResult();
{ "pile_set_name": "StackExchange" }
Q: sending div id through button click java-script method parameter can anyone please tell me how to send div id through button click java-script parameter. Here in the below code the main div id 'ricId_1' and the class name "ric_class1 rico_class0 ric1_class1 ric2_class3" is created dynamically has to be send through javascript method cancel('divid') in the button click.The div id is not static. <div id="ricId_1" class="ric_class1 rico_class0 ric1_class1 ric2_class3" style="width: 730px; left: 309px; top: 71.5px; z-index: 13000; display: block;"> <div class="ricTitle"> : </div> <div class="ricModal ng-scope" style="height: auto;"> : <div> <div> <div ng-controller="Manage" class="ng-scope"> <div class="ricG ricAlign"> <div class="ricGrid"><div class="ricGridTable"> : </div> </div> </div> </div> <div align="center" class="row btn-group"> <button onclick="cancel('divid')" class="ricButton" type="button" id="sss" ric:loaded="true">Close</button> </div> </div> A: Pass the button to cancel and use that id to get the closes ancestor with class ric_class1 rico_class0 ric1_class1 ric2_class3 having id ricId_1 Live Demo Html <button onclick="cancel(this)" class="ricButton" type="button" id="sss" ric:loaded="true">Close</button> Javascript function cancel(btn) { ricId_1 = $(btn).closest('ric_class1 rico_class0.ric1_class1 ric2_class3'); //or ricId_1 = $(btn).parent().parent(); }
{ "pile_set_name": "StackExchange" }
Q: What is the difference between browser.pause() and browser.enterRepl()? In protractor, there is the browser.pause() function: Beta (unstable) pause function for debugging webdriver tests. Use browser.pause() in your test to enter the protractor debugger from that point in the control flow. element(by.id('foo')).click(); browser.pause(); // Execution will stop before the next click action. element(by.id('bar')).click(); And, also, there is a less-known one - browser.enterRepl(): Beta (unstable) enterRepl function for entering the repl loop from any point in the control flow. Use browser.enterRepl() in your test. Does not require changes to the command line (no need to add 'debug'). element(by.id('foo')).click(); browser.enterRepl(); // Execution will stop before the next click action. element(by.id('bar')).click(); From the provided documentation and examples, it is clear that they both are used for debugging the tests. But, it is not clear, what is the difference between the two. When should we use pause() and when enterRepl()? A: It's explained in the docs in general, but I'll try to get a bit deeper. Protractor has two modes for debugging: DebuggerRepl and CommandRepl. Repl here stands for Read-eval-print-loop which usually means that whatever command you type in, it gets evaluated right away in the current context and you are provided with a result immediately. For example, the console in Chrome Developer Tools is kinda a REPL for Chrome's implementation of JavaScript/DOM, or when you run node in terminal, you get a REPL for Node.js's JavaScript context - you can type commands and get the result. When you use browser.pause() you are activating DebuggerRepl. It brings you a Repl where you can execute commands of this mode. You usually see this list of commands in the terminal: press c to continue to the next webdriver command press d to continue to the next debugger statement type "repl" to enter interactive mode type "exit" to break out of interactive mode press ^C to exit So you can go to the next WebDriver command using c command or jump to the next browser.pause() statement in your test using d command. They are executed right away as you use them. So this mode basically allows you to jump over page states and explore the result. (Note: this mode provides more commands; they do work, but I'm not sure what is the meaning of their output and if they are useful for a Protractor user at all.) When you use browser.enterRepl() you are activating CommandRepl mode. It allows you to use Protractor methods which you would use in tests, but in an interactive mode. You get access to element, browser and protractor objects, so you could run for example: > $('.hello').getText(); > 'World' It prints you back the result immediately, so it's sort of a sandbox where you can query the DOM on the current page state and see the results. As you may have noticed, the browser.pause() list of commands has a line: type "repl" to enter interactive mode It means that when you are in DebuggerRepl mode, you can execute the repl command to activate CommandRepl mode for the current page state where you've just run browser.pause(), so you can play with DOM as if you've just used browser.enterRepl(). You can go back to DebuggerRepl mode using the exit command. But if you've entered to CommandRepl mode using browser.enterRepl(), you can't switch to DebuggerRepl mode. Also, CommandRepl mode can be activated with a feature called elementExplorer. It can be used without any written tests; it just opens a URL in CommandRepl mode. tl;dr To summarize, I believe that they supposed to be used according to how they are called. browser.pause() - I want a browser to pause exactly in that place so I can see what's happening on the page. Then, on my command, I want it to jump to the next state so I can see what is happening here. If I need more information for current state, I can run repl and use the Protractor API (browser, element, protractor) to investigate. I can then exit this mode and continue jumping through states. browser.enterRepl() - I want a browser to pause exactly in that place and let me investigate a page using the Protractor API (browser, element, protractor) right away, and I don't need to be able to jump between states of the page.
{ "pile_set_name": "StackExchange" }
Q: Angular 2 routing in ES5? The Angular 2 ES5 cheat sheet says to do this: var MyComponent = ng.router.RouteConfig([ { path: '/:myParam', component: MyComponent, as: 'MyCmp' }, { path: '/staticPath', component: ..., as: ...}, { path: '/*wildCardParam', component: ..., as: ...} ]).Class({ constructor: function() {} }); However, I can't figure out how to specify the @Component stuff on that class so that I can actually instantiate it. For example, ng.router.RouteConfig([...]).Component({}) throws an exception because the result of .RouteConfig doesn't have a .Component method. Similarly, the result of .Component doesn't have a .RouteConfig method. How do you get this set up? A: I've done the following way which seems to work well. app.AppComponent = ng.core .Component({ selector: 'the-app', template: ` <h1>App!!!</h1> <a [routerLink]="['Children']">Children</a> <a [routerLink]="['Lists']">Lists</a> <router-outlet></router-outlet> `, directives:[ app.ListsComponent, app.ChildrenComponent, ng.router.ROUTER_DIRECTIVES ] }) .Class({ constructor: [ng.router.Route, function(_router) { this._router = _router; // use for navigation, etc }] }); app.AppComponent = ng.router .RouteConfig([ { path: '/', component:app.ListsComponent, name:'Lists' }, { path: '/children', component:app.ChildrenComponent, name:'Children' } ])(app.AppComponent); Since both ng.core.Component and ng.router.RouteConfig are decorators you can write: app.AppComponent = ng.core.Class(...); app.AppComponent = ng.core.Component(...)(app.AppComponent); app.AppComponent = ng.router.RouteConfig(...)(app.AppComponent); Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: jQuery conditional statement to check if a select option has either of 4 values selected I am working on this project that has a reservation form which allow users specify which sort of service they require. I have a select menu with eight (8) options and I have two divs which would either show/hide depending on the value of the option been selected. Seen below is the select element: <select name="serviceChoice" id="serviceChoice"> <option value="A">Option A</option> <option value="B">Option B</option> <option value="C" selected="selected">Option C</option> <option value="D">Option D</option> <option value="E">Option E</option> <option value="F">Option F</option> </select> <div id="field_1" class="optionBox">I have several form fields</div> <div id="field_2" class="optionBox">I have several form fields</div> I have written my jQuery code to alternate between these divs, however I would like to know if there is a shorter better way to get this done. I would also like to clear the values of any input elements in a div which has been hidden due to the choice of the user. My code is as follows: (function($){ $('#field_1').show(); $('select[name=serviceChoice]').change(function(){ if( $('select[name=serviceChoice] option:selected').val() == 'A' ) { $('.optionBox').hide(); $('#dropOff').show(); } else if ( $('select[name=serviceChoice] option:selected').val() == 'B' ) { $('.optionBox').hide(); $('#pickUp').show(); } else if ( $('select[name=serviceChoice] option:selected').val() == 'C' ) { $('.optionBox').hide(); $('#pickUp').show(); } else if ( $('select[name=serviceChoice] option:selected').val() == 'D' ) { $('.optionBox').hide(); $('#pickUp').show(); } else { $('.optionBox').show(); } }); })(jQuery); A: // You can use the document.ready as both encapsulation as well as // to make sure the DOM is ready for operation. $(function ($) { // Unless these are dynamic (the set could change), it's better to cache them var optionBox = $('.optionBox'); var dropOff = $('#dropOff'); var pickUp = $('#pickUp'); var field1 = $('#field_1'); field.show(); // Your select box has an ID. They are faster than attribute selectors // in both parsing ase well as fetching from the DOM $('#serviceChoice').change(function () { // The current context of this function is the DOM element, which is the select // You can use it to get the value, rather than using a selector again. Removes // the need for jQuery to parse the selector and look for it in the DOM switch ($(this).val()) { case 'A': optionBox.hide(); dropOff.show(); break; case 'B': case 'C': case 'D': optionBox.hide(); pickUp.show(); break; default: optionBox.show(); } }); }); Minus the comments, here's what you get: $(function ($) { var optionBox = $('.optionBox'); var dropOff = $('#dropOff'); var pickUp = $('#pickUp'); var field1 = $('#field_1'); field.show(); $('#serviceChoice').change(function () { switch ($(this).val()) { case 'A': optionBox.hide(); dropOff.show(); break; case 'B': case 'C': case 'D': optionBox.hide(); pickUp.show(); break; default: optionBox.show() } }) });
{ "pile_set_name": "StackExchange" }
Q: python access a column after groupby I would like to replace null value of stadium attendance (affluence in french) with their means. Therefore I do this to have the mean by seasons / teams : test = data.groupby(['season','domicile']).agg({'affluence':'mean'}) This code works and give me what I want (data is dataframe) : affluence season domicile 1999 AS Monaco 10258.647059 AS Saint-Etienne 27583.375000 FC Nantes 28334.705882 Girondins de Bordeaux 30084.941176 Montpellier Hérault SC 13869.312500 Olympique Lyonnais 35453.941176 Olympique de Marseille 51686.176471 Paris Saint-Germain 42792.647059 RC Strasbourg Alsace 19845.058824 Stade Rennais FC 13196.812500 2000 AS Monaco 8917.937500 AS Saint-Etienne 26508.750000 EA Guingamp 13056.058824 FC Nantes 31913.235294 Girondins de Bordeaux 29371.588235 LOSC 16793.411765 Olympique Lyonnais 34564.529412 Olympique de Marseille 50755.176471 Paris Saint-Germain 42716.823529 RC Strasbourg Alsace 13664.875000 Stade Rennais FC 19264.062500 Toulouse FC 19926.294118 .... So now I would like to do a condition on the season and the team. For example test[test.season == 1999]. However this doesn't work because I have only one column 'affluence'. It gives me the error : 'DataFrame' object has no attribute 'season' I tried : test = data[['season','domicile','affluence']].groupby(['season','domicile']).agg({'affluence':'mean'}) Which results as above. So I thought of maybe indexing the season/team, but how ? And after that how do I access it ? Thanks A: Doing test = data.groupby(['season','domicile'], as_index=False).agg({'affluence':'mean'}) should do the trick for what you're trying to do. The parameter as_index=False is particularly useful when you do not want to deal with MultiIndexes. Example: import pandas as pd data = { 'A' : [0, 0, 0, 1, 1, 1, 2, 2, 2], 'B' : list('abcdefghi') } df = pd.DataFrame(data) print(df) # A B # 0 0 a # 1 0 b # 2 0 c # 3 1 d # 4 1 e # 5 1 f # 6 2 g # 7 2 h # 8 2 i grp_1 = df.groupby('A').count() print(grp_1) # B # A # 0 3 # 1 3 # 2 3 grp_2 = df.groupby('A', as_index=False).count() print(grp_2) # A B # 0 0 3 # 1 1 3 # 2 2 3
{ "pile_set_name": "StackExchange" }
Q: NHibernate QueryOver with SelectList I have multiple queries against one table. As not all columns/properties are needed I specify the columns with the help of select list. Take the following method as example. This method is working public IEnumerable<ResultDto> GetEntityAsDto(eStatusBinderProduktion fromState, eStatusBinderProduktion toState) { EntityClass entityAlias = null; ResultDto resultAlias = null; var query = Session.QueryOver<EntityClass>(() => entityAlias) .Where(() => entityAlias.ProduktionStatus >= (byte)fromState) .And(() => entityAlias.ProduktionStatus <= (byte)toState); query.SelectList(list => list .Select(() => entityAlias.PrimaryID).WithAlias(() => resultAlias.PrimaryID) .Select(() => entityAlias.SecondaryID).WithAlias(() => resultAlias.SecondaryID) ); return query.TransformUsing(Transformers.AliasToBean<ResultDto>()) .List<ResultDto>(); } As I need to define the SelectList in multiple methods, I tried to to move the SelectList into a separate method. The following code is not working, NHibernate throws the exception NHibernate.QueryException: 'could not resolve property: entity.PrimaryID of: MyProjectNamespace.DAL.Interfaces.Entities.EntityClass' " public IEnumerable<ResultDto> GetEntityAsDto(eStatusBinderProduktion fromState, eStatusBinderProduktion toState) { EntityClass entityAlias = null; ResultDto resultAlias = null; var query = Session.QueryOver<EntityClass>(() => entityAlias) .Where(() => entityAlias.ProduktionStatus >= (byte)fromState) .And(() => entityAlias.ProduktionStatus <= (byte)toState); MapPropertiesOfEntityToResult(entityAlias, resultAlias, query); return query.TransformUsing(Transformers.AliasToBean<ResultDto>()) .List<ResultDto>(); } private void MapPropertiesOfEntityToResult(EntityClass entity, ResultDto resultAlias, IQueryOver<EntityClass, EntityClass> query) { query.SelectList(list => list .Select(() => entity.PrimaryID).WithAlias(() => resultAlias.PrimaryID) .Select(() => entity.SecondaryID).WithAlias(() => resultAlias.SecondaryID) ); } Additional information: - The mappings are correct - table is filled with test data A: We do not need alias for filling SelectList. We can profit from the Type parameters coming with IQueryOver<TRoot,TSubType>: //private void MapPropertiesOfEntityToResult(EntityClass entity // , ResultDto resultAlias, IQueryOver<EntityClass, EntityClass> query) private void MapPropertiesOfEntityToResult( // no need for entity ResultDto resultAlias, IQueryOver<EntityClass, EntityClass> query) { query.SelectList(list => list //.Select(() => entity.PrimaryID).WithAlias(() => resultAlias.PrimaryID) //.Select(() => entity.SecondaryID).WithAlias(() => resultAlias.SecondaryID) .Select(entity => entity.PrimaryID).WithAlias(() => resultAlias.PrimaryID) .Select(entity => entity.SecondaryID).WithAlias(() => resultAlias.SecondaryID) ); } The entity is now a parameter of the passed Function and its type is coming from IQueryOver definition
{ "pile_set_name": "StackExchange" }
Q: Do we have to explicitly recycle the bitmap if we don't need it? Bitmap has a recycle method, but do we have to invoke it explicitly if we don't need it any more? For example, an ImageView has a bitmap now. When user click a button, it will set a new bitmap to the ImageView. Do we have to recycle the original bitmap before assign the new one? A: yes you have if you are targeting devices with Android older the 3.0. That's will avoid you to incour in the OutOfMemoryException. Note: Before android 3 the Bitmap memory is allocated in the native heap. The java object will retains low memory from the GC perspective.
{ "pile_set_name": "StackExchange" }
Q: Create a map of spatial clusters LISA in R I would like to create a map showing local spatial cluster of a phenomenon, preferably using Local Moran (LISA). In the reproducible example below, I calculate the local moran's index using spdep but I would like to know if there is as simple way to map the clustes, prefebly using ggplot2. Help ? library(UScensus2000tract) library(ggplot2) library(spdep) # load data data("oregon.tract") # plot Census Tract map plot(oregon.tract) # create Queens contiguity matrix spatmatrix <- poly2nb(oregon.tract) #calculate the local moran of the distribution of black population lmoran <- localmoran(oregon.tract@data$black, nb2listw(spatmatrix)) Now to make this example more similar to my real dataset, I have some NA values in my shape file, which represent holes in the polygon, so these areas shouldn't be used in the calculation. oregon.tract@data$black[3:5] <- NA A: Here is a strategy: library(UScensus2000tract) library(spdep) library(ggplot2) library(dplyr) # load data data("oregon.tract") # plot Census Tract map plot(oregon.tract) # create Queens contiguity matrix spatmatrix <- poly2nb(oregon.tract) # create a neighbours list with spatial weights listw <- nb2listw(spatmatrix) # calculate the local moran of the distribution of white population lmoran <- localmoran(oregon.tract$white, listw) summary(lmoran) # padronize the variable and save it to a new column oregon.tract$s_white <- scale(oregon.tract$white) %>% as.vector() # create a spatially lagged variable and save it to a new column oregon.tract$lag_s_white <- lag.listw(listw, oregon.tract$s_white) # summary of variables, to inform the analysis summary(oregon.tract$s_white) summary(oregon.tract$lag_s_white) # moran scatterplot, in basic graphics (with identification of influential observations) x <- oregon.tract$s_white y <- oregon.tract$lag_s_white %>% as.vector() xx <- data.frame(x, y) moran.plot(x, listw) # moran sccaterplot, in ggplot # (without identification of influential observations - which is possible but requires more effort) ggplot(xx, aes(x, y)) + geom_point() + geom_smooth(method = 'lm', se = F) + geom_hline(yintercept = 0, linetype = 'dashed') + geom_vline(xintercept = 0, linetype = 'dashed') # create a new variable identifying the moran plot quadrant for each observation, dismissing the non-significant ones oregon.tract$quad_sig <- NA # high-high quadrant oregon.tract[(oregon.tract$s_white >= 0 & oregon.tract$lag_s_white >= 0) & (lmoran[, 5] <= 0.05), "quad_sig"] <- "high-high" # low-low quadrant oregon.tract[(oregon.tract$s_white <= 0 & oregon.tract$lag_s_white <= 0) & (lmoran[, 5] <= 0.05), "quad_sig"] <- "low-low" # high-low quadrant oregon.tract[(oregon.tract$s_white >= 0 & oregon.tract$lag_s_white <= 0) & (lmoran[, 5] <= 0.05), "quad_sig"] <- "high-low" # low-high quadrant oregon.tract@data[(oregon.tract$s_white <= 0 & oregon.tract$lag_s_white >= 0) & (lmoran[, 5] <= 0.05), "quad_sig"] <- "low-high" # non-significant observations oregon.tract@data[(lmoran[, 5] > 0.05), "quad_sig"] <- "not signif." oregon.tract$quad_sig <- as.factor(oregon.tract$quad_sig) oregon.tract@data$id <- rownames(oregon.tract@data) # plotting the map df <- fortify(oregon.tract, region="id") df <- left_join(df, oregon.tract@data) df %>% ggplot(aes(long, lat, group = group, fill = quad_sig)) + geom_polygon(color = "white", size = .05) + coord_equal() + theme_void() + scale_fill_brewer(palette = "Set1") This answer was based on this page, suggested by Eli Knaap on twitter, and also borrowed from the answer by @timelyportfolio to this question. I used the variable white instead of black because black had less explicit results. Concerning NAs, localmoran() includes the argument na.action, about which the documentation says: na.action is a function (default na.fail), can also be na.omit or > na.exclude - in these cases the weights list will be subsetted to remove NAs in the data. It may be necessary to set zero.policy to TRUE because this subsetting may create no-neighbour observations. Note that only weights lists created without using the glist argument to nb2listw may be subsetted. If na.pass is used, zero is substituted for NA values in calculating the spatial lag. I tried: oregon.tract@data$white[3:5] <- NA lmoran <- localmoran(oregon.tract@data$white, listw, zero.policy = TRUE, na.action = na.exclude) But run into problems in lag.listw but did not have time to look into it. Sorry.
{ "pile_set_name": "StackExchange" }
Q: How do I create a React Native project using Yarn? I am running the following commands in the DOS console on a Windows 7 (64-bit) machine. npm install -g yarn yarn add global react-native yarn add global react-native-cli react-native init sample After running react-native init sample, the console was closed. The error log shows: D:\Mobile>"$basedir/../../Users/pramaswamy/AppData/Local/Yarn/.global/node_modules/.bin/react-native.cmd" "$@" D:\Mobile>exit $? A: I think you're adding global dependencies wrong, and you shouldn't need to install react-native, globally or locally. react-native init will create a package.json with react-native listed as a dependency. You should be able to install react-native-cli globally with yarn global add react-native-cli, not yarn add global react-native-cli. You should be fine with running the following: npm install -g yarn yarn global add react-native-cli react-native init sample A: NEW SEP 2019, now it's more simple, use node10 and expo: (easy way) npm install -g expo-cli *to create project: expo init AwesomeProject cd AwesomeProject npm start *install the app 'expo' on your phone, and scan the qr code for the project and you can start to view your app more info: https://facebook.github.io/react-native/docs/getting-started.html UPDATE OCT 2018 Create React Native App (now discontinued) has been merged with Expo CLI You can now use expo init to create your project. See Quick Start in the Expo documentation for instructions on getting started using Expo CLI. Unfortunately, react-native-cli is outdated. Starting 13 March 2017, use create-react-native-app instead. Moreover, you shouldn't install Yarn with NPM. Instead, use one of the methods on the yarn installation page. 1. Install yarn Via NPM. According to its installation docs, you shouldn't install yarn via npm, but if necessary, you can still install it with a pre-v5 version of npm. UPDATE 2018 - OCTOBER Node 8.12.0 and NPM 6.4.1 is already compatible with create-react-native-app. Really some minors previous versions too. You don't need more downgrade your npm. On Ubuntu. curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list On macOS, use Homebrew or MacPorts. brew install yarn sudo port install yarn 2. Install the Create React Native App yarn global add create-react-native-app 3. Update your shell environment source ~/.bashrc 4. Create a React native project create-react-native-app myreactproj A: You got the order wrong. You should be yarn add global react-native-cli yarn add react-native react-native init sample
{ "pile_set_name": "StackExchange" }
Q: Fragment transitions in Android with MVVMCross In MVVMCross is easy to develop Activity transitions, but i'm finding so many troubles trying to develop this with fragments. I got an application with a Hamburger Menu, and I wanna be capable to edit my own transitions between fragments. I've been searching in the internet but i cant find any solution. Thank you for your attention. A: If you are using MvxCachingFragmentCompatActivityas the base type for your activity you can override OnBeforeFragmentChanging method to set a custom transition animation. public override void OnBeforeFragmentChanging( IMvxCachedFragmentInfo fragmentInfo, Android.Support.V4.App.FragmentTransaction transaction) { transaction.SetCustomAnimations( // Your entrance animation xml reference Resource.Animation.slide_in_from_right, // Your exit animation xml reference Resource.Animation.slide_out_to_left); base.OnBeforeFragmentChanging(fragmentInfo, transaction); }
{ "pile_set_name": "StackExchange" }
Q: When did Firefox change its Function.prototype.toString() behaviour? Nowadays, when you call a function's .toString(), browsers return the function's original declaration. But I remember that Firefox used to return an optimized version, eg. function fn() { return 2+3; } fn.toString() // Used to give: function fn() {return 5;} On which browsers is it safe to use this feature? A: From MDN: Since Gecko 17.0 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14), Function.prototype.toString() has been implemented by saving the function's source. The decompiler was removed, so that the indentation parameter is not needed any more. See bug 761723 for more details.
{ "pile_set_name": "StackExchange" }
Q: Scope between methods Another newbie question. I am trying to understand how to use scope effectively to organise my projects using classes to hold the data instead of having everything on the view controller. So, I am working on a couple of versions of a simple project to understand how scope works. I have a view controller hooked to a view. In that view there are buttons that when clicked show images. I want to add another button that randomizes the images. I also have a class called "Cards" to hold the cards and the methods for creating and shuffling the cards. I have duplicated the project, so I have one that works and one that doesn't. First project. These are the files: view controller h file: #import <UIKit/UIKit.h> #import "Cards.h" @interface ViewController : UIViewController - (IBAction)buttonPressed:(id)sender; @end view contoller m file: #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; Cards *instance = [[Cards alloc] init]; instance.images = [instance createImages]; NSLog(@"I've got %lu Images", (unsigned long)instance.images.count); instance.shuffled = [instance shuffleImages]; NSLog(@"Image numbers shuffled: %@", instance.shuffled); } - (IBAction)buttonPressed:(id)sender { //Nothing hooked to this yet } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end Cards h file: #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> @interface Cards : NSObject // Creating Images @property NSMutableArray *images; - (NSMutableArray*) createImages; //Shuffling Images @property NSMutableArray *shuffled; - (NSMutableArray*) shuffleImages; @end Cards m file: #import "Cards.h" @implementation Cards - (NSMutableArray*) createImages{ self.images = [[NSMutableArray alloc] initWithObjects: [UIImage imageNamed:@"Image1.png"], [UIImage imageNamed:@"Image2.png"], [UIImage imageNamed:@"Image3.png"], [UIImage imageNamed:@"Image4.png"], nil]; return self.images; } - (NSMutableArray*) shuffleImages{ NSUInteger imageCount = [self.images count]; NSMutableArray *localvar = [[NSMutableArray alloc]init]; for (int tileID = 0; tileID < imageCount; tileID++){ [localvar addObject:[NSNumber numberWithInt:tileID]]; } for (NSUInteger i = 0; i < imageCount; ++i) { NSInteger nElements = imageCount - i; NSInteger n = (arc4random() % nElements) + i; [localvar exchangeObjectAtIndex:i withObjectAtIndex:n]; } return localvar; } @end This works and I get the expected output on the console: 2015-12-31 23:43:44.885 VCScope[2138:533369] I've got 4 Images 2015-12-31 23:43:44.886 VCScope[2138:533369] Image numbers shuffled: ( 0, 2, 3, 1 ) Second project: What I want to do, is put a button to randomize the images only when the button is pressed and not as part of viewDidLoad. So, in my second project, I have the same files for the view controller.h and for both the Cards.h and Cards.m, but on the view controller.m I move the calling of the method for the shuffling of the cards to a UIButton method, like so: new View controller m file: #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; Cards *instance = [[Cards alloc] init]; instance.images = [instance createImages]; NSLog(@"I've got %lu Images", (unsigned long)instance.images.count); } - (IBAction)buttonPressed:(id)sender { Cards *instance = [[Cards alloc] init]; instance.shuffled = [instance shuffleImages]; NSLog(@"Image numbers shuffled: %@", instance.shuffled); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end This outputs to the console the following: 2015-12-31 23:32:07.495 4StackVCScope[2029:486608] I've got 4 Images 2015-12-31 23:32:11.924 4StackVCScope[2029:486608] Image numbers: ( ) So it's not working and I am guessing it's to do with scope. Can someone throw some light into this? thanks A: Welcome to Stack Overflow. You mention you're a "newbie", but it would be helpful to know what background you have so I know how much detail is needed here. Cards *instance = [[Cards alloc] init]; creates a fresh Cards instance in a local variable. You are doing this separately inside -viewDidLoad and in -buttonPressed:. If you want one Cards object per ViewController, then the view controller needs to have per-instance storage for it. There are several possible ways to do this. Which one you pick is a question of code style and API design. If the Cards instance is for internal use only, you can declare an ivar in your @implementation block: @implementation ViewController { Cards *_cards; } - (void)viewDidLoad { _cards = ... } - (IBAction)buttonPressed:(id)sender { access _cards } @end (Ivars can be declared in the public @interface as well, but I wouldn't recommend that as it leaks implementation details.) Or you can use a property in the public interface: // in your .h file: @interface ViewController @property (nonatomic) Cards *cards; @end // in your @implementation: - (void)viewDidLoad { self.cards = ... } - (IBAction)buttonPressed:(id)sender { access self.cards } A property can also be privately declared in a class extension: // in your .m file: @interface ViewController () @property (nonatomic) Cards *cards; @end
{ "pile_set_name": "StackExchange" }
Q: RxJS handling closure variables My scenario is following: - Reach to database for some object - After obtaining base object grab it's additional data - Merge additional data to base object I wish to write it in pure functional manner (i.e. with no side effects) but so far I'm unable to achieve it: getMeterPointWithMeterDatabyId(id: number, allowEmpty: boolean = false): Observable<MergeObject> { const params = this.getEmptyParams(); let mp: MergeObject; // This is my enclosed objects I refer to return this.masterService.getMasterById(params) .concatMap<MergeObject, MergeData[]>((master: MergeObject) => { mp = master; // This is side effect generation return this.meterService.getMasterData(params); }) .concatMap<MasterData[], MergeObject>((md: MasterData[]) => { mp.data = md.slice(); // Even more side effects return Observable.of(mp); // Final result generated form impure result }); I think I have a ggo understanding of how Rx works when there is no cycle dependency between objects (i.e. my call chain produced A -> B -> C) but I'm loosing my confidence when I need to step back at one processing step to grab some previous data (i.e. A -> B -> A , where A finally contains B) EDIT: As far a si know, zip operator is doing the trick, but I'd like to know, is it possible to achieve such manually A: If you actually need the base object to query the details (i.e., the requests must happen consecutively), you can do this.service.getMaster(id) .switchMap(master => this.service.getDetails(master) // .catch(…) <-- if you want to continue even if fetching the details fails .map(details => merge(master, details)) ) .subscribe(); The trick is to simply nest the map inside the switchMap, that way master stays in scope without having to jump through hoops. If the details request is actually independent, you can fire both in parallel using Observable.forkJoin( this.service.getMaster(id), this.service.getDetails(id) // .catch(…) <-- if you want to continue even if fetching the details fails ) .map(([master, details) => merge(master, details)) .subscribe(); The technique of delinearizing an operator chain, that is transforming source$ .switchMap(data1 => transformationA(data1)) // From here on out, you only see data1 .switchMap(data2 => transformationB(data2)) // From here on out, you only see data2 .subscribe(data3 => …); into source$ .switchMap(data1 => transformationA(data1) .switchMap(data2 => transformationB(data2) // You can see both data1 and data2 here! ) .subscribe(data3 => …); is useful quite often in order to keep data from multiple steps in scope, e.g. to combine them. It's definitely something to always keep in mind: you can also nest.
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of this cartoon by Dr. Seuss? I don't quite understand what the author was trying to say in this picture. Could anyone explain? http://libraries.ucsd.edu/speccoll/dswenttowar/#ark:bb4813149f A: It's possible the OP is asking this question because of the somewhat confusing verbiage on the flag in the cartoon. The flag says, "That cheap gunning for Eleanor Roosevelt." If this is the essence of the question, allow me to answer thus: "Gunning for" means "looking to, or attempting to, criticize, or in some way attack." If someone is "gunning for Roosevelt," they are looking for a chance to attack her. The cartoonist has extended the meaning slightly to include the actual attack itself. He is referring to the fact that many people "attacked" (criticized) Eleanor Roosevelt for her opinions about Japanese-American relationships. This phrase then becomes a pun when used in the cartoon, because the critics are depicted as firing actual guns. This, then, enables the cartoon Hitler to say sarcastically that Americans are good at attacking themselves, meaning Hitler is making fun of our ability to fight the war because we attack ourselves. Ultimately, the cartoonist's point is that we shouldn't be quarreling amongst ourselves, but focusing instead on the real enemy. Also, the cartoonist called the "gunning" cheap, which means it is "unworthy, too thoughtlessly done to be of any merit, and dishonorable."
{ "pile_set_name": "StackExchange" }
Q: Print all characters after every 3rd occurrence of comma in oracle I have a string as "12as3,45we6,7we89,101112,131415,3234,1234" and want to write a oracle regex function or a SQL to print all the characters after every 3rd occurrence of comma (,) . So the Output for this should be 12as3,45we6,7we89 101112,131415,3234 1234 I have tried regex but it is only printing the first occurrence. SELECT NVL( SUBSTR('12as3,45we6,7we89,101112,131415,3234,1234', 1, INSTR('12as3,45we6,7we89,101112,131415,3234,1234',',',1,3) -1), '12as3,45we6,7we89,101112,131415,3234,1234') FROM dual; OutPut is 12as3,45we6,7we89 I also tried this but it is printing after every comma. with t as ( select '12as3,45we6,7we89,101112,131415,3234,1234' as str from dual ) select extractvalue(value(x), '/b') x from t, table( xmlsequence( xmltype('<a><b>' || replace(str, ',', '</b><b>') || '</b></a>' ).extract('/*/*') ) ) x / Is there any way without using procedure of function, we can write in a select statement in Oracle. A: Here's one option, which uses a function. The idea is: split input string into rows concatenate its pieces (it is one) by 3 in a group, separated by a comma if it is the 3rd piece (see the MOD function), separate them by the line-feed character (CHR(10)) (it is the splitter) SQL> create or replace function f_split (par_str in varchar2) 2 return varchar2 3 is 4 l_str varchar2(200); 5 begin 6 for cur_r in (select mod(row_number() over (order by null), 3) rn_mod, 7 case when mod(row_number() over (order by null), 3) = 0 then chr(10) 8 else ',' 9 end splitter, 10 regexp_substr(par_str, '[^,]+', 1, level) one 11 from dual 12 connect by level <= regexp_count(par_str, ',') + 1 13 ) 14 loop 15 l_str := l_str || cur_r.one || cur_r.splitter; 16 end loop; 17 18 return (l_str); 19 end; 20 / Function created. SQL> select f_split('12as3,45we6,7we89,101112,131415,3234,1234') result from dual; RESULT -------------------------------------------------------------------------------- 12as3,45we6,7we89 101112,131415,3234 1234, SQL> Why not a simple SQL, which utilizes the same code? Because of this: SQL> with test (col) as 2 (select '12as3,45we6,7we89,101112,131415,3234,1234' from dual), 3 split_me as 4 (select row_number() over (order by null) rn, 5 case when mod(row_number() over (order by null), 3) = 0 then chr(10) 6 else ',' 7 end splitter, 8 regexp_substr(col, '[^,]+', 1, level) one 9 from test 10 connect by level <= regexp_count(col, ',') + 1 11 ) 12 select listagg(one, splitter) within group (order by rn) result 13 from split_me; select listagg(one, splitter) within group (order by rn) result * ERROR at line 12: ORA-30496: Argument should be a constant. SQL> I don't know how to fix that.
{ "pile_set_name": "StackExchange" }
Q: Need a site that will let you create your own html/css template that you can copy and paste to your site? I want to create a site but now I don't have time to create the template so I was wondering if there is a site that will allow me to do what the above question states. I want to have sounds on there, drop menus, etc. I did some googleing but I did not find any particular site. A: This is what you are looking for : http://www.noupe.com/css/50-free-css-x-html-templates.html
{ "pile_set_name": "StackExchange" }
Q: Best way to have a javascript load only on desktop version of site? I have a javascript (jQuery) that I am running on my WordPress site. I only want the script to load if the screen width is under 1024 pixels. The reason for this is because it has to do with how the top navigation menu functions. I only want this script to load when the screen width is under 1024 pixels, because anything under that is going to have a completely different menu style / functionality. Naturally I have plenty of media queries in my CSS file that change the design at min-width: 1024px. I've found several ways to do this, I'm just trying to determine what the best way to do it would be. Here is a copy of my current javascript file: function accordion_menus(){ // if we are not on mobile (menu icon is hidden) show sub items and bail console.log('debug: start'); if ( jQuery('#primary-navigation .menu-toggle').is(':hidden') ){ console.log('debug: yes, it is hidden'); // show sub menus $('#primary-navigation ul.nav-menu ul.sub-menu').show(); return; } else{ // hide sub menus $('#primary-navigation ul.nav-menu ul.sub-menu').hide(); } // top level nav click function $('#primary-navigation ul.nav-menu > li > a').click(function(e){ // store parent li to variable var parent_li = $(this).parent('li'); // if sub menu does not exist in parent li if ( !$('ul.sub-menu', parent_li).first().length ) { return; } // if sub menu is already active, bail if ( parent_li.hasClass('sub-menu-active') ){ parent_li.find('ul').slideUp(100, function(parent_li){ }); parent_li.removeClass('sub-menu-active'); return false; } // stop link click e.preventDefault(); // store current sub menu in variable var current_submenu = $('ul.sub-menu', parent_li).first(); // slide up non-current sub menus $('#primary-navigation').find('ul.sub-menu').not(current_submenu).slideUp(function(parent_li){ // remove sub-menu-active class from all first level items except current parent li $('#primary-navigation').find('li').not(parent_li).removeClass('sub-menu-active'); }); // slide down current sub menu current_submenu.slideDown(100, function(){ // add sub-menu-active to current parent li parent_li.addClass('sub-menu-active'); }); }); // second level nav click function jQuery('#primary-navigation ul.nav-menu ul.sub-menu > li > a').click(function(e){ // store parent li to variable var parent_li = jQuery(this).parent('li'); // if sub menu does not exist in parent li if ( !jQuery('ul.sub-menu', parent_li).first().length ) { return; } // if sub menu is already active, bail if ( parent_li.hasClass('sub-menu-active') ){ parent_li.find('ul').slideUp(100, function(){ // remove sub-menu-active class from all first level items except current parent li }); parent_li.removeClass('sub-menu-active'); return false; } // stop link click e.preventDefault(); // store current sub menu in variable var current_submenu = jQuery('ul.sub-menu', parent_li).first(); // slide up non-current sub menus jQuery('#primary-navigation ul.nav-menu ul.sub-menu > li > ul.sub-menu').not(current_submenu).slideUp(function(){ // remove sub-menu-active class from all second level items except current parent li jQuery('#primary-navigation ul.nav-menu ul.sub-menu > li').not(parent_li).removeClass('sub-menu-active'); }); // slide down current sub menu current_submenu.slideDown(100, function(){ // add sub-menu-active to current parent li parent_li.addClass('sub-menu-active'); }); }); } // load menu accordion on doc ready jQuery(document).ready(function($) { accordion_menus(); }); // load menu accordion on window resize jQuery(window).resize(function(){ accordion_menus(); }); A: jQuery(document).ready(function(){ function resizeForm(){ var width = (window.innerWidth > 0) ? window.innerWidth : document.documentElement.clientWidth; if(width > 1024){ } else { } } window.onresize = resizeForm; resizeForm(); }); I've used this alot. Will rerun JS on each window resize. If you don't want that, just remove window.onresize = resizeForm;. Should work in all browsers hence the width.innerWidth check.
{ "pile_set_name": "StackExchange" }
Q: Can I use React.Fragment for list rendering while have the "key" assigned? Can I use React.Fragment inside the list rendering and assign a key to this 'Fragment' parent? I'm trying to build a projects list layout using css grid, which requires all the elements is direct child of the container. Let's say the desired result will be look something like this. <div className="container"> <img src="imgPathFor1stProject"> <h1>title for 1st project</h1> <p>description for 1st project</p> <img src="imgPathFor2ndProject"> <h1>title for 2nd project</h1> <p>description for 2nd project</p> ... </div> But we all know the list render requires to return a single enclosing tag which we can tackle by using React.Fragment. Then the jsx will look like this: projects.map(project => ( <> <img src={project.imagePath}/> <h1>{project.title}</h2> <p>{project.description}</p> </> )); But here comes the problem, I can't assign a key to each child of the list since there's no actual element that wrapping all these elements. I tried do: < key={project.id}> and <React.Fragment key={project.id}>, both doesn't work. Is there a way to solve this? I still want to apply display:grid on .container element. Thanks! A: https://reactjs.org/docs/fragments.html Keyed Fragments Fragments declared with the explicit syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list: function Glossary(props) { return ( <dl> {props.items.map(item => ( // Without the `key`, React will fire a key warning <React.Fragment key={item.id}> <dt>{item.term}</dt> <dd>{item.description}</dd> </React.Fragment> ))} </dl> ); }
{ "pile_set_name": "StackExchange" }
Q: Onbeforeunload event support on iPad Is onbeforeunload event supported on iPad Safari ? If no, is there any alternate way to detect window closing on iPad ? Please help. A: This has been discussed previously here, and there are is some anecdotal evidence to say that it does work in some circumstances.
{ "pile_set_name": "StackExchange" }
Q: Java secondary not public Class usage produces error "Type is not Visible" even if accessed methods are public in Main class I have a Main.java file: public class Main{ private EntityDrawer entityDrawer; public void setEntityDrawer(EntityDrawer entityDrawer) { this.entityDrawer = entityDrawer; } public EntityDrawer getEntityDrawer() { return entityDrawer; } } class EntityDrawer { private Empleado empleado; public Empleado getEmpleado() { return empleado; } public void setEmpleado(Empleado empleado) { this.empleado = empleado; } } If I try to access from another file, it works if I only try to access the entityManager: Main main = new Main(); main.getEntityDrawer(); // NO PROBLEM! But if I try to access one of the attributes (even if public) from entityManager, it does not work: Main main = new Main(); main.getEntityDrawer().getEmpleado(); // Gives error "The type EntityDrawer is not visible" I cannot understand why is happening, could someone give me some insight into this issue?... A: I assume you are trying to use a package local class EntityDrawer in another package, which you cannot do. Try making the class public A: Make the class public or move the calling class to same package.
{ "pile_set_name": "StackExchange" }
Q: Does there exist a curve with non zero area? Does there exist a curve with a bounded infinitely diffrentiable derivative (i.e. has a minimum |curvature|) of hausdorf demension 2? Or even a diffrentiable curve of hausdorf demension 2? A: If $f: X \to Y$ is Lipschitz with Lipschitz constant $k$, i.e. $d(f(x),f(y)) \le k d(x,y)$, then for any $r$ we have $\mathcal H^r(f(X)) \le k^r \mathcal H^r(X)$, where $\mathcal H^r$ is $r$-dimensional Hausdorff measure. Since any continuously differentiable function on an interval is locally Lipschitz, it follows that the image of a $C^1$ curve has $\sigma$-finite $1$-dimensional Hausdorff measure, and in particular Hausdorff dimension $1$. This can be generalized slightly: the image of any differentiable curve has $\sigma$-finite $1$-dimensional Hausdorff measure. See this MO posting.
{ "pile_set_name": "StackExchange" }
Q: Bash Script - Copy latest version of a file in a directory recursively Below, I am trying to find the latest version of a file that could be in multiple directories. Example Directory: ~inventory/emails/2012/06/InventoryFeed-Activev2.csv 2012/06/05 ~inventory/emails/2012/06/InventoryFeed-Activev1.csv 2012/06/03 ~inventory/emails/2012/06/InventoryFeed-Activev.csv 2012/06/01 Heres the bash script: #!/bin/bash FILE = $(find ~/inventory/emails/ -name INVENTORYFEED-Active\*.csv | sort -n | tail -1) #echo $FILE #For Testing cp $FILE ~/inventory/Feed-active.csv; The error I am getting is: ./inventory.sh: line 5: FILE: command not found The script should copy the newest file as attempted above. Two questions: First, is this the best method to achive what I want? Secondly, Whats wrong above? A: It looks good, but you have spaces around the = sign. This won't work. Try: #!/bin/bash FILE=$(find ~/inventory/emails/ -name INVENTORYFEED-Active\*.csv | sort -n | tail -1) #echo $FILE #For Testing cp $FILE ~/inventory/Feed-active.csv;
{ "pile_set_name": "StackExchange" }
Q: AR9285 Wireless (Yet another) on Acer Aspire One 532h-2676 There are literally hundreds of questions with people asking about this wireless device on askubuntu.org. I've spent about 12 hours trying to get it working, to no avail. It's time to solicit some expert help. Information: Acer Aspire One 532h-2676 AR9285 Wireless Ubuntu 12.04 / Updated via ethernet connection (Ditched Windows - so this needs to work!) Problem: The wireless device connects to the router and receives an internal IP, however, no amount of finagling seems to be able to provide me with anything save momentary internet access. I can ping -c 10 192.168.0.XX my address, but I can't ping the router (192.168.0.1) or the internet (google.ca/com). What I've tried and read elsewhere on askubuntu/linuxforums/ubuntuforums Installed sudo apt-get install linux-backports-net-${uname -r) (Expected compatibility drivers) Edited ../ath9k.conf with options ath9k nohcrypt=1 (Read post about hardware encryption problem) Tried using wicd instead (Read post that this worked for some pre 12.04) Fully removed and reinstalled NM sudo apt-get purge network-manager* ... sudo apt-get install network-manager*(Read post that this worked for some) Details People Usually Ask for on Other Questions $ sudo lshw -C network *-network description: Ethernet interface product: AR8132 Fast Ethernet vendor: Atheros Communications Inc. physical id: 0 bus info: pci@0000:01:00.0 logical name: eth1 version: c0 serial: 70:5a:b6:d8:99:53 capacity: 100Mbit/s width: 64 bits clock: 33MHz capabilities: pm msi pciexpress vpd bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd autonegotiation configuration: autonegotiation=on broadcast=yes driver=atl1c driverversion=1.0.1.0-NAPI firmware=N/A latency=0 link=no multicast=yes port=twisted pair resources: irq:45 memory:57000000-5703ffff ioport:5000(size=128) *-network description: Wireless interface product: AR9285 Wireless Network Adapter (PCI-Express) vendor: Atheros Communications Inc. physical id: 0 bus info: pci@0000:02:00.0 logical name: wlan0 version: 01 serial: 78:e4:00:24:a0:19 width: 64 bits clock: 33MHz capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless configuration: broadcast=yes driver=ath9k driverversion=3.2.0-26-generic-pae firmware=N/A ip=192.168.0.19 latency=0 link=yes multicast=yes wireless=IEEE 802.11bgn resources: irq:17 memory:56000000-5600ffff $ rfkill list all 0: phy0: Wireless LAN Soft blocked: no Hard blocked: no 1: acer-wireless: Wireless LAN Soft blocked: no Hard blocked: no $ lspci 00:00.0 Host bridge: Intel Corporation N10 Family DMI Bridge 00:02.0 VGA compatible controller: Intel Corporation N10 Family Integrated Graphics Controller 00:02.1 Display controller: Intel Corporation N10 Family Integrated Graphics Controller 00:1b.0 Audio device: Intel Corporation N10/ICH 7 Family High Definition Audio Controller (rev 02) 00:1c.0 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 1 (rev 02) 00:1c.1 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 2 (rev 02) 00:1d.0 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #1 (rev 02) 00:1d.1 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #2 (rev 02) 00:1d.2 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #3 (rev 02) 00:1d.3 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #4 (rev 02) 00:1d.7 USB controller: Intel Corporation N10/ICH 7 Family USB2 EHCI Controller (rev 02) 00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev e2) 00:1f.0 ISA bridge: Intel Corporation NM10 Family LPC Controller (rev 02) 00:1f.2 SATA controller: Intel Corporation N10/ICH7 Family SATA Controller [AHCI mode] (rev 02) 00:1f.3 SMBus: Intel Corporation N10/ICH 7 Family SMBus Controller (rev 02) 01:00.0 Ethernet controller: Atheros Communications Inc. AR8132 Fast Ethernet (rev c0) 02:00.0 Network controller: Atheros Communications Inc. AR9285 Wireless Network Adapter (PCI-Express) (rev 01) dmesg at startup http://pastebin.com/GKRMmc93 (It's set to be removed in a month, if you see something in there that identifies the problem please denote it and I'll update the question with the line(s) in question so some other unlucky person can dmesg | grep ... for it. A: I have the same problem here and traced it to a conflict in two hardware rfkill switches. In syslog I noted the following details: NetworkManager[668]: <info> found WiFi radio killswitch rfkill0 (at /sys/devices/pci0000:00/0000:00:1c.1/0000:02:00.0/ieee80211/phy0/rfkill0) (driver (unknown)) NetworkManager[668]: <info> found WiFi radio killswitch rfkill1 (at /sys/devices/platform/acer-wmi/rfkill/rfkill1) (driver acer-wmi) I seem to have solved it by blacklisting acer-wmi in this manner: echo blacklist acer-wmi | sudo tee /etc/modprobe.d/blacklist-acer-wmi You can then reboot or enter sudo rmmod acer-wmi.
{ "pile_set_name": "StackExchange" }
Q: How to plot in python for count of repeated text I am trying to plot my data-frame using seaborn and matplotlib, but getting error like cannot convert string to float. My data is like: ID | Status | Date | Columns| -------+-------------+------+--------+ 28 | ACTIVE | | | 29 | ACTIVE | | | 49623 | TERMINATED | | | 49624 | TERMINATED | | | 49625 | TERMINATED | | | For what I have tried so far: df_count = df.apply(pd.value_counts) plt.plot(df_count) where df_count looks like |STATUS| -----------+------+ ACTIVE |38537 | TERMINATED |1185 | When trying to do sns.barplot(df) it gives following error: unsupported operand type(s) for +: 'int' and 'str' And trying to do plt.plot(df) it gives following error: ValueError: could not convert string to float: '12/31/2014 0:00' My python plotting seems to be quite zero please suggest. A: I think you have to specify the x and y. Please try: sns.barplot(x=df_count.index,y=df_count.Status) sns.plt.show() -edit test.csv: ,STATUS ACTIVE,38537 TERMINATED,1185 code: import pandas as pd import seaborn as sns df = pd.read_csv('test.csv', delimiter=',') df.index.names = ['Type'] sns.barplot(x=df.index,y=df.STATUS) sns.plt.show() output:
{ "pile_set_name": "StackExchange" }
Q: How to remove ellipsized property of TextView from code? I set my textView to be ellipsezed in xml. Now on click I want it to expend and become not ellipsized. A: Use setEllipsize() to change the ellipsize behavior of a TextView. For example, to turn off ellipsize use this: myTextView.setEllipsize(null);
{ "pile_set_name": "StackExchange" }
Q: Python subprocess Messy output With the following code: output = subprocess.check_output(['wmic', 'PATH', 'Win32_videocontroller', 'GET', 'description']) print(output , "\n") I get the next output: b'Description \r\r\nNVIDIA GeForce 710M \r\r\nIntel(R) HD Graphics 4000 \r\r\n\r\r\n' When I use the commando wmic path win32_videocontroller get desriptionin my CMD I get only the videocard info back. Is this possible in python aswell? With out the /r/r/r/r things? A: Use the argument "universal_newlines=True" when you call the function: output = subprocess.check_output(['wmic', 'PATH', 'Win32_videocontroller', 'GET', 'description'], universal_newlines=True) print(output , "\n")
{ "pile_set_name": "StackExchange" }