title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Django admin site is not showing default permissions of models
<p>My Django admin site does not show any default permissions of any models. Actually, I checked the database and I can't find any model permission in the <code>auth_permissions</code> table.</p> <p>I've already run <code>python manage.py makemigrations</code> and <code>python manage.py migrate</code>. I also tried deleting the database and migration files and run two above command again but doesn't work. I've already registered my models in admin.py.</p> <p>Any other solutions I can try ?</p> <p>admin.py</p> <pre><code>from django.contrib import admin from .Models import * # Register your models here. admin.site.register(LeaveRequest) admin.site.register(Worker) admin.site.register(TimeSheet) </code></pre> <p>settings.py</p> <pre><code>&quot;&quot;&quot; Django settings for WorkTime project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ &quot;&quot;&quot; from pathlib import Path import os import rest_framework import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECRET_KEY = '0yz04(%a^xuilqa8*@e^e)bj+n%&amp;+jou=tg$%lb&amp;#ox!lk1!x5' SECRET_KEY = os.environ.get( 'SECRET_KEY', '0yz04(%a^xuilqa8*@e^e)bj+n%&amp;+jou=tg$%lb&amp;#ox!lk1!x5') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG', '') != 'False' ALLOWED_HOSTS = ['worktime-management.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', 'rest_framework.authtoken', 'crispy_forms', 'web', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'WorkTime.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'WorkTime.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR,'static') STATICFILES_DIRS = [ STATIC_DIR, ] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Heroku: Update database configuration from $DATABASE_URL. db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Media root MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Email config EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = os.environ.get('MAIL_PASSWORD') EMAIL_HOST_USER = os.environ.get('MAIL_USERNAME') EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER # CSRF enable CSRF_COOKIE_SECURE = True # Rest Auth REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } # Boostrap4 CRISPY_TEMPLATE_PACK = 'bootstrap4' AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.AllowAllUsersModelBackend', ) </code></pre>
3
2,206
Get a .txt from the Internet, compare it and open a dialog in an AsyncTask
<p>I want to check, if there is an update for my app. For this I put up an txt file online with just an integer of the latest app version. This should get compared with the running app version and when there is a newer version, open a dialog for the user to give the choice of open a link to the new .apk in the browser or to cancel it. It's giving me trouble and I don't know what to do. Thanks for helping me out! </p> <p>The AsyncTask:</p> <pre><code>public class UpdateCheck extends AsyncTask &lt;Void, Void, Boolean&gt; { @Override protected Boolean doInBackground(Void... params) { String str = null; try { // Create a URL for the desired page URL url = new URL("http://googledrive.com/host/0B62qO_dIVN_hQ2lGNmJudDFEdHc/ver.txt"); // Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline character(s) } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } PackageInfo packageInfo; int curVersionCode = 0; try { packageInfo = getPackageManager().getPackageInfo("de.grevius.hhgvertretungsplan", 0); curVersionCode = packageInfo.versionCode; } catch (NameNotFoundException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } if (Integer.parseInt(str) &gt; curVersionCode) { return true; } return false; } @Override public void onPostExecute (Boolean bool){ if(bool){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Add the buttons builder.setPositiveButton("Ja", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://googledrive.com/host/0B62qO_dIVN_hQ2lGNmJudDFEdHc/Vertretungsplan.apk")); startActivity(intent); //activity.startIntent... } }); builder.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // Set other dialog properties builder.setMessage("Es ist eine neue Version der App verfügbar. Herunterladen?"); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.show(); } } } </code></pre> <p>Here is the Log Cat:</p> <pre><code> 12-09 17:10:37.305: E/AndroidRuntime(20346): FATAL EXCEPTION: AsyncTask #1 12-09 17:10:37.305: E/AndroidRuntime(20346): java.lang.RuntimeException: An error occured while executing doInBackground() 12-09 17:10:37.305: E/AndroidRuntime(20346): at android.os.AsyncTask$3.done(AsyncTask.java:299) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 12-09 17:10:37.305: E/AndroidRuntime(20346): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.lang.Thread.run(Thread.java:856) 12-09 17:10:37.305: E/AndroidRuntime(20346): Caused by: java.lang.NumberFormatException: Invalid int: "null" 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.lang.Integer.invalidInt(Integer.java:138) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.lang.Integer.parseInt(Integer.java:355) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.lang.Integer.parseInt(Integer.java:332) 12-09 17:10:37.305: E/AndroidRuntime(20346): at de.grevius.hhgvertretungsplan.MainActivity$UpdateCheck.doInBackground(MainActivity.java:204) 12-09 17:10:37.305: E/AndroidRuntime(20346): at de.grevius.hhgvertretungsplan.MainActivity$UpdateCheck.doInBackground(MainActivity.java:1) 12-09 17:10:37.305: E/AndroidRuntime(20346): at android.os.AsyncTask$2.call(AsyncTask.java:287) 12-09 17:10:37.305: E/AndroidRuntime(20346): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 12-09 17:10:37.305: E/AndroidRuntime(20346): ... 5 more </code></pre> <hr> <p>I just added some Log-Tags to the code and saw, that it is working until the <code>Integer.parseInt(str)</code>. At this time <code>str</code> is <code>&lt;html&gt;</code>, I don't know where this comes from, because when I look up the source code of my "page" it says just the number...`</p> <p>I solved it by changing the <code>while</code> loop to <code>while ((str = in.readLine()) != null) { sb.append(str); }</code> and <code>Integer.parseInt(sb.toString())</code>.</p>
3
2,352
Angular: E2E Test via login page
<p>I have an Angular application using an Express.js backend. It features a default address pathway to a login page <code>/avior/login</code>. I need to write an E2E Test for the whole application and I just started writing the first test part which is supposed to recognize the login page and login itself and then check whether the redirect was successful. I have wrote this error-prone code so far:</p> <pre class="lang-js prettyprint-override"><code>import { AppPage } from './app.po'; import { browser, logging, element } from 'protractor'; import { async, ComponentFixture, fakeAsync, TestBed, tick, } from '@angular/core/testing'; import {AppComponent} from '../../src/app/app.component' let comp: AppComponent; let fixture: ComponentFixture&lt;AppComponent&gt;; let page: AppPage; let router: Router; let location: SpyLocation; let username: 'Test'; let password: 'testtest'; let usernameInput: element(by.css('#inputUser')); let passwordInput: element(by.css('#inputPassword')); let loginButton: element(by.css('#loginSubmit')); describe('Avior App', () =&gt; { let page: AppPage; beforeEach(() =&gt; { page = new AppPage(); }); it('should navigate to "/avior/login" immediately', fakeAsync(() =&gt; { createComponent(); tick(); // wait for async data to arrive expect(location.path()).toEqual('/avior/login', 'after initialNavigation()'); expectElementOf(DashboardComponent); })); it('should display Login message in the header', () =&gt; { page.navigateTo(); expect(page.getTitleText()).toEqual('Anmeldung'); }); it('there should be username and password login fields', () =&gt; { // how to check? }); it('login using false credentials should make you stay put and throw an error', () =&gt; { // how to? }); it('login using Test:testtset (=successful credentials =&gt; successful login) should redirect to /avior/dashboard', () =&gt; { // how to? }); afterEach(async () =&gt; { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); }); function createComponent() { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; const injector = fixture.debugElement.injector; location = injector.get(Location) as SpyLocation; router = injector.get(Router); router.initialNavigation(); spyOn(injector.get(TwainService), 'getQuote') // fake fast async observable .and.returnValue(asyncData('Test Quote')); advance(); page = new Page(); } function loginFn() { usernameInput.sendKeys(username); passwordInput.sendKeys(password); loginButton.click(); }; </code></pre> <p>How to fix this code?</p> <p><strong>UPDATE</strong></p> <p>I tried simplifying my code to only include routing tests so far and I get new errors thrown out. My new code is the following:</p> <pre><code>import { AppPage } from './app.po'; import { browser, logging, element } from 'protractor'; import { async, ComponentFixture, fakeAsync, TestBed, tick, } from '@angular/core/testing'; import {AppComponent} from '../../src/app/app.component' import {Component} from "@angular/core"; import {RouterTestingModule} from "@angular/router/testing"; import {Routes} from "@angular/router"; import {Router} from "@angular/router"; import { AviorComponent } from '../../src/app/avior/avior.component'; import { DashboardComponent } from '../../src/app/avior/dashboard/dashboard.component'; import { ProfileComponent } from '../../src/app/avior/profile/profile.component'; import { SettingsComponent } from '../../src/app/avior/settings/settings.component'; import { LoginComponent } from '../../src/app/avior/login/login.component'; import { PageNotFoundComponent } from '../../src/app/avior/page-not-found/page-not-found.component'; import { InfoComponent } from '../../src/app/avior/info/info.component'; import { UsersComponent } from '../../src/app/avior/users/users.component'; import { MandatorsComponent } from '../../src/app/avior/mandators/mandators.component'; import { SystemComponent } from '../../src/app/avior/system/system.component'; import { WorkflowsComponent } from '../../src/app/avior/workflows/workflows.component'; import { MessagesComponent } from '../../src/app/avior/messages/messages.component'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; /* let comp: AppComponent; let fixture: ComponentFixture&lt;AppComponent&gt;; let page: AppPage; let router: Router; let location: SpyLocation; let username: 'Chad'; let password: 'chadchad'; let usernameInput: element(by.css('#inputUser')); let passwordInput: element(by.css('#inputPassword')); let loginButton: element(by.css('#loginSubmit')); */ const aviorRoutes: Routes = [{ path: '', component: AviorComponent, children: [ { path: '', component: ProfileComponent }, { path: 'dashboard', component: DashboardComponent, data: {title: 'Dashboard'}, }, { path: 'login', component: LoginComponent, data: {title: 'Login'}, }, { path: 'logout', component: LoginComponent, data: {title: 'Login'}, }, { path: 'profile', component: ProfileComponent, data: {title: 'Profil'}, }, { path: 'settings', component: SettingsComponent, data: {title: 'Einstellungen'}, }, { path: 'info', component: InfoComponent, data: {title: 'Info'}, }, { path: 'users', component: UsersComponent, data: {title: 'Benutzer'}, }, { path: 'workflows', component: WorkflowsComponent, data: {title: 'Workflows'}, }, { path: 'system', component: SystemComponent, data: {title: 'System'}, }, { path: 'mandators', component: MandatorsComponent, data: {title: 'Mandanten'} }, { path: 'messages', component: MessagesComponent, data: {title: 'Nachrichten'} }, { path: '404', component: PageNotFoundComponent, data: {title: 'Page not found'}, } ] }]; describe('Avior App', () =&gt; { let page: AppPage; beforeEach(() =&gt; { TestBed.resetTestEnvironment(); TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()) TestBed.configureTestingModule({ imports: [RouterTestingModule.withRoutes(aviorRoutes)], declarations: [ DashboardComponent, ProfileComponent, SettingsComponent, LoginComponent, PageNotFoundComponent, InfoComponent, UsersComponent, MandatorsComponent, SystemComponent, WorkflowsComponent, MessagesComponent ] }); page = new AppPage(); this.router = TestBed.get(Router); location = TestBed.get(Location); this.fixture = TestBed.createComponent(AppComponent); this.router.initialNavigation(); }); /* it('should navigate to "/avior/login" immediately', fakeAsync(() =&gt; { createComponent(); tick(); // wait for async data to arrive expect(location.path()).toEqual('/avior/login', 'after initialNavigation()'); expectElementOf(DashboardComponent); })); */ it('navigate to "" redirects you to /avior/login', fakeAsync(() =&gt; {   this.router.navigate(['']); tick(); expect(location.path()).toBe('/avior/login'); })); it('navigate to "dashboard" takes you to /dashboard', fakeAsync(() =&gt; {   this.router.navigate(['dashboard']);  tick(); expect(location.path()).toBe('avior/dashboard'); })); it('should display Anmeldung message in the header', () =&gt; { page.navigateTo(); expect(page.getTitleText()).toEqual('Anmeldung'); }); it('there should be username and password login fields', () =&gt; { }); it('login using false credentials should make you stay put and throw an error', () =&gt; { }); it('login using Chad:chadchad should redirect to /avior/dashboard', () =&gt; { }); afterEach(async () =&gt; { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); }); /* function createComponent() { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; const injector = fixture.debugElement.injector; location = injector.get(Location) as SpyLocation; router = injector.get(Router); router.initialNavigation(); spyOn(injector.get(TwainService), 'getQuote') // fake fast async observable .and.returnValue(asyncData('Test Quote')); advance(); page = new Page(); } function loginFn(username, password) { usernameInput.sendKeys(username); passwordInput.sendKeys(password); loginButton.click(); }; */ </code></pre> <p>The errors get thrown out during <code>ng e2e</code> runtime: <code>- Failed: Can't resolve all parameters for ApplicationModule: (?). - Failed: Cannot read property 'assertPresent' of null</code></p>
3
3,171
Listview taking too long to update C#
<p>I have a problem I have been stuck on for ages, was hopinh you can all help please.</p> <p>I have a listview which populates with data from my database upon the programs first load.</p> <p>In my program I have a button which 'Refreshes' this listview by wiping all of the data out of the listview and running the same method which populates the listview upon program load. However, this refresh button is taking far too long (about 10 seconds) to refresh. </p> <p>How is it that the program can load in 2 seconds with the listview populated however when running the method again it takes much longer.</p> <p>Please see my attached code and suggest any changes, I apologise for the length. Thank you.</p> <pre><code>public void AllHomeworkers() { //This updates the homeworkers listview to contain all the records from the homeworkers table. listHomeworkersAll.BeginUpdate(); //This uses the begin update process on the listview, this is used to stop flickering listHomeworkersAll.Items.Clear(); //Clears all the items from the listview // this takes the datatable returned from AllHomeworkers stored procedure. // It then loops through the datatable adding every row to the list view. DataTable dtHomeworkers = _businessLayer.AllHomeworkers(); for (int i = 0; i &lt; dtHomeworkers.Rows.Count; i++) { DataRow drowHomeworkers = dtHomeworkers.Rows[i]; if (drowHomeworkers.RowState != DataRowState.Deleted) { ListViewItem lvi = new ListViewItem(drowHomeworkers["StaffID"].ToString()); lvi.SubItems.Add(drowHomeworkers["Title"].ToString()); lvi.SubItems.Add(drowHomeworkers["Initials"].ToString()); lvi.SubItems.Add(drowHomeworkers["Forename"].ToString()); lvi.SubItems.Add(drowHomeworkers["Surname"].ToString()); lvi.SubItems.Add(drowHomeworkers["Address"].ToString()); lvi.SubItems.Add(drowHomeworkers["Address2"].ToString()); lvi.SubItems.Add(drowHomeworkers["City"].ToString()); lvi.SubItems.Add(drowHomeworkers["Postcode"].ToString()); lvi.SubItems.Add(drowHomeworkers["CostCentre"].ToString()); lvi.SubItems.Add(drowHomeworkers["Email"].ToString()); lvi.SubItems.Add(drowHomeworkers["Telephone"].ToString()); lvi.SubItems.Add(drowHomeworkers["Mobile"].ToString()); lvi.SubItems.Add(drowHomeworkers["FMID"].ToString()); lvi.SubItems.Add(drowHomeworkers["Comments"].ToString()); lvi.SubItems.Add(drowHomeworkers["Leaver"].ToString()); lvi.SubItems.Add(drowHomeworkers["LeavingDate"].ToString()); lvi.SubItems.Add(drowHomeworkers["Base"].ToString()); lvi.SubItems.Add(drowHomeworkers["NextVisit"].ToString()); var deleted = drowHomeworkers["Deleted"].ToString(); if (deleted != "") { lvi.ForeColor = Color.Red; } listHomeworkersAll.Items.Add(lvi); } } listHomeworkersAll.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); // this sorts the columns to the size of the largest object stored inside them. listHomeworkersAll.EndUpdate(); // this ends the listview update process. } </code></pre>
3
1,289
ComplexityObject ksoap2 Android Magento error
<p>I'm trying to use ksoap2 in order to create an order on a remote Magento installation. I'm able to perform basic operations with the SOAP v2 Api but I got stuck on a complexity object.</p> <p>This is the part of the wsdl I'm trying to interface with</p> <pre><code>&lt;complexType name="shoppingCartProductEntityArray"&gt; &lt;complexContent&gt; &lt;restriction base="soapenc:Array"&gt; &lt;attribute ref="soapenc:arrayType" wsdl:arrayType="typens:shoppingCartProductEntity[]"/&gt; &lt;/restriction&gt; &lt;/complexContent&gt; &lt;/complexType&gt; &lt;complexType name="shoppingCartProductResponseEntityArray"&gt; &lt;complexContent&gt; &lt;restriction base="soapenc:Array"&gt; &lt;attribute ref="soapenc:arrayType" wsdl:arrayType="typens:catalogProductEntity[]"/&gt; &lt;/restriction&gt; &lt;/complexContent&gt; &lt;/complexType&gt; ..... &lt;message name="shoppingCartProductAddRequest"&gt; &lt;part name="sessionId" type="xsd:string"/&gt; &lt;part name="quoteId" type="xsd:int"/&gt; &lt;part name="products" type="typens:shoppingCartProductEntityArray"/&gt; &lt;part name="storeId" type="xsd:string"/&gt; &lt;/message&gt; ..... &lt;operation name="shoppingCartProductAdd"&gt; &lt;documentation&gt;Add product(s) to shopping cart&lt;/documentation&gt; &lt;input message="typens:shoppingCartProductAddRequest"/&gt; &lt;output message="typens:shoppingCartProductAddResponse"/&gt; &lt;/operation&gt; </code></pre> <p>I tried the following</p> <pre><code>env = getEnvelope(); request = new SoapObject(NAMESPACE, MethodName_AddProduct); request.addProperty("sessionId",_SessionId ); SoapObject SingleProduct = new SoapObject(NAMESPACE, "shoppingCartProductEntity"); PropertyInfo pi = new PropertyInfo(); pi.setName("product_id"); pi.setValue(Products[0][0]); pi.setType(String.class); SingleProduct.addProperty(pi); pi = new PropertyInfo(); pi.setName("sku"); pi.setValue(Products[0][1]); pi.setType(String.class); SingleProduct.addProperty(pi); pi = new PropertyInfo(); pi.setName("qty"); pi.setValue(1); pi.setType(Double.class); SingleProduct.addProperty(pi); SoapObject EntityArray = new SoapObject(NAMESPACE, "shoppingCartProductEntityArray"); EntityArray.addProperty("productData",SingleProduct); request.addProperty("quoteId",cartId); request.addProperty("productsData",EntityArray); env.setOutputSoapObject(request); androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SoapAction_AddProduct, env); </code></pre> <p>But I get the following message</p> <blockquote> <p>SoapFault - faultcode: '1021' faultstring: 'Product's data is not valid.' faultactor: 'null' detail: null</p> </blockquote> <p>I've also tried to print the request that seems correctly formatted to me</p> <blockquote> <p>DEBUG REQUEST : shoppingCartProductAdd{sessionId=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; quoteId=31; productsData=shoppingCartProductEntityArray{productData=shoppingCartProductEntity{product_id=1; sku=PLM01; qty=1; }; }; }</p> </blockquote>
3
1,044
How to solve a system of stochastic differential equations with time dependent parameters in R?
<p>I am trying to solve this system of SDEs in R, dX = (-X*a + (Y-X)<em>b + h)dt + g dW and dY = (-Y</em>a + (X-Y)*b)dt for time [0,200], a=0.30, b=0.2, g=1 and h is 1 for time [50,70] and 0 otherwise. I have the following code for the system for constant h=1:</p> <pre><code>library(diffeqr) ##for solving ODEs SDEs DDEs.. library(deSolve) library(Julia) ##used for the sde library(JuliaCall) library(data.table) library(minpack.lm) tryCatch(system2(file.path(JULIA_HOME, &quot;julia&quot;), &quot;-E \&quot;try println(JULIA_HOME) catch e println(Sys.BINDIR) end;\&quot;&quot;, stdout = TRUE)[1], warning = function(war) {}, error = function(err) NULL) julia_setup(JULIA_HOME =&quot;/home/tim/.local/share/R/JuliaCall/julia/v1.5.0/bin&quot;) ##calling Julia JuliaCall:::julia_locate(JULIA_HOME = &quot;/home/tim/.local/share/R/JuliaCall/julia/v1.5.0/bin&quot;) ## setup of the packages de &lt;- diffeqr::diffeq_setup() julia &lt;- julia_setup() #u0 is the starting value for the vector #func1 is the ODE TO SOLVE #f is the drift part in the sde #g is the diffusion part in the sde #p are the parameters associated to the sde # noise_rate_prototype is a sparse matrix by making a dense matrix and setting some values as not zero #starting value for the three variables u0&lt;-c(0,0) ## parameters a=0.33; b=0.2; g=1; h=1; ## parameters of the sde p&lt;-c(a, b, g, h) ## drift part in the SDE f &lt;- JuliaCall::julia_eval(&quot; function f(dy,y,p,t) dy[1] = -y[1]*p[1] + (y[2]-y[1])*p[2] + p[4] dy[2] = -y[2]*p[1] + (y[1]-y[2])*p[2] end&quot;) ## diffusion part in the SDE g &lt;- JuliaCall::julia_eval(&quot; function g(dy,y,p,t) dy[1,1] = p[3] dy[2,1] = 0 end&quot;) ## matrix associated to the noise noise_rate_prototype &lt;- matrix(rep(1,2), nrow = 2, ncol = 1) tspan &lt;- c(0.,200) JuliaCall::julia_assign(&quot;u0&quot;, u0); ## initial value JuliaCall::julia_assign(&quot;tspan&quot;, tspan); ## grid JuliaCall::julia_assign(&quot;p&quot;, p); ## parameters JuliaCall::julia_assign(&quot;noise_rate_prototype&quot;, noise_rate_prototype); ## matrix associated to the noise ## call the SDE problem prob &lt;- JuliaCall::julia_eval(&quot;SDEProblem(f, g, u0,tspan,p, noise_rate_prototype=noise_rate_prototype)&quot;); sol &lt;- de$solve(prob) udf &lt;- as.data.frame(t(sapply(sol$u,identity))) #plot the 2 figures, plot(sol$t,udf$V1,type=&quot;l&quot;,col=&quot;purple&quot;, ylab=&quot;Y1&quot;) #L lines(sol$t,udf$V2,col=&quot;red&quot;,ylab=&quot;Y2&quot;) #R </code></pre> <p>I am not sure how to include the time dependence of <code>h</code>, I tried to do it by including a <a href="https://stackoverflow.com/questions/69843063/how-to-solve-a-system-of-ode-with-time-dependent-parameters-in-r/69846444#69846444">forcing variable</a> but I got a lengthy Julia error (stating that <code>h</code> is not defined- code below) . So perhaps thats not the way to go. I'd appreciate any help regarding this.</p> <p>The chunk of the code I changed to include the time dependent parameters is this (the new or changes lines have an arrow to their right):</p> <pre><code>## drift part in the SDE f &lt;- JuliaCall::julia_eval(&quot; function f(dy,y,p,t) MU &lt;- signal(t) # &lt;- dy[1] = -y[1]*p[1] + (y[2]-y[1])*p[2] + MU # &lt;- dy[2] = -y[2]*p[1] + (y[1]-y[2])*p[2] end&quot;) signal &lt;- approxfun(x = c(0, 35, 125, 200), # &lt;- y = c(0, 1, 0, 0), method = &quot;constant&quot;, rule = 2) ## diffusion part in the SDE g &lt;- JuliaCall::julia_eval(&quot; function g(dy,y,p,t) dy[1,1] = p[3] dy[2,1] = 0 end&quot;) ## matrix associated to the noise noise_rate_prototype &lt;- matrix(rep(1,2), nrow = 2, ncol = 1) tspan &lt;- c(0,200) JuliaCall::julia_assign(&quot;u0&quot;, u0); ## initial value JuliaCall::julia_assign(&quot;tspan&quot;, tspan); ## grid JuliaCall::julia_assign(&quot;p&quot;, p); ## parameters JuliaCall::julia_assign(&quot;signal&quot;, signal); # &lt;- JuliaCall::julia_assign(&quot;noise_rate_prototype&quot;, noise_rate_prototype); ## matrix associated to the noise ## call the SDE problem prob &lt;- JuliaCall::julia_eval(&quot;SDEProblem(f, g, u0,tspan,p, noise_rate_prototype=noise_rate_prototype, signal=signal)&quot;); # &lt;- </code></pre> <p>The rest of the code remained the same.</p>
3
2,038
Reload <ul> with event handler function
<p>I am extremely new to JavaScript/HTML/CSS. As a first website project I am working on my online shop using Shopify.</p> <p><a href="https://tpvm5oi54gjh03pr-51451003036.shopifypreview.com/collections/lo-mas-popular/products/cilindro" rel="nofollow noreferrer">This is My Website</a></p> <p>I am trying to update the list of images (thumbnails below the main picture) after one of the options is changed (size or color).</p> <p>I have managed to display the correct images when the page first loads by using the alt_text of each figure. For example, if you change the options and reload the website, you will see the appropriate figures. I did that as follows:</p> <pre><code>{% assign wanted_alts = product.selected_or_first_available_variant.options %} &lt;ul&gt; {% for media in product.media %} {% if wanted_alts contains media.alt or media.alt == &quot;All&quot; %} &lt;li&gt; ... &lt;/li&gt; {% endif %} {% endfor %} &lt;/ul&gt; </code></pre> <p>Basically, I just load the images that have an alt_text equal to the selected options.</p> <p>I now want to change all the thumbnails when an option is selected e.g. you select a different color. At the moment it only works if you</p> <ol> <li>First select the options.</li> <li>Then you refresh the page.</li> </ol> <p>I want the list to update automatically. I was able to find that the event of choosing another option is handled by this function:</p> <pre><code>_onSelectChange: function() { var variant = this._getVariantFromOptions(); this.container.dispatchEvent( new CustomEvent('variantChange', { detail: { variant: variant }, bubbles: true, cancelable: true }) ); if (!variant) { return; } this._updateMasterSelect(variant); this._updateImages(variant); this._updatePrice(variant); this._updateSKU(variant); this.currentVariant = variant; if (this.enableHistoryState) { this._updateHistoryState(variant); } } </code></pre> <p>I want to achieve something like (forgive my ignorance):</p> <pre><code>_onSelectChange: function() { ... /* Reload the &lt;ul&gt; tag that sets which figures to display */ } </code></pre> <p>Can someone point me into the right direction?</p> <p><strong>EDIT:</strong> I have been able to get the desired behaviour (in a non-optimal way) with the following:</p> <pre><code>_onSelectChange: function() { ... location.reload(); } </code></pre> <p>Which reloads the entire page.</p> <p>I have tried to reload just the <code>&lt;ul&gt;</code>, but I don't know how to do it. I have tried the following, but it didn't work:</p> <pre><code>&lt;div id=&quot;myID&quot;&gt; {% assign wanted_alts = product.selected_or_first_available_variant.options %} &lt;ul&gt; {% for media in product.media %} {% if wanted_alts contains media.alt or media.alt == &quot;All&quot; %} &lt;li&gt; ... &lt;/li&gt; {% endif %} {% endfor %} &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>And:</p> <pre><code>_onSelectChange: function() { ... $('#myID').load(document.URL + ' #myID'); } </code></pre> <p>Any help is appreciated.</p>
3
1,272
Xamarin Essentials MediaPicker not working on iOS
<p>I'm using Xamarin Essentials MediaPicker (v1.7.3) on my Xamarin Forms 5 app and it just freezes and eventually crashes the app on iOS but works perfectly fine on Android.</p> <p>My app uses the <code>MVVM</code> pattern so I have an <code>ImageButton</code> that's wired to a method in my view model and the code for that method looks like this:</p> <pre><code>async Task Add_Image_Tapped() { try { var photosPermission = await Permissions.CheckStatusAsync&lt;Permissions.Photos&gt;(); var cameraPermission = await Permissions.CheckStatusAsync&lt;Permissions.Camera&gt;(); if (photosPermission != PermissionStatus.Granted || photosPermission != PermissionStatus.Restricted) photosPermission = await Permissions.RequestAsync&lt;Permissions.Photos&gt;(); if (cameraPermission != PermissionStatus.Granted || cameraPermission != PermissionStatus.Restricted) cameraPermission = await Permissions.RequestAsync&lt;Permissions.Camera&gt;(); if ((photosPermission == PermissionStatus.Granted || photosPermission == PermissionStatus.Restricted) &amp;&amp; (cameraPermission == PermissionStatus.Granted || cameraPermission == PermissionStatus.Restricted)) await HandleImagePicker(); } catch(Exception e) { throw new Exception(e.Message); } } </code></pre> <p>And if the permissions check out fine, here's the method that handles the image pick up:</p> <pre><code>private async Task HandleImagePicker() { try { var filePath = string.Empty; var fileName = string.Empty; MainThread.BeginInvokeOnMainThread(() =&gt; { var result = MediaPicker.PickPhotoAsync(new MediaPickerOptions { Title = &quot;Pick Image&quot; }).Result; if (result == null) return; filePath = result.FullPath; fileName = result.FileName; }); if (!string.IsNullOrEmpty(filePath) &amp;&amp; !string.IsNullOrEmpty(fileName)) { // Do something with the image } } catch(Exception e) { throw new Exception(e.Message); } } </code></pre> <p>I'm using <code>Xamarin Forms 5.0.0.2401</code>, <code>Xamarin Community Toolkit 2.0.2</code> and <code>Xamarin Essentials 1.7.3</code>. I also have the following permissions in my <code>Info.plist</code>:</p> <pre><code>&lt;key&gt;NSCameraUsageDescription&lt;/key&gt; &lt;string&gt;MyApp would like to access your camera&lt;/string&gt; &lt;key&gt;NSMicrophoneUsageDescription&lt;/key&gt; &lt;string&gt;MyApp would like to access your microphone&lt;/string&gt; &lt;key&gt;NSPhotoLibraryUsageDescription&lt;/key&gt; &lt;string&gt;MyApp would like to access your photo library&lt;/string&gt; &lt;key&gt;NSPhotoLibraryAddUsageDescription&lt;/key&gt; &lt;string&gt;MyApp would like to access your photo library&lt;/string&gt; </code></pre> <p>I also initialize Xamarin Essentials in <code>AppDelegate</code> <code>FinishedLaunching()</code> method as below:</p> <pre><code>Xamarin.Essentials.Platform.Init(() =&gt; new UIViewController()); </code></pre> <p>Any idea what maybe the issue here?</p> <p>UPDATE:</p> <p>The above code reflects the current code I have after making changes based on suggestions such as using the main thread.</p> <p>Currently, if I run the app on iOS Simulator on a Mac, it literally hangs forever. Never throws an exception or crashes.</p> <p>If I run it on a real device i.e. iPhone Xs, it will hang for quite a while and eventually crash the whole app.</p> <p>As mentioned earlier, it all works perfectly fine on Android.</p>
3
1,296
Firebase Crashlogs leads me astray (iOS crash log)
<p>I have a bug in my app which I am not able to reproduce on my own device and the firebase crash log doesn't really help me. Or maybe I am not able to understand it correctly. What is really weird is that it tells me lines of code where the crash happens which is in the millions.</p> <pre><code>Crashed: com.apple.main-thread </code></pre> <p>0 Flax 0x102359394 CategoriesViewController.loadPosts(more:) + 4338652052 (CategoriesViewController.swift:4338652052)</p> <p>1 Flax 0x1023598d0 closure #1 in CategoriesViewController.loadPosts(more:) + 361 (CategoriesViewController.swift:361)</p> <p>2 Flax 0x102332c7c closure #5 in closure #1 in PostsAPI.loadPostsOrdered(start:order:limit:category:controller:onSuccess:) + 342 (PostAPI.swift:342)</p> <p>3 Flax 0x1022f9240 thunk for @escaping @callee_guaranteed () -&gt; () + 4338258496 (:4338258496)</p> <p>4 libdispatch.dylib 0x186e5ca84 _dispatch_call_block_and_release + 32</p> <p>5 libdispatch.dylib 0x186e5e81c _dispatch_client_callout + 20</p> <p>6 libdispatch.dylib 0x186e6cc70 _dispatch_main_queue_callback_4CF + 884</p> <p>7 CoreFoundation 0x1871eb398 <strong>CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE</strong> + 16</p> <p>8 CoreFoundation 0x1871e5270 __CFRunLoopRun + 2524</p> <p>9 CoreFoundation 0x1871e4360 CFRunLoopRunSpecific + 600</p> <p>10 GraphicsServices 0x19e822734 GSEventRunModal + 164</p> <p>11 UIKitCore 0x189c5f584 -[UIApplication _run] + 1072</p> <p>12 UIKitCore 0x189c64df4 UIApplicationMain + 168</p> <p>13 Flax 0x1022b2e44 main + 21 (HashtagTableViewCell.swift:21)</p> <p>14 libdyld.dylib 0x186ea0cf8 start + 4</p> <p>The crash happens rarely. The two lines which make sense (361 (CategoriesViewController.swift:361) and PostsAPI.loadPostsOrdered(start:order:limit:category:controller:onSuccess:) + 342 (PostAPI.swift:342) are actually empty lines which makes it even more confusing.</p> <p>Like I said those functions are called thousands of times a day and crash maybe every 1000th time.</p> <p>Any idea how to understand this crash log?</p> <p>edit: The HashtagTableviewCell</p> <pre><code>import Foundation import KILabel class HashtagTableViewCell: UITableViewCell { @IBOutlet weak var hashtagCounter: UILabel! @IBOutlet weak var HashTagLabel: UILabel! var hashtag: Hashtag! func updateView(hashtag:Hashtag) { self.hashtag = hashtag HashTagLabel.text = hashtag.mentions != -100 ? &quot;# \(hashtag.tag!)&quot; : &quot;\(hashtag.tag!)&quot; HashTagLabel.font = UIFont.systemFont(ofSize: 18) hashtagCounter.text = hashtag.mentions == 1 ? &quot;\(hashtag.mentions ?? 0) \(NSLocalizedString(&quot;HASHTAG_CELL_POSTS_1&quot;, comment: &quot;&quot;))&quot; : &quot;\(hashtag.mentions ?? 0) \(NSLocalizedString(&quot;HASHTAG_CELL_POSTS&quot;, comment: &quot;&quot;))&quot; if hashtag.mentions == -100 { hashtagCounter.text = &quot;&quot; } } override func awakeFromNib() { super.awakeFromNib() HashTagLabel.font = UIFont.systemFont(ofSize: 18) } override func prepareForReuse() { HashTagLabel.font = UIFont.systemFont(ofSize: 18) } } </code></pre>
3
1,578
How I add extra table under the third mainpanel to shiny app
<p>I have put together a shiny app. Now, I need to add another panel to that but by simply adding extra mainplanel to the code, my other two panels being deactivated</p> <p>This is my app</p> <pre><code>navbarPageWithText &lt;- function(..., text) { navbar &lt;- navbarPage(...) textEl &lt;- tags$p(class = "navbar-text", text) navbar[[3]][[1]]$children[[1]] &lt;- htmltools::tagAppendChild( navbar[[3]][[1]]$children[[1]], textEl) navbar } # Call this function with an input (such as `textInput("text", NULL, "Search")`) if you # want to add an input to the navbar navbarPageWithInputs &lt;- function(..., inputs) { navbar &lt;- navbarPage(...) form &lt;- tags$form(class = "navbar-form", inputs) navbar[[3]][[1]]$children[[1]] &lt;- htmltools::tagAppendChild( navbar[[3]][[1]]$children[[1]], form) navbar } library(shiny) library(DT) Patient_005=as.data.frame(read.table(text = " Driver SNV_Tumour_005 SNV_Organoid_005 INDEL_Tumour_005 INDEL_Organoid_005 Deletion_Organoid_005 ABCB1 * * * - - - ACVR1B * * - - - - ACVR2A * - - - - - ")) Patient_013=as.data.frame(read.table(text = " Driver SNV_Tumour_013 SNV_Organoid_013 INDEL_Tumour_013 INDEL_Organoid_013 Deletion_Tumour_013 Deletion_Organoid_013 ABCB1 * - * - - - - ACVR1B * - - - - - - ACVR2A * - - - - - - ")) Patient_036 = as.data.frame(read.table(text = " Driver SNV_Organoid_036 INDEL_Organoid_036 Deletion_Organoid_036 ABCB1 * - * - ACVR1B * * * - ACVR2A * * - - ")) Patient_021 = as.data.frame(read.table(text = " Driver SNV_Organoid_021 INDEL_Organoid_021 ABCB1 * * - ACVR1B * * - ACVR2A * * * ")) ui &lt;- shinyUI(navbarPage("Patients", tabPanel("Table",theme = "bootstrap.css", headerPanel("Genomic variations in OESO driver genes"), sidebarPanel(br(), tags$style("#select1 {border: 2px solid #dd4b39;}"), div( id = "loading-content", h2("Binary output"), navbarPageWithText( "* means that gene carries an event", text = "- means that no event has been observed" ) ), selectInput( "table_dataset", "Choose patient:", choices = c("Patient_005","Patient_013","Patient_036","Patient_021") ) ), mainPanel(DT::dataTableOutput("table")) ), tabPanel("Image", sidebarPanel( br(), tags$style("#select2 {background-color:blue;}"), selectInput( "image_dataset", "Choose image:", choices = c("Mutational_Signatures"="https://i.ibb.co/hZYc9nM/Mutational-Signatures1.png", "Total_and_Minor_Copy_Number" = "https://i.ibb.co/pRYxfwF/Total-and-Minor-Copy-Number.png", "Structural_Variations" = "https://i.ibb.co/JB4z6y6/Strutural-Variations.png", "Statistics" = "https://i.ibb.co/DYm2nm4/Statistics.png" , "Major_and_Minor_Copy_Number" = "https://i.ibb.co/ZV3DTXN/Major-and-Minor-Copy-Number.png", "Mutational_consequences_SNVs" = "https://i.ibb.co/CpyqRdr/Mutational-consequences.png" , "Mutational_consequences_INDEL" = "https://i.ibb.co/Vt4nwqd/Mutational-consequences-indel.png" , "Segment_mean" = "https://i.ibb.co/Cthk4ZD/Segment-mean.png" , "RNA_seq_Driver_Genes" = "https://i.ibb.co/qr9cvdN/RNA-seq.png" ) ) ), mainPanel( uiOutput("image") ), div( id = "loading-content", h2("Loading..."), navbarPageWithText( "Images of", text = "Organoid models" ) ) ),tags$head( tags$style(type = 'text/css', HTML('.navbar { background-color: skin-blue;} .navbar-default .navbar-brand{color: black;} .tab-panel{ background-color: skin-blue; color: black} .navbar-default .navbar-nav &gt; .active &gt; a, .navbar-default .navbar-nav &gt; .active &gt; a:focus, .navbar-default .navbar-nav &gt; .active &gt; a:hover { color: #555; background-color: pink; }') ) ) )) server &lt;- function(input, output) { # Related to displaying tables table_data &lt;- reactive({ switch(input$table_dataset, "Patient_005" = Patient_005 ,"Patient_013" = Patient_013,"Patient_036" = Patient_036,"Patient_021" = Patient_021) }) column_data &lt;- reactive({ switch(input$table_dataset, "Patient_005" = c('Driver','SNV_Tumour_005','SNV_Organoid_005','INDEL_Tumour_005','INDEL_Organoid_005','Deletion_Organoid_005'), "Patient_013" = c('SNV_Tumour_013','SNV_Organoid_013','INDEL_Tumour_013','INDEL_Organoid_013','Deletion_Tumour_013','Deletion_Organoid_013') ) }) output$table &lt;- DT::renderDataTable({ datatable(table_data()) %&gt;% formatStyle( column_data(), backgroundColor = styleEqual(c("*", "-"), c('green', 'red')) ) }) # Related to displaying images output$image &lt;- renderUI({ tags$img(src = input$image_dataset) }) } shinyApp(ui=ui,server=server) </code></pre> <p>I need to add this table as another panel with the title of MetaData</p> <pre><code> &gt; head(MetaData) Clinical.ID Barcode WTSI.Model.ID Tissue.Origin 1 OCC/SH/253/S/T 2000003422203 WTSI-OESO_005 Oesophageal 2 OCC/SH/254/S/T CGAP-A3F3F WTSI-OESO_013 Oesophageal 3 OCC/SH/255/S/T CGAP-73FED WTSI-OESO_036 Oesophageal 4 OCC/SH/255/S/N CGAP-70672 WTSI-OESO_037 Oesophageal Sample.type 1 Tumour 2 Tumour 3 Tumour 4 Normal &gt; &gt; dput(head(MetaData)) structure(list(Clinical.ID = structure(c(1L, 2L, 4L, 3L), .Label = c("OCC/SH/253/S/T", "OCC/SH/254/S/T", "OCC/SH/255/S/N", "OCC/SH/255/S/T"), class = "factor"), Barcode = structure(c(1L, 4L, 3L, 2L), .Label = c("2000003422203", "CGAP-70672", "CGAP-73FED", "CGAP-A3F3F"), class = "factor"), WTSI.Model.ID = structure(1:4, .Label = c("WTSI-OESO_005", "WTSI-OESO_013", "WTSI-OESO_036", "WTSI-OESO_037"), class = "factor"), Tissue.Origin = structure(c(1L, 1L, 1L, 1L), .Label = "Oesophageal", class = "factor"), Sample.type = structure(c(2L, 2L, 2L, 1L), .Label = c("Normal", "Tumour"), class = "factor")), row.names = c(NA, 4L), class = "data.frame") &gt; </code></pre> <p>Could you please give me a hand in adding this table as the third panel to my app?</p>
3
5,130
SelectList in QueryOver
<p>I have some problem with selecting by QueryOver, here are my model classes:</p> <pre><code>public class BaseModel { public virtual int Id { get; set; } public virtual DateTime ModifyDate { get; set; } public virtual DateTime CreateDate { get; set; } public virtual User CreateUser { get; set; } public virtual User ModifyUser { get; set; } public virtual bool IsActive { get; set; } } public class BaseClassMap&lt;T&gt; : ClassMap&lt;T&gt; where T : BaseModel { public BaseClassMap() { Id(x =&gt; x.Id).GeneratedBy.Identity(); References(x =&gt; x.CreateUser, "CreateUser_Id"); References(x =&gt; x.ModifyUser, "ModifyUser_Id"); Map(x =&gt; x.CreateDate).Not.Nullable().Default("GETDATE()"); Map(x =&gt; x.ModifyDate).Not.Nullable().Default("GETDATE()"); ; Map(x =&gt; x.IsActive).Not.Nullable().Default("1"); } } public class Expenditure : BaseModel { public virtual decimal Amount { get; set; } public virtual Category Category { get; set; } public virtual string Comment { get; set; } public virtual DateTime Month { get; set; } } public class ExpenditureMap : BaseClassMap&lt;Expenditure&gt; { public ExpenditureMap() { Schema("[budget]"); Table("[Expenditure]"); Id(x =&gt; x.Id); Map(x =&gt; x.Amount).Not.Nullable(); Map(x =&gt; x.Comment); Map(x =&gt; x.Month).Not.Nullable(); References(x =&gt; x.Category, "Category_Id").Not.Nullable(); } } public class User : BaseModel { public virtual string Login { get; set; } public virtual string Email { get; set; } public virtual string Password { get; set; } public virtual string PasswordSalt { get; set; } public virtual string HashAlgorithm { get; set; } } public class UserMap : BaseClassMap&lt;User&gt; { public UserMap() { Schema("[permission]"); Table("[User]"); Id(x =&gt; x.Id); Map(x =&gt; x.Login).Not.Nullable(); Map(x =&gt; x.Email).Not.Nullable(); Map(x =&gt; x.Password).Not.Nullable(); Map(x =&gt; x.PasswordSalt); Map(x =&gt; x.HashAlgorithm).Not.Nullable(); } } public class ExpenseDetailsItemVm { public int Id { get; set; } public string Comment { get; set; } public decimal Amount { get; set; } public DateTime CreateDate { get; set; } public string CreateUser { get; set; } } </code></pre> <p>And here is my query:</p> <pre><code>var user = new User(); var result = new ExpenseDetailsItemVm(); var expenses = SessionManager.Session.QueryOver&lt;Expenditure&gt;() .JoinAlias(x =&gt; x.CreateUser, () =&gt; user) .Where(x =&gt; x.IsActive &amp;&amp; x.Category.Id == categoryId &amp;&amp; x.Month == date.ToFirstDayOfMonth()) .SelectList(list =&gt; list .Select(x =&gt; x.Id).WithAlias(() =&gt; result.Id) .Select(x =&gt; x.Amount).WithAlias(() =&gt; result.Amount) .Select(x =&gt; x.Comment).WithAlias(() =&gt; result.Comment) .Select(x =&gt; x.CreateDate).WithAlias(() =&gt; result.CreateDate) .Select(()=&gt; user.Login).WithAlias(() =&gt; result.CreateUser) ).TransformUsing(Transformers.AliasToBean&lt;ExpenseDetailsItemVm&gt;()) .List&lt;ExpenseDetailsItemVm&gt;(); </code></pre> <p>I'm getting this error:</p> <blockquote> <p>Object reference not set to an instance of an object.</p> </blockquote> <p>I'm sure the problem on this line of code:</p> <pre><code> .Select(()=&gt; user.Login).WithAlias(() =&gt; result.CreateUser) </code></pre> <p>If I comment this line out, the query works fine and return result without error.</p> <p>To eliminate mapping mistake, I tried this:</p> <pre><code>var u = SessionManager.Session.QueryOver&lt;User&gt;().Where(x =&gt; x.Id == 1). SelectList(list =&gt; list. Select(x =&gt; x.Login).WithAlias(() =&gt; result.CreateUser)) .TransformUsing(Transformers.AliasToBean&lt;ExpenseDetailsItemVm&gt;()) .List&lt;ExpenseDetailsItemVm&gt;(); </code></pre> <p>And this also works fine.</p> <p>In my <code>Expenditure</code> table, the column <code>CreateUser_Id</code> everywhere has a value</p>
3
2,092
Django images uploaded by admin will not display in production or development
<p>I have Django 1.10 and whitenoise 3.3 and the website is deployed on Heroku. My static files are fine in development and production. My media files, however do not load in production and development. </p> <p>When debug = True, the media files render properly in both production and development. What I really want is for the media files to render properly even when debug = False. </p> <p>Everything was fine and dandy until I realized I deployed my site with debug = True. So, I changed it to debug = False. Now the static and media files failed. I did some research and went to whitenoise docs to follow setup. Then the static files worked. However, the media files still failed. I read the docs on media and static files on Django, but unfortunately only saw some samples with nginx and the doc says there are many ways to do this and can only provide structure. </p> <p>I am seeking a solution that will allow me to continue to add things to my site in production via admin and still allow my to run my website with heroku. </p> <p>settings.py</p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', #'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_URL = '/static/' #STATIC_URL = '/site_media/' #STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'mysite/static'), #] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #STATIC_ROOT = '' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' </code></pre> <p>models.py</p> <pre><code>from django.db import models class Post(models.Model): pub_date = models.DateTimeField('date published') title = models.CharField(max_length=200) thumbnail = models.ImageField(upload_to='static') def __str__(self): return self.title class Image(models.Model): image = models.ImageField(max_length=100, upload_to='static') pub_date = models.DateTimeField('date_published') post = models.ForeignKey('Post', default=0, on_delete=models.CASCADE,) title = models.CharField(max_length=200) def __str__(self): return self.title class Text(models.Model): text = models.TextField() pub_date = models.DateTimeField('date_published') post = models.ForeignKey('Post', default=0, on_delete=models.CASCADE,) title = models.CharField(max_length=200) def __str__(self): return self.title </code></pre> <p>here are the html files inside blog/templates/blog/</p> <p>about.html </p> <pre><code>{% load static %} &lt;html&gt; &lt;head&gt; &lt;title&gt; and1can's Blog &lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'blog/about.css' %}"/&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Josefin+Slab" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class='header'&gt; &lt;a class='title' href="/"&gt; &lt;h1 class='title'&gt; and1can &lt;/h1&gt;&lt;/a&gt; &lt;/div&gt; &lt;h3 class='intro'&gt; Machine Learning, Statistics, and all that other fun stuff &lt;/h3&gt; &lt;div class='about_title'&gt; Andy Chu &lt;/div&gt; &lt;/div&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; &lt;div class="wrapper"&gt; &lt;div class="line"&gt;&lt;hr width="90%"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/br&gt; &lt;div class='blurb'&gt; I am interested in what we are able to learn from data. I am looking to join a data science team that shares this interest and satisfaction gained when making predictions that would otherwise not be possible without analyzing data. Statistics, machine learning, artificial intelligence, computer vision, and computational geometry are my fields of interest. &lt;/div&gt; &lt;/br&gt; &lt;div class="container"&gt; &lt;div class='email'&gt; Contact: &lt;/br&gt; &lt;/br&gt; &lt;/div&gt; &lt;a href="https://linkedin.com/in/andy-chu-76456a32"&gt; &lt;img src="/media/static/linkedin.png" height=40; width=40;/&gt; &lt;/a&gt; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;a href="https://github.com/and1can"&gt; &lt;img src="/media/static/github.png" height=40; width=40/&gt; &lt;/a&gt; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;a href="https://www.kaggle.com/and1can"&gt; &lt;img src="/media/static/kaggle.png" height=40; width=60/&gt; &lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>index.html </p> <pre><code> {% load static %} &lt;html&gt; &lt;head&gt; &lt;title&gt; and1can's Blog &lt;/title&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'blog/blog.css' %}"/&gt; &lt;link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Josefin+Slab" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;h1 class='title'&gt; and1can &lt;/h1&gt; &lt;h3 class='intro'&gt; Machine Learning, Statistics, and all that other fun stuff &lt;/h3&gt; &lt;a class='about' href="/blog/about"&gt; &lt;h1 class='title'&gt; about &lt;/h1&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="line"&gt;&lt;hr width="90%"&gt;&lt;/div&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; &lt;ul&gt; {% for p in latest_posts %} &lt;/br&gt; &lt;div class="header"&gt; &lt;a href="/blog/{{ p.id }}"&gt; {{ p.title }} &lt;/a&gt; &lt;/div&gt; &lt;div class='intro'&gt; {{ p.pub_date}} &lt;/div&gt; &lt;/br&gt; &lt;/br&gt; &lt;a href="/blog/{{ p.id }}"&gt; &lt;img class="image" src="{{ p.thumbnail.url }}" height=400 width=400/&gt; &lt;/a&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; {% endfor %} &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>post.html </p> <pre><code>{% load static %} &lt;html&gt; &lt;head&gt; &lt;title&gt; and1can's Blog &lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'blog/post.css' %}"/&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Josefin+Slab" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class='header'&gt; &lt;a class='title' href="/"&gt; &lt;h1 class='title'&gt; and1can &lt;/h1&gt;&lt;/a&gt; &lt;h3 class='intro'&gt; Machine Learning, Statistics, and all that other fun stuff &lt;/h3&gt; &lt;a class='about' href="/blog/about"&gt; &lt;h1 class='title'&gt; about &lt;/h1&gt;&lt;/a&gt; &lt;/div&gt; &lt;/br&gt; &lt;/br&gt; &lt;/br&gt; &lt;div class="wrapper"&gt; &lt;div class="line"&gt;&lt;hr width="93%"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/br&gt; &lt;/br&gt; &lt;/div&gt; &lt;div class='post'&gt; &lt;div class='post_intro'&gt; {{ post.pub_date }} &lt;/div&gt; &lt;/div&gt; &lt;div class='post_title'&gt; {{ post.title }} &lt;/div&gt; &lt;/br&gt; &lt;/br&gt; &lt;img class="image" src="{{ post.thumbnail.url }}" width=300, height=300/&gt; &lt;ul class='content'&gt; {% for o in output %} &lt;/br&gt; {% if o.image %} {% block content %} &lt;img class="image" src="{{ o.image.url }}" /&gt; {% endblock %} {% else %} &lt;div class="text"&gt; {{o.text}} &lt;/div&gt; {% endif %} &lt;/br&gt; {% endfor %} &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
4,742
Adding items to VB.NET ListView and having them shown in the order they were added
<p>I am creating an app launcher - that is basically a ListView with a "group" of shortcuts files ( ie images associated with a shortcut and the text is the name of the shortcut ) in it. It's all been working fine and dandy, except this last thing that I want to do. The apps that appear in the listview are stored in an xml file and what I'm trying to do is add the apps into the listview in the order they appear in the xml file i.e. this probably won't be alphabetical.</p> <p>So I read an app name from the xml file, find it's shortcut lnk file, extract the icon from the file and add it to the Listview; using:</p> <pre><code>lvPrograms.LargeImageList = ProgramIcons Dim item As ListViewItem Dim FileName = Path.GetFileNameWithoutExtension(shortcutFile.Name) item = New ListViewItem(FileName, 1) item.ImageKey = FileName iconFile = System.Drawing.Icon.ExtractAssociatedIcon(shortcutFile.FullName) ProgramIcons.Images.Add(FileName, iconFile) lvPrograms.Items.Add(item) </code></pre> <p>I also set the Sorting property of the listView to None</p> <p>When the code has added all the apps, I was hoping for them to appear in the order I added them, but it just seems to add them in a random order ie.. not my order or ascending or descending ?!</p> <p>If I check the contents of lvPrograms.Items(X).Text in the debug window, then (0) is not the first one I added and (6) is not the seventh one I added ?!</p> <p>Hope this makes sense and someone could help me get the apps listed in the order that I added them ?</p> <p>Cheers,</p> <p>Chris.</p> <p>Extra Info asked for my Plutonix:</p> <p>Basically my xml is read into an object called UserAppSettings which has a collection of Application objects and their Name property if the name of the app. Also the ProgramDetails is a structure that holds various properties about a shortcut - name, working folder etc </p> <p>The image lists (in case relevant are 32bit &amp; 16bit in depth )</p> <pre><code> lvPrograms.Clear() ProgramIcons.Images.Clear() ProgramIconsSmall.Images.Clear() lvPrograms.LargeImageList = ProgramIcons lvPrograms.SmallImageList = ProgramIconsSmall Dim dir As New System.IO.DirectoryInfo(userShortcutsFolder) lvPrograms.BeginUpdate() lvPrograms.Sorting = SortOrder.None Dim shortcutFile As FileInfo For Each AppToShow As Application In UserAppSettings.Applications shortcutFile = New FileInfo(userShortcutsFolder + AppToShow.Name + ".lnk") addShortcutToListView(shortcutFile) Next Private Sub addShortcutToListView(shortcutFile As FileInfo) Dim CurrentProgram As ProgramDetails Dim item As ListViewItem CurrentProgram = New ProgramDetails With CurrentProgram .FullName = shortcutFile.FullName .Name = shortcutFile.Name .NameWithoutExtension = Path.GetFileNameWithoutExtension(shortcutFile.Name) item = New ListViewItem(.NameWithoutExtension, 1) .Icon = System.Drawing.Icon.ExtractAssociatedIcon(.FullName) getShortcutProperties(CurrentProgram) ProgramIcons.Images.Add(.NameWithoutExtension, .Icon) ProgramIconsSmall.Images.Add(.NameWithoutExtension, .Icon) item.ImageKey = .NameWithoutExtension End With item.Tag = CurrentProgram lvPrograms.Items.Add(item) ' MsgBox(item.Text + vbNewLine + lvPrograms.Items(lvPrograms.Items.Count - 1).Text) End Sub </code></pre>
3
1,125
IndexError: tuple index out of range BLSTM
<p>Please Help me, i want to generate and evaluating accuracy of text summarize model. When i call the evaluating model and generating text from the vector, i just got error tuple index out of range, and what i know the shape in the model was already customized by me.</p> <p>This is the code :</p> <pre><code>MAX_LEN = 300 en_shape=np.shape(MAX_LEN,) de_shape=np.shape(MAX_LEN,) def generateText(SentOfVecs): SentOfVecs=np.reshape(SentOfVecs,de_shape) kk=&quot;&quot; for k in SentOfVecs: kk = kk + label_encoder.inverse_transform([argmax(k)])[0].strip()+&quot; &quot; #kk=kk+((getWord(k)[0]+&quot; &quot;) if getWord(k)[1]&gt;0.01 else &quot;&quot;) return kk def summarize(article): stop_pred = False article = np.reshape(article,(1,en_shape[0],en_shape[1])) #get initial h and c values from encoder init_state_val = encoder.predict(article) target_seq = np.zeros((1,1,de_shape[1])) #target_seq =np.reshape(train_data['summaries'][k][0],(1,1,de_shape[1])) generated_summary=[] while not stop_pred: decoder_out,decoder_h,decoder_c= decoder.predict(x=[target_seq]+init_state_val) generated_summary.append(decoder_out) init_state_val= [decoder_h,decoder_c] #get most similar word and put in line to be input in next timestep #target_seq=np.reshape(model.wv[getWord(decoder_out)[0]],(1,1,emb_size_all)) target_seq=np.reshape(decoder_out,(1,1,de_shape[1])) if len(generated_summary)== de_shape[0]: stop_pred=True break return generated_summary def evaluate_summ(article): ref='' for k in wt(train_data['gold_summary'][article])[:20]: ref=ref+' '+k gen_sum = generateText(summarize(train_data[&quot;article&quot;][article])) print(&quot;-----------------------------------------------------&quot;) print(&quot;Original summary&quot;) print(ref) print(&quot;-----------------------------------------------------&quot;) print(&quot;Generated summary&quot;) print(gen_sum) print(&quot;-----------------------------------------------------&quot;) rouge = Rouge155() score = rouge.score_summary(ref, gen_sum) print(&quot;Rouge1 Score: &quot;,score) </code></pre> <p>And this was the error i got :</p> <pre><code>--------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-73-033edff49496&gt; in &lt;module&gt;() ----&gt; 1 evaluate_summ(10) 2 3 print(generateText(summarize(train_data[&quot;text_clean&quot;][8]))) 4 print(train_data[&quot;gold_summary&quot;][8]) 5 print(train_data[&quot;article&quot;][8]) 1 frames &lt;ipython-input-72-c6ea0ce23227&gt; in evaluate_summ(article) 36 for k in wt(train_data['gold_summary'][article])[:20]: 37 ref=ref+' '+k ---&gt; 38 gen_sum = generateText(summarize(train_data[&quot;article&quot;][article])) 39 print(&quot;-----------------------------------------------------&quot;) 40 print(&quot;Original summary&quot;) &lt;ipython-input-72-c6ea0ce23227&gt; in summarize(article) 14 def summarize(article): 15 stop_pred = False ---&gt; 16 article = np.reshape(article,(1,en_shape[0],en_shape[1])) 17 #get initial h and c values from encoder 18 init_state_val = encoder.predict(article) IndexError: tuple index out of range </code></pre>
3
1,344
i want to make my layout non focusable
<p>i want to make my layout non focusable ie: i want the user can not click the buttons on the layout until the parsing is done i have done to make button non clickable and clickable when parsing is done</p> <p>but if i can make the layout non focusable</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); progress_waiting1=(ProgressBar)findViewById(R.id.progress1); progress_waiting1.setVisibility(ProgressBar.VISIBLE); progress_waiting2=(ProgressBar)findViewById(R.id.progress2); progress_waiting2.setVisibility(ProgressBar.VISIBLE); Typeface tf_helvetica = Typeface.createFromAsset(getAssets(),"fonts/HelveticaNw.ttf"); Typeface tf_helvetica_bold = Typeface.createFromAsset(getAssets(),"fonts/HelveticaNwBd.ttf"); Config.TF_HELVETICA=tf_helvetica; Config.TF_HELVETICA_BOLD=tf_helvetica_bold; bttn_bedpress=(ImageButton)findViewById(R.id.bttn_bedpress); bttn_news=(ImageButton)findViewById(R.id.bttn_news); bttn_logo=(ImageButton)findViewById(R.id.bttn_logo); bttn_faq=(ImageButton)findViewById(R.id.bttn_faq); bttn_cv=(ImageButton)findViewById(R.id.bttn_cv); bttn_omnu=(ImageButton)findViewById(R.id.bttn_omnu); bttn_recent=(ImageButton)findViewById(R.id.button1); bttn_bedpress.setClickable(false); bttn_news.setClickable(false); bttn_logo.setClickable(false); bttn_faq.setClickable(false); bttn_cv.setClickable(false); bttn_omnu.setClickable(false); bttn_recent.setClickable(false); img_gray_bg=(RelativeLayout)findViewById(R.id.img_gray_bg); img_gray_bg.setVisibility(ImageView.VISIBLE); txt_wait=(TextView)findViewById(R.id.txt_wait); txt_wait.setVisibility(TextView.VISIBLE); txt_wait.setTypeface(Config.TF_HELVETICA_BOLD); topheading=(TextView)findViewById(R.id.txt_topheading); topheading.setTypeface(Config.TF_HELVETICA_BOLD); headline=(TextView)findViewById(R.id.txt_headline); headline.setTypeface(Config.TF_HELVETICA_BOLD); date=(TextView)findViewById(R.id.txt_date); date.setTypeface(Config.TF_HELVETICA_BOLD); txt_place=(TextView)findViewById(R.id.txt_place); txt_place.setTypeface(Config.TF_HELVETICA_BOLD); img_company=(ImageView)findViewById(R.id.img_company); txt_news=(TextView)findViewById(R.id.txt_news); txt_news.setTypeface(Config.TF_HELVETICA_BOLD); txt_career=(TextView)findViewById(R.id.txt_career); txt_career.setTypeface(Config.TF_HELVETICA_BOLD); txt_bedpress=(TextView)findViewById(R.id.txt_bedpress); txt_bedpress.setTypeface(Config.TF_HELVETICA_BOLD); txt_cv=(TextView)findViewById(R.id.txt_cv); txt_cv.setTypeface(Config.TF_HELVETICA_BOLD); txt_faq=(TextView)findViewById(R.id.txt_faq); txt_faq.setTypeface(Config.TF_HELVETICA_BOLD); txt_logo=(TextView)findViewById(R.id.txt_logo); txt_logo.setTypeface(Config.TF_HELVETICA_BOLD); doAction(); } public void doAction() { progress_waiting1.setVisibility(ProgressBar.VISIBLE); progress_waiting2.setVisibility(ProgressBar.VISIBLE); img_gray_bg.setVisibility(ImageView.VISIBLE); txt_wait.setVisibility(TextView.VISIBLE); topheading.setTypeface(Config.TF_HELVETICA_BOLD); headline.setTypeface(Config.TF_HELVETICA_BOLD); date.setTypeface(Config.TF_HELVETICA_BOLD); txt_place.setTypeface(Config.TF_HELVETICA_BOLD); txt_news.setTypeface(Config.TF_HELVETICA_BOLD); txt_career.setTypeface(Config.TF_HELVETICA_BOLD); txt_bedpress.setTypeface(Config.TF_HELVETICA_BOLD); txt_cv.setTypeface(Config.TF_HELVETICA_BOLD); txt_faq.setTypeface(Config.TF_HELVETICA_BOLD); txt_logo.setTypeface(Config.TF_HELVETICA_BOLD); if(!HaveNetworkConnection()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Nettverk ikke tilgjengelig") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } final Thread parseThread=new Thread(new Runnable() { public void run() { if(HaveNetworkConnection()) { parseDataBedPres(Config.URL_BedPres); parseDataNyheter(Config.URL_Nyheter); Collections.sort(mydate); } else { parseDataBedPresLocal(); parseDataNyheterLocal(); } } }); parseThread.start(); Thread displayThread = new Thread(new Runnable() { public void run() { try { parseThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.post(new Runnable() { public void run() { progress_waiting1.setVisibility(ProgressBar.GONE); progress_waiting2.setVisibility(ProgressBar.GONE); txt_wait.setVisibility(TextView.GONE); img_gray_bg.setVisibility(ImageView.GONE); String month[]=getResources().getStringArray(R.array.month_array); if(data_bedpres_future.size()!=0) { int pos=data_bedpres_future.get(0).size()-1; DateFormat df=new SimpleDateFormat("yyyy-MM-dd"); Date dt = null; Calendar cal = Calendar.getInstance(); try { dt = df.parse(data_bedpres_future.get(1).get(pos)); cal.setTime(dt); } catch (ParseException e1) { e1.printStackTrace(); } DateFormat df2=new SimpleDateFormat("hh:mm:ss"); Date dt2 = null; Calendar cal2 = Calendar.getInstance(); try { dt2 = df2.parse(data_bedpres_future.get(2).get(pos)); cal2.setTime(dt2); } catch (ParseException e1) { e1.printStackTrace(); } date.setText("Tid: "+cal.get(Calendar.DATE)+" "+month[cal.get(Calendar.MONTH)]+" kl "+cal2.get(Calendar.HOUR_OF_DAY)+":"+cal2.get(Calendar.MINUTE)); //date.setText("Tid : "+data_bedpres_future.get(1).get(0)); headline.setText("Neste Bed.pres: "+data_bedpres_future.get(0).get(pos)); txt_place.setText("Sted: "+data_bedpres_future.get(3).get(pos)); try { Drawable img = drawable_from_url(data_bedpres_future.get(4).get(pos),"icon"); if(img!=null) { int height,width,w; height = img.getMinimumHeight() &gt; 52 ? 52 :img.getMinimumHeight(); int ratio = (((img.getMinimumHeight() - height)*100)/img.getMinimumHeight()); int wi = (img.getMinimumWidth() * ratio) /100; width = img.getMinimumWidth() -wi; w=width; int width1 = width &gt; 211 ? 211 :width; if (width&gt;0) { ratio = (((width - width1)*100)/width); int hi = (height * ratio) /100; height = height -hi; w=width1; } ViewGroup.LayoutParams params = img_company.getLayoutParams(); params.height = height; params.width = w; img_company.setLayoutParams(params); img_company.setBackgroundDrawable(drawable_from_url(data_bedpres_future.get(4).get(pos),"icon")); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if(data_nyheter_future.size()!=0) { date.setText(data_nyheter_future.get(2).get(0)); headline.setText("Siste nyhet: "+data_nyheter_future.get(3).get(0)); try { Drawable img = drawable_from_url(data_nyheter_future.get(0).get(0),"icon"); if(img!=null) { int height,width,w; height = img.getMinimumHeight() &gt; 52 ? 52 :img.getMinimumHeight(); int ratio = (((img.getMinimumHeight() - height)*100)/img.getMinimumHeight()); int wi = (img.getMinimumWidth() * ratio) /100; width = img.getMinimumWidth() -wi; w=width; int width1 = width &gt; 211 ? 211 :width; if (width&gt;0) { ratio = (((width - width1)*100)/width); int hi = (height * ratio) /100; height = height -hi; w=width1; } ViewGroup.LayoutParams params = img_company.getLayoutParams(); params.height = height; params.width = w; img_company.setLayoutParams(params); img_company.setBackgroundDrawable(img); } }catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if(data_nyheter_past.size()!=0) { DateFormat df=new SimpleDateFormat("yyyy-MM-dd"); Date dt = null; Calendar cal = Calendar.getInstance(); try { dt = df.parse(data_nyheter_past.get(2).get(0)); cal.setTime(dt); } catch (ParseException e1) { e1.printStackTrace(); } date.setText("Dato: "+cal.get(Calendar.DATE)+"."+(cal.get(Calendar.MONTH)+1)+"."+cal.get(Calendar.YEAR)); headline.setText("Siste nyhet: "+data_nyheter_past.get(3).get(0)); try { Drawable img = drawable_from_url(data_nyheter_past.get(0).get(0),"icon"); if(img!=null) { int height,width,w; height = img.getMinimumHeight() &gt; 52 ? 52 :img.getMinimumHeight(); int ratio = (((img.getMinimumHeight() - height)*100)/img.getMinimumHeight()); int wi = (img.getMinimumWidth() * ratio) /100; width = img.getMinimumWidth() -wi; w=width; int width1 = width &gt; 211 ? 211 :width; if (width&gt;0) { ratio = (((width - width1)*100)/width); int hi = (height * ratio) /100; height = height -hi; w=width1; } ViewGroup.LayoutParams params = img_company.getLayoutParams(); params.height = height; params.width = w; img_company.setLayoutParams(params); img_company.setBackgroundDrawable(img); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } bttn_bedpress.setClickable(true); bttn_news.setClickable(true); bttn_logo.setClickable(true); bttn_faq.setClickable(true); bttn_cv.setClickable(true); bttn_omnu.setClickable(true); bttn_recent.setClickable(true); } }); } }); displayThread.start(); </code></pre>
3
7,991
SetBackgroundColor to listview item on Custom Adapter does not work
<p>I have a working Custom Adapter that I have put to a listview.<br> I now add 15 items successfully.</p> <p>I now try to set the background color on item 3 to orange. This work!</p> <p>However when I scroll down and up, the background color dissapears.<br> How can we prevent this?</p> <p>//MENU.axml with the listview1 <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>MENU.axml &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#70292929" android:layout_gravity="top|right" android:orientation="horizontal"&gt; &lt;ListView android:id="@+id/listview1" android:background="#1b4f72" android:layout_weight="0.5" android:layout_gravity="top|left" android:layout_width="10px" android:layout_height="match_parent"&gt; &lt;/ListView&gt; &lt;/LinearLayout&gt;</code></pre> </div> </div> </p> <p>//C# code to add items to the listview1 and try to set the background on item 3 to orange</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>Android.Views.View MENUVIEW = LayoutInflater.Inflate(Resource.Layout.MENU, null); ListView LISTVIEW1 = MENUVIEW.FindViewById&lt;ListView&gt;(Resource.Id.listview1); //Add Items to the listview1 List&lt;String&gt; itemLIST = new List&lt;String&gt;(); for (int i = 0; i &lt; 15; i++) { itemLIST.Add("hello" + i); } Adapter1 adapter1 = new Adapter1(this, Android.Resource.Layout.SimpleListItem1, itemLIST); LISTVIEW1.Adapter = adapter1; //Set backgroundcolor on item 3 LISTVIEW1.GetChildAt(3).SetBackgroundColor(Android.Graphics.Color.Orange); TextView tview = listview.GetChildAt(3).FindViewById&lt;TextView&gt;(Resource.Id.itemtext); tview.SetBackgroundColor(Android.Graphics.Color.Orange);</code></pre> </div> </div> </p> <p>//Code for the Adapter1</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> class Adapter1 : BaseAdapter { Context context; int item = 0; List&lt;String&gt; items = new List&lt;String&gt;(); public Adapter1(Context context, int resource, List&lt;String&gt; itemArray) { items = itemArray; item = resource; this.context = context; } public override Java.Lang.Object GetItem(int position) { return position; } public override long GetItemId(int position) { return position; } public String getItem(int position) { return items[position]; //returns list item at the specified position } public override int GetItemViewType(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { var view = convertView; Adapter1ViewHolder holder = null; if (holder == null) { holder = new Adapter1ViewHolder(); var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast&lt;LayoutInflater&gt;(); view = inflater.Inflate(Resource.Layout.textview, parent, false); String currentItem = getItem(position); //get the TextView for item name and item description TextView textViewItemName = view.FindViewById&lt;TextView&gt;(Resource.Id.itemtext); //sets the text for item name and item description from the current item object textViewItemName.SetText(currentItem, TextView.BufferType.Normal); holder.Title = textViewItemName; holder.Title.Text = currentItem; view.Tag = holder; } return view; } //Fill in cound here, currently 0 public override int Count { get { return items.Count; } } } class Adapter1ViewHolder : Java.Lang.Object { //Your adapter views to re-use public TextView Title { get; set; } }</code></pre> </div> </div> </p>
3
2,155
how do I output the filtered todo list in React TypeScript
<p>It is console logging the right array out all the time, but the point here is that it should be outputting that in the 'TodoList.tsx'. Not sure how to get that fixed in this case. Anyone who could help me with this. To see the bigger picture, please click on this link:</p> <p><a href="https://codesandbox.io/s/github/chiholiu/todo-react-typescript" rel="nofollow noreferrer">Link to codesandbox todo</a></p> <p>I want the returned value from <strong>App.js</strong> currentFilter function pass it to <strong>TodoListItem.js</strong>, so it will update the map function constantly when user clicks on filter buttons. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// TodoFilter import React from 'react'; interface TodoListFilter { currentFilter: CurrentFilter; } export const TodoFilter: React.FC&lt;TodoListFilter&gt; = ({ currentFilter }) =&gt; { return ( &lt;ul&gt; Filter &lt;li onClick={() =&gt; currentFilter('All')}&gt;All&lt;/li&gt; &lt;li onClick={() =&gt; currentFilter('Complete')}&gt;Completed&lt;/li&gt; &lt;li onClick={() =&gt; currentFilter('Incomplete')}&gt;Incompleted&lt;/li&gt; &lt;/ul&gt; ) } // App.js const currentFilter: CurrentFilter = filterTodo =&gt; { let activeFilter = filterTodo; switch (activeFilter) { case 'All': return todos; case 'Complete': return todos.filter(t =&gt; t.complete); case 'Incomplete': return todos.filter(t =&gt; !t.complete); default: console.log('Default'); } } return ( &lt;React.Fragment&gt; &lt;TodoList todos={todos} toggleTodo={toggleTodo} deleteTodo={deleteTodo} editTodo={editTodo} saveEditedTodo={saveEditedTodo} getEditText={getEditText} /&gt; &lt;TodoFilter currentFilter={currentFilter}/&gt; &lt;AddTodoForm addTodo={addTodo}/&gt; &lt;/React.Fragment&gt; ) // TodoListItem import React from 'react'; import { TodoListItem } from "./TodoListItems"; interface TodoListProps { todos: Array&lt;Todo&gt;; toggleTodo: ToggleTodo; deleteTodo: DeleteTodo; editTodo: EditTodo; getEditText: GetEditText; saveEditedTodo: SaveEditedTodo; currentFilter: CurrentFilter; } export const TodoList: React.FC&lt;TodoListProps&gt; = ({ todos, toggleTodo, deleteTodo, editTodo, getEditText, saveEditedTodo, currentFilter }) =&gt; { return ( &lt;ul&gt; {todos.map((todo, i) =&gt; { return &lt;TodoListItem key={i} todo={todo} toggleTodo={toggleTodo} deleteTodo={deleteTodo} editTodo={editTodo} saveEditedTodo={saveEditedTodo} getEditText={getEditText} /&gt; })} &lt;/ul&gt; ) } //Folder structure src -App.tsx -AddTodoForm.tsx -TodoFilter.tsx -TodoList.tsx</code></pre> </div> </div> </p>
3
1,505
Azure DevOps WorkItem Tracking not working when code generated
<p>I have a problem with azure devops workitem tracking. So we want to use WorkItem tracking for work items, that do not need changes in our source code.</p> <p>Currently we are tracking Builds and Releases with C# and the <code>Microsoft.TeamFoundation.WorkItemTracking</code> NuGet packages.</p> <p>The visualization for the build tracking is ok, but the deployments won´t show in the details pane of a ticket.</p> <p>OK</p> <p><img src="https://i.stack.imgur.com/tAlfN.png" alt="Ticket related with code" /></p> <p>Not OK</p> <p><img src="https://i.stack.imgur.com/dhM7c.png" alt="Ticket related with CI/CD" /></p> <p>The relations both in azure devops and as shown in the debugger seem to be the same:</p> <p><img src="https://i.stack.imgur.com/AIpMN.png" alt="Ticket Links from ticket related in code" /></p> <p>This is our patch operation:</p> <pre><code>new JsonPatchOperation() { Operation = Operation.Add, Path = &quot;/relations/-&quot;, Value = new { rel = &quot;ArtifactLink&quot;, url = &quot;vstfs:///ReleaseManagement/ReleaseEnvironment/&quot; + temp.Href.Split('/')[4] + &quot;:&quot;+ release.Id + &quot;:&quot; + environment.Id, attributes = new { authorizedDate = DateTime.Now, //comment = &quot;This build was automatically linked to this work item based on the Tool&quot;, resourceCreatedDate = DateTime.Now, resourceModifiedDate = DateTime.Now, name = &quot;Integrated in release environment&quot;, revisedDate = new DateTime(9999, 1, 1, 0, 0, 0, 0) } } } </code></pre> <p>What should I do, to have the related Release displayed in the details pane of the ticket? I compared every attribute while debugging with a sample ticket I created with CI/CD, every link and relation is OK. Builds are shown, releases not.</p>
3
1,202
Visual Studio Online Build and Release - Copy files to another project
<p>In a solution, I have three projects (for the sake of this example):</p> <h3>- MyWebJob</h3> <h3>- MyFrontendWebsite</h3> <h3>- MyBackendWebsite</h3> <ul> <li>/Views/EmailTemplates/SomeEmailTemplate.cshtml (file in MyBackendWebsite)</li> </ul> <p>When deployed, <strong>MyWebJob</strong> runs as we webjob below <strong>MyFrontendWebsite</strong>.</p> <p>However, it needs the email templates from the <strong>MyBackendWebsite</strong> Emailtemplates folder.</p> <hr /> <p>I think the solution could be...:</p> <ol> <li>Publish the EmailTemplates as an artifact.</li> </ol> <p><a href="https://i.stack.imgur.com/Vbbcc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vbbcc.png" alt="enter image description here" /></a></p> <ol start="2"> <li>During release, copy that artifact to the webjob folder, using a &quot;Copy Files&quot; task.</li> </ol> <p><a href="https://i.stack.imgur.com/l9QUL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l9QUL.png" alt="enter image description here" /></a></p> <p>The problem is, I don't know what to enter in the Target Folder.</p> <p>Using KUDU, I know that the webjob is stored in<br /> D:\home\site\wwwroot\app_data\jobs\continuous\MyWebJob, but setting that as the target folder does not copy anything, despite the release log file telling me it did copy the file to that folder...</p> <pre><code>2017-10-25T15:09:11.7357129Z ##[section]Starting: Copy Files to: D:\home\site\wwwroot\app_data\jobs\continuous\MyWebJob 2017-10-25T15:09:11.7591720Z ============================================================================== 2017-10-25T15:09:11.7591720Z Task : Copy Files 2017-10-25T15:09:11.7591720Z Description : Copy files from source folder to target folder using match patterns (The match patterns will only match file paths, not folder paths) 2017-10-25T15:09:11.7591720Z Version : 2.117.0 2017-10-25T15:09:11.7591720Z Author : Microsoft Corporation 2017-10-25T15:09:11.7591720Z Help : [More Information](https://go.microsoft.com/fwlink/?LinkID=708389) 2017-10-25T15:09:11.7591720Z ============================================================================== 2017-10-25T15:09:14.3013048Z found 1 files 2017-10-25T15:09:14.3013048Z Copying d:\a\r1\a\MyBuildDefinition\EmailTemplates\SomeEmailTemplate.cshtml to D:\home\site\wwwroot\app_data\jobs\continuous\MyWebJob\EmailTemplates\SomeEmailTemplate.cshtml 2017-10-25T15:09:14.3043047Z ##[section]Finishing: Copy Files to: D:\home\site\wwwroot\app_data\jobs\continuous\MyWebJob\EmailTemplates 2017-10-25T15:09:14.3093036Z ##[section]Finishing: Release </code></pre> <p>What am I missing here? How do I copy that email template to where the webjob can get to it?</p> <p>Pre-empting what I myself would have asked...:</p> <p>Q: Why not just put the templates in the webjob project in the first place?</p> <p>A: Because the template is actually used in the MyBackendWebsite as well, to preview emails.</p>
3
1,045
Client not receiving new message sent from Controller after save
<p>I have a project generated with jhipster 3.12.2 and I'm trying to send an Alarm message through websockets from my controller after I have saved it to the db. The RestController can be called from the jhipster frontend (create new entity) or from a mobile application which send HTTP POST.</p> <p>For some reason my client (mobile application generated with ionic and angular) isn't receiving any new messages. What's wrong with my code?</p> <pre><code>@RestController @RequestMapping("/api") public class AlarmResource { private final Logger log = LoggerFactory.getLogger(AlarmResource.class); @Inject private AlarmService alarmService; @Inject SimpMessageSendingOperations messagingTemplate; @PostMapping(value = "/alarms") @Timed @CrossOrigin @Secured({AuthoritiesConstants.ALARM, AuthoritiesConstants.ADMIN, AuthoritiesConstants.EDITOR}) public ResponseEntity&lt;Alarm&gt; createAlarm(@RequestBody Alarm alarm) throws URISyntaxException { log.debug("REST request to save Alarm : {}", alarm); if (alarm.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("alarm", "idexists", "A new alarm cannot already have an ID")).body(null); } if(alarm.getTimestamp_ms() == null) { BigDecimal now = new BigDecimal(System.currentTimeMillis()); alarm.setTimestamp_ms(now); } Alarm result = alarmService.save(alarm); System.out.println("Sending ne alarm message"); String dest = "/topic/alarmactivity"; messagingTemplate.convertAndSend(dest, result); return ResponseEntity.created(new URI("/api/alarms/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert("alarm", result.getId().toString())) .body(result); } </code></pre> <p>AlarmMessageService:</p> <pre><code>@Controller public class AlarmMessageService { private static final Logger log = LoggerFactory.getLogger(AlarmMessageService.class); private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @SubscribeMapping("/topic/alarmactivity") @SendTo("/topic/alarmtracker") public Alarm sendAlarm(@Payload Alarm newAlarm, StompHeaderAccessor stompHeaderAccessor, Principal principal) { log.debug("Sending user tracking data {}", newAlarm); return newAlarm; } } </code></pre> <p>And tracker-service.js in client-side:</p> <pre><code>(function() { 'use strict'; /* globals SockJS, Stomp */ angular .module('exampleApp') .factory('ExAlarmTrackerService', ExAlarmTrackerService); ExAlarmTrackerService.$inject = ['$rootScope', '$window', '$localStorage', '$http', 'API_URL','$q', 'AuthServerProvider', '$stomp']; function ExAlarmTrackerService ($rootScope, $window, $localStorage, $http, API_URL, $q, AuthServerProvider, $stomp) { var stompClient = null; var subscriber = null; var listener = $q.defer(); var connected = $q.defer(); var alreadyConnectedOnce = false; var service = { connect: connect, disconnect: disconnect, receive: receive, sendActivity: sendActivity, subscribe: subscribe, unsubscribe: unsubscribe }; return service; function connect () { //building absolute path so that websocket doesnt fail when deploying with a context path var loc = $window.location; var url = API_URL + 'websocket/tracker'; var authToken = AuthServerProvider.getToken(); if(authToken){ url += '?access_token=' + authToken; } var socket = new SockJS(url); stompClient = Stomp.over(socket); var stateChangeStart; var headers = {}; stompClient.connect(headers, function() { connected.resolve('success'); //sendActivity(); if (!alreadyConnectedOnce) { stateChangeStart = $rootScope.$on('$stateChangeStart', function () { //sendActivity(); console.log("statechange"); }); alreadyConnectedOnce = true; } }); $rootScope.$on('$destroy', function () { if(angular.isDefined(stateChangeStart) &amp;&amp; stateChangeStart !== null){ stateChangeStart(); } }); } function disconnect () { if (stompClient !== null) { stompClient.disconnect(); stompClient = null; } } function receive () { return listener.promise; } function sendActivity() { if (stompClient !== null &amp;&amp; stompClient.connected) { stompClient .send('/topic/activity', {}, angular.toJson({'page': $rootScope.toState.name})); } } function subscribe () { connected.promise.then(function() { subscriber = stompClient.subscribe('/topic/alarmtracker', function(data) { listener.notify(angular.fromJson(data.body)); }); }, null, null); } function unsubscribe () { if (subscriber !== null) { subscriber.unsubscribe(); } listener = $q.defer(); } } })(); </code></pre> <p>And in my controller.js:</p> <pre><code> ExAlarmTrackerService.receive().then(null, null, function(activity) { console.log(activity); }); </code></pre>
3
2,109
Firebase Database Get All Value In Order Cloud Functions
<p>I develop for Firebase Cloud Functions. I have a Firebase Realtime Database like this:</p> <pre><code>----- myData -------eqewrwrepere (this one is a device token) ---------Lta+sde-fer (this one is a firebase id) firstvalue : "a" secondvalue : "b" ----------Qrgd+ad-qdda (this one is second firebase id) firstvalue : "c" secondvalue : "d" -------eqwerSAsdqe (this one is another device token) ---------Lta+sde-fer (this one is a firebase id) firstvalue : "x" secondvalue : "y" ----------Qrgd+ad-qdda (this one is second firebase id) firstvalue : "z" secondvalue : "t" </code></pre> <p>I fetch these data by this code. With this code i fetch all data and put them an array. And when fetching done, i loop this array for finding items. I am an iOS developer, so i am a newbie for NodeJS. Here is what i want to do:</p> <ol> <li>Get <code>firstvalue</code> for each database data.</li> <li>Make a api request with firstvalue of each database data.</li> <li>Api returns an image.</li> <li>Write image temp directory.</li> <li>Process this image for visionApi.</li> <li>Extract text.</li> <li>Update database.</li> <li>Send notification for deviceToken</li> </ol> <p>Now i am able to retrieve database items in my array. When i make a request in for loop, request called async. So for loop continues, but request response or writing file and vision processing executed only once. </p> <p>In for loop, get databasearray[0], make request, write file, process it with vision api, update database and go for next databasearray[1] item.</p> <p>I read about <code>Promises</code> on different pages. But i did not understand.</p> <p>Thank you.</p> <pre><code>'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); var request = require('request'); var fs = require('fs'); //var fs = require("fs"); // Get a reference to the Cloud Vision API component const Vision = require('@google-cloud/vision'); const vision = new Vision.ImageAnnotatorClient(); // Imports the Google Cloud client library //const {Storage} = require('@google-cloud/storage'); var fs = require("fs"); var os = require("os"); var databaseArray = []; exports.hourly_job = functions.pubsub .topic('hourly-job') .onPublish((event) =&gt; { console.log("Hourly Job"); var db = admin.database(); var ref = db.ref("myData") ref.once("value").then(function(allData) { allData.forEach(function(deviceToken) { deviceToken.forEach(function(firebaseIDs) { var deviceTokenVar = deviceToken.key; var firebaseIDVar = firebaseIDs.key; var firstvalue = firebaseIDs.child("firstvalue").val(); var secondvalue = firebaseIDs.child("secondvalue").val(); var items = [deviceTokenVar, firebaseIDVar, firstvalue, secondvalue]; databaseArray.push([...items]); }); }); return databaseArray; }).then(function(databasem) { var i; for (i = 0; i &lt; databaseArray.length; i++) { var databaseArrayDeviceToken = databaseArray[i][0]; console.log("DeviceToken: " + databaseArrayDeviceToken); var databaseArrayFirebaseID = databaseArray[i][1]; console.log("FirebaseID: " + databaseArrayFirebaseID); var databaseArrayfirstvalue = databaseArray[i][2]; console.log("firstval: " + databaseArrayfirstvalue); var databaseArraysecondval = databaseArray[i][3]; console.log("Second: " + databaseArraysecondval); var url = "http://api.blabla" + databaseArrayfirstvalue; /////////////here make a request, pause loop, process returned image, but how ////////////////////// request.get({ url: url, encoding: 'binary' }, function(error, httpResponse, body) { if (!error &amp;&amp; httpResponse.statusCode == 200) { fs.writeFileSync('/tmp/processed.jpg', body, 'binary') console.log("file written"); }) } }); return true; }); </code></pre>
3
2,012
unable to make 2nd circle follow its own path
<p>I am unable to create more circles which follows its own path with drawCircle . </p> <p>I have used the code below which creates another circle but follows the path along the lines of 1st circle but not independent .How do I move both circles independent of each other?</p> <p>I have added </p> <pre><code> c.drawCircle(ballX-100, ballY-100, 50, ballPaintyellow); </code></pre> <p>How do I make the above circle independent from the 1st circle?. I really appreciate any help.Thanks in Advance.</p> <p>BouncingBallActivity.java</p> <pre><code> package com.stuffthathappens.games; import static android.hardware.SensorManager.DATA_X; import static android.hardware.SensorManager.DATA_Y; import static android.hardware.SensorManager.SENSOR_ACCELEROMETER; import static android.hardware.SensorManager.SENSOR_DELAY_GAME; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Vibrator; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.SurfaceHolder.Callback; /** * This activity shows a ball that bounces around. The phone's * accelerometer acts as gravity on the ball. When the ball hits * the edge, it bounces back and triggers the phone vibrator. */ @SuppressWarnings("deprecation") public class BouncingBallActivity extends Activity implements Callback, SensorListener { private static final int BALL_RADIUS =20; private SurfaceView surface; private SurfaceHolder holder; private final BouncingBallModel model = new BouncingBallModel(BALL_RADIUS); private GameLoop gameLoop; private Paint backgroundPaint; private Paint ballPaint; private SensorManager sensorMgr; private long lastSensorUpdate = -1; private Paint ballPaintyellow; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bouncing_ball); surface = (SurfaceView) findViewById(R.id.bouncing_ball_surface); holder = surface.getHolder(); surface.getHolder().addCallback(this); backgroundPaint = new Paint(); backgroundPaint.setColor(Color.WHITE); ballPaint = new Paint(); ballPaint.setColor(Color.BLUE); ballPaint.setAntiAlias(true); ballPaintyellow = new Paint(); ballPaintyellow.setColor(Color.YELLOW); ballPaintyellow.setAntiAlias(true); } @Override protected void onPause() { super.onPause(); model.setVibrator(null); sensorMgr.unregisterListener(this, SENSOR_ACCELEROMETER); sensorMgr = null; model.setAccel(0, 0); } @Override protected void onResume() { super.onResume(); sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); boolean accelSupported = sensorMgr.registerListener(this, SENSOR_ACCELEROMETER, SENSOR_DELAY_GAME); if (!accelSupported) { // on accelerometer on this device sensorMgr.unregisterListener(this, SENSOR_ACCELEROMETER); // TODO show an error } // NOTE 1: you cannot get system services before onCreate() // NOTE 2: AndroidManifest.xml must contain this line: // &lt;uses-permission android:name="android.permission.VIBRATE"/&gt; Vibrator vibrator = (Vibrator) getSystemService(Activity.VIBRATOR_SERVICE); model.setVibrator(vibrator); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { model.setSize(width, height); } public void surfaceCreated(SurfaceHolder holder) { gameLoop = new GameLoop(); gameLoop.start(); } private void draw() { // thread safety - the SurfaceView could go away while we are drawing Canvas c = null; try { // NOTE: in the LunarLander they don't have any synchronization here, // so I guess this is OK. It will return null if the holder is not ready c = holder.lockCanvas(); // this needs to synchronize on something if (c != null) { doDraw(c); } } finally { if (c != null) { holder.unlockCanvasAndPost(c); } } } private void doDraw(Canvas c) { int width = c.getWidth(); int height = c.getHeight(); c.drawRect(0, 0, width, height, backgroundPaint); float ballX, ballY; synchronized (model.LOCK) { ballX = model.ballPixelX; ballY = model.ballPixelY; } c.drawCircle(ballX, ballY, BALL_RADIUS, ballPaint); c.drawCircle(ballX-100, ballY-100, 50, ballPaintyellow); } public void surfaceDestroyed(SurfaceHolder holder) { try { model.setSize(0,0); gameLoop.safeStop(); } finally { gameLoop = null; } } private class GameLoop extends Thread { private volatile boolean running = true; public void run() { while (running) { try { // don't like this hardcoding TimeUnit.MILLISECONDS.sleep(5); draw(); model.updatePhysics(); } catch (InterruptedException ie) { running = false; } } } public void safeStop() { running = false; interrupt(); } } public void onAccuracyChanged(int sensor, int accuracy) { } public void onSensorChanged(int sensor, float[] values) { if (sensor == SENSOR_ACCELEROMETER) { long curTime = System.currentTimeMillis(); // only allow one update every 50ms, otherwise updates // come way too fast if (lastSensorUpdate == -1 || (curTime - lastSensorUpdate) &gt; 50) { lastSensorUpdate = curTime; model.setAccel(values[DATA_X], values[DATA_Y]); } } } } </code></pre> <p>Bouncingballmodel.java</p> <pre><code>package com.stuffthathappens.games; import java.util.concurrent.atomic.AtomicReference; import android.os.Vibrator; /** * This data model tracks the width and height of the playing field along * with the current position of a ball. */ public class BouncingBallModel { // the ball speed is meters / second. When we draw to the screen, // 1 pixel represents 1 meter. That ends up too slow, so multiply // by this number. Bigger numbers speeds things up. private final float pixelsPerMeter = 10; private final int ballRadius; // these are public, so make sure you synchronize on LOCK // when reading these. I made them public since you need to // get both X and Y in pairs, and this is more efficient than // getter methods. With two getters, you'd still need to // synchronize. public float ballPixelX, ballPixelY; private int pixelWidth, pixelHeight; // values are in meters/second private float velocityX, velocityY; // typical values range from -10...10, but could be higher or lower if // the user moves the phone rapidly private float accelX, accelY; /** * When the ball hits an edge, multiply the velocity by the rebound. * A value of 1.0 means the ball bounces with 100% efficiency. Lower * numbers simulate balls that don't bounce very much. */ private static final float rebound = 0.8f; // if the ball bounces and the velocity is less than this constant, // stop bouncing. private static final float STOP_BOUNCING_VELOCITY = 2f; private volatile long lastTimeMs = -1; public final Object LOCK = new Object(); private AtomicReference&lt;Vibrator&gt; vibratorRef = new AtomicReference&lt;Vibrator&gt;(); public BouncingBallModel(int ballRadius) { this.ballRadius = ballRadius; } public void setAccel(float ax, float ay) { synchronized (LOCK) { this.accelX = ax; this.accelY = ay; } } public void setSize(int width, int height) { synchronized (LOCK) { this.pixelWidth = width; this.pixelHeight = height; } } public int getBallRadius() { return ballRadius; } /** * Call this to move the ball to a particular location on the screen. This * resets the velocity to zero, but the acceleration doesn't change so * the ball should start falling shortly. */ public void moveBall(int ballX, int ballY) { synchronized (LOCK) { this.ballPixelX = ballX; this.ballPixelY = ballY; velocityX = 0; velocityY = 0; } } public void updatePhysics() { // copy everything to local vars (hence the 'l' prefix) float lWidth, lHeight, lBallX, lBallY, lAx, lAy, lVx, lVy; synchronized (LOCK) { lWidth = pixelWidth; lHeight = pixelHeight; lBallX = ballPixelX; lBallY = ballPixelY; lVx = velocityX; lVy = velocityY; lAx = accelX; lAy = -accelY; } if (lWidth &lt;= 0 || lHeight &lt;= 0) { // invalid width and height, nothing to do until the GUI comes up return; } long curTime = System.currentTimeMillis(); if (lastTimeMs &lt; 0) { lastTimeMs = curTime; return; } long elapsedMs = curTime - lastTimeMs; lastTimeMs = curTime; // update the velocity // (divide by 1000 to convert ms to seconds) // end result is meters / second lVx += ((elapsedMs * lAx) / 1000) * pixelsPerMeter; lVy += ((elapsedMs * lAy) / 1000) * pixelsPerMeter; // update the position // (velocity is meters/sec, so divide by 1000 again) lBallX += ((lVx * elapsedMs) / 1000) * pixelsPerMeter; lBallY += ((lVy * elapsedMs) / 1000) * pixelsPerMeter; boolean bouncedX = false; boolean bouncedY = false; if (lBallY - ballRadius &lt; 0) { lBallY = ballRadius; lVy = -lVy * rebound; bouncedY = true; } else if (lBallY + ballRadius &gt; lHeight) { lBallY = lHeight - ballRadius; lVy = -lVy * rebound; bouncedY = true; } if (bouncedY &amp;&amp; Math.abs(lVy) &lt; STOP_BOUNCING_VELOCITY) { lVy = 0; bouncedY = false; } if (lBallX - ballRadius &lt; 0) { lBallX = ballRadius; lVx = -lVx * rebound; bouncedX = true; } else if (lBallX + ballRadius &gt; lWidth) { lBallX = lWidth - ballRadius; lVx = -lVx * rebound; bouncedX = true; } if (bouncedX &amp;&amp; Math.abs(lVx) &lt; STOP_BOUNCING_VELOCITY) { lVx = 0; bouncedX = false; } // safely copy local vars back to object fields synchronized (LOCK) { ballPixelX = lBallX; ballPixelY = lBallY; velocityX = lVx; velocityY = lVy; } if (bouncedX || bouncedY) { Vibrator v = vibratorRef.get(); if (v != null) { v.vibrate(20L); } } } public void setVibrator(Vibrator v) { vibratorRef.set(v); } } </code></pre>
3
5,721
How to protect spammers to apache?
<p>I have the following for <code>www.domain.com</code> and <code>login.domain.com</code>. But spammers forward there site to <code>login.domain.com</code> and it works. How can I block them?</p> <p>Ex: <code>http://spammerexmaple.sex.com</code> opens <code>http://login.domain.com</code> (I want to block this)</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName login.domain.com ServerAlias login.domain.com DocumentRoot /var/www/html/com/public &lt;Directory /var/www/html/com/public&gt; #AddDefaultCharset utf-8 DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:80&gt; ServerName www.domain.com ServerAlias domain.com DocumentRoot /var/www/html/www/public &lt;Directory /var/www/html/www/public&gt; # Compress output AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4.0[678] no-gzip BrowserMatch bMSIE !no-gzip !gzip-only-text/html #AddDefaultCharset utf-8 DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p><strong>Follow up:</strong></p> <p>Spammers forward <code>www.spammer.com</code> to <code>login.domain.com</code> or <code>www.spammer.sex.com</code> anything someone can forward to <code>login.domain.com</code> and it works.</p> <p>How can I block this?</p> <pre><code>[root@d dd.dd.com]# httpd -S VirtualHost configuration: wildcard NameVirtualHosts and _default_ servers: _default_:443 d (/etc/httpd/conf.d/ssl.conf:81) *:80 is a NameVirtualHost default server dummy.com (/etc/httpd/conf/httpd.conf:1028) port 80 namevhost dummy.com (/etc/httpd/conf/httpd.conf:1028) port 80 namevhost dd.dd.com (/etc/httpd/conf/httpd.conf:1039) port 80 namevhost aa.aa.com (/etc/httpd/conf/httpd.conf:1058) Syntax OK &lt;VirtualHost *:80&gt; ServerName dummy.com DocumentRoot /tmp &lt;Directory /tmp&gt; deny from all &lt;/Directory&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:80&gt; ServerName dd.dd.com #ServerAlias dd.dd.com DocumentRoot /var/www/html/dd.dd.com/public &lt;Directory /var/www/html/dd.dd.com/public&gt; #AddDefaultCharset utf-8 DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:80&gt; ServerName aa.aa.com ServerAlias aa.com DocumentRoot /var/www/html/aa.aa.com/public &lt;Directory /var/www/html/aa.aa.com/public&gt; # Compress output AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4.0[678] no-gzip BrowserMatch bMSIE !no-gzip !gzip-only-text/html #AddDefaultCharset utf-8 DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all &lt;/Directory&gt; </code></pre>
3
1,328
onNextStep is not a function, functional components
<p>I have a parent component with the state which is number, and I'm passing state to RegistrationForm component and <code>setActiveForm</code> to StepperComponent. In the stepper Component, there is a button on which click it should change state. But I'm getting 'onNextStep is not a function'</p> <p>Parent component:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useState } from 'react' import { Box, Divider, Flex } from '@chakra-ui/react' import Logo from 'components/navigation/Logo' import Footer from 'components/footer/Footer' import RegistrationForm from 'components/forms/RegistrationForm' import StepperComponent from 'components/stepper/StepperComponent' import Section from 'components/section/Section' import { SubTitle, Title } from 'components/UI' import SuccessRegistration from 'components/forms/SuccessRegistration' const RegisterPage = () =&gt; { const [activeForm, setActiveForm] = useState&lt;number&gt;(0) return ( &lt;&gt; &lt;Box maxWidth="1450px" px={['16px', '43px', '83px']} mx="auto"&gt; &lt;Logo /&gt; &lt;/Box&gt; &lt;Section pt="23px"&gt; &lt;Box maxWidth="580px" ml={['0', '0', '200px']} mb="25px"&gt; &lt;Title value="React Week 2021- Event Registraton Form" mb="8px" /&gt; &lt;SubTitle value="React Week talks, classes and workshops will feature advanced topics aimed for junior and medior software developers, and consultants." fontSize="16px" /&gt; &lt;/Box&gt; &lt;Divider d={['none', 'none', 'none', 'block', 'block']} /&gt; &lt;Flex flexDirection={['column', 'column', 'row', 'row']}&gt; &lt;StepperComponent onNextStep={setActiveForm} /&gt; &lt;Box&gt; &lt;Divider orientation="vertical" d={['none', 'none', 'none', 'block', 'block']} /&gt; &lt;/Box&gt; &lt;RegistrationForm activeForm={activeForm} /&gt; &lt;/Flex&gt; &lt;/Section&gt; &lt;Footer /&gt; &lt;/&gt; ) } export default RegisterPage</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>RegistrationForm component:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react' import { Box } from '@chakra-ui/react' import PersonalInfoForm from './PersonalInfoForm' import TicketOptionForm from './TicketOptionForm' import AdditionalInfoForm from './AdditionalInfoForm' import FormContainer from './FormContainer' import SuccessRegistration from './SuccessRegistration' interface Props { activeForm: number } const RegistrationForm = ({ activeForm }: Props) =&gt; { const forms = [&lt;PersonalInfoForm /&gt;, &lt;TicketOptionForm /&gt;, &lt;AdditionalInfoForm /&gt;] return &lt;FormContainer&gt;{forms[activeForm]}&lt;/FormContainer&gt; } export default RegistrationForm</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Stepper component:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useEffect } from 'react' import { Box, Button } from '@chakra-ui/react' import { Step, Steps, useSteps } from 'chakra-ui-steps' interface Props { onNextStep: React.Dispatch&lt;React.SetStateAction&lt;number&gt;&gt; } const steps = [ { label: 'Step 1', description: 'Personal Info', }, { label: 'Step 2', description: 'Ticket Options', }, { label: 'Step 3', description: 'Additional Info', }, ] const StepperComponent = ({ onNextStep }: Props) =&gt; { const { nextStep, prevStep, reset, activeStep } = useSteps({ initialStep: 0, }) useEffect(() =&gt; { onNextStep(activeStep) }, [activeStep]) return ( &lt;Box w={['100%', '200px']} mt={['12px', '43px']}&gt; &lt;Steps activeStep={activeStep} orientation="vertical" colorScheme="blue" textAlign="center"&gt; {steps.map(({ label, description }) =&gt; ( &lt;Step label={label} description={description} key={label}&gt;&lt;/Step&gt; ))} &lt;/Steps&gt; &lt;Button onClick={nextStep}&gt;NextStep&lt;/Button&gt; &lt;/Box&gt; ) } export default StepperComponent</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
3
2,474
Draggable text box scales more than expected
<p>I made a text box and boxes on the corners for resizing. The first time I drag, it works perfectly fine, but after the 1st time, the dragging amount seems to multiply. (Don't mind the position of the dragging nodes). If you drag once, it scales fine with the mouse. It seems as if every time after that, when you drag, it scales farther and farther from the user's mouse, causing an 'uncontrollable' scale. I reset the values of the prevX and prevY values at the end of the move function. I'm not sure if that's the issue though. The issue, I believe, is with the scaling with getBoundingClientRect() in the resize portion. Moving the textbox, however, works perfectly fine. Here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var textBox = document.querySelector(".text-box"); var textArea = document.querySelector('.text-field'); textArea.focused = false; textBox.addEventListener('mousedown', mousedown); let isResizing = false; let isTyping = false; textArea.addEventListener('dblclick', type) function type(){ if (!isTyping){ isTyping = true; textArea.style.cursor = 'text'; }else { isTyping = false; textArea.style.cursor = 'default'; } } document.body.onclick = function(e){ if (e.target != textArea){ isTyping = false; e.target.style.cursor = 'default'; } } function mousedown(e){ if (e.target == textArea){ e.target.style.cursor = 'default'; } window.addEventListener('mousemove', mousemove); window.addEventListener('mouseup', mouseup); let prevX = e.clientX; let prevY = e.clientY; function mousemove(e){ if(!isResizing &amp;&amp; !isTyping){ let newX = prevX - e.clientX; let newY = prevY - e.clientY; const rect = textBox.getBoundingClientRect(); textBox.style.left = rect.left - newX + "px"; textBox.style.top = rect.top - newY + "px"; prevX = e.clientX; prevY = e.clientY; } } function mouseup(){ window.removeEventListener('mousemove', mousemove); window.removeEventListener('mouseup', mouseup); } const handles = document.querySelectorAll('.handle'); let currentHandle; for(let handle of handles){ handle.addEventListener('mousedown', mousedown); function mousedown(e){ currentHandle = e.target; isResizing = true; let prevX = e.clientX; let prevY = e.clientY; window.addEventListener('mousemove', mousemove); window.addEventListener('mouseup', mouseup); function mousemove(e){ const rect = textBox.getBoundingClientRect(); if (currentHandle.classList.contains("se")) { textBox.style.width = rect.width - (prevX - e.clientX) + "px"; textBox.style.height = rect.height - (prevY - e.clientY) + "px"; } else if (currentHandle.classList.contains("sw")) { textBox.style.width = rect.width + (prevX - e.clientX) + "px"; textBox.style.height = rect.height - (prevY - e.clientY) + "px"; textBox.style.left = rect.left - (prevX - e.clientX) + "px"; } else if (currentHandle.classList.contains("ne")) { textBox.style.width = rect.width - (prevX - e.clientX) + "px"; textBox.style.height = rect.height + (prevY - e.clientY) + "px"; textBox.style.top = rect.top - (prevY - e.clientY) + "px"; } else { textBox.style.width = rect.width + (prevX - e.clientX) + "px"; textBox.style.height = rect.height + (prevY - e.clientY) + "px"; textBox.style.top = rect.top - (prevY - e.clientY) + "px"; textBox.style.left = rect.left - (prevX - e.clientX) + "px"; } prevX = e.clientX; prevY = e.clientY; } function mouseup(){ window.removeEventListener('mousemove', mousemove); window.removeEventListener('mouseup', mouseup); textArea.focused = false; isResizing = false; } } } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.text-box{ height: 50px; width: 150px; position: absolute; } .handle{ position: absolute; width: 5px; height: 5px; background-color: blue; z-index: 2; } .ne{ top: -1px; right: -1px; cursor: ne-resize; } .nw{ top: -1px; left: -1px; cursor: nw-resize; } .sw{ bottom: -1px; left: -1px; cursor: sw-resize; } .se{ bottom: -1px; right: -1px; cursor: se-resize; } .text-field { width: 100%; height: 100%; resize: none; cursor: default; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="text-box"&gt; &lt;textarea class="text-field"&gt;Click to add text...&lt;/textarea&gt; &lt;div class="handle ne"&gt;&lt;/div&gt; &lt;div class="handle nw"&gt;&lt;/div&gt; &lt;div class="handle sw"&gt;&lt;/div&gt; &lt;div class="handle se"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
3,765
Prevent related records being updated in Entity Framework
<p>I have an entity (Skill) which has a relationship to another entity (Game):</p> <pre><code> public class Skill { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] public Guid Id { get; set; } public virtual Game Game { get; set; } public virtual IdentityUser TeamMember { get; set; } public int SkillPoints1 { get; set; } public int SkillPoints2 { get; set; } public int SkillPoints3 { get; set; } public int SkillPoints4 { get; set; } public int SkillPoints5 { get; set; } public bool Spectator { get; set; } public Skillset SelectedSkillNumber { get; set; } } </code></pre> <p>The Game entity also has related entities:</p> <pre><code> public class Game { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] public Guid Id { get; set; } public string GameTitle { set; get; } public DateTime Created { get; set; } public GameState GameState { get; set; } public virtual Team GameTeamMembers { get; set; } public virtual IdentityUser GameOwner { get; set; } public virtual ICollection&lt;Backlog&gt; ProductBacklog { get; set; } </code></pre> <p>At some point, I'm loading in the &quot;Skills&quot; for a particular Game, so I have to include the game record in order to return the Skill records:</p> <pre><code>List&lt;Skill&gt; allSkillsets = _context.Skills.Include(x =&gt; x.Game).Where(x =&gt; x.Game.Id == gameId).Include(x =&gt; x.TeamMember).ToList(); </code></pre> <p>However, when I'm looping through these records to update some of the properties, EF tries to update the &quot;Game&quot; record as well:</p> <pre><code> foreach (Skill player in allSkillsets) { try { player.SkillPoints1 = player.SelectedSkillNumber == Skillset.Skill1 ? 5 : boost_skillset1_by + 1; player.SkillPoints2 = player.SelectedSkillNumber == Skillset.Skill2 ? 5 : boost_skillset2_by + 1; player.SkillPoints3 = player.SelectedSkillNumber == Skillset.Skill3 ? 5 : boost_skillset3_by + 1; player.SkillPoints4 = player.SelectedSkillNumber == Skillset.Skill4 ? 5 : boost_skillset4_by + 1; player.SkillPoints5 = player.SelectedSkillNumber == Skillset.Skill5 ? 5 : boost_skillset5_by + 1; //_context.Entry(player.Game).State = EntityState.Detached; _context.Entry(player.Game).State = EntityState.Unchanged; _context.Skills.Attach(player); _context.Entry(player).Property(x =&gt; x.SkillPoints1).IsModified = true; _context.Entry(player).Property(x =&gt; x.SkillPoints2).IsModified = true; _context.Entry(player).Property(x =&gt; x.SkillPoints3).IsModified = true; _context.Entry(player).Property(x =&gt; x.SkillPoints4).IsModified = true; _context.Entry(player).Property(x =&gt; x.SkillPoints5).IsModified = true; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { _logger.LogErrorWithObject(&quot;Could not write backlog item to database&quot;, &quot;UpdatePlayerSkills&quot;, player); throw; } </code></pre> <p>Because the &quot;Game&quot; entity doesn't have all of it's related entities loaded in (e.g. ProductBacklog), the update wipes out all of these records. Is there a way I can just update the 5 properties in the Skill record, without also updating it's related Game record?</p> <p>I've also tried setting Game to null, but then this removes the Id in the foreign key column</p>
3
1,443
Grid items are off center
<p>Whenever I resize the browser to max, everything works but the cards in the packages section aren't center. What am I missing?</p> <p><a href="https://jolly-poitras-00d5ec.netlify.app/" rel="nofollow noreferrer">https://jolly-poitras-00d5ec.netlify.app/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Packages */ .packages { background-color: #F3F1F6; text-align: center; font-family: 'Roboto', sans-serif; padding: 50px 0; } .packages-title h4 { font-weight: 300; opacity: 50%; } .packages-title h2 { font-size: 2em; } .packages-cards h1 { font-family: 'Lato'; font-size: 4em; padding: 10px 0 20px; } .packages-cards div { background-color: #fff; margin: 50px auto; padding: 50px 0; max-width: 350px; -webkit-box-shadow: 0px 0px 15px 2px rgba(0, 0, 0, 0.15); box-shadow: 0px 0px 15px 2px rgba(0, 0, 0, 0.15); } .packages-cards h4 { font-weight: 300; opacity: 50%; } .packages-cards p { font-weight: 300; opacity: 50%; line-height: 2; padding-bottom: 20px; } @media(min-width: 996px) { .container { margin: 0 10%; } .showcase { background-image: url('imgs/cityline.jpg'); } .showcase-content h1 { font-size: 2.5em; } .showcase-content p { margin: 20px 0 45px 0; } .about-cards { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 60px; } .about-cards div { max-width: 300px; } .packages-cards { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 30px; } .packages-cards div { margin: 50px 0; max-width: 300px; } .sign-up { background-image: url('imgs/signup-1200.jpg'); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section class="packages"&gt; &lt;div class="packages-title"&gt; &lt;h4&gt;A plan for everyone&lt;/h4&gt; &lt;h2&gt;Plans &amp;amp; Pricing&lt;/h2&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="packages-cards"&gt; &lt;div class="basic"&gt; &lt;h4&gt;Basic Plan&lt;/h4&gt; &lt;h1&gt;$49&lt;/h1&gt; &lt;p&gt; Up to 1000 Mbps up &amp;amp; down &lt;br&gt; Lowest ping times &lt;br&gt; No setup fees &lt;br&gt; No data cap &lt;br&gt; No contract &lt;br&gt; 24/7 support &lt;/p&gt; &lt;button class="btn"&gt;Sign Up&lt;/button&gt; &lt;/div&gt; &lt;div class="plus"&gt; &lt;h4&gt;Plus Plan&lt;/h4&gt; &lt;h1&gt;$79&lt;/h1&gt; &lt;p&gt; Up to 1000 Mbps up &amp;amp; down &lt;br&gt; Lowest ping times &lt;br&gt; No setup fees &lt;br&gt; No data cap &lt;br&gt; No contract &lt;br&gt; 24/7 support &lt;/p&gt; &lt;button class="btn"&gt;Sign Up&lt;/button&gt; &lt;/div&gt; &lt;div class="pro"&gt; &lt;h4&gt;Pro Plan&lt;/h4&gt; &lt;h1&gt;$99&lt;/h1&gt; &lt;p&gt; Up to 1000 Mbps up &amp;amp; down &lt;br&gt; Lowest ping times &lt;br&gt; No setup fees &lt;br&gt; No data cap &lt;br&gt; No contract &lt;br&gt; 24/7 support &lt;/p&gt; &lt;button class="btn"&gt;Sign Up&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
3
1,615
How to make a selector of extended state from a entity feature inside ngrx?
<p><strong>Problem:</strong> This selector <code>entity.selectAll</code> will not include the extended state.</p> <h2><strong>Question:</strong></h2> <p><strong>How do I include my extend state inside selectAll OR how can I create a custom selector for my selected state?</strong></p> <p>My UxeGallery Model is: </p> <pre><code>export interface UxeGallery { id: string; imgSrc: string; name: string; details?: string; } </code></pre> <p>Here I have my EntityState and I have added some state to it:</p> <pre><code>export interface State extends EntityState&lt;UxeGallery&gt; { selectedItem: string | null; hiddenItem: string | null; bottombarTemplate: boolean; topbarTemplate: boolean; topbarTemplateType: string; modalTemplate: boolean; canvasTemplate: boolean; canvasImg: string | null; } </code></pre> <p>I create the adapter:</p> <pre><code>export const adapter: EntityAdapter&lt;UxeGallery&gt; = createEntityAdapter&lt;UxeGallery&gt;(); </code></pre> <p>Set the init state:</p> <pre><code>export const initialState: State = adapter.getInitialState({ ids: ['0'], entities: { '0': { imgSrc: 'url', name: 'dog', details: 'some dog', } }, selectedItem: null, hiddenItem: null, topbarTemplateType: TopbarType.WHITE, topbarTemplate: false, bottombarTemplate: false, modalTemplate: false, canvasTemplate: false, canvasImg: null, }); </code></pre> <p>Create my featureSelector:</p> <pre><code>export const getState = createFeatureSelector&lt;any&gt;('uxeGallery'); </code></pre> <p>Export adapter selectors:</p> <pre><code>export const { selectIds, selectEntities, selectAll, selectTotal, } = adapter.getSelectors(getState); </code></pre> <p>From my app component I selectAll from my entity:</p> <pre><code>import * as fromUxeGallery from '../../reducers/uxe-gallery.reducer'; import { UxeGallery } from '../../uxe-gallery.model'; export class UxeGalleryMasterComponent implements OnInit { private obs: Observable&lt;UxeGallery[]&gt;; private obsExtended: Observable&lt;any&gt;; constructor(private store: Store&lt;fromUxeGallery.State&gt;) { } ngOnInit() { this.obs = this.store.pipe(select(fromUxeGallery.selectAll)); this.obs.subscribe(console.log); /** This will return [ { details:"some dog", imgSrc:"url", name:"dog" } ] */ } } </code></pre> <p><strong>How can I make a selector that will grab the extended state from my Entity model?</strong></p> <p>e.g</p> <pre><code> selectedItem: null, hiddenItem: null, topbarTemplateType: TopbarType.WHITE, topbarTemplate: false, bottombarTemplate: false, modalTemplate: false, canvasTemplate: false, canvasImg: null, </code></pre> <p>UPDATE:</p> <p>I added this:</p> <pre><code>export const getState = createFeatureSelector&lt;any&gt;('uxeGallery'); export const selectFeatureExtended = createSelector(getState, (state: State) =&gt; { return { selectedItem: state.selectedItem, hiddenItem: state.hiddenItem, bottombarTemplate: state.bottombarTemplate, topbarTemplate: state.topbarTemplate, topbarTemplateType: state.topbarTemplateType, modalTemplate: state.modalTemplate, canvasTemplate: state.canvasTemplate, canvasImg: state.canvasImg, }; }); </code></pre> <p>It feels pretty verbose but if theres no other solution it works as intended :(</p>
3
1,259
How to avoid reading data from R environment within Rcpp function
<p>Even though <code>MyCppFunction(NumericVector x)</code> returns the desired output, I am not sure of a proper/efficient way to avoid reading the data on variable <code>myY</code> withou passing it as a function argument.</p> <p>The reason I do not pass the data as an argument is that I will eventually pass the C++ function as an objective function to minimize and the minimization routine accepts a function of one argument only, namely <code>myX</code>. <s>Just as an example: in R, I would pass <code>myY</code> to <code>optim(...)</code> in the following way : <code>optim(par,fn=MyRFunction,y=myY)</code>.</s></p> <p>Any advice on how to properly access <code>myY</code> from within the C++ function is appreciated, here's a minimal example of what I am afraid is a really wrong way to do it:</p> <p><strong>Update</strong> : I've modified the code to better reflect the context as well as what has been proposed in the answers. Just in case, the focus of my question lies on this line : <code>NumericVector y = env["myY"]; // How to avoid this?</code></p> <pre><code>#include &lt;Rcpp.h&gt; using namespace Rcpp; // [[Rcpp::export]] double MyCppFunction(NumericVector x) { Environment env = Environment::global_env(); NumericVector y = env["myY"]; // How to avoid this? double res = 0; for (int i = 0; i &lt; x.size(); i++) res = res + (x(i) * y(i)); return res; } double MyCppFunctionNoExport(NumericVector x) { Environment env = Environment::global_env(); NumericVector y = env["myY"]; // How to avoid this? double res = 0; for (int i = 0; i &lt; x.size(); i++) res = res + (x(i) * y(i)); return res; } // [[Rcpp::export]] double MyCppFunction2(NumericVector x, NumericVector y) { double res = 0; for (int i = 0; i &lt; x.size(); i++) res = res + (x(i) * y(i)); return res; } // [[Rcpp::export]] double MyRoutine(NumericVector x, Function fn) { for (int i = 0; i &lt; x.size(); i++) fn(x); return 0; } // [[Rcpp::export]] double MyRoutineNoExport(NumericVector x) { for (int i = 0; i &lt; x.size(); i++) MyCppFunctionNoExport(x); return 0; } /*** R MyRFunction &lt;- function(x, y=myY) { res = 0 for(i in 1:length(x)) res = res + (x[i]*y[i]) return (res) } callMyCppFunction2 &lt;- function(x) { MyCppFunction2(x, myY) } set.seed(123456) myY = rnorm(1e3) myX = rnorm(1e3) all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX)) require(rbenchmark) benchmark(MyRoutine(myX, fn=MyCppFunction), MyRoutine(myX, fn=MyRFunction), MyRoutine(myX, fn=callMyCppFunction2), MyRoutineNoExport(myX), order="relative")[, 1:4] */ </code></pre> <p><strong>Output</strong>:</p> <blockquote> <pre><code>$ Rscript -e 'Rcpp::sourceCpp("stack.cpp")' &gt; MyRFunction &lt;- function(x, y = myY) { + res = 0 + for (i in 1:length(x)) res = res + (x[i] * y[i]) + return(res) + } &gt; callMyCppFunction2 &lt;- function(x) { + MyCppFunction2(x, myY) + } &gt; set.seed(123456) &gt; myY = rnorm(1000) &gt; myX = rnorm(1000) &gt; all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX)) [1] TRUE &gt; require(rbenchmark) Loading required package: rbenchmark &gt; benchmark(MyRoutine(myX, fn = MyCppFunction), MyRoutine(myX, + fn = MyRFunction), MyRoutine(myX, fn = callMyCppFunction2), + MyRoutineNoEx .... [TRUNCATED] test replications elapsed relative 4 MyRoutineNoExport(myX) 100 1.692 1.000 1 MyRoutine(myX, fn = MyCppFunction) 100 3.047 1.801 3 MyRoutine(myX, fn = callMyCppFunction2) 100 3.454 2.041 2 MyRoutine(myX, fn = MyRFunction) 100 8.277 4.892 </code></pre> </blockquote>
3
1,548
Cascading drop down list (SubLocality) not working in asp.net mvc
<p><strong>I have three dropdown List.The First action method for City drop down is as---</strong></p> <pre><code> public ActionResult Create() { List&lt;SelectListItem&gt; li = new List&lt;SelectListItem&gt;(); li.Add(new SelectListItem { Text = "Select your City", Value = "----" }); li.Add(new SelectListItem { Text = "Faridabaad", Value = "Faridabaad" }); li.Add(new SelectListItem { Text = "Greater Noida", Value = "Greater Noida" }); li.Add(new SelectListItem { Text = "Gurgaon", Value = "Gurgaon" }); li.Add(new SelectListItem { Text = "Noida", Value = "Noida" }); li.Add(new SelectListItem { Text = "New Delhi", Value = "New Delhi" }); ViewData["City"] = li; return View(); } </code></pre> <p><strong>then i have action method for my Locality drop down list which changes as we change city name like this------</strong></p> <pre><code> public JsonResult LoadLocalities(string id) { List&lt;SelectListItem&gt; localities = new List&lt;SelectListItem&gt;(); switch(id) { case"New Delhi": localities.Add(new SelectListItem { Text = "Select your locality", Value = "0" }); localities.Add(new SelectListItem{ Text ="East Delhi", Value = "1" }); localities.Add(new SelectListItem{ Text ="West Delhi", Value = "2" }); localities.Add(new SelectListItem{ Text ="North Delhi", Value = "3" }); localities.Add(new SelectListItem { Text = "South Delhi", Value = "4" }); break; } return Json(new SelectList(localities, "Value", "Text")); } </code></pre> <p><strong>and the action method for the last sub locality drop down which changes with the change in locality name is like this---</strong></p> <pre><code> public JsonResult LoadSubLocalities(string id) { List&lt;SelectListItem&gt; sublocalities = new List&lt;SelectListItem&gt;(); switch (id) { case"1": sublocalities.Add(new SelectListItem { Text = "Select your sublocality", Value = "0" }); sublocalities.Add(new SelectListItem { Text = "Region1", Value = "1" }); sublocalities.Add(new SelectListItem { Text = "Region2", Value = "2" }); break; } return Json(new SelectList(sublocalities, "Value", "Text")); } </code></pre> <p><strong>now the view page is something like this------</strong></p> <pre><code> &lt;!DOCTYPE html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;script src="~/Scripts/jquery-2.1.4.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery.unobtrusive-ajax.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="map_canvas" style="width: 800px; height: 700px; float:left"&gt;&lt;/div&gt; @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) &lt;fieldset&gt; &lt;legend&gt;Enter the Project Details&lt;/legend&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.City) &lt;/div&gt; &lt;div class="editor-field"&gt; @if (ViewData.ContainsKey("City")){ @Html.DropDownListFor(model =&gt; model.City, ViewData["City"] as List&lt;SelectListItem&gt;, new { style = "width:250px", @class = "DropDown1"}) @Html.ValidationMessageFor(model =&gt; model.City) } &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Locality) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.DropDownList("Locality", new SelectList(string.Empty,"Value","Text"),"Please Select a locality", new { style = "width:250px", @class = "DropDown1" }) @Html.ValidationMessageFor(model =&gt; model.Locality) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.SubLocality) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.DropDownList("SubLocality", new SelectList(string.Empty, "Value", "Text"), "Please Select a sub locality", new { style = "width:250px", @class = "DropDown1" }) @Html.ValidationMessageFor(model =&gt; model.SubLocality) &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Save Project" /&gt; &lt;/p&gt; &lt;/fieldset&gt; </code></pre> <p><strong>Now my javaScript code is something like this where i have written code to fetch city from controller then change locality as the city name changes and change sub locality name with change in locality name-----</strong></p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function () { $("#City").change(function () { $("#Locality").empty(); $.ajax({ type: 'POST', url: '@Url.Action("LoadLocalities","Project")', dataType: 'json', data: { id: $("#City").val() }, success: function (localities) { $.each(localities, function (i, locality) { $("#Locality").append('&lt;option value="' + locality.Value + '"&gt;' + locality.Text + '&lt;/option&gt;'); }); }, error: function (ex) { alert('Failed to retreive Locality.' + ex); } }); return false; }) $("#Locality").change(function () { $("#SubLocality").empty(); $.ajax({ type: 'POST', url: '@Url.Action("LoadSubLocalities")', dataType: 'Json', data: { id: $("Locality").val() }, success: function (sublocalities) { $.each(sublocalities, function (i, sublocality) { $("#SubLocality").append('&lt;option value="' + sublocality.Value + '"&gt;' + sublocality.Text + '&lt;/option&gt;'); }); }, error: function (ex) { alert('Failed to retrieve SubLocality.' + ex); } }); return false; }) }); &lt;/script&gt; } </code></pre> <p><strong>Now, My problem is that my Locality is working fine with change in city name but SubLocality drop down is not working with change in locality name---</strong></p>
3
3,304
Accessing the value of query returning list in controller
<p>Here is my schedule class</p> <pre><code>[Table("Schedules", Schema = "Expedia")] public class Schedule { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ScheduleId { get; set; } [ForeignKey("Inventory")] public int FlightId { get; set; } public FlightInventory Inventory { get; set; } [Display(Name = "Departure city")] public string DepartureCity { get; set; } [Display(Name = "Arrival city")] public string DestiationCity { get; set; } [Display(Name = "Departure date")] [Required] public string DepartureDate { get; set; } [Required] [Display(Name = "Arrival date")] public string ArrivalDate { get; set; } [Required] [Display(Name = "Departure Time")] public string Departure { get; set; } [Required] [Display(Name = "Arrival Time")] public string Arrival { get; set; } [Display(Name = "Price/Ticket")] public int Price { get; set; } } } </code></pre> <p>here is my context class</p> <pre><code> public class UsersContext : DbContext { public UsersContext() : base("Expedia") { } public DbSet&lt;Schedule&gt; schedules { get; set; } } </code></pre> <p>Here is My Function Returning the query result:</p> <pre><code> public dynamic Details(int ScheduleID) { var query =(from f in db.schedules.Where(f =&gt; f.ScheduleId== ScheduleID) select new { f.ScheduleId, f.DepartureDate, f.ArrivalDate, f.Departure, f.Arrival, f.DepartureCity, f.DestiationCity, f.Inventory.provider, f.Inventory.nonstop, f.Price, f.Inventory.Available }).ToList(); return query.AsEnumerable(); } </code></pre> <p>When I call this in my controller: </p> <pre><code>var result= x.Details(selectedID); </code></pre> <p>the result variable shows <code>null</code> value although the query is returning a value.</p> <p>How to access the query result in the controller?</p> <p>Please provide any link, reference, hint.</p>
3
1,118
Run multiple classes in the same time?
<p>hi i am new to android encoding , i need a sample program that read data from the accelerometer and send them via wifi to my pc </p> <p>i have the accelerometer program that works fine and also a program that send data via wifi to my pc </p> <p>so the problem is that i dont know how to combine this two programs as a result i hope that the accelerometer class run in the background and return x and y values to the main program that send them </p> <p><strong>accelerometer class</strong> </p> <pre><code>public class MainActivity extends Activity implements SensorEventListener { private SensorManager mSensorManager; private Sensor mAccelerometer; TextView title,tv,tv1,tv2; RelativeLayout layout; @Override public final void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); //get layout layout = (RelativeLayout)findViewById(R.id.relative); //get textviews title=(TextView)findViewById(R.id.name); tv=(TextView)findViewById(R.id.xval); tv1=(TextView)findViewById(R.id.yval); tv2=(TextView)findViewById(R.id.zval); } @Override public final void onAccuracyChanged(Sensor sensor, int accuracy) { // Do something here if sensor accuracy changes. } @Override public final void onSensorChanged(SensorEvent event) { // Many sensors return 3 values, one for each axis. float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; //display values using TextView title.setText(R.string.app_name); tv.setText("X axis" +"\t\t"+x); tv1.setText("Y axis" + "\t\t" +y); tv2.setText("Z axis" +"\t\t" +z); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } } </code></pre> <p><strong>wifi communication class</strong> </p> <pre><code> package net.client; import eneter.messaging.diagnostic.EneterTrace; import eneter.messaging.endpoints.typedmessages.*; import eneter.messaging.messagingsystems.messagingsystembase.*; import eneter.messaging.messagingsystems.tcpmessagingsystem.TcpMessagingSystemFactory; import eneter.net.system.EventHandler; import android.R.string; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class AndroidNetCommunicationClientActivity extends Activity { Thread anOpenConnectionThread = new Thread(); boolean bool = false; // Request message type // The message must have the same name as declared in the service. // Also, if the message is the inner class, then it must be static. public static class MyRequest { public String Text; } // Response message type // The message must have the same name as declared in the service. // Also, if the message is the inner class, then it must be static. public static class MyResponse { public int Length; } // UI controls private Handler myRefresh = new Handler(); private EditText myMessageTextEditText; private EditText myResponseEditText; private Button mySendRequestBtn , mbutton1; // Sender sending MyRequest and as a response receiving MyResponse. private IDuplexTypedMessageSender&lt;MyResponse, MyRequest&gt; mySender; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get UI widgets. myMessageTextEditText = (EditText) findViewById(R.id.messageTextEditText); myResponseEditText = (EditText) findViewById(R.id.messageLengthEditText); mySendRequestBtn = (Button) findViewById(R.id.sendRequestBtn); mbutton1 = (Button) findViewById(R.id.button1); // Subscribe to handle the button click. mySendRequestBtn.setOnClickListener(myOnSendRequestClickHandler); mbutton1.setOnClickListener(bot); // Open the connection in another thread. // Note: From Android 3.1 (Honeycomb) or higher // it is not possible to open TCP connection // from the main thread. } @Override public void onDestroy() { // Stop listening to response messages. mySender.detachDuplexOutputChannel(); super.onDestroy(); } private void openConnection() throws Exception { // Create sender sending MyRequest and as a response receiving MyResponse IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory(); mySender = aSenderFactory.createDuplexTypedMessageSender(MyResponse.class, MyRequest.class); // Subscribe to receive response messages. mySender.responseReceived().subscribe(myOnResponseHandler); // Create TCP messaging for the communication. // Note: 10.0.2.2 is a special alias to the loopback (127.0.0.1) // on the development machine. IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory(); IDuplexOutputChannel anOutputChannel = aMessaging.createDuplexOutputChannel("tcp://192.168.43.44:8060/"); //= aMessaging.createDuplexOutputChannel("tcp://192.168.1.102:8060/"); // Attach the output channel to the sender and be able to send // messages and receive responses. mySender.attachDuplexOutputChannel(anOutputChannel); } private void onSendRequest(View v) { // Create the request message. final MyRequest aRequestMsg = new MyRequest(); aRequestMsg.Text = myMessageTextEditText.getText().toString(); // Send the request message. try { mySender.sendRequestMessage(aRequestMsg); } catch (Exception err) { EneterTrace.error("Sending the message failed.", err); } } private void onResponseReceived(Object sender, final TypedResponseReceivedEventArgs&lt;MyResponse&gt; e) { // Display the result - returned number of characters. // Note: Marshal displaying to the correct UI thread. myRefresh.post(new Runnable() { @Override public void run() { myResponseEditText.setText(Integer.toString(e.getResponseMessage().Length)); } }); } private EventHandler&lt;TypedResponseReceivedEventArgs&lt;MyResponse&gt;&gt; myOnResponseHandler = new EventHandler&lt;TypedResponseReceivedEventArgs&lt;MyResponse&gt;&gt;() { @Override public void onEvent(Object sender, TypedResponseReceivedEventArgs&lt;MyResponse&gt; e) { onResponseReceived(sender, e); } }; private OnClickListener myOnSendRequestClickHandler = new OnClickListener() { @Override public void onClick(View v) { onSendRequest(v); } }; private OnClickListener bot = new OnClickListener() { @Override public void onClick(View v) { Thread anOpenConnectionThread = new Thread(new Runnable() { @Override public void run() { try { openConnection(); } catch (Exception err) { EneterTrace.error("Open connection failed.", err); } } }); anOpenConnectionThread.start(); } }; } </code></pre> <p>thanks and forgive my poor english</p>
3
3,436
Panning in SharpGL distorts image
<p>I have this code in SharpGL where zoom and pan were implemented. This is de draw method:</p> <pre><code>private void OpenGLDraw(object sender, SharpGL.WPF.OpenGLRoutedEventArgs args) { // Enable finish button if (openFileOk &amp;&amp; dispCBOk) { finish_btn.IsEnabled = true; } else { finish_btn.IsEnabled = false; } // Get the OpenGL object OpenGL gl = GLControl.OpenGL; // Set The Material Color float[] glfMaterialColor = new float[] { 0.4f, 0.2f, 0.8f, 1.0f }; float w = (float)GLControl.ActualWidth; float h = (float)GLControl.ActualHeight; // Perspective projection gl.Viewport(0, 0, (int)w, (int)h); gl.Ortho(0, w, 0, h, -100, 100); // Clear The Screen And The Depth Buffer gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT); gl.Material(OpenGL.GL_FRONT_AND_BACK, OpenGL.GL_AMBIENT_AND_DIFFUSE, glfMaterialColor); gl.MatrixMode(MatrixMode.Modelview); gl.LoadIdentity(); gl.Scale(scale,scale,1); // Camera Position gl.LookAt(_position[0], _position[1], _position[2], _viewPoint[0], _viewPoint[1], _viewPoint[2], _upVector[0], _upVector[1], _upVector[2]); // Draw the helix float[][] points = vertexes.ToArray(); Helix(points.Length, points); } </code></pre> <p>What I have here is a perspective projection using Viewport (the ortho projection and scale are used for zooming). This is the code for panning whatever is drawn on the screen:</p> <pre><code>// pan // y axis // Up if (keyCode == 1) { _viewPoint[1] += _moveDistance; _position[1] += _moveDistance; } // Down else if (keyCode == 2) { _viewPoint[1] += -_moveDistance; _position[1] += -_moveDistance; } // x axis // Left else if (keyCode == 3) { _viewPoint[2] += _moveDistance; _position[2] += _moveDistance; } // Right else if (keyCode == 4) { _viewPoint[2] += -_moveDistance; _position[2] += -_moveDistance; } </code></pre> <p>The thing is that when I move too much to any one of the sides (up, down, left, right), the drawing gets really distorted. I didn't notice it at first because I was working with the image very zoomed in and couldn't see the difference, but now I see that the distortion always happens, it's just more intense the more you move away from the image. All I want to know is why this happens, and if possible, a solution for it, thank you.</p> <p>Here is an example of what happens:</p> <p><a href="https://i.stack.imgur.com/DvmRr.png" rel="nofollow noreferrer">Normal view</a><br /> <a href="https://i.stack.imgur.com/DvmRr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DvmRr.png" alt="" /></a></p> <p><a href="https://i.stack.imgur.com/1PezI.png" rel="nofollow noreferrer">Distorted view</a> <a href="https://i.stack.imgur.com/1PezI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1PezI.png" alt="" /></a></p>
3
1,117
Bootstrap 4 Cards - How to set 2 cards in the row
<p>How can i make 2 cards to seem next to eachother, in same row while the view is horizontal?</p> <p>My code:</p> <pre><code>h2 { display: block; font-size: 2.50em; margin-top: 0.25em; margin-bottom: 0.25em; margin-left: 0; margin-right: 0; font-weight: bold; } *{ box-sizing: border-box; } card-deck{ /*Assuming this class as parent of all your cards*/ column-count: 2; column-gap: 2.5rem; /*According to need*/ } card{ width: 45%; /*According to need , such that no vertical scroll apear*/ height: 30%; /*According to need*/ padding: 20px; /*According to need*/ } &lt;/style&gt; &lt;?php include '728x90.php'; ?&gt; &lt;div class=&quot;text-center py-6&quot;&gt;&lt;h3 class=&quot;mb-1&quot;&gt;Offerwalls&lt;/h3&gt; &lt;p class=&quot;text-base leading-none&quot;&gt;Earn a huge amount of Coins by completing many different types of tasks, watching video, playing games and others.&lt;/p&gt;&lt;/div&gt; &lt;div class=&quot;alert alert-warning alert-dismissible fade show&quot; role=&quot;alert&quot;&gt; &lt;center&gt;There is 10% Bonus For Cpx Research! &lt;/div&gt; &lt;?php if ($settings['cpx_status'] == 'on') { ?&gt; &lt;div align=&quot;center&quot; class=&quot;justify-content-center&quot;&gt; &lt;div class=&quot;col-md-6&quot;&gt; &lt;div class=&quot;card-deck&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width:330px&quot;&gt; &lt;center&gt;&lt;h2 style=&quot;color:LightBlue;&quot;&gt;CPX&lt;/h2&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot;&gt;BONUS&lt;/span&gt; &lt;span class=&quot;badge badge-light-warning badge-pill ml-auto mr-1&quot;&gt;Featured&lt;/span&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot; data-toggle=&quot;popover&quot; data-content=&quot;Complete Surveys To Earn High Amount Of Coins&quot; data-trigger=&quot;hover&quot; data-original-title=&quot;Surveys&quot; data-placement=&quot;bottom&quot;&gt;Surveys&lt;/span&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot; data-toggle=&quot;popover&quot; data-content=&quot;Earn High Amount Of Coins&quot; data-trigger=&quot;hover&quot; data-original-title=&quot;Reward&quot; data-placement=&quot;bottom&quot;&gt;High Reward&lt;/span&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;row border-top text-center mx-0&quot;&gt;&lt;/div&gt;&lt;br&gt; &lt;center&gt; &lt;a class=&quot;btn btn-primary&quot; href=&lt;?= base_url() ?&gt;&gt;View&lt;/a&gt;&lt;/center&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ($settings['wannads_status'] == 'on') { ?&gt; &lt;div align=&quot;center&quot; class=&quot;justify-content-center&quot;&gt; &lt;div class=&quot;col-md-6&quot;&gt; &lt;div class=&quot;card-deck&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width:330px&quot;&gt; &lt;center&gt;&lt;h2 style=&quot;color:Orange;&quot;&gt;Wannads&lt;/h2&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot; data-toggle=&quot;popover&quot; data-content=&quot;Complete Surveys To Earn High Amount Of Coins&quot; data-trigger=&quot;hover&quot; data-original-title=&quot;Surveys&quot; data-placement=&quot;bottom&quot;&gt;Surveys&lt;/span&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot; data-toggle=&quot;popover&quot; data-content=&quot;Earn High Amount Of Coins&quot; data-trigger=&quot;hover&quot; data-original-title=&quot;Reward&quot; data-placement=&quot;bottom&quot;&gt;Apps&lt;/span&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;row border-top text-center mx-0&quot;&gt;&lt;/div&gt;&lt;br&gt; &lt;center&gt; &lt;a class=&quot;btn btn-primary&quot; href=&lt;?= base_url() ?&gt;&gt;View&lt;/a&gt;&lt;/center&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if ($settings['wannads_status'] == 'on') { ?&gt; &lt;div align=&quot;center&quot; class=&quot;justify-content-center&quot;&gt; &lt;div class=&quot;col-md-6&quot;&gt; &lt;div class=&quot;card-deck&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width:330px&quot;&gt; &lt;center&gt;&lt;h2 style=&quot;color:Orange;&quot;&gt;Wannads&lt;/h2&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot; data-toggle=&quot;popover&quot; data-content=&quot;Complete Surveys To Earn High Amount Of Coins&quot; data-trigger=&quot;hover&quot; data-original-title=&quot;Surveys&quot; data-placement=&quot;bottom&quot;&gt;Surveys&lt;/span&gt; &lt;span class=&quot;badge badge-light-primary badge-pill ml-auto mr-1&quot; data-toggle=&quot;popover&quot; data-content=&quot;Earn High Amount Of Coins&quot; data-trigger=&quot;hover&quot; data-original-title=&quot;Reward&quot; data-placement=&quot;bottom&quot;&gt;Apps&lt;/span&gt;&lt;br&gt;&lt;br&gt; &lt;div class=&quot;row border-top text-center mx-0&quot;&gt;&lt;/div&gt;&lt;br&gt; &lt;center&gt; &lt;a class=&quot;btn btn-primary&quot; href=&lt;?= base_url() ?&gt;&gt;View&lt;/a&gt;&lt;/center&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/qSsa3.jpg" rel="nofollow noreferrer">You can see how it looks like in my codes.</a> But as i said I want them to be in same row for every 2 cards</p> <p>i realy realy.. need help i tryed several codes but i can’t do it im using bootsrap and try to divide cards like 2-2</p>
3
2,872
Analog clock app state stopping when submitting form
<p>I am working on this React app to make an Analog Clock with optional Inputs available to the user to change the color of the clock hands, clock border, etc.</p> <p>But when I try to press the submit button sometimes, the second hand stops moving all of a sudden and seems like the 'time' states are not changing. The colors however do always change as intended so color states do change.</p> <p>I tried to incorporate preventDefault() but it's a no go...</p> <p>The first code snippet is defining the hooks, second is the form and third is the main App js file. I didn't include the JS/CSS files that include the transform and styling info.</p> <pre><code>import { useEffect, useRef } from 'react'; export const useInterval = (callback, delay) =&gt; { const savedCallback = useRef() // Remembers latest callback useEffect(() =&gt; { savedCallback.current = callback }, [callback]) //Set-up the interval useEffect(() =&gt; { const tick = () =&gt; { savedCallback.current() } if (delay !== null) { let id = setInterval(tick, delay) return () =&gt; clearInterval(id) } }, [delay]) } </code></pre> <pre><code>import React, { useState } from 'react'; import './App.css'; import './CustomForm.css';; function CustomForm(props) { const [options, setOptions] = useState(props.defaultOptions) const setClockColor = (event) =&gt; { event.preventDefault(); let clockColors = { ...options.clockColors }; clockColors[event.target.name] = event.target.value; setOptions({ ...options, clockColors }); } const buildClock = (event) =&gt; { event.preventDefault(); setTimeout(() =&gt; props.updateClock(options), 1000); } return ( &lt;form onSubmit={(event) =&gt; buildClock(event)}&gt; &lt;div className='custom-title'&gt;Custom Analog Clock &lt;/div&gt; &lt;div className='all-hand-color-container'&gt; &lt;div className='input-label-container'&gt; &lt;input className='color-input' placeholder='Second-color' label='Second Hand Color' name='second' type='text' onChange={setClockColor} /&gt; &lt;/div&gt; &lt;div className='input-label-container'&gt; &lt;input className='color-input' placeholder='Minute-color' label='Minute Hand Color' name='minute' type='text' onChange={setClockColor} /&gt; &lt;/div&gt; &lt;div className='input-label-container'&gt; &lt;input className='color-input' placeholder='Hour-color' label='Hour Hand Color' name='hour' type='text' onChange={setClockColor} /&gt; &lt;/div&gt; &lt;div className='input-label-container'&gt; &lt;input className='color-input' placeholder='Border-color' label='Border Color' name='border' type='text' onChange={setClockColor} /&gt; &lt;/div&gt; &lt;div className='input-label-container'&gt; &lt;input className='color-input' placeholder='Base-color' label='Base Color' name='base' type='text' onChange={setClockColor} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className='custom-submit-button-container'&gt; &lt;button className='custom-submit-button' type='submit'&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; ) } export default CustomForm; </code></pre> <pre><code>import React, { useState } from 'react'; import { useInterval } from './Hook'; import { ClockBase, Center, SecondHand, MinuteHand, HourHand } from './Components'; import CustomForm from './CustomForm'; import './App.css' const App = () =&gt; { const date = new Date(); const [seconds, setSeconds] = useState(0) const [minutes, setMinutes] = useState(0) const [hours, setHours] = useState(0) const [options, setOptions] = useState({ clockColors: { second: 'green', minute: 'blue', hour: 'red', border: 'gray', base: 'black' } }) const updateClock = (new_options) =&gt; { setOptions({ ...new_options }); } useInterval(() =&gt; { setSeconds(date.getSeconds()) setMinutes(date.getMinutes()) setHours(date.getHours() % 12 || 12) }, 1000 ) return( &lt;div className='main-container'&gt; &lt;h1 className='form-container'&gt; &lt;CustomForm defaultOptions={options} updateClock={updateClock} /&gt; &lt;/h1&gt; &lt;div className='clock-container'&gt; &lt;ClockBase color={options}&gt; &lt;Center /&gt; &lt;SecondHand fraction={seconds} color={options}/&gt; &lt;MinuteHand fraction={minutes} color={options}/&gt; &lt;HourHand fraction={hours} color={options}/&gt; &lt;/ClockBase&gt; &lt;/div&gt; &lt;/div&gt; ) } export default App; </code></pre>
3
2,304
How to make the filtering queries more efficient using flask sqlalchemy?
<p>I have a following table in a flask app</p> <pre><code>class Price(db.Model): __tablename__ = "prices" id = db.Column(db.Integer, primary_key=True) country_code = db.Column(db.String(2), nullable=False) value = db.Column(db.Float(precision=2), nullable=False) start = db.Column(db.DateTime(timezone=True), nullable=False) end = db.Column(db.DateTime(timezone=True), nullable=False) price_type = db.Column(db.String(32), nullable=False) </code></pre> <p>The following parameters are being taken as input to the <code>get</code> method</p> <pre><code>from flask_restx import Resource, reqparse, inputs parser = reqparse.RequestParser() parser.add_argument("country_code", default=None, type=str, choices=("DE", "NL"), help="Country code") parser.add_argument("price_type", default=None, type=str, help="Price type") parser.add_argument("page", default=1, type=int, help="Page Number") parser.add_argument("limit", default=24, type=int, help="Number of items to be displayed on one page") parser.add_argument("value_from", type=float, help="Starting value to filter values") parser.add_argument("value_to", type=float, help="Ending value to filter values") parser.add_argument("sort", default="start", type=str, choices=("id", "country_code", "value", "start", "end", "price_type"), help="Column to sort on") parser.add_argument("dir", default="asc", type=str, choices=("asc", "desc"), help="Sort the column by ascending or descending") parser.add_argument("start", type=inputs.date, help="Start date (YYYY-MM-DD)") parser.add_argument("end", type=inputs.date, help="End date (YYYY-MM-DD)") @ns.route("/") class Prices(Resource) @ns.expect(parser, validate=True) def get(self): args = parser.parse_args() return DatabaseService.read_list(**args) </code></pre> <p>where <code>ns</code> is a namespace I am using</p> <p>I am currently working on enabling filtering on the table and I have the following code:</p> <pre><code>class DatabaseService: @staticmethod def read_list(**filters): page = filters.pop('page') limit = filters.pop('limit') direction = filters.pop('dir') sort = filters.pop('sort') start_date = filters.pop('start') end_date = filters.pop('end') value_from = filters.pop('value_from') value_to = filters.pop('value_to') if all(filters[c] is not None for c in ('country_code', 'price_type')): print('Both are not none') items = Price.query.filter_by(**filters) elif all(filters[c] is None for c in ('country_code', 'price_type')): print('Both are none') items = Price.query elif filters['country_code'] is None: filters.pop('country_code') items = Price.query.filter_by(**filters) elif filters['price_type'] is None: filters.pop('price_type') items = Price.query.filter_by(**filters) </code></pre> <p>The code shown above works perfectly fine, but I was wondering if there is more efficient way of filtering the data. For example, if there is a way to combine the last 2 <code>elif</code> statements into one and do the filtering using <code>filter_by</code> or <code>filter</code></p> <p><strong>Sample Data</strong></p> <pre><code>{ "items": [ { "id": 1, "value": 21.4, "start": "2020-05-12T00:00:00+02:00", "end": "2020-05-12T01:00:00+02:00", "country_code": "DE", "price_type": "DAY_AHEAD" }, { "id": 2, "value": 18.93, "start": "2020-05-12T01:00:00+02:00", "end": "2020-05-12T02:00:00+02:00", "country_code": "DE", "price_type": "DAY_AHEAD" }, { "id": 3, "value": 18.06, "start": "2020-05-12T02:00:00+02:00", "end": "2020-05-12T03:00:00+02:00", "country_code": "LU", "price_type": "DAY_AHEAD" }, { "id": 4, "value": 17.05, "start": "2020-05-12T03:00:00+02:00", "end": "2020-05-12T04:00:00+02:00", "country_code": "DE", "price_type": "TODAY" }]} </code></pre>
3
2,157
Add a Chronometer Ticklistener and change the text color in a custom Android Notification
<p>I create a foreground service with a custom notification and want to add a <code>TickListener</code> and change the text color of the chronometer. The notification is displayed as defined in the XML file and can not be changed afterwards. If I change the text color or add a listener nothing happens. </p> <pre><code>public void onCreate() { super.onCreate(); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.service_location_gps_notification, null); chronometer = layout.findViewById(R.id.chronometer_Service_Location_GPS_Notification); chronometer.setTextColor(Color.BLUE); chronometer.setOnChronometerTickListener(chronometerOnClickListener); chronometer.setText("00:00:00"); remoteViews = new RemoteViews(getPackageName(), R.layout.service_location_gps_notification); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.app_name); NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT); notificationChannel.setLockscreenVisibility(VISIBILITY_PUBLIC); notificationManager.createNotificationChannel(notificationChannel); } startForeground(NOTIFICATION_ID, getNotification()); } private Notification getNotification() { Intent intent = new Intent(this, ServiceLocationGPS.class); PendingIntent servicePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent activityPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); int drawable; String modus; if(FragmentDistanceLocation.DISTANCE_MODE) { remoteViews.setTextViewText(R.id.textView_Service_Location_GPS_Notification_Titel, String.valueOf(this.meter) + " Meter"); modus = "Strecken Modus"; drawable = R.drawable.ic_directions_run_white_24dp; chronometer.setTextColor(getResources().getColor(R.color.ColorGreen)); } else { remoteViews.setTextViewText(R.id.textView_Service_Location_GPS_Notification_Titel, this.locationname); modus = "HealthPoint Modus"; drawable = R.drawable.ic_fitness_center_white_24dp; chronometer.setTextColor(getResources().getColor(R.color.ColorBlue)); } remoteViews.setChronometer(chronometer.getId(), SystemClock.elapsedRealtime() - timerSeconds, null, true); NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentIntent(activityPendingIntent) .addAction(R.drawable.logo_group_background, "Workout beenden", servicePendingIntent) .setSmallIcon(drawable) .setStyle(new NotificationCompat.DecoratedCustomViewStyle()) .setCustomContentView(remoteViews) .setPriority(Notification.PRIORITY_HIGH) .setOngoing(true) .setVisibility(VISIBILITY_PUBLIC) .setWhen(System.currentTimeMillis()) .setSubText(modus) .setAutoCancel(true); return notificationCompatBuilder.build(); } Chronometer.OnChronometerTickListener chronometerOnClickListener = new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { long time = SystemClock.elapsedRealtime() - chronometer.getBase(); int h = (int) (time / 3600000); int m = (int) (time - h * 3600000) / 60000; int s = (int) (time - h * 3600000 - m * 60000) / 1000; String hh = h &lt; 10 ? "0" + h : h + ""; String mm = m &lt; 10 ? "0" + m : m + ""; String ss = s &lt; 10 ? "0" + s : s + ""; chronometer.setText(hh + ":" + mm + ":" + ss); } }; </code></pre> <p>This is <code>layout_Service_Location_GPS_Notification.xml</code>:</p> <pre><code>&lt;TextView android:id="@+id/textView_Service_Location_GPS_Notification_Titel" style="@style/TextAppearance.Compat.Notification.Title" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/ColorPrimary" android:gravity="center_horizontal|center" android:text="Strecke" android:textColor="@color/ActionbarColor" /&gt; &lt;Chronometer android:id="@+id/chronometer_Service_Location_GPS_Notification" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/ColorPrimary" android:clickable="false" android:fontFamily="sans-serif-thin" android:gravity="center_vertical|center_horizontal" android:longClickable="false" android:textColor="@color/ColorGreen" android:textSize="@dimen/_22sdp" android:textStyle="bold" /&gt; </code></pre> <p>Does anybody have any ideas?</p>
3
1,877
Can't get my if statement to work with html form input in js
<p>Without my if statement I'm able to store the data but when i want to check against an html form value, Im unable to do so. P.S I'm fairly new to js so please bear with me. </p> <pre><code>&lt;script&gt; var signupForm = document.getElementById('signup-form'); var signupSuccess = document.getElementById('signup-success'); var signupError = document.getElementById('signup-error'); var signupBtn = document.getElementById('signup-button'); var day_Imp = document.getElementById('D-day').value; var onSignupComplete = function(error) { signupBtn.disabled = false; if (error) { signupError.innerHTML = 'Sorry. Your Booking failed.'; } else { signupSuccess.innerHTML = 'Thanks for playing at Total Football!'; // hide the form signupForm.style.display = 'none'; } }; function signup(formObj) { console.log(day_Imp); // Store emails to firebase if(day_Imp==='monday'){ var myFirebaseRef = new Firebase("https://fiery-torch-164.firebaseio.com/days/monday"); myFirebaseRef.push({ email: formObj.email.value, name: formObj.name.value, number: formObj.number.value, }, onSignupComplete); signupBtn.disabled = true; return false; } } </code></pre> <p></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script src="https://cdn.firebase.com/js/client/1.0.18/firebase.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="infoCSS.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="signup"&gt; &lt;h2 class="signup-title"&gt;Enter your information please&lt;/h2&gt; &lt;p id="signup-success" class="text-success"&gt;&lt;/p&gt; &lt;p id="signup-error" class="text-danger"&gt;&lt;/p&gt; &lt;form class="signup-form form-inline" id="signup-form" role="form" onsubmit="return signup(this)"&gt; &lt;label&gt;Full Name&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;input class="form-control" name="name" type="text" required&gt;&lt;br&gt;&lt;br&gt; &lt;label&gt;Email&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;input class="form-control" name="email" type="email" placeholder="Your email. eg., joe@acme.com" required&gt;&lt;br&gt;&lt;br&gt; &lt;label&gt;Cell Phone&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;input class="form-control" name="number" type="tel" required&gt;&lt;br&gt;&lt;br&gt; &lt;label&gt;Day&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;input type="text" id="D-day"&gt;&lt;br&gt;&lt;br&gt; &lt;button class="btn btn-success" id="signup-button" type="submit" &gt;#Allin!&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;script&gt; var signupForm = document.getElementById('signup-form'); var signupSuccess = document.getElementById('signup-success'); var signupError = document.getElementById('signup-error'); var signupBtn = document.getElementById('signup-button'); // var day_Imp = document.getElementById('D-day'); var onSignupComplete = function(error) { signupBtn.disabled = false; if (error) { signupError.innerHTML = 'Sorry. Your Booking failed.'; } else { signupSuccess.innerHTML = 'Thanks for playing at Total Football!'; // hide the form signupForm.style.display = 'none'; } }; function signup(formObj) { // Store emails to firebase $('#D-day').on('input', function() { var day_Imp = document.getElementById('D-day').value; console.log(day_Imp); if (day_Imp == 'monday') { var myFirebaseRef = new Firebase("https://fiery-torch-164.firebaseio.com/days/monday"); myFirebaseRef.push({ email: formObj.email.value, name: formObj.name.value, number: formObj.number.value, }, onSignupComplete); signupBtn.disabled = true; return false; } }); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Here is the updated version including all the html and js. </p>
3
1,814
Error while setting the marker listener on Google map in android api 10
<p>I am trying to add the marker listener by implementing the <strong>OnMarkerClickListener</strong> and setting <strong>googleMap.setOnMarkerClickListener((OnMarkerClickListener)this)</strong> </p> <p>It is working fine with the actual device but giving the <strong>NullPointerException</strong> error on the emulator. It is also working fine with the device with api 19, but Why is this happening with emulator. </p> <p>I am using the SupportMapFragment for displaying the map.</p> <p>Here is the code</p> <pre><code>@SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.orderlayout); Log.i(TAG, "Started order onCreate method Activity"); status = GooglePlayServicesUtil .isGooglePlayServicesAvailable(getApplicationContext()); if (status == ConnectionResult.SUCCESS) { // Success! Do what you want mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).build(); } else { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setTitle("Debugging"); ad.setMessage("Error getting the GooglePlayServicesUtilities"); ad.setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //comeHome(); dialog.dismiss(); } }); AlertDialog dialog = ad.create(); dialog.show(); } // Setting the map features mMapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mMapFragment.getMapAsync(this); gMap = ((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map)).getMap(); gMap = mMapFragment.getMap(); // set the click listeners for the marker in map try{ gMap.setOnMarkerClickListener((OnMarkerClickListener) this); }catch(Exception e){Log.v(TAG,"Error setting the click listener for the marker: "+e.toString());} try { gMap.getUiSettings().setMyLocationButtonEnabled(true); } catch (Exception e) { Log.e("Buzz", "Error with the current location button" + e.toString()); } LatLng latLng = getCurrentLocation(this); Log.v(TAG,latLng.latitude+latLng.longitude+""); gMap.addMarker(new MarkerOptions().position( new LatLng(latLng.latitude, latLng.longitude)).title("Your Current Location")); try { gMap.setMyLocationEnabled(true); } catch (Exception e) { Log.e("Buzz", "Error while enabling the current location" + e.toString()); } </code></pre> <p>} </p> <p>@Override public boolean onMarkerClick(final Marker marker) { return false; }</p> <p>and My Logcat is:</p> <pre><code>03-17 12:15:50.119: E/AndroidRuntime(562): FATAL EXCEPTION: main 03-17 12:15:50.119: E/AndroidRuntime(562): java.lang.RuntimeException: Unable to start activity ComponentInfo{blr.infovita.buzzpharma/blr.infovita.buzzpharma.OrderActivity}: java.lang.NullPointerException 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.os.Handler.dispatchMessage(Handler.java:99) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.os.Looper.loop(Looper.java:123) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.ActivityThread.main(ActivityThread.java:3683) 03-17 12:15:50.119: E/AndroidRuntime(562): at java.lang.reflect.Method.invokeNative(Native Method) 03-17 12:15:50.119: E/AndroidRuntime(562): at java.lang.reflect.Method.invoke(Method.java:507) 03-17 12:15:50.119: E/AndroidRuntime(562): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-17 12:15:50.119: E/AndroidRuntime(562): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-17 12:15:50.119: E/AndroidRuntime(562): at dalvik.system.NativeStart.main(Native Method) 03-17 12:15:50.119: E/AndroidRuntime(562): Caused by: java.lang.NullPointerException 03-17 12:15:50.119: E/AndroidRuntime(562): at blr.infovita.buzzpharma.OrderActivity.onCreate(OrderActivity.java:278) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 03-17 12:15:50.119: E/AndroidRuntime(562): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 03-17 12:15:50.119: E/AndroidRuntime(562): ... 11 more </code></pre>
3
1,942
Changing cursor when rendering a JList
<p>I've achieved what I'm trying to do, but I can't help but to think there is a more efficient way...allow me to illustrate.</p> <p>In short, the question I'm asking is if there's a way to determine when a component has finished it's initial rendering.</p> <p>I have a JList, which is hooked up to a DefaultListModel and getting painted by a custom renderer which extends the DefaultListCellRenderer.</p> <p>This intention of the JList is to "page" through a log file, populating 2500 elements every time a new page is loaded. On my machine it usually takes a couple seconds to fully render the JList, which is not really a problem because changing the cursor to a wait cursor would be acceptable because it would give the user immediate feedback. Unfortunately, I cannot figure out an elegant way to know when the initial rendering has completed.</p> <p>Below is the code of my renderer, in it you'll see I'm counting the number of iterations on the renderer. If that is between 0 and N-20, the cursor changes to a wait cursor. Once N-20 has been reached, it reverts back to a default cursor. Like I previously mentioned, this works just fine, but the solution really feels like a hack. I've implemented the ListDataListener of the DefaultListModel and the PropertyChangeListener of the JList, but neither produce the functionality I'm looking for.</p> <pre><code>/** * Renders the MessageHistory List based on the search text and processed events */ public class MessageListRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; String lineCountWidth = Integer.toString(Integer.toString(m_MaxLineCount).length()); @Override public Component getListCellRendererComponent(JList l, Object value, int index, boolean isSelected, boolean haveFocus) { JLabel retVal = (JLabel)super.getListCellRendererComponent(l, value, index, isSelected, haveFocus); retVal.setText(formatListBoxOutput((String)value, index)); // initial rendering is beginning - change the cursor if ((renderCounter == 0) &amp;&amp; !renderCursorIsWait) { m_This.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); renderCursorIsWait = true; } // initial rendering is complete - change the cursor back if ((renderCounter &gt; (l.getModel().getSize() - 20)) &amp;&amp; renderCursorIsWait) { m_This.setCursor(Cursor.getDefaultCursor()); renderCursorIsWait = false; } renderCounter++; return retVal; } /** * Adds font tags (marks as red) around all values which match the search criteria * * @param lineValue string to search in * @param lineIndex line number being processed * @return string containing the markup */ private String formatListBoxOutput(String lineValue, int lineIndex) { // Theoretically the count should never be zero or less, but this will avoid an exception just in case if (m_MaxLineCount &lt;= 0) return lineValue; String formattedLineNumber = String.format("%" + Integer.toString(Integer.toString(m_MaxLineCount).length()) + "s", m_CurrentPage.getStartLineNumber() + lineIndex) + ": "; // We're not searching, simply return the line plus the added line number if((m_lastSearchText == null) || m_lastSearchText.isEmpty()) return "&lt;html&gt;&lt;font color=\"#4682B4\"&gt;" + formattedLineNumber.replaceAll(" ", "&amp;nbsp;") + "&lt;/font&gt;" + lineValue + "&lt;/html&gt;"; // break up the search string by the search value in case there are multiple entries String outText = ""; String[] listValues = lineValue.split(m_lastSearchText); if(listValues.length &gt; 1) { // HTML gets rid of the preceding whitespace, so change it to the HTML code outText = "&lt;html&gt;&lt;font color=\"#4682B4\"&gt;" + formattedLineNumber.replaceAll(" ", "&amp;nbsp;") + "&lt;/font&gt;"; for(int i = 0; i &lt; listValues.length; i++) { outText += listValues[i]; if(i + 1 &lt; listValues.length) outText += "&lt;font color=\"red\"&gt;" + m_lastSearchText + "&lt;/font&gt;"; } return outText + "&lt;/html&gt;"; } return "&lt;html&gt;&lt;font color=\"#4682B4\"&gt;" + formattedLineNumber.replaceAll(" ", "&amp;nbsp;") + "&lt;/font&gt;" + lineValue + "&lt;/html&gt;"; } } </code></pre> <p>All I'm doing to populate the model is this:</p> <pre><code>// reset the rendering counter this.renderCounter = 0; // Reset the message history and add all new values this.modelLogFileData.clear(); for (int i = 0; i &lt; this.m_CurrentPage.getLines().size(); i++) this.modelLogFileData.addElement(this.m_CurrentPage.getLines().elementAt(i)); </code></pre>
3
1,763
Is there something wrong with my CMakeLists?
<p>The following is my CMakeLists file. By default, I expect it to define the symbol ALLEGRO_STATICLINK in the agui_allegro5 library, but it does not, however when I check off WANT_SHARED it defines it, which it shouldnt, but does not define AGUI_BACKEND_BUILD as it should. Is my logic flawed or something?</p> <pre><code>cmake_minimum_required(VERSION 2.6) project(agui) OPTION(WANT_SHARED "Build agui and the backend as a shared library" OFF) OPTION(WANT_ALLEGRO5_BACKEND "Build the Allegro 5 backend" ON) set(AGUI_SOURCES src/Agui/ActionEvent.cpp src/Agui/ActionListener.cpp src/Agui/BaseTypes.cpp src/Agui/BlinkingEvent.cpp src/Agui/BorderLayout.cpp src/Agui/Color.cpp src/Agui/Dimension.cpp src/Agui/EmptyWidget.cpp src/Agui/EventArgs.cpp src/Agui/FlowLayout.cpp src/Agui/FocusListener.cpp src/Agui/FocusManager.cpp src/Agui/Font.cpp src/Agui/FontLoader.cpp src/Agui/Graphics.cpp src/Agui/GridLayout.cpp src/Agui/Gui.cpp src/Agui/Image.cpp src/Agui/ImageLoader.cpp src/Agui/Input.cpp src/Agui/KeyboardListener.cpp src/Agui/Layout.cpp src/Agui/MouseListener.cpp src/Agui/Point.cpp src/Agui/Rectangle.cpp src/Agui/ResizableText.cpp src/Agui/ResizableBorderLayout.cpp src/Agui/SelectionListener.cpp src/Agui/TopContainer.cpp src/Agui/Widget.cpp src/Agui/WidgetListener.cpp src/Agui/Widgets/Button/Button.cpp src/Agui/Widgets/Button/ButtonListener.cpp src/Agui/Widgets/CheckBox/CheckBox.cpp src/Agui/Widgets/CheckBox/CheckBoxListener.cpp src/Agui/Widgets/DropDown/DropDown.cpp src/Agui/Widgets/DropDown/DropDownListener.cpp src/Agui/Widgets/Frame/Frame.cpp src/Agui/Widgets/Frame/FrameListener.cpp src/Agui/Widgets/Label/Label.cpp src/Agui/Widgets/Label/LabelListener.cpp src/Agui/Widgets/ListBox/ListBox.cpp src/Agui/Widgets/ListBox/ListBoxListener.cpp src/Agui/Widgets/RadioButton/RadioButton.cpp src/Agui/Widgets/RadioButton/RadioButtonListener.cpp src/Agui/Widgets/RadioButton/RadioButtonGroup.cpp src/Agui/Widgets/ScrollBar/HScrollBar.cpp src/Agui/Widgets/ScrollBar/HScrollBarListener.cpp src/Agui/Widgets/ScrollBar/VScrollBar.cpp src/Agui/Widgets/ScrollBar/VScrollBarListener.cpp src/Agui/Widgets/ScrollPane/ScrollPane.cpp src/Agui/Widgets/Slider/Slider.cpp src/Agui/Widgets/Slider/SliderListener.cpp src/Agui/Widgets/Tab/Tab.cpp src/Agui/Widgets/Tab/TabbedPane.cpp src/Agui/Widgets/Tab/TabbedPaneListener.cpp src/Agui/Widgets/TextBox/TextBox.cpp src/Agui/Widgets/TextBox/TextBoxListener.cpp src/Agui/Widgets/TextBox/ExtendedTextBox.cpp src/Agui/Widgets/TextField/TextField.cpp src/Agui/Widgets/TextField/TextFieldListener.cpp ) set(ALLEGRO5_BACKEND_SOURCES src/Agui/Backends/Allegro5/Allegro5Font.cpp src/Agui/Backends/Allegro5/Allegro5FontLoader.cpp src/Agui/Backends/Allegro5/Allegro5Graphics.cpp src/Agui/Backends/Allegro5/Allegro5Image.cpp src/Agui/Backends/Allegro5/Allegro5ImageLoader.cpp src/Agui/Backends/Allegro5/Allegro5Input.cpp ) include_directories (./include) if(WANT_SHARED) add_library(agui SHARED ${AGUI_SOURCES}) set_target_properties(agui PROPERTIES DEFINE_SYMBOL "AGUI_BUILD") if(WANT_ALLEGRO5_BACKEND) add_library(agui_allegro5 SHARED ${ALLEGRO5_BACKEND_SOURCES}) set_target_properties(agui_allegro5 PROPERTIES DEFINE_SYMBOL "AGUI_BACKEND_BUILD") target_link_libraries (agui_allegro5 agui) endif() else() add_library(agui STATIC ${AGUI_SOURCES}) if(WANT_ALLEGRO5_BACKEND) add_library(agui_allegro5 STATIC ${ALLEGRO5_BACKEND_SOURCES}) set_target_properties(agui_allegro5 PROPERTIES DEFINE_SYMBOL "ALLEGRO_STATICLINK") endif() endif() </code></pre> <p>Thanks</p>
3
1,689
Should I use LinearLayout or RelativeLayout to have 4 objects fill a screen?
<p>I am learning about the difference between <code>LinearLayout</code> and <code>RelativeLayout</code> and am confused about the best way to solve my specific problem. I want to have 4 buttons fill a screen, each with some different action. After having trouble with <code>RelativeLayout</code>, I was recommended to switch to <code>LinearLayout</code> by <a href="https://stackoverflow.com/questions/6982395/set-two-buttons-to-same-width-regardless-of-screen-size">this</a> SO thread. Using a nested <code>LinearLayout</code> and the <code>android:weight</code> value, I got a solution that does work properly. However, now I get the warning: "Nested weights are bad for performance." I propmtly looked that up on SO and found <a href="https://stackoverflow.com/questions/9430764/why-are-nested-weights-bad-for-performance-alternatives">this</a> article, telling me to switch back to <code>RelativeLayout</code>. </p> <p>What's the right answer? Is there a good way to have objects fill an area like this in <code>RelativeLayout</code>? </p> <p>This is my current code. Excuse the extra stuff, not sure what to leave in and what to just take out.</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/motherStack" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" &gt; &lt;LinearLayout android:id="@+id/rowOne" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="1"&gt; &lt;Button android:id="@+id/redButton" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/red_button_text" android:textColor="@color/RED" /&gt; &lt;Button android:id="@+id/blueButton" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/blue_button_text" android:textColor="@color/BLUE" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/rowTwo" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="1"&gt; &lt;Button android:id="@+id/greenButton" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/green_button_text" android:textColor="@color/GREEN" /&gt; &lt;Button android:id="@+id/yellowButton" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/yellow_button_text" android:textColor="@color/YELLOW" /&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>I would post an image but I just joined and have no reputation. :(</p>
3
1,207
Cross browser support for get and set properties
<p>My goal is to implement get and set properties on Javascript objects.</p> <p><code>Object.defineProperty</code> seems to be supported in IE9+ on a non DOM <code>Object</code>. I want it to work down to IE7.</p> <p><code>__defineGetter__</code> is <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineGetter" rel="nofollow noreferrer">deprecated</a></p> <p>There seems to be some <a href="http://johndyer.name/native-browser-get-set-properties-in-javascript/" rel="nofollow noreferrer">workarounds</a> aka "hacks":</p> <pre><code>// Super amazing, cross browser property function, based on http://thewikies.com/ function addProperty(obj, name, onGet, onSet) { // wrapper functions var oldValue = obj[name], getFn = function () { return onGet.apply(obj, [oldValue]); }, setFn = function (newValue) { return oldValue = onSet.apply(obj, [newValue]); }; // Modern browsers, IE9+, and IE8 (must be a DOM object), if (Object.defineProperty) { Object.defineProperty(obj, name, { get: getFn, set: setFn }); // Older Mozilla } else if (obj.__defineGetter__) { obj.__defineGetter__(name, getFn); obj.__defineSetter__(name, setFn); // IE6-7 // must be a real DOM object (to have attachEvent) and must be attached to document (for onpropertychange to fire) } else { var onPropertyChange = function (e) { if (event.propertyName == name) { // temporarily remove the event so it doesn't fire again and create a loop obj.detachEvent("onpropertychange", onPropertyChange); // get the changed value, run it through the set function var newValue = setFn(obj[name]); // restore the get function obj[name] = getFn; obj[name].toString = getFn; // restore the event obj.attachEvent("onpropertychange", onPropertyChange); } }; obj[name] = getFn; obj[name].toString = getFn; obj.attachEvent("onpropertychange", onPropertyChange); } } // must be a DOM object (even if it's not a real tag) attached to document var myObject = document.createElement('fake'); document.body.appendChild(myObject); // create property myObject.firstName = 'John'; myObject.lastName = 'Dyer'; addProperty(myObject, 'fullname', function() { return this.firstName + ' ' + this.lastName; }, function(value) { var parts = value.split(' '); this.firstName = parts[0]; this.lastName = (parts.length &gt; 1) ? parts[1] : ''; }); console.log(myObject.fullname); // returns 'John Dyer' </code></pre> <p><a href="http://ejohn.org/blog/javascript-getters-and-setters/" rel="nofollow noreferrer">Another alternative by John Resig</a></p> <p>I'm not a fan of the code above due to the DOM element part. Are there any "better" options as of today? Most of the posts that I've found on this subject are at least one year old.</p> <p><a href="https://stackoverflow.com/questions/9106936/cross-browser-getter-and-setter">Similar SO thread</a> </p>
3
1,311
What is the correct foreign key constraint syntax for a database migration in Laravel 8.X Eloquent?
<p>I am a Laravel and Eloquent noob.</p> <p>I'm trying to do a simple foreign key in a &quot;checklist items&quot; table that takes the primary ID from the &quot;users&quot; table as a foreign key.</p> <p>Here are my two database migrations:</p> <p>users:</p> <pre><code>&lt;?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table-&gt;id(); $table-&gt;string('name'); $table-&gt;string('email')-&gt;unique(); $table-&gt;timestamp('email_verified_at')-&gt;nullable(); $table-&gt;string('password'); $table-&gt;rememberToken(); $table-&gt;timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } } </code></pre> <p>items:</p> <pre><code>&lt;?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateItemsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('items', function (Blueprint $table) { $table-&gt;id(); $table-&gt;integer('user_id')-&gt;unsigned(); $table-&gt;string('itemName'); $table-&gt;string('itemDescription'); $table-&gt;timestamps(); }); Schema::table('items', function($table) { $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('items'); } } </code></pre> <p>attempting to run <code>php artisan migrate</code> yields the following error:</p> <pre><code>Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (0.49 seconds) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (0.59 seconds) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (0.33 seconds) Migrating: 2021_05_04_085648_create_items_table Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `items` add constraint `items_user_id_foreign` foreign key (`user_id`) references `users` (`id`)) at D:\Applications\laragon\www\ToDoApp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:671 667| // If an exception occurs when attempting to run a query, we'll format the error 668| // message to include the bindings with SQL, which will make this exception a 669| // lot more helpful to the developer instead of just the database's errors. 670| catch (Exception $e) { &gt; 671| throw new QueryException( 672| $query, $this-&gt;prepareBindings($bindings), $e 673| ); 674| } 675| 1 D:\Applications\laragon\www\ToDoApp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:464 PDOException::(&quot;SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint&quot;) 2 D:\Applications\laragon\www\ToDoApp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:464 PDOStatement::execute() </code></pre> <p>It should be noted that I can achieve what I need fine in the PHPMyAdmin GUI directly, or using basic PHP PDOs, but I don't understand Eloquent and need to understand what I am doing wrong.</p> <p>I have a feeling that it's to do with a mismatch in the attribute definitions between the two table migrations, but the few things I tried caused alternate errors.</p>
3
1,697
How to @Autowire generic type to inner generic class' bean without xml configuration?
<p>I have a generic class DefaultBatchReportService. I want to pass different POJO class, Service &amp; Dao into this generic class.</p> <p>However, I find difficulties in passing specific classes to generic abstract class with inner autowired generic class.</p> <p>I got errors as following:</p> <blockquote> <p>Feb 02, 2016 1:49:10 PM com.sun.faces.application.view.ViewScopeManager <p>Feb 02, 2016 1:49:10 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute WARNING: Error creating bean with name 'rt001Bean': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.edgar.report.core.DefaultBatchReportService com.edgar.test.RT001Bean.bReportController; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultBatchReportService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.edgar.report.core.SingleReportService com.edgar.report.core.DefaultBatchReportService.singleReportService; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.edgar.report.core.SingleReportService] is defined: expected single matching bean but found 3: RT001Service, RT002Service, RT003Service org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rt001Bean': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.edgar.report.core.DefaultBatchReportService com.edgar.test.RT001Bean.bReportController; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultBatchReportService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.edgar.report.core.SingleReportService com.edgar.report.core.DefaultBatchReportService.singleReportService; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.edgar.report.core.SingleReportService] is defined: expected single matching bean but found 3: RT001Service,RT002Service,RT003Service at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:342) at com.gitgub.javaplugs.jsf.ViewScope.get(ViewScope.java:69) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956) at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:55) at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71) at org.apache.el.parser.AstValue.getTarget(AstValue.java:93) at org.apache.el.parser.AstValue.invoke(AstValue.java:259) at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) at org.primefaces.application.DialogActionListener.processAction(DialogActionListener.java:45) at javax.faces.component.UICommand.broadcast(UICommand.java:315) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) at com.edgar.bean.MDCFilterSecurityInterceptor.doFilter(MDCFilterSecurityInterceptor.java:24) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:168) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)</p> </blockquote> <h1>Batch Report Service:</h1> <pre><code>@Component @Scope("prototype") public class DefaultBatchReportService &lt;T extends SingleReportService, I extends ReportInputParam, M extends ReportMeta, MD extends ReportMetaDetail, C extends ReportContent, P extends ReportDao&lt;I , M, MD, C&gt;&gt; { @Setter private I inputParam; @Setter private M meta; @Autowired @Setter private T singleReportService; @Autowired @Setter private P reportDao; } </code></pre> <h1>Managed Bean Class:</h1> <pre><code>@Component @SpringScopeView @Getter @Setter public class RT001Bean extends BaseBean { @Autowired private DefaultBatchReportService&lt;RT001Service, RT001_InputParam, RT001_Meta, RT001_Meta.Detail, RT001_Content, RT001Dao&gt; bReportController; private RT001_InputParam inputParam; public void generateBatchReport() { //Start Report Generation try { bReportController.doSomething(inputParam); .... } catch (CustomException e) { // Print Error Message } } </code></pre> <p>In this project, my team is using JSF-Spring integrated framework. Normal standard injection of controls works fine (without Generic Types).</p> <p>There are more than one Batch Report with same procedures in my project, thats why I want to use DefaultBatchReportService to handle every BatchReport by passing different class to it. (RT001..., RT002..., RT003..) Then, developers can focus on drawing the 'single' report.</p> <p>Sorry for my poor English :/</p>
3
4,493
How I can get only div. Without content (javascript)
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var desc = document.querySelectorAll(".desc"); function change() { var how = desc.length; for(var i = 0; i &lt; how; i++) { desc[i].getElementsByTagName("p")[1].style.display = "none"; } } change(); function show(e) { var target = e.target; console.log(target); } for(var i = 0; i &lt; desc.length; i++) { desc[i].onclick = show; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.desc { width: 80%; margin: 0 auto; border: 3px solid #cccccc; padding: 5px; margin-bottom: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="desc"&gt; &lt;p&gt;Pytanie: Dlaczego JavaScript jest taki fajny ?&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dapibus tortor lectus, in pellentesque sapien viverra eget. Ut maximus magna vitae mollis fringilla. In sit amet odio tincidunt, finibus arcu et, ullamcorper nisi. Nunc congue ut augue quis viverra. Donec sagittis, felis et bibendum condimentum, est ligula tempus quam, vel hendrerit tortor ipsum id enim. Mauris nisl ante, convallis sit amet orci a, blandit pellentesque mauris. Etiam sed elementum ipsum. Nullam consequat risus augue, nec ullamcorper massa varius eu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed eget sem in purus hendrerit aliquam. Vivamus at consequat tellus. Cras et eros mauris.&lt;/p&gt; &lt;/div&gt; &lt;div class="desc"&gt; &lt;p&gt;Pytanie: Dlaczego JavaScript jest taki fajny ?&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dapibus tortor lectus, in pellentesque sapien viverra eget. Ut maximus magna vitae mollis fringilla. In sit amet odio tincidunt, finibus arcu et, ullamcorper nisi. Nunc congue ut augue quis viverra. Donec sagittis, felis et bibendum condimentum, est ligula tempus quam, vel hendrerit tortor ipsum id enim. Mauris nisl ante, convallis sit amet orci a, blandit pellentesque mauris. Etiam sed elementum ipsum. Nullam consequat risus augue, nec ullamcorper massa varius eu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed eget sem in purus hendrerit aliquam. Vivamus at consequat tellus. Cras et eros mauris.&lt;/p&gt; &lt;/div&gt; &lt;div class="desc"&gt; &lt;p&gt;Pytanie: Dlaczego JavaScript jest taki fajny ?&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dapibus tortor lectus, in pellentesque sapien viverra eget. Ut maximus magna vitae mollis fringilla. In sit amet odio tincidunt, finibus arcu et, ullamcorper nisi. Nunc congue ut augue quis viverra. Donec sagittis, felis et bibendum condimentum, est ligula tempus quam, vel hendrerit tortor ipsum id enim. Mauris nisl ante, convallis sit amet orci a, blandit pellentesque mauris. Etiam sed elementum ipsum. Nullam consequat risus augue, nec ullamcorper massa varius eu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed eget sem in purus hendrerit aliquam. Vivamus at consequat tellus. Cras et eros mauris.&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I have problem: I get the target but I don't want a paragraph, but div with class .desc. And then I want to refer to this target and choose children. How I can do it? So, when someone clicks in this this or the text inside this div, I want to get in target only this div with class desc.</p>
3
1,594
Show specific text from a php loop of database results using jquery
<p>I have selected data from my database and I have looped through the results to display them on my page. I have 3 results which are shown. Each result has a button with an id called decrease. When I click this button, an alert with the name of the item containing the alert button should be displayed. I am using jQuery to achieve this. </p> <p>My problem is that whenever I click the button, the name of only the first item in the results array is displayed. The buttons in the other two results don't seem to work. What am I doing wrong?</p> <p>The code that loops through the result and displays the items in the database table:</p> <pre><code>if(mysqli_num_rows($run) &gt;= 1){ while($row = mysqli_fetch_assoc($run)) { $name = $row['name']; $quantity = $row['quantity']; $price = $row['price']; $image = $row['image']; $category = $row['category']; $total = $price * $quantity; echo "&lt;div class=\"post-container\"&gt;\n"; echo "&lt;div class=\"post-thumb\"&gt;\n"; echo "&lt;img src='$image'&gt;\n"; echo "&lt;/div&gt;\n"; echo "&lt;div class=\"post-title\"&gt;\n"; echo "&lt;h4 style=\"font-weight:bold;\"&gt;\n"; echo "&lt;a href=\"view.php?name=$name&amp;category=$category\" class=\"links\" target=\"_blank\"&gt;$name&lt;/a&gt;\n"; echo "&lt;span id=\"deletion\"&gt;Delete&lt;/span&gt;\n"; echo "&lt;/h4&gt;\n"; echo "&lt;/div&gt;\n"; echo "&lt;div class=\"post-content\"&gt;\n"; echo "&lt;ul style=\"list-style-type:none;\"&gt;\n"; echo "&lt;li&gt;Cost Per Item: &lt;span id=\"cost\"&gt;$price&lt;/span&gt;/=&lt;/li&gt;\n"; echo "&lt;li&gt;\n"; echo "Quantity: \n"; echo "&lt;button type=\"submit\" id=\"decrease\" class=\"glyphicon glyphicon-minus\" title=\"Decrease Quantity\"&gt;&lt;/button&gt;\n"; echo "\n"; echo "&lt;span id=\"cost\" class=\"quantity\"&gt;&amp;nbsp$quantity&amp;nbsp&lt;/span&gt;\n"; echo "\n"; echo "&lt;button type=\"submit\" id=\"increase\" class=\"glyphicon glyphicon-plus\" title=\"Increase Quantity\"&gt;&lt;/button&gt;\n"; echo "&lt;/li&gt;\n"; echo "&lt;li&gt;Total Cost: &lt;span id=\"cost\"&gt;$total&lt;/span&gt;/=&lt;/li&gt;\n"; echo "&lt;/ul&gt;\n"; echo "&lt;/div&gt;\n"; echo "&lt;/div&gt;"; } } </code></pre> <p>And here's the jquery:</p> <pre><code>$("#decrease").click(function(){ var name = $(this).parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text(); alert(name); }); </code></pre>
3
1,171
Fail to start HBase in Pseudo-Distributed mode throws "Failed construction RegionServer"
<p>I am trying to run HBase pseudo-distributed in a docker image of ubuntu.</p> <p>After start-hbase.sh, HMaster and RegionServer don't run properly.</p> <p>Both RegionServer and Master log shows:</p> <pre><code>ERROR [main] regionserver.HRegionServer: Failed construction RegionServer java.io.IOException: Couldn't create proxy provider class org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider at org.apache.hadoop.hdfs.NameNodeProxiesClient.createFailoverProxyProvider(NameNodeProxiesClient.java:261) at org.apache.hadoop.hdfs.NameNodeProxiesClient.createFailoverProxyProvider(NameNodeProxiesClient.java:224) at org.apache.hadoop.hdfs.NameNodeProxiesClient.createProxyWithClientProtocol(NameNodeProxiesClient.java:134) at org.apache.hadoop.hdfs.DFSClient.&lt;init&gt;(DFSClient.java:374) at org.apache.hadoop.hdfs.DFSClient.&lt;init&gt;(DFSClient.java:308) at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:184) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:3414) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:158) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:3474) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:3442) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:524) at org.apache.hadoop.hbase.fs.HFileSystem.&lt;init&gt;(HFileSystem.java:91) at org.apache.hadoop.hbase.regionserver.HRegionServer.initializeFileSystem(HRegionServer.java:763) at org.apache.hadoop.hbase.regionserver.HRegionServer.&lt;init&gt;(HRegionServer.java:653) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at org.apache.hadoop.hbase.regionserver.HRegionServer.constructRegionServer(HRegionServer.java:3155) at org.apache.hadoop.hbase.regionserver.HRegionServerCommandLine.start(HRegionServerCommandLine.java:63) at org.apache.hadoop.hbase.regionserver.HRegionServerCommandLine.run(HRegionServerCommandLine.java:87) at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76) at org.apache.hadoop.hbase.util.ServerCommandLine.doMain(ServerCommandLine.java:149) at org.apache.hadoop.hbase.regionserver.HRegionServer.main(HRegionServer.java:3173) </code></pre> <p>jps shows:</p> <pre><code>31168 HQuorumPeer 14801 NodeManager 2049 Jps 12435 SecondaryNameNode 12105 NameNode 14699 ResourceManager 14141 DataNode </code></pre> <p>core-site.xml is :</p> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;hadoop.tmp.dir&lt;/name&gt; &lt;value&gt;/bigdata/hadoop/tmp&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;fs.default.name&lt;/name&gt; &lt;value&gt;hdfs://localhost:9000&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; </code></pre> <p>The hdfs-site.xml shows:</p> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;dfs.replication&lt;/name&gt; &lt;value&gt;1&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;dfs.namenode.name.dir&lt;/name&gt; &lt;value&gt;/usr/local/hadoop/yarn_data/hdfs/namenode&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;dfs.datanode.data.dir&lt;/name&gt; &lt;value&gt;/usr/local/hadoop/yarn_data/hdfs/datanode&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;dfs.namenode.http-address&lt;/name&gt; &lt;value&gt;localhost:50070&lt;/value&gt; &lt;/property&gt; &lt;configuration&gt; &lt;property&gt; &lt;name&gt;dfs.client.failover.proxy.provider.hdfscluster&lt;/name&gt; &lt;value&gt;org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; &lt;/configuration&gt; </code></pre> <p>Both of the config files are soft linked from hadoop/etc/hadoop/ I don't know how to fix this issue base on the log. Thanks for the help!</p> <hr /> <p>Update: After fixing the syntax error in hdfs-site.xml pointing out by majid.</p> <pre><code>&quot;ERROR [main] regionserver.HRegionServer: Failed construction RegionServer java.lang.IllegalArgumentException: java.net.UnknownHostException: hdfs at org.apache.hadoop.security.SecurityUtil.buildTokenService(SecurityUtil.java:448) at org.apache.hadoop.hdfs.NameNodeProxiesClient.createProxyWithClientProtocol(NameNodeProxiesClient.java:139)&quot; </code></pre>
3
1,994
ASP.net core: Model is null during rendering a page to string
<p>I want to render a page as email template. <br> But I get an error when the renderer wants to use the model <br> I follow this tutorial: <a href="https://www.learnrazorpages.com/advanced/render-partial-to-string" rel="nofollow noreferrer">learnrazorpages.com</a></p> <p>RazorRenderer.cs:</p> <pre><code>public class RazorRenderer : IRazorRenderer { private readonly IRazorViewEngine _viewEngine; private readonly ITempDataProvider _tempDataProvider; private readonly IServiceProvider _serviceProvider; public RazorRenderer( IRazorViewEngine viewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider) { _viewEngine = viewEngine; _tempDataProvider = tempDataProvider; _serviceProvider = serviceProvider; } public async Task&lt;string&gt; ToStringAsync&lt;TModel&gt;(string partialName, TModel model) { var actionContext = GetActionContext(); var partial = FindView(actionContext, partialName); var viewData = new ViewDataDictionary&lt;TModel&gt;(new EmptyModelMetadataProvider(), new ModelStateDictionary()); var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider); viewData.Model = model; await using var stringWriter = new StringWriter(); var viewContext = new ViewContext( actionContext, partial, viewData, tempData, stringWriter, new HtmlHelperOptions() ); await partial.RenderAsync(viewContext); return stringWriter.ToString(); } private IView FindView(ActionContext actionContext, string partialName) { var getPartialResult = _viewEngine.GetView(null, partialName, false); if (getPartialResult.Success) { return getPartialResult.View; } var findPartialResult = _viewEngine.FindView(actionContext, partialName, false); if (findPartialResult.Success) { return findPartialResult.View; } var searchedLocations = getPartialResult.SearchedLocations.Concat(findPartialResult.SearchedLocations); var errorMessage = string.Join( Environment.NewLine, new[] { $&quot;Unable to find partial '{partialName}'. The following locations were searched:&quot; }.Concat(searchedLocations)); throw new InvalidOperationException(errorMessage); } private ActionContext GetActionContext() { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; return new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); } } </code></pre> <p>Test.cs:</p> <pre><code>public class TestModel : PageModel { private readonly IRazorRenderer _razorRenderer; public RecoveryModel(IRazorRenderer razorRenderer) { _razorRenderer = razorRenderer; } public void OnGet() { } public async Task&lt;IActionResult&gt; OnPost() { var body = await _razorRenderer.ToStringAsync( &quot;Email&quot;, new Test { Email = &quot;Email@Test.com&quot; }); return Content(body); } } </code></pre> <p>Email.cshtml.cs</p> <pre><code>public class EmailModel : PageModel { public string Email { get; set; } public void OnGet() { } } </code></pre> <p>Email.cshtml:</p> <pre><code>@page @model EmailModel @{ Layout = null; } @Model.Email // Here I get the exception (Model is null) </code></pre> <p>Where did I do the wrong thing?</p>
3
1,534
dependency injection in asp.net core with generic parameters
<p>I am getting the following error during usage of service collection:</p> <blockquote> <p>Error while validating the service descriptor 'ServiceType: HappinessMeter.BL.GenericBL.IGenericBL'1[HappinessMeter.Entity.Models.MCountry] Lifetime: Singleton ImplementationInstance: HappinessMeter.BL.EFCoreCountryBL': Constant value of type 'HappinessMeter.BL.EFCoreCountryBL' can't be converted to service type 'HappinessMeter.BL.GenericBL.IGenericBL`1[HappinessMeter.Entity.Models.MCountry]'</p> </blockquote> <p>in <code>Startup.cs</code></p> <pre class="lang-cs prettyprint-override"><code>services.Add(new ServiceDescriptor(typeof(IGenericBL&lt;MCountry&gt;), new EFCoreCountryBL(new EFCoreCountryRepository(context)))); services.Add(new ServiceDescriptor(typeof(IGenericBL&lt;User&gt;), new EFCoreUserBL(new EFCoreUserRepository(context)))); </code></pre> <p>my code is for EFCoreRepository is :</p> <pre><code>public class EFCoreRepository&lt;Tentity, Tcontext&gt; : IRepository&lt;Tentity&gt; where Tentity : class where Tcontext : DbContext { public readonly Tcontext context; public EFCoreRepository(Tcontext _context) { context = _context; } public async Task&lt;Tentity&gt; Add(Tentity entity) { context.Set&lt;Tentity&gt;().Add(entity); await context.SaveChangesAsync(); return entity; } public async Task&lt;Tentity&gt; Delete(long id) { var entity = await context.Set&lt;Tentity&gt;().FindAsync(id); if (entity == null) { return entity; } context.Set&lt;Tentity&gt;().Remove(entity); await context.SaveChangesAsync(); return entity; } public async Task&lt;Tentity&gt; Get(long id) =&gt; await context.Set&lt;Tentity&gt;().FindAsync(id); public async Task&lt;List&lt;Tentity&gt;&gt; GetAll() =&gt; await context.Set&lt;Tentity&gt;().ToListAsync(); public async Task&lt;Tentity&gt; Update(Tentity entity) { context.Entry(entity).State = EntityState.Modified; await context.SaveChangesAsync(); return entity; } } </code></pre> <p>and EFCoreCountryRepository is</p> <pre><code>public class EFCoreCountryRepository : EFCoreRepository&lt;MCountry, HMDEVContext&gt; { public EFCoreCountryRepository(HMDEVContext context) : base(context) { } public async Task&lt;MCountry&gt; GetByAlpha(string alpha) { return await context.MCountry.FirstOrDefaultAsync(x =&gt; x.Alpha2Code == alpha); } } </code></pre>
3
1,157
Could this publish / check-for-update class for a single writer + reader use memory_order_relaxed or acquire/release for efficiency?
<h1>Introduction</h1> <p>I have a small class which make use of std::atomic for a lock free operation. Since this class is being called massively, it's affecting the performance and I'm having trouble.</p> <h1>Class description</h1> <p>The class similar to a LIFO, but once the pop() function is called, it only return the last written element of its ring-buffer (only if there are new elements since last pop()). </p> <p>A single thread is calling push(), and another single thread is calling pop(). </p> <h1>Source I've read</h1> <p>Since this is using too much time of my computer time, I decided to study a bit further the std::atomic class and its memory_order. I've read a lot of memory_order post avaliable in StackOverflow and other sources and books, but I'm not able to get a clear idea about the different modes. Specially, I'm struggling between acquire and release modes: I fail too see why they are different to memory_order_seq_cst.</p> <h1>What I <strong>think</strong> each memory order do using my words, from my own research</h1> <p><strong>memory_order_relaxed:</strong> In the same thread, the atomic operations are instant, but other threads may fail to see the lastest values instantly, they will need some time until they are updated. The code can be re-ordered freely by the compiler or OS.</p> <p><strong>memory_order_acquire / release:</strong> Used by atomic::load. It prevents the lines of code there are before this from being reordered (the compiler/OS may reorder after this line all it want), and reads the lastest value that was stored on this atomic using <strong>memory_order_release</strong> or <strong>memory_order_seq_cst</strong> in this thread or another thread. <strong>memory_order_release</strong> also prevents that code after it may be reordered. So, in an acquire/release, all the code between both can be shuffled by the OS. I'm not sure if that's between same thread, or different threads. </p> <p><strong>memory_order_seq_cst:</strong> Easiest to use because it's like the natural writting we are used with variables, instantly refreshing the values of other threads load functions.</p> <h1>The LockFreeEx class</h1> <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T&gt; class LockFreeEx { public: void push(const T&amp; element) { const int wPos = m_position.load(std::memory_order_seq_cst); const int nextPos = getNextPos(wPos); m_buffer[nextPos] = element; m_position.store(nextPos, std::memory_order_seq_cst); } const bool pop(T&amp; returnedElement) { const int wPos = m_position.exchange(-1, std::memory_order_seq_cst); if (wPos != -1) { returnedElement = m_buffer[wPos]; return true; } else { return false; } } private: static constexpr int maxElements = 8; static constexpr int getNextPos(int pos) noexcept {return (++pos == maxElements)? 0 : pos;} std::array&lt;T, maxElements&gt; m_buffer; std::atomic&lt;int&gt; m_position {-1}; }; </code></pre> <h1>How I expect it could be improved</h1> <p>So, my first idea was using memory_order_relaxed in all atomic operations, since the pop() thread is in a loop looking for avaliable updates in pop function each 10-15 ms, then it's allowed to fail in the firsts pop() functions to realize later that there is a new update. It's only a bunch of milliseconds.</p> <p>Another option would be using release/acquire - but I'm not sure about them. Using release in <strong>all</strong> store() and acquire in <strong>all</strong> load() functions.</p> <p>Unfortunately, <em>all the memory_order I described seems to work</em>, and I'm not sure when will they fail, if they are supposed to fail.</p> <h1>Final</h1> <p>Please, could you tell me if you see some problem using relaxed memory order here? Or should I use release/acquire (maybe a further explanation on these could help me)? why?</p> <p>I think that <em>relaxed</em> is the best for this class, in all its store() or load(). But I'm not sure!</p> <p>Thanks for reading.</p> <h1>EDIT: EXTRA EXPLANATION:</h1> <p>Since I see everyone is asking for the 'char', I've changed it to int, problem solved! But it doesn't it the one I want to solve. </p> <p>The class, as I stated before, is something likely to a LIFO but where only matters the last element pushed, if there is any.</p> <p>I have a big struct T (copiable and asignable), that I must share between two threads in a lock-free way. So, the only way I know to do it is using a circular buffer that writes the last known value for T, and a atomic which know the index of the last value written. When there isn't any, the index would be -1.</p> <p>Notice that my push thread must know when there is a "new T" avaliable, that's why pop() returns a bool.</p> <p>Thanks again to everyone trying to assist me with memory orders! :)</p> <h1>AFTER READING SOLUTIONS:</h1> <pre><code>template&lt;typename T&gt; class LockFreeEx { public: LockFreeEx() {} LockFreeEx(const T&amp; initValue): m_data(initValue) {} // WRITE THREAD - CAN BE SLOW, WILL BE CALLED EACH 500-800ms void publish(const T&amp; element) { // I used acquire instead relaxed to makesure wPos is always the lastest w_writePos value, and nextPos calculates the right one const int wPos = m_writePos.load(std::memory_order_acquire); const int nextPos = (wPos + 1) % bufferMaxSize; m_buffer[nextPos] = element; m_writePos.store(nextPos, std::memory_order_release); } // READ THREAD - NEED TO BE VERY FAST - CALLED ONCE AT THE BEGGINING OF THE LOOP each 2ms inline void update() { // should I change to relaxed? It doesn't matter I don't get the new value or the old one, since I will call this function again very soon, and again, and again... const int writeIndex = m_writePos.load(std::memory_order_acquire); // Updating only in case there is something new... T may be a heavy struct if (m_readPos != writeIndex) { m_readPos = writeIndex; m_data = m_buffer[m_readPos]; } } // NEED TO BE LIGHTNING FAST, CALLED MULTIPLE TIMES IN THE READ THREAD inline const T&amp; get() const noexcept {return m_data;} private: // Buffer static constexpr int bufferMaxSize = 4; std::array&lt;T, bufferMaxSize&gt; m_buffer; std::atomic&lt;int&gt; m_writePos {0}; int m_readPos = 0; // Data T m_data; }; </code></pre>
3
2,225
Cant display values from a bean method into <table>
<p>I have this problem. i implemented this table in my xhtml:</p> <pre><code> &lt;table id="tbResult" class="table table-bordered table-striped"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;#{msg.Sgc001tbcod}&lt;/th&gt; &lt;th&gt;Browser&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;th&gt;Rendering engine&lt;/th&gt; &lt;th&gt;Browser&lt;/th&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;/table&gt; </code></pre> <p>And this select on my BEAN:</p> <pre><code>public void select(int first, int pageSize, String sortField, Object filterValue) throws SQLException, ClassNotFoundException, NamingException { //System.out.println("entre al metodo SELECT"); Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Consulta paginada String query = "SELECT * FROM"; query += "(select query.*, rownum as rn from"; query += "(SELECT A.CODIGO, A.DESCR "; query += " FROM PRUEBA1 A"; query += " GROUP BY A.CODIGO, A.DESCR"; query += ")query ) " ; query += " WHERE ROWNUM &lt;="+pageSize; query += " AND rn &gt; ("+ first +")"; query += " ORDER BY " + sortField.replace("z", ""); pstmt = con.prepareStatement(query); //System.out.println(query); r = pstmt.executeQuery(); while (r.next()){ Prueba select = new Prueba(); select.setZcodigo(r.getString(1)); select.setZdesc(r.getString(2)); //Agrega la lista list.add(select); } //Cierra las conecciones pstmt.close(); con.close(); } </code></pre> <p>How can i make it so that i can display the values of the Select() method in the table?</p> <p>so far i havent made any progress.</p>
3
1,362
How to add empty value from gridview cell to list?
<p>I want to enter guest details(Title,Firstname,midname lastname) in a <code>list&lt;string&gt;</code> ,the guest details can be empty.I'm using LINQ for inserting in the list.I had referred this question for the LINQ code <a href="https://stackoverflow.com/questions/21314109/datagridview-write-all-values-from-a-column-to-list">DataGridView write all values from a column to list</a></p> <p>All I want to do is enter the text into the list if it has or insert empty string if it doesn't have.Right now if I leave textboxes blank it will throw <code>object reference not set to instance of an object exception</code></p> <pre><code>private string SaveGuestDetails() { string strRet = string.Empty; Reservation obj = new Reservation(); FinalReservationDetails f = new FinalReservationDetails(); try { //int i = dgvTextBoxes.Rows.Count; List&lt;DataRow&gt; personsList = new List&lt;DataRow&gt;(); int j = 0; for (int i = 0; i &lt; dgvTextBoxes.Rows.Count; i++) { f.SubSrNo = j + 1; f.GuestTitle = dgvTextBoxes.Rows .OfType&lt;DataGridViewRow&gt;() .Select(r =&gt; r.Cells["txtTitle"].Value.ToString()) .ToList(); f.FirstName = dgvTextBoxes.Rows .OfType&lt;DataGridViewRow&gt;() .Select(r =&gt; r.Cells["txtFname"].Value.ToString()) .ToList(); f.MidName = dgvTextBoxes.Rows .OfType&lt;DataGridViewRow&gt;() .Select(r =&gt; r.Cells["txtMName"].Value.ToString()) .ToList(); f.LastName = dgvTextBoxes.Rows .OfType&lt;DataGridViewRow&gt;() .Select(r =&gt; r.Cells["txtLname"].Value.ToString()) .ToList(); } } catch (Exception ex) { } return strRet; } </code></pre>
3
1,117
Open Source Spell Check for javascript Typo.js
<p>As I try to use the typo.js spell checker in my file. But it's throw some error's I can't find the solutions. I just followed the Typo.js Documentation Here is the document link. <a href="https://github.com/cfinke/Typo.js/" rel="nofollow noreferrer">https://github.com/cfinke/Typo.js/</a> Kindly check the below issue and help me to reach out this issue</p> <p><a href="https://i.stack.imgur.com/4EEYa.png" rel="nofollow noreferrer">Here is the console issue image</a></p> <p>Here is the used code</p> <p><strong>JS</strong></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Typo.js Example&lt;/title&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;typo/typo.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt; var dictionary = new Typo(&quot;en_US&quot;, false, false, { dictionaryPath: &quot;typo/dictionaries&quot; }); // function load() { // $('#loading-progress').append('Loading affix data...').append($('&lt;br /&gt;')); // $.get('typo/dictionaries/en_US/en_US.aff', function (affData) { // $('#loading-progress').append('Loading English dictionary (this takes a few seconds)...').append($('&lt;br /&gt;')); // $.get('typo/dictionaries/en_US/en_US.dic', function (wordsData) { // $('#loading-progress').append('Initializing Typo...'); // dictionary = new Typo(&quot;en_US&quot;, affData, wordsData); // checkWord('mispelled'); // }); // }); // } checkWord('mispelled'); function checkWord(word) { var wordForm = $('#word-form'); wordForm.hide(); var resultsContainer = $('#results'); resultsContainer.html(''); resultsContainer.append($('&lt;p&gt;').text(&quot;Is '&quot; + word + &quot;' spelled correctly?&quot;)); var is_spelled_correctly = dictionary.check(word); resultsContainer.append($('&lt;p&gt;').append($('&lt;code&gt;').text(is_spelled_correctly ? 'yes' : 'no'))); if (!is_spelled_correctly) { resultsContainer.append($('&lt;p&gt;').text(&quot;Finding spelling suggestions for '&quot; + word + &quot;'...&quot;)); var array_of_suggestions = dictionary.suggest(word); resultsContainer.append($('&lt;p&gt;').append($('&lt;code&gt;').text(array_of_suggestions.join(', ')))); } wordForm.show(); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Typo.js Demo&lt;/h1&gt; &lt;p&gt;This page is an example of how you could use &lt;a href=&quot;http://github.com/cfinke/Typo.js&quot;&gt;Typo.js&lt;/a&gt; in a webpage if you need spellchecking beyond what the OS provides.&lt;/p&gt; &lt;p id=&quot;loading-progress&quot;&gt;&lt;/p&gt; &lt;div id=&quot;results&quot;&gt;&lt;/div&gt; &lt;form method=&quot;GET&quot; action=&quot;&quot; onsubmit=&quot;checkWord( document.getElementById( 'word' ).value ); return false;&quot; id=&quot;word-form&quot; style=&quot;display: none;&quot;&gt; &lt;p&gt;Try another word:&lt;/p&gt; &lt;input type=&quot;text&quot; id=&quot;word&quot; value=&quot;mispelled&quot; /&gt; &lt;input type=&quot;submit&quot; value=&quot;Spellcheck&quot; /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
1,710
C Pthread taking much longer than single threaded
<p>I've made a matrix multiplier piece of code designed to quantify how much faster threading is for each size of matrix. The code where threads are made and executed is below. I'm new to threading but whenever I use threading it seems to take about 12 times longer, am I doing something wrong or does anyone know why it's so much slower?</p> <p>Thanks,</p> <pre><code>void *vectorMultiply(void *arguments){ struct vectorV *args = arguments; int sum = 0; for (int iii = 0; iii &lt; args-&gt;n; iii++) { sum = sum + args-&gt;first[args-&gt;i][iii] * args-&gt;second[iii][args-&gt;ii]; } args-&gt;out[args-&gt;i][args-&gt;ii] = sum; } void singleThreadVectorMultiply(int n,int i,int ii, int **first, int **second, int **out){ int sum = 0; for (int iii = 0; iii &lt; n; iii++) { sum = sum + first[i][iii] * second[iii][ii]; } out[i][ii] = sum; } void multiplyMatrix(int n, int** first, int** second, int** out){ pthread_t tid[n][n]; struct vectorV values[n][n]; for (int i = 0; i &lt; n; i++) { for (int ii = 0; ii &lt; n; ii++) { if(!SINGLETHREAD){ values[i][ii].n=n; values[i][ii].i=i; values[i][ii].ii=ii; values[i][ii].first = first; values[i][ii].second=second; values[i][ii].out=out; pthread_create(&amp;tid[i][ii], NULL, vectorMultiply, (void *)&amp;values[i][ii]); } else{ clock_t time; time = clock(); singleThreadVectorMultiply(n,i,ii,first,second,out); time = clock() - time; totalTime+=time; } } } if(!SINGLETHREAD){ clock_t time; time = clock(); for(int i=0; i &lt; n; i++) for(int ii=0; ii &lt; n; ii++) pthread_join( tid[i][ii], NULL); time = clock() - time; totalTime+=time; } } </code></pre>
3
1,070
EJB, JPA/Hibernate. I cannot make an insert in a database
<p>I am using Glassfish, EJB, JPA and Hibernate as a JPA implementation. I can get a select from a database via JPA but an insert does not work. Looks like a problem with JTA(may be a transaction was not completed or I use an another transaction) Persistence content does not flush to a database. The same code works properly when I use eclipselink as JPA implementation but I have to use hibernate.</p> <pre> <code> @Stateless @LocalBean public class BeanISManagedByContainer { @PersistenceContext(unitName = "com.company_JPATest2-ejb_ejb_1.0PU") EntityManager entityManager; public String getMessage(int id) { return entityManager.find(Message.class, id).getText(); } public void addMessaage(String txt) { Message message = new Message(); message.setText(txt); entityManager.persist(message); } } </code> </pre> <p>getMessage() method is works properly, but addMessaage() does not insert any data to a database and there are not any logs. Persistence context was not flushed to a database. I have tried to manage a transaction manually but the same result. I do not know what is wrong with a hibernate configuration. Please advise.</p> <pre> <code> @Stateless @LocalBean @TransactionManagement(TransactionManagementType.BEAN) public class ManualTransactions { @PersistenceContext(unitName = "com.company_JPATest2-ejb_ejb_1.0PU") EntityManager entityManager; @Resource private UserTransaction transaction; public void addMessaage(String txt) throws Exception { Message message = new Message(); message.setText(txt); transaction.begin(); Logger.getLogger(ManualTransactions.class.getName()) .info("transaction status: " + transaction.getStatus()); entityManager.persist(message); Logger.getLogger(ManualTransactions.class.getName()) .info("transaction status: " + transaction.getStatus()); transaction.commit(); Logger.getLogger(ManualTransactions.class.getName()) .info("transaction status: " + transaction.getStatus()); } } **logs:** Info: transaction status: 0 Info: transaction status: 0 Info: transaction status: 6 </code> </pre> <p><strong>persistance.xml</strong> <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"&gt; &lt;persistence-unit name="com.company_JPATest2-ejb_ejb_1.0PU" transaction-type="JTA"&gt; &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt; &lt;jta-data-source&gt;jdbc/JPATestPool&lt;/jta-data-source&gt; &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt; &lt;properties&gt; &lt;property name="hibernate.show_sql" value="true"/&gt; &lt;property name="hibernate.format_sql" value="true"/&gt; &lt;property name="hibernate.use_sql_comments" value="true"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt;</code></pre> </div> </div> </p> <p>pow.xml</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;artifactId&gt;JPATest2&lt;/artifactId&gt; &lt;groupId&gt;com.company&lt;/groupId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/parent&gt; &lt;groupId&gt;com.company&lt;/groupId&gt; &lt;artifactId&gt;JPATest2-ejb&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;packaging&gt;ejb&lt;/packaging&gt; &lt;name&gt;JPATest2-ejb&lt;/name&gt; &lt;properties&gt; &lt;endorsed.dir&gt;${project.build.directory}/endorsed&lt;/endorsed.dir&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;5.2.12.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;compilerArguments&gt; &lt;endorseddirs&gt;${endorsed.dir}&lt;/endorseddirs&gt; &lt;/compilerArguments&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-ejb-plugin&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;ejbVersion&gt;3.1&lt;/ejbVersion&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;validate&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${endorsed.dir}&lt;/outputDirectory&gt; &lt;silent&gt;true&lt;/silent&gt; &lt;artifactItems&gt; &lt;artifactItem&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-endorsed-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;type&gt;jar&lt;/type&gt; &lt;/artifactItem&gt; &lt;/artifactItems&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt;</code></pre> </div> </div> </p>
3
3,964
Creating user accounts for pre-registered users in Django
<p>I have a website that has a registration system and a blog with some registered users. Yesterday, I added a new app that creates dedicated profile pages for each one of those users. </p> <p>The issue being, the profile pages aren't getting created for the users that have already registered. This is, I guess because the user profile creation logic allows for profile creations only after the user has registered.</p> <p>Below is the code in my <strong><em>models.py</em></strong></p> <pre><code>from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def create_account(sender, instance, created, *args, **kwargs): if created: profile, new = UserAccount.objects.get_or_create(user=instance) post_save.connect(create_account, sender=settings.AUTH_USER_MODEL) </code></pre> <p>So, what can I do to create those profile pages?</p> <p>I tried the following:<br> 1. Manually creating a profile page against each registered users' username. (But this isn't the way I want to lean on. This is just a temporary arrangement)</p> <p>Issue with this, when the superuser who creates these profile pages calls for his private profile page [at /u/], the code looks towards all the users created by the superuser instead of his own. </p> <p>This is the error that's shown:</p> <pre><code>MultipleObjectsReturned at /u/ get() returned more than one UserAccount -- it returned 2! . . . instance = get_object_or_404(UserAccount) </code></pre> <p>So, what's the issue in code here? [my views.py]</p> <pre><code># public user profile def user_account(request, username): instance = get_object_or_404(UserAccount, user__username=username) context = { 'instance' : instance, 'title' : "User Account", } template = "user_accounts/public_account.html" return render(request, template, context) # private user profile. @login_required def self_user_account(request): if not request.user.is_authenticated: raise Http404 instance = get_object_or_404(UserAccount) if not request.user == instance.user: raise Http404 context = { 'instance' : instance, 'title' : 'Your Account', } template = "user_accounts/self_account.html" return render(request, template, context) # ability to update the user profile @login_required def update_user_account(request): if not request.user.is_authenticated: raise Http404 instance = get_object_or_404(UserAccount) if not request.user == instance.user: raise Http404 if request.method == 'POST': form = UserAccountForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Account Updated.") return HttpResponseRedirect("/u/") else: messages.error(request, "Something went wrong. Profile not created.") else: form = UserAccountForm(instance=instance) context = { 'title': 'Update Your Account', 'form' : form, } template = "user_accounts/update.html" return render(request, template, context) </code></pre> <p>Below is my <strong><em>urls.py</em></strong> These are populated after /u/ from the main <strong><em>urls.py</em></strong> </p> <pre><code>urlpatterns = [ # for updating url(r'^update/$', views.update_user_account, name="update_user_account"), # for outside world url(r'^(?P&lt;username&gt;[\w.@+-]+)/$', views.user_account, name="public_user_account"), # for the user himself url(r'^$', views.self_user_account, name="self_user_account"), ] </code></pre> <p>Below is my <strong><em>models.py</em></strong> script</p> <pre><code># uploading profile photos def upload_location(instance, filename): return "account_photos/%s/%s" %(instance.user, filename) # Create your models here. class UserAccount(models.Model): user = models.OneToOneField(User) photo = models.ImageField( upload_to=upload_location, # there needs to be a upload location tho # most probably a cdn server blank=True, null=True, width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=0, null=True) height_field = models.IntegerField(default=0, null=True) bio = models.TextField(max_length=60, null=True, blank=True, verbose_name="You in 60 words.") phone = PhoneNumberField(blank=True, verbose_name="Contact Number") status = models.CharField(max_length=128, default="Student") totos = models.IntegerField(default=0, verbose_name="Contribution") user_since = models.DateTimeField(auto_now=True) # social links email = models.EmailField(verbose_name="email address", max_length=255, unique=True, null=True, blank=True) custom_link = models.URLField(null=True, blank=True) facebook_link = models.URLField(null=True, blank=True) twitter_link = models.URLField(null=True, blank=True) linkedin_link = models.URLField(null=True, blank=True) github_link = models.URLField(null=True, blank=True) reddit_link = models.URLField(null=True, blank=True) def __str__(self): return self.user.username def get_absolute_url(self): return self.reverse("accounts:public_user_account", kwargs={"username":self.user__username}) from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) # User is coming from the user=models.OneToOneField(&lt;User&gt;) def create_account(sender, instance, created, *args, **kwargs): if created: profile, new = UserAccount.objects.get_or_create(user=instance) post_save.connect(create_account, sender=settings.AUTH_USER_MODEL) </code></pre>
3
2,417
Adding TextView into another layout programatically
<p>I am strugling with one problem. I have got one main view with two layouts inside it:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".TestMainActivity" &gt; &lt;HorizontalScrollView android:id="@+id/menuView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" &gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" &gt; &lt;Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add" /&gt; &lt;Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add2" /&gt; &lt;/LinearLayout&gt; &lt;/HorizontalScrollView&gt; &lt;com.test.board.Board android:id="@+id/boardView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/menuView" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Board layout is my class which is inhariting from ViewGroup. What I want to achive is to add TextView (or any other Layout elent like Image, button, another layout) into my canvas (borad).</p> <p>This is how am I doing it now:</p> <pre><code>Button textBold = (Button) findViewById(R.id.button1); textBold.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView txt1 = new TextView(TestMainActivity.this); txt1.setText("Sample text"); txt1.setTextColor(Color.BLUE); txt1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); myView.addView(txt1); } }); </code></pre> <p>myView is object of class Board.</p> <p>When I am checking the number of child elements is increasing each time, but I don't see this TextView.</p> <p>Can someone please tell me, what I have to do to make this text visible?</p> <p><strong>EDIT</strong></p> <p>It might be a mistake that I didn't put whole onCreat method, where I initialize myView. So there it is:</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myView = (Board) findViewById(R.id.boardView1); myView.setBackgroundColor(Color.WHITE); myView.refreshView(); //function below Button textBold = (Button) findViewById(R.id.button1); textBold.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView txt1 = new TextView(TestMainActivity.this); txt1.setText("Sample text"); txt1.setTextColor(Color.BLUE); txt1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); myView.addView(txt1); } }); </code></pre> <p>there is refreshView() function just for extra:</p> <pre><code>public void refreshView() { // redraw the view invalidate(); requestLayout(); } </code></pre>
3
1,705
error: no matching member function for call to 'upper_bound' => only on macOS => Windows and Linux are fine
<p>I'm compiling a code inspired by <a href="https://codereview.stackexchange.com/q/158369/141750">this</a> with Qt Creator. Code compiles fine on Windows 10 and openSUSE Leap 15 but throws this error on macOS High Sierra:</p> <pre><code>error: no matching member function for call to 'upper_bound' auto end = band.upper_bound({ 0, last-&gt;y + d }); ~~~~~^~~~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/set:692:14: note: candidate function not viable: cannot convert initializer list argument to 'const std::__1::set&lt;Point, std::__1::less&lt;Point&gt;, std::__1::allocator&lt;Point&gt; &gt;::key_type' (aka 'const Point') iterator upper_bound(const key_type&amp; __k) ^ </code></pre> <p>My header contains:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;cmath&gt; #include &lt;iostream&gt; struct Point { float x{0}, y{0}; // Used by the `set&lt;point&gt;` to keep the points in the band // sorted by Y coordinates. bool operator&lt;(Point const &amp;other) const { return y &lt; other.y; } friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, Point const &amp;p) { return os &lt;&lt; "(" &lt;&lt; p.x &lt;&lt; ", " &lt;&lt; p.y &lt;&lt; ")"; } }; </code></pre> <p>My source contains:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;set&gt; std::pair&lt;Point, Point&gt; nearest_pair(std::vector&lt;Point&gt; points) { std::sort(points.begin(), points.end(), [](Point const &amp;a, Point const &amp;b) { return a.x &lt; b.x; } ); // First and last points from `point` that are currently in the "band". auto first = points.cbegin(); auto last = first + 1; // The two closest points we've found so far: auto first_point = *first; auto second_point = *last; std::set&lt;Point&gt; band{ *first, *last }; float d = dist(*first, *last); while (++last != points.end()) { while (last-&gt;x - first-&gt;x &gt; d) { band.erase(*first); ++first; } auto begin = band.lower_bound({ 0, last-&gt;y - d }); // ERROR line auto end = band.upper_bound({ 0, last-&gt;y + d }); // ERROR line assert(std::distance(begin, end) &lt;= 6); for (auto p = begin; p != end; ++p) { if (d &gt; dist(*p, *last)) { first_point = *p; second_point = *last; d = dist(first_point, second_point); } } band.insert(*last); } return std::make_pair(first_point, second_point); } </code></pre> <p>I guess I need to modify my <code>Point</code> structure, but I'm not sure how. Can anybody help?</p> <hr> <h2>Update</h2> <p>Error got resolved by adding these two constructors to <code>Point</code> structure:</p> <pre class="lang-cpp prettyprint-override"><code> Point(){ } Point(float x, float y): x(x) , y(y) { } </code></pre>
3
1,363
vba - saving file to my personal desktop code
<p>I have the following code which is designed so I can quick save to my desktop and then put the file into a folder. This code works fine if the file is already saved in an .xls, .csv, .xlsx or .xlsm file extension, however, when the file IS NOT saved, I only get the pop-up message boxes, and nothing happens. I was thinking about re-structuring using a CASE STATEMENT with right(activeworkbook.name, 4), but didn't know how to structure as I am not familiar with these statements. Thank you.</p> <pre><code>Sub SavetoDesktop() 'this macro will save the activesheet into the default path giving it the current name and xlsx extension Dim fname As String ' If Right(ActiveWorkbook.Name, 5) &lt;&gt; ".xlsx" And Right(ActiveWorkbook.Name, 5) &lt;&gt; ".xls" And _ ' Right(ActiveWorkbook.Name, 5) &lt;&gt; ".xlsm" And Right(ActiveWorkbook.Name, 5) &lt;&gt; ".csv" Then If Right(ActiveWorkbook.Name, 5) = ".xlsx" Then fname = Application.DefaultFilePath &amp; "\" &amp; Application.WorksheetFunction.Substitute(ActiveWorkbook.Name, ".xlsx", "") &amp; ".xlsx" ActiveWorkbook.SaveAs Filename:=fname Else MsgBox "Not an .xlsx file!" ActiveWorkbook.SaveAs Filename:="C:\Users\mmirabelli\Desktop\" &amp; ActiveWorkbook.Name &amp; ".xlsx" End If If Right(ActiveWorkbook.Name, 4) = ".csv" Then fname = Application.DefaultFilePath &amp; "\" &amp; Application.WorksheetFunction.Substitute(ActiveWorkbook.Name, ".csv", "") &amp; ".csv" ActiveWorkbook.SaveAs Filename:=fname Else MsgBox "Not an .csv file!" MsgBox ActiveWorkbook.Name End If If Right(ActiveWorkbook.Name, 4) = ".xls" Then fname = Application.DefaultFilePath &amp; "\" &amp; Application.WorksheetFunction.Substitute(ActiveWorkbook.Name, ".xls", "") &amp; ".xls" ActiveWorkbook.SaveAs Filename:=fname Else MsgBox "Not an .xls file!" End If If Right(ActiveWorkbook.Name, 5) = ".xlsm" Then fname = Application.DefaultFilePath &amp; "\" &amp; Application.WorksheetFunction.Substitute(ActiveWorkbook.Name, ".xlsm", "") &amp; ".xlsm" ActiveWorkbook.SaveAs Filename:=fname Else MsgBox "Not an .xlsm file!" End If ' Else ' ' ActiveWorkbook.SaveAs Filename:="C:\Users\mmirabelli\Desktop\" &amp; ActiveWorkbook.Name &amp; ".xlsx" ' End If 'MsgBox Application.DefaultFilePath 'MsgBox ActiveWorkbook.Name ' ' ActiveWorkbook.SaveAs Filename:=fname ' End Sub </code></pre>
3
1,325
Problems building a flooding script that uses sockets
<p>I'm trying to improve 2 projects of flooders (not mine) making my own script that these 2 ones. Doing that, I've almost finished but I'm stuck in a point where the script does nothing. Here is the code:</p> <pre><code>import socket, threading, random, time, urllib.request, re, os.path from bs4 import BeautifulSoup useragents=["Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko", "Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0", "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16", "Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/533.1 (KHTML, like Gecko) Maxthon/3.0.8.2 Safari/533.1",] def checkurl(): global url url = input("Insert URL: ") if url[0]+url[1]+url[2]+url[3] == "www.": url = "http://" + url elif url[0]+url[1]+url[2]+url[3] == "http": pass else: url = "http://" + url def threads(): global thread try: thread = int(input("Thread (800): ")) except: thread = 800 def proxymode(): global choise1 choise1 = input("Do you want proxy mode? Answer 'y' to enable it: ") if choise1 == "y": choisedownproxy() else: exit(0) def choisedownproxy(): choise2 = input("Do you want to download a fresh list of proxy? Answer 'y' to do it: ") print ("") if choise2 == "y": proxyget() else: proxylist() def proxyget(): if os.path.isfile("proxy.txt"): out_file = open("proxy.txt","w") out_file.write("") out_file.close() else: pass url = "https://www.inforge.net/xi/forums/liste-proxy.1118/" soup = BeautifulSoup(urllib.request.urlopen(url), "lxml") base = "https://www.inforge.net/xi/" for tag in soup.find_all("a", {"class":"PreviewTooltip"}): links = tag.get("href") final = base + links result = urllib.request.urlopen(final) for line in result : ip = re.findall("(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3}):(?:[\d]{1,5})", str(line)) if ip: print("Proxy grabbed=&gt; "+'\n'.join(ip)) for x in ip: out_file = open("proxy.txt","a") while True: out_file.write(x+"\n") out_file.close() break proxylist() def proxylist(): global proxy global entries out_file = str(input("Enter the proxy list: ")) entries = open(out_file).readlines() proxy = random.choice(entries).strip().split(':') requestproxy() def requestproxy(): global proxy host = proxy[0] port = proxy[1] host_url = url.replace("http://", "").replace("https://", "").split('/')[0] get_host = "GET " + url + " HTTP/1.1\r\nHost: " + host_url + "\r\n" useragent = "User-Agent: " + random.choice(useragents) + "\r\n" accept = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate" connection = "Connection: Keep-Alive\r\n" request = get_host + useragent + accept + connection + "\r\n" while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send(request) except: proxy = random.choice(entries).strip().split(':') checkurl() threads() proxymode() </code></pre> <p>As you can see, this script uses a list of proxies to send request (using socket library) to target. But when I arrive at "Enter the proxy list" and after typed "proxy.txt", the script gets stuck! What did I do wrong? Can you help me?</p>
3
2,252
Floating div's left or right depending on variable WITHOUT columns
<p>I'm modifying my current build of one of my pages where there are X amount of boxes with varying content in each box, some float to the left, some float to the right and some fill the whole column space. The way this is currently done is like this:</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="doubleColumn"&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;div class="singleColumn left"&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="singleColumn right"&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.doubleColumn { float: left; width: 100%; } .singleColumn { width: 49%; } .contentBox { border: 1px solid RGB(0, 0, 0); box-sizing: border-box; -moz-box-sizing: border-box; margin-bottom: 20px; padding: 10px; width: 100%; } .left { float: left; } .right { float: right; } </code></pre> <p>For the current solution there is no issues as the layout works perfectly and if below the left and right columns i wanted to add another 2 wider content boxes, i simply add those, then perhaps another 2 inside a left column below that. The issue comes when i try to assign variables to determine which box goes where, because i'm trying to make it so we can adjust each box to be either at the top, bottom or middle or wherever else we wish it to be, and also adjust whether it sits on the left, right or fills the whole box. I got a "half-working" solution in which i use the to run a check that if a boxes position equals one, it fills the space, if it equals 2 it floats left and if it equals 3 it floats right. I'll demonstrate once again below:</p> <p><strong>HTML</strong></p> <pre><code>&lt;cfquery datasource="datasource" name="boxes"&gt; Select * From boxes Order by box_order &lt;/cfquery&gt; &lt;div class="doubleColumn"&gt; &lt;cfoutput query="boxes"&gt; &lt;cfif box_position eq 1&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;cfelseif box_position eq 2&gt; &lt;div style="clear: left; float: left; width: 49%;"&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;/div&gt; &lt;cfelseif box_position eq 3&gt; &lt;div style="clear: right; float: right; width: 49%;"&gt; &lt;div class="contentBox"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/cfif&gt; &lt;/cfoutput&gt; &lt;/div&gt; </code></pre> <p>But if I have two in a row that float left, then one that float right it (as it would) floats next to the second one on the left rather than the first one because of using clear, but if i don't use clear then the second left will sit alongside the first left. I'm stuck and don't know how to solve this issue.</p>
3
1,138
how to programmatically show a colored disk behind a UIImageView, in swift on an iOS device
<p>I have an icon that I programmatically display.<br /> How can I display a solid, colored disk behind the icon, at the same screen position?</p> <p>Icon is opaque.</p> <p>I will sometimes programmatically change screen position and disk's diameter and color.</p> <p>Here's how I programmatically display the icon now.............</p> <pre><code>DispatchQueue.main.async { ViewController.wrist_band_UIImageView.frame = CGRect( x: screen_position_x, y: screen_position_y, width: App_class.screen_width, height: App_class.screen_height) } </code></pre> <p><strong>UPDATE #1</strong> for D.Mika below... <a href="https://i.stack.imgur.com/gOJLE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gOJLE.png" alt="enter image description here" /></a></p> <p><strong>UPDATE #2</strong> for D.Mika below...</p> <pre><code>import UIKit import Foundation class ViewController: UIViewController { static var circleView: UIView! static let wrist_band_UIImageView: UIImageView = { let theImageView = UIImageView() theImageView.image = UIImage( systemName: &quot;applewatch&quot; ) theImageView.translatesAutoresizingMaskIntoConstraints = false return theImageView }() override func viewDidLoad() { super.viewDidLoad() view.addSubview( ViewController.wrist_band_UIImageView ) // Init disk image: ViewController.circleView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)) ViewController.circleView.backgroundColor = .red ViewController.circleView.layer.cornerRadius = view.bounds.size.height / 2.0 ViewController.circleView.clipsToBounds = true // Add view to view hierarchy below image view ViewController.circleView.insertSubview(view, belowSubview: ViewController.wrist_band_UIImageView) App_class.display_single_wearable() } } class App_class { static var is_communication_established = false static var total_packets = 0 static func display_single_wearable() { ViewController.wrist_band_UIImageView.frame = CGRect(x: 0, y: 0, width: 100, height: 100) ViewController.circleView.frame = CGRect( x: 0, y: 0, width: 100, height: 100) ViewController.circleView.layer.cornerRadius = 100 } static func process_location_xy(text_location_xyz: String) {} } // App_class </code></pre> <p><a href="https://i.stack.imgur.com/BBUMc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBUMc.png" alt="enter image description here" /></a></p>
3
1,424
windows spyder invalid syntax error while running py file
<p>I am trying to run the last example from the <a href="https://www.analyticsvidhya.com/blog/2019/08/comprehensive-guide-language-model-nlp-python-code/" rel="nofollow noreferrer">page</a>. I have cloned the repository in the directory <code>C:/Users/nn/Desktop/BERT/transformers-master</code>. I am on windows machine and using spyder IDE. Why i do get below error and how could i resolve it? How do i input the initial part of the poem?</p> <pre><code>import os os.chdir('C:/Users/nn/Desktop/BERT/transformers-master/examples') os.listdir()# It shows run_generation.py file python run_generation.py \ --model_type=gpt2 \ --length=100 \ --model_name_or_path=gpt2 \ python run_generation.py \ --model_type=gpt2 \ --length=100 \ --model_name_or_path=gpt2 \ File "&lt;ipython-input-10-501d266b0e64&gt;", line 1 python run_generation.py \ ^ SyntaxError: invalid syntax </code></pre> <p>I went to command prompt and tried below</p> <pre><code>cd C:/Users/nn/Desktop/BERT/transformers-master/examples python3 run_generation.py \--model_type=gpt2 \--length=100 \--model_name_or_path=gpt2 \--promt="Hello world" </code></pre> <p>nothing happens :(</p> <p>when i try the same with python command i get an error as below :(</p> <pre><code>python run_generation.py \--model_type=gpt2 \--length=100 \--model_name_or_path=gpt2 \--promt="Hello world" 2019-12-04 11:23:36.345648: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_100.dll'; dlerror: cudart64_100.dll not found 2019-12-04 11:23:36.352875: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. usage: run_generation.py [-h] --model_type MODEL_TYPE --model_name_or_path MODEL_NAME_OR_PATH [--prompt PROMPT] [--padding_text PADDING_TEXT] [--xlm_lang XLM_LANG] [--length LENGTH] [--num_samples NUM_SAMPLES] [--temperature TEMPERATURE] [--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P] [--no_cuda] [--seed SEED] [--stop_token STOP_TOKEN] run_generation.py: error: the following arguments are required: --model_type, --model_name_or_path </code></pre> <p><strong><em>####update 2 ------------------</em></strong></p> <p>I followed suggestions in the comments and it worked. It seems that the code downloads 3 files. </p> <ol> <li>Can i copy those files manually so that I dont have to rely on downloading them every time in a temp folder? </li> <li>Where should i store those files? which folder location? would it be <code>C:\Users\nnn\Desktop\BERT\transformers-master\examples</code> - same as <code>run_generation.py</code> file?</li> </ol> <p><code>abc</code></p> <pre><code>C:\Users\nnn\Desktop\BERT\transformers-master\examples&gt;python run_generation.py --model_type=gpt2 --length=100 --model_name_or_path=gpt2 --prompt="My job is" 2019-12-12 11:11:57.740810: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_100.dll'; dlerror: cudart64_100.dll not found 2019-12-12 11:11:57.748330: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 12/12/2019 11:12:01 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpt_29gyqi 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1042301/1042301 [00:00&lt;00:00, 2275416.04B/s] 12/12/2019 11:12:02 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpt_29gyqi to cache at C:\Users\nnn\.cache\torch\transformers\f2808208f9bec2320371a9f5f891c184ae0b674ef866b79c58177067d15732dd.1512018be4ba4e8726e41b9145129dc30651ea4fec86aa61f4b9f40bf94eac71 12/12/2019 11:12:02 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\f2808208f9bec2320371a9f5f891c184ae0b674ef866b79c58177067d15732dd.1512018be4ba4e8726e41b9145129dc30651ea4fec86aa61f4b9f40bf94eac71 12/12/2019 11:12:02 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpt_29gyqi 12/12/2019 11:12:03 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpj1_y4sn8 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 456318/456318 [00:00&lt;00:00, 1456594.78B/s] 12/12/2019 11:12:03 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpj1_y4sn8 to cache at C:\Users\nnn\.cache\torch\transformers\d629f792e430b3c76a1291bb2766b0a047e36fae0588f9dbc1ae51decdff691b.70bec105b4158ed9a1747fea67a43f5dee97855c64d62b6ec3742f4cfdb5feda 12/12/2019 11:12:03 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\d629f792e430b3c76a1291bb2766b0a047e36fae0588f9dbc1ae51decdff691b.70bec105b4158ed9a1747fea67a43f5dee97855c64d62b6ec3742f4cfdb5feda 12/12/2019 11:12:03 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpj1_y4sn8 12/12/2019 11:12:03 - INFO - transformers.tokenization_utils - loading file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json from cache at C:\Users\nnn\.cache\torch\transformers\f2808208f9bec2320371a9f5f891c184ae0b674ef866b79c58177067d15732dd.1512018be4ba4e8726e41b9145129dc30651ea4fec86aa61f4b9f40bf94eac71 12/12/2019 11:12:03 - INFO - transformers.tokenization_utils - loading file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt from cache at C:\Users\nnn\.cache\torch\transformers\d629f792e430b3c76a1291bb2766b0a047e36fae0588f9dbc1ae51decdff691b.70bec105b4158ed9a1747fea67a43f5dee97855c64d62b6ec3742f4cfdb5feda 12/12/2019 11:12:04 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpyxywrts1 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 176/176 [00:00&lt;00:00, 17738.31B/s] 12/12/2019 11:12:04 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpyxywrts1 to cache at C:\Users\nnn\.cache\torch\transformers\4be02c5697d91738003fb1685c9872f284166aa32e061576bbe6aaeb95649fcf.085d5f6a8e7812ea05ff0e6ed0645ab2e75d80387ad55c1ad9806ee70d272f80 12/12/2019 11:12:04 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\4be02c5697d91738003fb1685c9872f284166aa32e061576bbe6aaeb95649fcf.085d5f6a8e7812ea05ff0e6ed0645ab2e75d80387ad55c1ad9806ee70d272f80 12/12/2019 11:12:04 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpyxywrts1 12/12/2019 11:12:04 - INFO - transformers.configuration_utils - loading configuration file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json from cache at C:\Users\nnn\.cache\torch\transformers\4be02c5697d91738003fb1685c9872f284166aa32e061576bbe6aaeb95649fcf.085d5f6a8e7812ea05ff0e6ed0645ab2e75d80387ad55c1ad9806ee70d272f80 12/12/2019 11:12:04 - INFO - transformers.configuration_utils - Model config { "attn_pdrop": 0.1, "embd_pdrop": 0.1, "finetuning_task": null, "initializer_range": 0.02, "layer_norm_epsilon": 1e-05, "n_ctx": 1024, "n_embd": 768, "n_head": 12, "n_layer": 12, "n_positions": 1024, "num_labels": 1, "output_attentions": false, "output_hidden_states": false, "output_past": true, "pruned_heads": {}, "resid_pdrop": 0.1, "summary_activation": null, "summary_first_dropout": 0.1, "summary_proj_to_labels": true, "summary_type": "cls_index", "summary_use_proj": true, "torchscript": false, "use_bfloat16": false, "vocab_size": 50257 } 12/12/2019 11:12:04 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-pytorch_model.bin not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpn8i9o_tm 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 548118077/548118077 [01:12&lt;00:00, 7544610.26B/s] 12/12/2019 11:13:18 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpn8i9o_tm to cache at C:\Users\nnn\.cache\torch\transformers\4295d67f022061768f4adc386234dbdb781c814c39662dd1662221c309962c55.778cf36f5c4e5d94c8cd9cefcf2a580c8643570eb327f0d4a1f007fab2acbdf1 12/12/2019 11:13:24 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\4295d67f022061768f4adc386234dbdb781c814c39662dd1662221c309962c55.778cf36f5c4e5d94c8cd9cefcf2a580c8643570eb327f0d4a1f007fab2acbdf1 12/12/2019 11:13:24 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpn8i9o_tm 12/12/2019 11:13:24 - INFO - transformers.modeling_utils - loading weights file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-pytorch_model.bin from cache at C:\Users\nnn\.cache\torch\transformers\4295d67f022061768f4adc386234dbdb781c814c39662dd1662221c309962c55.778cf36f5c4e5d94c8cd9cefcf2a580c8643570eb327f0d4a1f007fab2acbdf1 12/12/2019 11:13:32 - INFO - __main__ - Namespace(device=device(type='cpu'), length=100, model_name_or_path='gpt2', model_type='gpt2', n_gpu=0, no_cuda=False, num_samples=1, padding_text='', prompt='My job is', repetition_penalty=1.0, seed=42, stop_token=None, temperature=1.0, top_k=0, top_p=0.9, xlm_lang='') 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:23&lt;00:00, 2.49it/s] to know when it will change, it's up to you." National Communications Director Alex Brynner said the Trump administration needs to help then-Secretary of State Rex Tillerson learn from him. "The Cabinet, like any other government job, has to be attentive to the needs of an individual that might challenge his or her position," Brynner said. "This is especially true in times of renewed volatility." Brynner said Tillerson has not "failed at vetting </code></pre>
3
4,353
Hello, I have some problems with ffmpeg.concat, there are logs
<p>Log:</p> <pre><code>[swscaler @ 0x27d3c10] [swscaler @ 0x2886fe0] deprecated pixel format used, make sure you did set range correctly [swscaler @ 0x27d3c10] [swscaler @ 0x283be10] deprecated pixel format used, make sure you did set range correctly Output #0, avi, to '/home/pi/Desktop/VIDEOREG/2022:05:12_09:51:57:856_v1.avi': Metadata: software : Lavf58.45.100 ISFT : Lavf59.20.101 Stream #0:0: Video: mpeg4 (FMP4 / 0x34504D46), yuv420p(tv, bt470bg/unknown/unknown, progressive), 1080x720, q=2-31, 200 kb/s, 25 fps, 25&gt; Metadata: encoder : Lavc59.25.100 mpeg4 Side data: cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A Output #0, avi, to '/home/pi/Desktop/VIDEOREG/2022:05:12_09:51:57:911_v3.avi': Metadata: software : Lavf58.45.100 ISFT : Lavf59.20.101 Stream #0:0: Video: mpeg4 (FMP4 / 0x34504D46), yuv420p(tv, bt470bg/unknown/unknown, progressive), 1080x720, q=2-31, 200 kb/s, 25 fps, 25&gt; Metadata: encoder : Lavc59.25.100 mpeg4 Side data: cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A Output #0, avi, to '/home/pi/Desktop/VIDEOREG/2022:05:12_09:51:57:890_v2.avi': Metadata: software : Lavf58.45.100 ISFT : Lavf59.20.101 Stream #0:0: Video: mpeg4 (FMP4 / 0x34504D46), yuv420p(tv, bt470bg/unknown/unknown, progressive), 1080x720, q=2-31, 200 kb/s, 25 fps, 25&gt; Metadata: encoder : Lavc59.25.100 mpeg4 Side data: cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A [mjpeg @ 0x27aaa10] mjpeg_decode_dc: bad vlc: 0:0 (0x27b7c20)trate=8122.4kbits/s speed=1.33e+04x [mjpeg @ 0x27aaa10] error dc [mjpeg @ 0x27aaa10] error y=18 x=37 [mjpeg @ 0x27aaa10] EOI missing, emulating [mjpeg @ 0x29551c0] error count: 65 [mjpeg @ 0x29551c0] error y=2 x=17 ############################################### </code></pre> <p>My part of code for concatenation audio and video:</p> <pre><code>def video_with_audio(number, filename, video): ms = datetime.today().strftime('%f') + '0000' ms = ms[:3] name = datetime.today().strftime('%Y:%m:%d_%H:%M:%S:') title_video = f'/home/pi/Desktop/VIDEOREG/{name}{ms}{number}.avi' print(title_video) os.system(&quot;ffmpeg -i &quot; + video + &quot; -vf setpts=PTS*2 &quot; + title_video) #################################################### ms_1 = datetime.today().strftime('%f') + '0000' ms_1 = ms_1[:3] name_1 = datetime.today().strftime('%Y:%m:%d_%H:%M:%S:') title_video = f'/home/pi/Desktop/VIDEOREG/{name}{ms}{number}.avi' title_video_1 = f'/home/pi/Desktop/VIDEOREG/{name_1}{ms_1}{number}.avi' input_audio = ffmpeg.input(filename) input_video = ffmpeg.input(title_video) print(title_video_1) ffmpeg.concat(input_video, input_audio, v=1, a=1).output(title_video_1).run() </code></pre> <p>There are slight delays during video recording, because I print information from sensors on video, can this affect the concatenation of video with audio? (Saved video is accelerated? that's why at the beginning I used slowing video down.)</p>
3
1,502
Tkinter Scrollbar inactive untill the window is manually resized
<p>The scrollbar activates only when the window is rezised, despite reconfiguring the scrollregion everytime a widget(Button in this case) is added.</p> <pre><code>class Editor: def __init__(self,master): self.master = master self.master.resizable(True,False) self.edit_frame = tk.Frame(self.master) self.edit_frame.pack(fill=&quot;none&quot;) self.elem_frame = tk.Frame(self.master,width=700) self.elem_frame.pack(fill=&quot;y&quot;, expand=1) self.my_canvas = tk.Canvas(self.elem_frame, width = 700) self.my_canvas.pack(side = &quot;left&quot;, fill=&quot;both&quot;, expand=1) my_scrollbar = ttk.Scrollbar(self.elem_frame, orient = &quot;vertical&quot;, command =self.my_canvas.yview) my_scrollbar.pack(side = &quot;right&quot;,fill=&quot;y&quot;) self.my_canvas.configure(yscrollcommand=my_scrollbar.set) self.my_canvas.bind('&lt;Configure&gt;', self.movescroll ) self.second_frame = tk.Frame(self.my_canvas, bg = &quot;black&quot;, width=700) self.my_canvas.create_window((0,0), window=self.second_frame, anchor=&quot;nw&quot;) self.naz = Nazioni() paesi = [*self.naz.iso3] print(paesi) self.comb_paese = ttk.Combobox(self.edit_frame, value = paesi) self.comb_paese.current(1) self.kwordvar= tk.StringVar() entry_keyword = tk.Entry(self.edit_frame, textvariable=self.kwordvar) entry_keyword.bind(&quot;&lt;FocusOut&gt;&quot;, self.callback) writer = tk.Text(self.edit_frame) self.edit_frame.pack(side=&quot;left&quot;) writer.pack() self.comb_paese.pack() entry_keyword.pack() def callback(self, *args): kword = self.kwordvar.get() self.colonnarisultati(kword) def colonnarisultati(self, keyword): #TROVA IL VALORE CODICE ISO A 3CHAR IN BASE ALLA NAZIONE NEL COMBOBOX p = self.comb_paese.get() paese = self.naz.iso3[p] ricerca = Ricerca(paese, keyword) &quot;&quot;&quot; for label in self.elem_frame.winfo_children(): label.destroy() &quot;&quot;&quot; self.count = 0 print(&quot;ciao&quot;) for x in ricerca.listaricerca: tit = str(x['titolo']).lstrip(&quot;&lt;h4&gt;&quot;).rstrip(&quot;&lt;/h4&gt;&quot;) print(tit) self.elementotrovato(tit,self.count) self.count +=1 self.my_canvas.configure(scrollregion=self.my_canvas.bbox(&quot;all&quot;)) def movescroll(self, *args): self.my_canvas.configure(scrollregion=self.my_canvas.bbox(&quot;all&quot;)) def elementotrovato(self, testobottone, conta): Bott_ecoifound = tk.Button(self.second_frame, text = testobottone,width = 100 ,height = 30, font = (&quot;Helvetica&quot;, 12, &quot;bold&quot;), wraplength=200, justify=&quot;left&quot;) print(&quot;CIAONE&quot;) Bott_ecoifound.pack(fill=&quot;both&quot;, expand=1) self.my_canvas.configure(scrollregion=self.my_canvas.bbox(&quot;all&quot;)) </code></pre> <p>The last method is the one adding button to the scrollable frame. After the window is manually resized, no matter if back to its original size, the scrollbar activates and works fine.</p>
3
1,787
How to create a “sessionId” column using timestamps and userid in PySpark?
<p>I have a data set which contains fields such as: userId, event, pageName, and timestamp, while lacking of the sessionId. I want to create a sessionId for each record based on the timestamp and a pre-defined value &quot;finish&quot; (which indicates after how many minutes of inactivity a session ends). Only users with the same UserId can be in the same session.</p> <p>If the &quot;finish&quot; value is 30 minutes (1800 difference in timestamp), and a sample DataFrame is:</p> <pre><code>from pyspark.sql import functions as F from pyspark.sql.window import Window df = spark.createDataFrame([ (&quot;blue&quot;, &quot;view&quot;, 1610494094750, 11), (&quot;green&quot;, &quot;add to bag&quot;, 1510593114350, 21), (&quot;red&quot;, &quot;close&quot;, 1610493115350, 41), (&quot;blue&quot;, &quot;view&quot;, 1610494094350, 11), (&quot;blue&quot;, &quot;close&quot;, 1510593114312, 21), (&quot;red&quot;, &quot;view&quot;, 1610493114350, 41), (&quot;red&quot;, &quot;view&quot;, 1610593114350, 41), (&quot;green&quot;, &quot;purchase&quot;, 1610494094350, 31) ], [&quot;item&quot;, &quot;event&quot;, &quot;timestamp&quot;, &quot;userId&quot;]) +-----+----------+-------------+------+ | item| event| timestamp|userId| +-----+----------+-------------+------+ | blue| view|1610494094750| 11| |green|add to bag|1510593114350| 21| | red| close|1610493115350| 41| | blue| view|1610494094350| 11| | blue| close|1510593114312| 21| | red| view|1610493114350| 41| | red| view|1610593114350| 41| |green| purchase|1610494094350| 31| +-----+----------+-------------+------+ </code></pre> <p>The end result should be something like this:</p> <pre><code>+--------+----------+-------------+------+---------+ | item| event| timestamp|userId|sessionId| +--------+----------+-------------+------+---------+ | blue| close|1510593114312| 21| session1| | green|add to bag|1510593114350| 21| session1| | red| view|1610493114350| 41| session2| | blue| view|1610494094350| 11| session3| | red| close|1610493115350| 41| session2| | green| purchase|1610494094350| 31| session4| | blue| view|1610494094750| 11| session3| | red| view|1610593114350| 41| session5| +--------+----------+-------------+------+---------+ </code></pre> <p>I'm trying to solve this problem using PySpark. Any advice is welcome.</p> <p>Edit: I've edited the timestamp</p>
3
1,065
This loop only allows me to choose one option for various questions although they all have their varying options
<p>php code to loop through to fetch questions and answers from database. This is mainly where my problem is. I see all the questions and their options but I can only answer for one question </p> <pre><code>&lt;?php while ($data = mysql_fetch_assoc($result) ) { $qID = $data['QID']; $question = $data['Question']; $A = $data['qA']; $B = $data['qB']; $C = $data['qC']; ?&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;?php echo $qID?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $question ?&gt; &lt;/td&gt; </code></pre> <p>Loop to bring out available options per question</p> <pre><code> &lt;td&gt; &lt;div&gt; &lt;input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" /&gt; &lt;label for="question-1-answers-A"&gt;A)&amp;nbsp; &lt;?php echo $data["qA"]; ?&gt; &lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" /&gt; &lt;label for="question-1-answers-B3"&gt;B)&amp;nbsp; &lt;?php echo $data["qB"]; ?&gt; &lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" /&gt; &lt;label for="question-1-answers-C3"&gt;C)&amp;nbsp; &lt;?php echo $data["qC"]; ?&gt; &lt;/label&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>End of the loop </p>
3
1,345
How can I get the current value from a variable when passing it to an event?
<p>I have the following problem. I'm making an ajax request to an API which returns a <strong>json</strong>. I iterate through the json object and list the results in li tags the tricky part comes here when I make the <em>li.OnClick()</em> event I need to pass the current index of the selected item but i always get the last one. I think it's because it is passed by reference not by value. How can I cope with this problem?</p> <p>Here is the code: </p> <pre><code>$StiboJQuery.ajax({ url: loqateApiEndpoint, type: 'POST', data: { "lqtkey":"key", "query":street, "country":country }, success: function(response) { debugger; if(response.Status === "OK" &amp;&amp; response.output.length &gt; 0) { $StiboJQuery('#' + divId).remove(); var ul = document.createElement('ul'); var div = document.createElement('div'); div.id = divId; div.className = 'address-suggestions'; for(var i = 0; i &lt; response.output.length; i++) { var elNumber = [index: i]; var label = response.output[i]; var li = document.createElement('li'); li.setAttribute('Country', response.metadata[i].CountryName || ''); li.setAttribute('Street', response.metadata[i].DeliveryAddress || ''); li.setAttribute('City', response.metadata[i].Locality || ''); li.setAttribute('State', response.metadata[i].AdministrativeArea || ''); li.setAttribute('Postcode', response.metadata[i].PostalCode || ''); debugger; li.innerHTML = response.output[i]; //Here is where I'm passing the i variable li.onclick = function() { listItemClickEventHandler(this, div, isForBilling, i); } li.onmouseover = function(){ this.setAttribute("style", "background: #d7ebf9; padding: 3px 5px; cursor: pointer;"); } li.onmouseout = function(){ this.setAttribute("style", "background: #fff; padding: 3px 5px;"); } $StiboJQuery(ul).append(li); } $StiboJQuery(div).append(ul); isForBilling ? $StiboJQuery("[id$='billingStreet']").after(div) : $StiboJQuery("[id$='shippingStreet']").after(div); } } }); } function getCountry(isForBilling) { return isForBilling ? $StiboJQuery("[id$='billingCountry']").val() : $StiboJQuery("[id$='shippingCountry']").val(); } function getStreet(isForBilling) { return isForBilling ? $StiboJQuery("[id$='billingStreet']").val() : $StiboJQuery("[id$='shippingStreet']").val(); } function listItemClickEventHandler(sender, container, isForBilling, num) { debugger; var idPart = isForBilling ? 'billing' : 'shipping'; var captureApiEndpoint = "https://api.everythinglocation.com/address/capture"; var country = getCountry(isForBilling); var street = getStreet(isForBilling); // And here is where I use it and I always get the value of 10 $StiboJQuery.ajax({ url: captureApiEndpoint, type: 'POST', dataType: "xml", data: { "lqtkey":"key", "query":street, "country":country, "result": num }, success: function(response) { debugger; if(response.Status === "OK" &amp;&amp; response.output.length &gt; 0) { var address = response.output; console.log(address); } } }); $StiboJQuery("[id$='"+idPart+"Country']").val(sender.getAttribute('Country')); $StiboJQuery("[id$='"+idPart+"Street']").val(sender.getAttribute('Street')); $StiboJQuery("[id$='"+idPart+"City']").val(sender.getAttribute('City')); $StiboJQuery("[id$='"+idPart+"State']").val(sender.getAttribute('State')); $StiboJQuery("[id$='"+idPart+"PostalCode']").val(sender.getAttribute('Postcode')); $StiboJQuery(container).remove(); } &lt;/script&gt; </code></pre>
3
2,248
Why does interp1d throw LinAlgError("SVD did not converge")?
<p>I have a sequence of 2 dimensional points (so: (x,y) coordinates) and I want to fit a cubic spline through it. So I split the sequence in two sequences <code>xs</code>, <code>ys</code> with the following properties:</p> <ul> <li><code>len(xs) = len(ys) &gt; 4</code></li> <li><code>xs</code> is strictly increasing</li> </ul> <p>So there should be a cubic spline through those points. But I still get an error:</p> <pre><code>#!/usr/bin/env python import numpy import scipy from scipy.interpolate import interp1d import sys print("Python: %s" % sys.version) print("numpy: %s" % numpy.__version__) print("scipy: %s " % scipy.__version__) print("numpy config:") numpy.show_config() xs = [0, 31, 39, 48, 58, 75, 91, 108, 127, 141, 158, 175, 194, 208, 224, 241, 258, 291, 310, 343, 379, 427, 444, 459, 493, 526, 560, 580, 626, 659, 693, 726, 759, 793, 826, 859, 893, 926, 958, 993, 1025, 1059, 1093, 1125, 1159, 1193, 1224, 1257, 1278, 1310, 1343, 1379, 1410, 1443, 1478, 1512, 1558, 1662, 1815, 1823, 1831, 1845, 1860, 1876] ys = [0.7072243346007605, 0.6996197718631179, 0.6844106463878327, 0.6730038022813688, 0.6577946768060836, 0.6159695817490495, 0.5665399239543726, 0.5019011406844106, 0.43346007604562736, 0.3840304182509506, 0.3041825095057034, 0.2623574144486692, 0.23574144486692014, 0.20532319391634982, 0.155893536121673, 0.11406844106463879, 0.07984790874524715, 0.026615969581749048, 0.0076045627376425855, 0.0, 0.0, 0.0038022813688212928, 0.022813688212927757, 0.053231939163498096, 0.12927756653992395, 0.17870722433460076, 0.22433460076045628, 0.24334600760456274, 0.30798479087452474, 0.33840304182509506, 0.376425855513308, 0.3840304182509506, 0.376425855513308, 0.3574144486692015, 0.3041825095057034, 0.2509505703422053, 0.21292775665399238, 0.1520912547528517, 0.12167300380228137, 0.09885931558935361, 0.09125475285171103, 0.09125475285171103, 0.11787072243346007, 0.1596958174904943, 0.20152091254752852, 0.24714828897338403, 0.28517110266159695, 0.3155893536121673, 0.33840304182509506, 0.3688212927756654, 0.39543726235741444, 0.44106463878326996, 0.4828897338403042, 0.5057034220532319, 0.5247148288973384, 0.5285171102661597, 0.532319391634981, 0.5361216730038023, 0.5475285171102662, 0.5627376425855514, 0.5779467680608364, 0.5893536121673004, 0.6007604562737643, 0.6083650190114068] print("xs length: %i" % len(xs)) print("ys length: %i" % len(ys)) print("Is xs strictly increasing? %r" % all(x &lt; y for x, y in zip(xs, xs[1:]))) xs = numpy.array(xs) fx = interp1d(xs, ys, kind='cubic') </code></pre> <p>with the output:</p> <pre><code>./test.py Python: 2.7.5+ (default, Feb 27 2014, 19:37:08) [GCC 4.8.1] numpy: 1.8.1 scipy: 0.14.0 numpy config: lapack_info: NOT AVAILABLE lapack_opt_info: NOT AVAILABLE blas_info: NOT AVAILABLE atlas_threads_info: NOT AVAILABLE blas_src_info: NOT AVAILABLE atlas_blas_info: NOT AVAILABLE lapack_src_info: NOT AVAILABLE openblas_info: NOT AVAILABLE atlas_blas_threads_info: NOT AVAILABLE blas_mkl_info: NOT AVAILABLE blas_opt_info: NOT AVAILABLE atlas_info: NOT AVAILABLE lapack_mkl_info: NOT AVAILABLE mkl_info: NOT AVAILABLE xs length: 64 ys length: 64 Is xs strictly increasing? True Traceback (most recent call last): File "./test.py", line 23, in &lt;module&gt; fx = interp1d(xs, ys, kind='cubic') File "/usr/local/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 412, in __init__ self._spline = splmake(x, y, order=order) File "/usr/local/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 2110, in splmake coefs = func(xk, yk, order, conds, B) File "/usr/local/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 1800, in _find_smoothest u, s, vh = np.dual.svd(B) File "/usr/local/lib/python2.7/dist-packages/scipy/linalg/decomp_svd.py", line 103, in svd raise LinAlgError("SVD did not converge") numpy.linalg.linalg.LinAlgError: SVD did not converge </code></pre> <p>The question is: Why does <code>interp1d</code> throw <code>LinAlgError(“SVD did not converge”)</code> and how can I fix it?</p> <h2>My system</h2> <p>I have <code>numpy</code> version 1.8.1, <code>scipy</code> version <code>0.14.0</code>, <code>Python 2.7.5+</code> on a Linux Mint 16 Petra.</p>
3
1,952
Put Json/Jsonp data to a form using ajax
<p>The chinese map service "Tencent map" provides a Json/Jsonp URL to get the location information, the URL is like:</p> <p><a href="http://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&amp;key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&amp;get_poi=1" rel="nofollow">http://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&amp;key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&amp;get_poi=1</a></p> <p>Assume that I fill the latitude and longitude into a form, how to use JS/JQ to get the Json date and fill the "pois"(which in the json-> result -> pois ) data to a drop-down menu in the form?</p> <p>The html I wrote is like:</p> <pre><code>&lt;from&gt; &lt;lable&gt;Oraginal GPS coordinates&lt;/lable&gt;&lt;/br&gt; &lt;input type="text" id="geo_latitude" name="geo_latitude" value="39.86343486063931"&gt; &lt;input type="text" id="geo_longitude" name="geo_longitude" value="116.37321682380312"&gt; &lt;button onclick="getLocation()"&gt;GET it&lt;/button&gt; &lt;select id="geo_spot" name="geo_spot"&gt; &lt;option&gt;&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>The Js is:(to make it jsonp I added "?output=jsonp" in the url to make it Jsonp to avoid Cross domain error)</p> <pre><code> jQuery(document).ready(function(){ var lat = parseFloat(document.getElementById("geo_latitude").value); var lng = parseFloat(document.getElementById("geo_longitude").value); var url='http://apis.map.qq.com/ws/geocoder/v1/?output=jsonp&amp;location='+lat+','+lng+'&amp;key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&amp;get_poi=1&amp;callback=?'; jQuery.ajax({ url:url, dataType:'jsonp', processData: true, type:'get', jsonp: "callback", contentType: "application/jsonp; charset=utf-8", success:function(data){ alert(jsonp.result.pois); }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); }}); }); </code></pre> <p>My target is to add up all Pois date in Jsonp into that drop down options, but after tried and tried, I can't even get the date....</p> <p>Can you point out the mistake of my code? That would be very helpful!</p> <p>I put a sample here so you can test my MISTAKE <a href="http://fireso.com/geo.html" rel="nofollow">http://fireso.com/geo.html</a> </p> <p>PS, I can't modify the server part code, and have to use the api in a different domain, so the only way is working with the html js part.</p> <p>Thank you for any help!</p>
3
1,185
Unable to implement CustomAuthenticationProvider with Spring Security: BeanCreationException while autowiring
<p>I am implementing CustomAuthenticationProvider in Spring Security. I have created the CustomAuthenticationProvider class which implements AuthenticationProvider. However, when I define this CustomAuthenticationProvider in my SecurityConfiguration class and autowire it, the application throws following error:</p> <pre><code>2020-03-08 19:27:42 [main] ERROR o.s.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.highrise.isimwebapp.config.customauth.CustomAuthenticationProvider com.highrise.isimwebapp.config.SecurityConfiguration.authProvider; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.highrise.isimwebapp.config.customauth.CustomAuthenticationProvider] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} </code></pre> <p>I have included the @Component annotation in my CustomAuthenticationProvider class. Also, the package under which this class is defined, is included in the @ComponentScan. The context is not picking up CustomAuthenticationProvider bean. The other defined classes are successfully getting picked up by the context as defined in the @ComponentScan and no such error is received on their autowired objects. What could be wrong from my side? Any help regarding how this can be fixed would be highly appreciated.</p> <p>CustomAuthenticationProvider.java</p> <pre><code>@Component public class CustomAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // TODO Auto-generated method stub String name = authentication.getName(); String password = authentication.getCredentials().toString(); if(name.equalsIgnoreCase("testuser1") &amp;&amp; password.equalsIgnoreCase("demo")) return new UsernamePasswordAuthenticationToken(name, password); else throw new BadCredentialsException("Authentication failed"); } @Override public boolean supports(Class&lt;?&gt; authentication) { // TODO Auto-generated method stub return authentication.equals(UsernamePasswordAuthenticationToken.class); } } </code></pre> <p>SecurityConfiguration.java</p> <pre><code>@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationProvider authProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/resources/**").permitAll() .antMatchers("/icon/**").permitAll() .anyRequest().authenticated() .and().formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll().defaultSuccessUrl("/persons/listall") .and().csrf().disable(); } } </code></pre> <p>SpringWebConfig.java</p> <pre><code>@EnableWebMvc @Configuration @ComponentScan({ "com.highrise.isimwebapp.config", "com.highrise.isimwebapp.config.customauth", "com.highrise.isimwebapp.config.servlet3", "com.highrise.isimwebapp.web", "com.highrise.isimwebapp.service", "com.highrise.isimwebapp.dao", "com.highrise.isimwebapp.exception", "com.highrise.isimwebapp.validator" }) public class SpringWebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/jsp/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource rb = new ResourceBundleMessageSource(); rb.setBasenames(new String[] { "messages/messages", "messages/validation" }); return rb; } } </code></pre>
3
1,278
React and Axios Post payload formatting
<p>I'm really new to this so forgive me if I word things wrong. So right now I have a simple web UI with a text box for a Name, and then a checkmark selection box for a type, along with a submit button.</p> <p>Test code looks something like this:</p> <pre><code>value = &quot;val7&quot;; key = &quot;63&quot;; typeID = 103; name = &quot;testname&quot;; const onSubmitClick = (event) =&gt; { axiosPost('testurl', { Message: { Type: typeID, Payload: { title: null, messagebody: null, data: { value, key, }, }, Delivery: { Name: [{&quot;Name&quot;: name}] } } }) } </code></pre> <p>and when I press submit, the Payload looks like this:</p> <pre><code>{ &quot;Message&quot;: { &quot;Type&quot;: 103, &quot;Payload&quot;: { &quot;title&quot;: null, &quot;messagebody&quot;: null, &quot;data&quot;: { &quot;value&quot;: &quot;val17&quot;, &quot;key&quot;: &quot;63&quot; } }, &quot;Delivery&quot;: { &quot;Name&quot;: [{ &quot;Name&quot;: &quot;testname&quot; }] } } } </code></pre> <p>However, I need the data portion of the payload to look more like this:</p> <pre><code>{ &quot;Message&quot;: { &quot;Type&quot;: 103, &quot;Payload&quot;: { &quot;title&quot;: null, &quot;messagebody&quot;: null, &quot;data&quot;: { &quot;val17&quot;: &quot;63&quot; } }, &quot;Delivery&quot;: { &quot;Name&quot;: [{ &quot;Name&quot;: &quot;testname&quot; }] } } } </code></pre> <p>How do I go about doing this?</p>
3
1,140
Fading element in the center of window by scrolling
<p>I use a script in which elements fade in from the left and right as soon as the respective element has been scrolled completely into view. The problem is, the fade-in remains until the element has completely disappeared from the field of view. I try to implement it in such a way that it fades out as soon as it is no longer completely in sight. Otherwise, all elements are shown at the same time when scrolling.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Utils() {} Utils.prototype = { constructor: Utils, isElementInView: function(element, fullyInView) { var pageTop = $(window).scrollTop(); var pageBottom = pageTop + $(window).height(); var elementTop = $(element).offset().top; var elementBottom = elementTop + $(element).height(); if (fullyInView === true) { return ((pageTop &lt; elementTop) &amp;&amp; (pageBottom &gt; elementBottom)); } else { return ((elementTop &lt;= pageBottom) &amp;&amp; (elementBottom &gt;= pageTop)); } } }; var Utils = new Utils(); $(window).on('load', addFadeIn()); $(window).scroll(function() { addFadeIn(true); }); function addFadeIn(repeat) { var classToFadeIn = ".will-fadeIn"; $(classToFadeIn).each(function(index) { var isElementInView = Utils.isElementInView($(this), false); if (isElementInView) { if (!($(this).hasClass('fadeInRight')) &amp;&amp; !($(this).hasClass('fadeInLeft'))) { if (index % 2 == 0) $(this).addClass('fadeInRight'); else $(this).addClass('fadeInLeft'); } } else if (repeat) { $(this).removeClass('fadeInRight'); $(this).removeClass('fadeInLeft'); } }); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#locations-mobile { height: auto; display: block; } #loc1, #loc2, #loc3, #loc4 { height: 300px; background-size: cover; } .locimg { width: 100%; background-size: cover; background-repeat: no-repeat; } .loc { cursor: pointer; height: 100%; width: 100%; background-size: cover; background-repeat: no-repeat; background-position: center; position: relative; overflow: hidden; text-align: center; } .loc .fadedbox, .loc-selected { background-color: #202020; position: absolute; top: 0; left: 0; color: #fff; -webkit-transition: all 300ms ease-out; -moz-transition: all 300ms ease-out; -o-transition: all 300ms ease-out; -ms-transition: all 300ms ease-out; transition: all 300ms ease-out; opacity: 0; width: 100%; height: 100%; } .loc:hover .fadedbox, .loc-selected { opacity: 0.8; } .loc .text, .loc .text a, .will-fadeIn .text, .will-fadeIn .text p, .will-fadeIn .text p a { top: 0%; left: 0%; position: relative; text-align: center; color: #fff; text-decoration: none; -webkit-transition: all 300ms ease-out; -moz-transition: all 300ms ease-out; -o-transition: all 300ms ease-out; -ms-transition: all 300ms ease-out; transition: all 300ms ease-out; transform: translateY(50px); -webkit-transform: translateY(50px); } .loc .text, .loc .text a, .will-fadeIn .text, .will-fadeIn .text p, .will-fadeIn .text p a { transform: translateY(30px); -webkit-transform: translateY(30px); } .loc .title { font-size: 2.5em; text-align: center; text-transform: uppercase; opacity: 0; transition-delay: 0.2s; transition-duration: 0.3s; } .will-fadeIn .text .title a { color: #fff; font-size: 2.5em; } #loc1 { grid-area: 1 / 1 / 2 / 2; background-image: url(https://images.pexels.com/photos/380769/pexels-photo-380769.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=750&amp;w=1260) } #loc2 { grid-area: 1 / 2 / 2 / 3; background-image: url(https://images.pexels.com/photos/380769/pexels-photo-380769.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=750&amp;w=1260) } #loc3 { grid-area: 1 / 3 / 2 / 4; background-image: url(https://images.pexels.com/photos/380769/pexels-photo-380769.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=750&amp;w=1260) } #loc4 { grid-area: 1 / 4 / 2 / 5; background-image: url(https://images.pexels.com/photos/380769/pexels-photo-380769.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=750&amp;w=1260) } .doing { transform: rotate(-35deg); display: block; position: absolute; top: 0; left: -90px; margin-top: 25px; text-align: center; width: 300px; color: #fff; } .will-fadeIn { display: block; width: 100%; max-width: 640px; margin: 0px auto; height: 100%; background-color: #202020; } .fadeInRight { -webkit-animation: fadeInRight .5s ease .4s both; -moz-animation: fadeInRight .5s ease .4s both; -ms-animation: fadeInRight .5s ease .4s both; -o-animation: fadeInRight .5s ease .4s both; animation: fadeInRight .5s ease .4s both; } @media (prefers-reduced-motion) { .fadeInRight .animated { -webkit-animation: unset !important; animation: unset !important; -webkit-transition: none !important; transition: none !important; } } .fadeInLeft { -webkit-animation: fadeInLeft .5s ease .4s both; -moz-animation: fadeInLeft .5s ease .4s both; -ms-animation: fadeInLeft .5s ease .4s both; -o-animation: fadeInLeft .5s ease .4s both; animation: fadeInLeft .5s ease .4s both; } @media (prefers-reduced-motion) { .fadeInLeft .animated { -webkit-animation: unset !important; animation: unset !important; -webkit-transition: none !important; transition: none !important; } } @-webkit-keyframes fadeInRight { from { opacity: 0; -webkit-transform: translate3d(100%, 0, 0); -moz-transform: translate3d(100%, 0, 0); -ms-transform: translate3d(100%, 0, 0); -o-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-moz-keyframes fadeInRight { from { opacity: 0; -webkit-transform: translate3d(100%, 0, 0); -moz-transform: translate3d(100%, 0, 0); -ms-transform: translate3d(100%, 0, 0); -o-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-ms-keyframes fadeInRight { from { opacity: 0; -webkit-transform: translate3d(100%, 0, 0); -moz-transform: translate3d(100%, 0, 0); -ms-transform: translate3d(100%, 0, 0); -o-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-o-keyframes fadeInRight { from { opacity: 0; -webkit-transform: translate3d(100%, 0, 0); -moz-transform: translate3d(100%, 0, 0); -ms-transform: translate3d(100%, 0, 0); -o-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @keyframes fadeInRight { from { opacity: 0; -webkit-transform: translate3d(100%, 0, 0); -moz-transform: translate3d(100%, 0, 0); -ms-transform: translate3d(100%, 0, 0); -o-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-webkit-keyframes fadeInLeft { from { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); -moz-transform: translate3d(-100%, 0, 0); -ms-transform: translate3d(-100%, 0, 0); -o-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-moz-keyframes fadeInLeft { from { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); -moz-transform: translate3d(-100%, 0, 0); -ms-transform: translate3d(-100%, 0, 0); -o-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-ms-keyframes fadeInLeft { from { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); -moz-transform: translate3d(-100%, 0, 0); -ms-transform: translate3d(-100%, 0, 0); -o-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @-o-keyframes fadeInLeft { from { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); -moz-transform: translate3d(-100%, 0, 0); -ms-transform: translate3d(-100%, 0, 0); -o-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } @keyframes fadeInLeft { from { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); -moz-transform: translate3d(-100%, 0, 0); -ms-transform: translate3d(-100%, 0, 0); -o-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } to { opacity: .8; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;section id="locations-mobile"&gt; &lt;div id="loc1"&gt; &lt;div class="fadedbox will-fadeIn"&gt; &lt;div class="text"&gt; &lt;p class="title"&gt;&lt;a href="/standorte/1#"&gt;#&lt;/a&gt;&lt;/p&gt; &lt;p&gt; &lt;a href="#" target="_blank"&gt; &lt;i class="fas fa-map-marker-alt"&gt;&lt;/i&gt;#&lt;br /&gt; # &lt;/a&gt; &lt;/p&gt; &lt;p&gt;&lt;a href="#"&gt;&lt;i class="fas fa-phone"&gt;&lt;/i&gt;#&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="loc2"&gt; &lt;div class="fadedbox will-fadeIn"&gt; &lt;div class="text"&gt; &lt;p class="title"&gt;&lt;a href="/standorte/2#"&gt;#&lt;/a&gt;&lt;/p&gt; &lt;p&gt; &lt;a href="#" target="_blank"&gt; &lt;i class="fas fa-map-marker-alt"&gt;&lt;/i&gt;#&lt;br /&gt; # &lt;/a&gt; &lt;/p&gt; &lt;p&gt;&lt;a href="#"&gt;&lt;i class="fas fa-phone"&gt;&lt;/i&gt;#&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="loc3"&gt; &lt;div class="fadedbox will-fadeIn"&gt; &lt;div class="text"&gt; &lt;p class="title"&gt;&lt;a href="/standorte/3#"&gt;#&lt;/a&gt;&lt;/p&gt; &lt;p&gt; &lt;a href="#" target="_blank"&gt; &lt;i class="fas fa-map-marker-alt"&gt;&lt;/i&gt;#&lt;br /&gt; # &lt;/a&gt; &lt;/p&gt; &lt;p&gt;&lt;a href="#"&gt;&lt;i class="fas fa-phone"&gt;&lt;/i&gt;#&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="loc4"&gt; &lt;div class="fadedbox will-fadeIn"&gt; &lt;div class="text"&gt; &lt;p class="title"&gt;&lt;a href="/standorte/4#"&gt;#&lt;/a&gt;&lt;/p&gt; &lt;p&gt; &lt;a href="#" target="_blank"&gt; &lt;i class="fas fa-map-marker-alt"&gt;&lt;/i&gt;#&lt;br /&gt; # &lt;/a&gt; &lt;/p&gt; &lt;p&gt;&lt;a href="#"&gt;&lt;i class="fas fa-phone"&gt;&lt;/i&gt;#&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
3
6,936
Swift - Visual format language - how to make multiple rows and columns
<p>I just started swift programming and i'm facing difficulties with visual format constraints. I'm trying to make multiple tables of 3 by 6 rows and columns with and header on top of the table. I have added the names of the row and columns but it's not aligned in the expected (by me) order. The problem in below code is: the line</p> <pre><code>&gt; addConstraintsWithFormat(format: "H:|-40-[v0][v1][v2]-[v3]-[v4]-|", &gt; views: cashLabel, pinLabel, idealLabel, houseLabel, &gt; totalPerPayMethodLabel) is placed in between the rows of &gt; addConstraintsWithFormat(format: "V:|-[v0(30)]-[v1]-[v2]-[v3]-|", &gt; views: timePeriodLabel, highBtwLabel, lowBtwLabel, totalPerBtwLabel). </code></pre> <p>Also the cashLabel has a big gap with the pinLabel. When i remove the (30) from view v0 the line with the cashLabel, pinLabel etc. is placed above the other rows (V:) as expected. Also the cashLabel does not seem to be affected by the H:-40-[v0] etc.</p> <p>class AccountingCell: UITableViewCell {</p> <pre><code>override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } let timePeriodLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.red label.text = "Header" label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center return label }() let highBtwLabel: UILabel = { let label = UILabel() label.text = "high vat" label.translatesAutoresizingMaskIntoConstraints = false return label }() let lowBtwLabel: UILabel = { let label = UILabel() label.text = "low vat" label.translatesAutoresizingMaskIntoConstraints = false return label }() let cashLabel: UILabel = { let label = UILabel() label.text = "Cash" label.translatesAutoresizingMaskIntoConstraints = false return label }() let pinLabel: UILabel = { let label = UILabel() label.text = "Pin" label.translatesAutoresizingMaskIntoConstraints = false return label }() let idealLabel: UILabel = { let label = UILabel() label.text = "IDEAL" label.translatesAutoresizingMaskIntoConstraints = false return label }() let houseLabel: UILabel = { let label = UILabel() label.text = "House" label.translatesAutoresizingMaskIntoConstraints = false return label }() let totalPerBtwLabel: UILabel = { let label = UILabel() label.text = "Totaal" label.translatesAutoresizingMaskIntoConstraints = false return label }() let totalPerPayMethodLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.red label.text = "Totaal" label.translatesAutoresizingMaskIntoConstraints = false return label }() func setupViews() { addSubview(timePeriodLabel) addSubview(highBtwLabel) addSubview(lowBtwLabel) addSubview(cashLabel) addSubview(pinLabel) addSubview(idealLabel) addSubview(houseLabel) addSubview(totalPerBtwLabel) addSubview(totalPerPayMethodLabel) addConstraintsWithFormat(format: "H:|[v0]|", views: timePeriodLabel) addConstraintsWithFormat(format: "H:|-40-[v0][v1][v2]-[v3]-[v4]-|", views: cashLabel, pinLabel, idealLabel, houseLabel, totalPerPayMethodLabel) addConstraintsWithFormat(format: "H:|[v0]|", views: timePeriodLabel) addConstraintsWithFormat(format: "H:|[v0]|", views: highBtwLabel) addConstraintsWithFormat(format: "H:|[v0]|", views: lowBtwLabel) addConstraintsWithFormat(format: "H:|[v0]|", views: totalPerBtwLabel) addConstraintsWithFormat(format: "V:|-[v0(30)]-[v1]-[v2]-[v3]-|", views: timePeriodLabel, highBtwLabel, lowBtwLabel, totalPerBtwLabel) addConstraintsWithFormat(format: "V:|-[v0]-|", views: cashLabel) addConstraintsWithFormat(format: "V:|-[v0]-|", views: pinLabel) addConstraintsWithFormat(format: "V:|-[v0]-|", views: idealLabel) addConstraintsWithFormat(format: "V:|-[v0]-|", views: houseLabel) addConstraintsWithFormat(format: "V:|-[v0]-|", views: totalPerPayMethodLabel) } </code></pre>
3
1,593
Microsoft Chart size varies on different build server despite defining the fixed height and width
<p>I have a problem where I am rendering MS Chart on Pdf on Active Report 6 (Picture control) through memory stream. I have encountered a problem where the size of my chart is varying based on the build server. Not sure which property is causing this issue. On few build machine the Chart is huge and on few the chart size is reduced.</p> <p>Any pointer ??</p> <p>I have a scheduler service built on DotNet framework 3.5 running on my local machine Windows 10. MS chart version being used - 3.5 Framework Active Reports - version 6</p> <p>Where as when actually the service being delivered to QA which is Windows server 2016, the size of chart is being changed .</p> <p>Below is the code</p> <p>//*********Chart defining</p> <pre><code> Chart chart = new Chart(); chart.Height = 100; chart.Width = 250; chart.ChartAreas.Add(new ChartArea("Default")); ChartArea chartArea = chart.ChartAreas["Default"]; chart.ChartAreas["Default"].InnerPlotPosition.Auto = false; chart.ChartAreas["Default"].InnerPlotPosition.X = 10F; chart.ChartAreas["Default"].InnerPlotPosition.Height = 95F; chart.ChartAreas["Default"].InnerPlotPosition.Width = 54.30373F; chart.ChartAreas["Default"].InnerPlotPosition.Y = 2.500001F; chart.Legends.Add(new Legend("Default")); chart.Legends[0].Enabled = true; chart.Legends[0].Alignment = StringAlignment.Near; chart.Legends[0].TitleAlignment = StringAlignment.Center; chart.Legends[0].LegendStyle = LegendStyle.Column; chart.Legends[0].Docking = Docking.Right; chart.Legends[0].Font = new Font("Arial", 5f); LegendCellColumn valuey = new LegendCellColumn("", LegendCellColumnType.Text, "#VALY{N0}", ContentAlignment.MiddleCenter); LegendCellColumn symbolCol = new LegendCellColumn("", LegendCellColumnType.SeriesSymbol, "", ContentAlignment.TopLeft); chart.Legends[0].CellColumns.Add(symbolCol); chart.Legends[0].CellColumns.Add(valuey); chart.Legends[0].Position.Auto = false; chart.Legends[0].Position = new ElementPosition(55, 55, 35, 45); chart.ChartAreas[0].AxisX.LabelStyle.Enabled = false; chart.ChartAreas[0].AxisY.LabelStyle.Enabled = false; //chart.Titles[0].DockedToChartArea = ; chart.Titles.Add(new Title(chartName)); chart.Titles[0].Alignment = System.Drawing.ContentAlignment.BottomRight; chart.Titles[0].Name = chartName; chart.Titles[0].Font = new Font("Arial", 5.1f); chart.Titles[0].Position.Auto = false; chart.Titles[0].Alignment = System.Drawing.ContentAlignment.TopLeft; chart.Titles[0].Position.Height = 40F; chart.Titles[0].Position.Width = 40F; chart.Titles[0].Position.X = 60F; chart.Titles[0].Position.Y = 30F; chart.Titles[0].Text = chartName; </code></pre>
3
1,177
Make my MySQL query less verbose
<p>The following query was a real challenge for me to build for a Wordpress site using the wordpress wp_post table and the wp_postmeta table and the wp_user table. It works perfectly but it contains a lot of repeated statements. I am not sure how to simplify this (or if it can be). Any tips for simplifying and ridding the repetition would be appreciated.</p> <p>The tables contain data like this:</p> <pre><code>wp_posts ID | post_author | post_parent | post_type | post_title | post_date 2258 163 0 fep_message a 2262 1 2258 fep_message re:a 2264 163 2258 fep_message re:a 1698 1 0 fep_message b 1692 1 0 fep_message c wp_postmeta meta_id | post_id | meta_key | meta_value 14696 2258 _fep_participants 1 14697 2258 _fep_participants 163 9819 1698 _fep_participants 163 9820 1698 _fep_participants 1 9759 1692 _fep_participants 163 9760 1692 _fep_participants 1 9815 1692 _fep_delete_by_1 1499496054 13751 1698 _fep_delete_by_163 1501044119 wp_user ID | user_login 1 myname 163 theirname </code></pre> <p>This is the query</p> <pre><code>SELECT a.* FROM ( SELECT p.id, p.post_date, p.post_title, uf.user_login AS from_login, ut.user_login AS to_login FROM wp_posts AS p JOIN wp_postmeta pm_to ON (p.id = pm_to.post_id AND pm_to.meta_key = '_fep_participants' AND p.post_parent = 0 AND pm_to.meta_value &lt;&gt; p.post_author) JOIN wp_postmeta pm_delete ON (p.id = pm_delete.post_id) LEFT JOIN wp_users AS uf ON uf.ID = p.post_author LEFT JOIN wp_users AS ut ON ut.ID = pm_to.meta_value WHERE (p.post_type = 'fep_message' AND pm_delete.meta_value &lt;&gt; '_fep_delete_by_1' AND uf.user_login = 'myname' OR p.post_type = 'fep_message' AND pm_delete.meta_value &lt;&gt; '_fep_delete_by_1' AND ut.user_login = 'myname') AND p.post_date &gt;= '2017-07-07 00:00:00' AND p.post_date &lt;= '2017-08-12 23:59:59' ORDER BY p.post_date ) a UNION SELECT b.* FROM ( SELECT p.id, p.post_date, p.post_title, uf.user_login AS from_login, ut.user_login AS to_login FROM wp_posts AS p JOIN wp_postmeta pm_to ON (p.post_parent = pm_to.post_id AND p.post_parent &lt;&gt; 0 AND pm_to.meta_key = '_fep_participants' AND pm_to.meta_value &lt;&gt; p.post_author) JOIN wp_postmeta pm_delete ON (p.id = pm_delete.post_id) LEFT JOIN wp_users AS uf ON uf.ID = p.post_author LEFT JOIN wp_users AS ut ON ut.ID = pm_to.meta_value WHERE (p.post_type = 'fep_message' AND pm_delete.meta_value &lt;&gt; '_fep_delete_by_1' AND uf.user_login = 'myname' OR p.post_type = 'fep_message' AND pm_delete.meta_value &lt;&gt; '_fep_delete_by_1' AND ut.user_login = 'myname') AND p.post_date &gt;= '2017-07-07 00:00:00' AND p.post_date &lt;= '2017-08-12 23:59:59' ORDER BY p.post_date ) b </code></pre> <p>The result it produces is:</p> <pre><code>id |post_date |post_title |from_login |to_login 1692 2017-07-07 11:45:03 c myname theirname 1698 2017-07-08 16:28:18 b myname theirname 2258 2017-08-11 23:15:10 a theirname myname 2262 2017-08-12 16:48:05 re:a myname theirname </code></pre>
3
1,693
Enable horizontal scroll in linear layout
<p>This is my layout without scroll and the out is <a href="http://i.stack.imgur.com/QQeXd.png" rel="nofollow">http://i.stack.imgur.com/QQeXd.png</a> . Inside the "AlphebtesLinearLayout" I am creating listView dynamically. And still some portion is hidden at right so I need to go for Horizontal scroll. </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;LinearLayout android:id="@+id/AlphebtesLinearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" &gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>After adding horizontal scroll my output is this <a href="http://i.stack.imgur.com/ki86x.png" rel="nofollow">http://i.stack.imgur.com/ki86x.png</a> the list disappears. Plz help me how to add horizontal scroll.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;HorizontalScrollView android:layout_height="wrap_content" android:layout_width="match_parent"&gt; &lt;LinearLayout android:id="@+id/AlphebtesLinearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" &gt; &lt;/LinearLayout&gt; &lt;/HorizontalScrollView&gt; &lt;/LinearLayout&gt; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tamil_alphabets); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); LinearLayout AlphebtesLinearLayout=(LinearLayout)findViewById(R.id.AlphebtesLinearLayout); int width=AlphebtesLinearLayout.getWidth(); LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(width/8, width/8 /*LinearLayout.LayoutParams.FILL_PARENT)*/); //list.setLayoutParams(para); createList(width); } public void createList(int width){ map= new HashMap&lt;String, String&gt;(); map2= new HashMap&lt;String, String&gt;(); //-------------------------------------------- final String[] Uirkeys = {"அ","ஆ","இ","ஈ","உ","ஊ","எ","ஏ","ஐ","ஒ","ஓ","ஔ","ஃ"}; final String[] Uirvalues = {"a","aa","e","ee","ou","ou.","ay","ay.","ai","o","o.","ow","aak"}; //----------------------------------------------------- final String[] Uirkeys1={"க்","ங்","ச்","ஞ்","ட்","ண்","த்","ந்","ப்","ம்","ய்","ர்","ல்","வ்","ழ்", "ள்","ற்","ன்"}; final String[] Uirvalues1 = {"ik","ing","each","inj","it","in","ith","ind","ip","im","ye","er","il","ev","ill", "ill.","er.","inn"}; //------------------------------------------------------ final String[] Uirkeys2={"க","ங","ச","ஞ","ட","ண","த","ந","ப","ம","ய","ர","ல","வ","ழ", "ள","ற","ன"}; final String[] Uirvalues2 = {"ka","na.","sa","gna","ta","naa","tha","nha","pa","ma","ya", "ra","la","va","la..","la.","ra","na"}; //------------------------------------------------------- for(int loop=0;loop&lt;15;loop++){ if(count==0){ SelectKey=Uirkeys; SelectValue=Uirvalues; }else if(count==1){ SelectKey=Uirkeys1; SelectValue=Uirvalues1; }else if(count==2){ SelectKey=Uirkeys2; SelectValue=Uirvalues2; } for(int i=0;i&lt;SelectKey.length;i++){ map.put(SelectKey[i],SelectValue[i]); } for(int j=0;j&lt;SelectKey.length;j++){ map2.put(SelectValue[j],SelectKey[j]); } LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(width/8, LinearLayout.LayoutParams.FILL_PARENT); //para.weight=1; Activity activity = TamilAlphabets.this; TamilLetters=new TextView(TamilAlphabets.this); AlphebtesLinearLayout=(LinearLayout)findViewById(R.id.AlphebtesLinearLayout); //AlphebtesLinearLayout.setBackgroundColor(Color.RED); list=new ListView(this); list.setLayoutParams(para); GradientDrawable gd=new GradientDrawable(); gd.setStroke(4, Color.BLACK); list.setBackgroundDrawable(gd); ListAdapterTamil LstAdapter=new ListAdapterTamil(TamilAlphabets.this,map,map2,SelectKey,SelectValue,activity); String s=map.get("a"); list.setAdapter(LstAdapter); AlphebtesLinearLayout.addView(list); TamilLetters.setText("aa"); TamilLetters.setLayoutParams(para); //TamilLetters.setText(map.get(Uirvalues[0])); //AlphebtesLinearLayout.addView(TamilLetters); //count++; } } } class ListAdapterTamil extends BaseAdapter{ Context context; Map&lt;String,String&gt; map=new HashMap&lt;String, String&gt;(); Map&lt;String,String&gt; map2=new HashMap&lt;String, String&gt;(); private Activity activity; String[] key; String[] values; public ListAdapterTamil(Context context,Map&lt;String,String&gt; map,Map&lt;String,String&gt; map2,String[] key,String[] values,Activity activity){ this.context=context; this.map=map; this.map2=map2; this.key=key; this.values=values; this.activity=activity; } @Override public int getCount() { // TODO Auto-generated method stub return key.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.tamil_alphabets, parent, false); TextView txt=new TextView(activity); LinearLayout AlphebtesLinearLayout=(LinearLayout)rowView.findViewById(R.id.AlphebtesLinearLayout); AlphebtesLinearLayout.addView(txt); //txt.setText("ddd"); //txt.setText(entry.getKey()); txt.setText(map2.get(values[position])); txt.setPadding( 0, 0,0,50); return rowView; } } </code></pre>
3
3,362
SCSS Won't Compile, Throwing an Error
<pre><code>.sw-theme-default { -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3); box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3); .sw-container { min-height: 250px; } .step-content { padding: 10px; border: 0px solid #D4D4D4; background-color: #FFF; text-align: left; } .sw-toolbar { background: #f9f9f9; border-radius: 0 !important; padding-left: 10px; padding-right: 10px; padding: 10px; margin-bottom: 0 !important } .sw-toolbar-top { border-bottom-color: #ddd !important; } .sw-toolbar-bottom { border-top-color: #ddd !important; } &gt; ul.step-anchor { &gt; li { position: relative; margin-right: 2px; &gt; a, &gt; a:hover { border: none !important; color: #bbb; text-decoration: none; outline-style: none; background: transparent !important; border: none !important; cursor: not-allowed; } &gt; a::after { content: ""; background: #4285F4; height: 2px; position: absolute; width: 100%; left: 0px; bottom: 0px; -webkit-transition: all 250ms ease 0s; transition: all 250ms ease 0s; -webkit-transform: scale(0); -ms-transform: scale(0); transform: scale(0); } &amp;.clickable { &gt; a:hover { color: #4285F4 !important; background: transparent !important; cursor: pointer; } } &amp;.active { &gt; a { border: none !important; color: #4285F4 !important; background: transparent !important; cursor: pointer; &amp;::after { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } } } &amp;.done { &gt; a { border: none !important; color: #000 !important; background: transparent !important; cursor: pointer; &amp;::after { background: #5cb85c; -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } } } &amp;.danger { &gt; a { border: none !important; color: #d9534f !important; /* background: #d9534f !important; */ cursor: pointer; &amp;::after { background: #d9534f; border-left-color: #f8d7da; -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); } } } &amp;.disabled { &gt; a, &gt; a:hover { color: #eee !important; cursor: not-allowed; } } } } } // this is line 155 of my file noted in the error } </code></pre> <p>Error:</p> <blockquote> <p>Module build failed: } ^ Invalid CSS after " }": expected selector or at-rule, was "}" in /Users/me/Code/builder/resources/assets/sass/wizard/_wizard.scss (line 155, column 3)</p> </blockquote> <p>Does anyone see the problem with this block, cause it looks good to me?</p>
3
2,544
How to use spring mvc with thymeleaf to iterate over a list?
<p><em>My goal is to cycle through a list of objects, some to be displayed on the screen, others to be passed into a form as an object of which I can define certain aspects and then return to the controller the object and attribute to be modified.</em></p> <p><em>The problem with the following approach is that the object in the list is not passed correctly to the form and thus gives an error because it is trying to make changes to a non-existent object.</em></p> <p>If, on the other hand, I try to pass it as an object via ModelAndView it obviously works but does not have all the characteristics of the object I passed via the list.</p> <p><strong>Controller</strong></p> <pre><code>@GetMapping(&quot;/&quot;) public ModelAndView home() throws IOException { ModelAndView mv = new ModelAndView(); mv.setViewName(&quot;home&quot;); List&lt;Comics&gt; allComics = cs.getAll(); mv.addObject(&quot;comics&quot;, allComics); return mv; } @PostMapping(&quot;/update&quot;) public ModelAndView update(Comics com, @RequestParam(&quot;attr&quot;) String attr) throws IOException { ModelAndView mv = new ModelAndView(); com.setLastRead(attr); cs.updateAttributes(com); mv.setViewName(&quot;home&quot;); List&lt;Comics&gt; allComics = cs.getAll(); mv.addObject(&quot;comics&quot;, allComics); return mv; } </code></pre> <p><strong>home.html</strong></p> <pre><code>&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt; &lt;tr th:each=&quot;comic : ${comics}&quot;&gt; &lt;td th:text=&quot;${comic.title}&quot;&gt;&lt;/td&gt; &lt;td th:text=&quot;${comic.lastChapter}&quot;&gt;&lt;/td&gt; &lt;td&gt; &lt;a th:href=&quot;${comic.lastChapterLink}&quot; target=&quot;_blank&quot; role=&quot;button&quot; class=&quot;btn btn-md btn-block btn-info&quot;&gt; Link &lt;/a&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt; &lt;form th:action=&quot;@{/update}&quot; th:object=&quot;${comic}&quot; method=&quot;post&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;attr&quot; id=&quot;attr&quot;/&gt; &lt;button type=&quot;submit&quot;&gt;Sub&lt;/button&gt; &lt;/form&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>PS: I cut out the head of the html page because it was full of non-relevant CDNs</p> <p><em>How can I integrate Spring MVC with Thymeleaf to achieve the result whereby passing a list of objects can be displayed on the screen and used for other purposes within the html page without throwing errors?</em></p> <p>Obviously if you know of more efficient methods to achieve the result I'm listening; I only used this method because I didn't know of any others.</p> <p>Thank you</p> <p><strong>Answer to @RafaeldaSilva:</strong></p> <p>I agree, but that does not solve the problem. Let me explain: the attribute I am going to modify through the form already has its name to allow what you wrote. But the object iterated through:</p> <pre><code>tr th:each=&quot;comic : ${comics}&quot;&gt; </code></pre> <p>cannot be passed directly as input, as it is a value that is taken from a list and exists individually only in the html page. One might think of passing it as hidden input, but in this case the result would be the same (I have tried):</p> <pre><code>&lt;form th:action=&quot;@{/update}&quot; th:object=&quot;${comic}&quot; method=&quot;post&quot;&gt; &lt;input type=&quot;hidden&quot; value=&quot;${comic}&quot; name=&quot;com&quot;/&gt; &lt;input type=&quot;text&quot; name=&quot;attr&quot; id=&quot;attr&quot;/&gt; &lt;button type=&quot;submit&quot;&gt;Sub&lt;/button&gt; &lt;/form&gt; @PostMapping(&quot;/update&quot;) public ModelAndView update(@RequestParam(&quot;com&quot;) Comics com, @RequestParam(&quot;attr&quot;) String attr) throws IOException { ModelAndView mv = new ModelAndView(); com.setLastRead(attr); System.out.println(&quot;Comic: &quot; + com); cs.updateAttributes(com); mv.setViewName(&quot;home&quot;); List&lt;Comics&gt; allComics = cs.getAll(); mv.addObject(&quot;comics&quot;, allComics); return mv; } </code></pre> <p><strong>Error:</strong> [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'com' for method parameter type Comics is present but converted to null]</p>
3
2,170
Python3: GUI later cannot display output properly?
<p>I'm designing a GUI application that converts between celsius and fahrenheit. For now, there're primarily two problems that I'm not able to tackle:</p> <p><strong>1)</strong> When I enter an integer that needs to be converted based on the given conversion formula, the Label from <code>tkinter</code> cannot display the output properly. In fact, it shows something like this: </p> <pre><code>&lt;conversionModel.Conversion object at 0x1057b11d0&gt; </code></pre> <p>which made it really difficult for debug to a beginner like me.</p> <p><strong>2)</strong> There's a <code>quitButton</code>, thought which we can <code>destroy()</code> the GUI application. The problem is that when I close the GUI by clicking the red cross of the window, the Shell says: </p> <p><code>_tkinter.TclError: can't invoke "destroy" command: application has been destroyed</code></p> <p>I checked answers to other questions regarding the same problem, it turned out that it was because this GUI application was destroyed before closing. I had no idea how to address this particular problem.</p> <p>Below are three pieces of code written in Model/View/Controller form:</p> <p><strong>The Model in conversionModel.py:</strong></p> <pre><code>class Conversion: """ class Conversion is the Model for a celsius-fahrenheit conversion application. It converts celsius into fahrenheit and fahrenheit into celsius. """ def toCelsius(self, temp): return (5 / 9) * (temp - 32) def toFahrenheit(self, temp): return ((9 / 5) * temp) + 32 </code></pre> <p><strong>The View in conversionView.py:</strong></p> <pre><code>import tkinter class MyFrame(tkinter.Frame): def __init__(self, controller): tkinter.Frame.__init__(self) self.pack() self.controller = controller self.tempEntry = tkinter.Entry() self.tempEntry.insert(0, "0") self.tempEntry.pack({"side": "left"}) self.celsiusButton = tkinter.Button(self) self.celsiusButton["text"] = "Celsius" self.celsiusButton["command"] = self.controller.buttonToC self.celsiusButton.pack({"side": "left"}) self.fahrenheitButton = tkinter.Button(self) self.fahrenheitButton["text"] = "Fahrenheit" self.fahrenheitButton["command"] = self.controller.buttonToF self.fahrenheitButton.pack({"side": "left"}) self.labelForOutput = tkinter.Label(self) self.labelForOutput["text"] = 0 self.labelForOutput.pack ({"side": "left"}) self.quitButton = tkinter.Button(self) self.quitButton["text"] = "Quit" self.quitButton["command"] = self.quit self.quitButton.pack({"side": "left"}) </code></pre> <p><strong>The Controller in controller.py:</strong></p> <pre><code>import tkinter import conversionView import conversionModel class Controller: def __init__(self): root = tkinter.Tk() self.model = conversionModel.Conversion() self.view = conversionView.MyFrame(self) self.value = float(self.view.tempEntry.get()) self.view.mainloop() root.destroy() def buttonToC(self): self.model.toCelsius(self.value) self.view.labelForOutput["text"] = str(self.model) + " °C" def buttonToF(self): self.model.toFahrenheit(self.value) self.view.labelForOutput["text"] = str(self.model) + " °F" if __name__ == "__main__": c = Controller() </code></pre>
3
1,247
How do I make a box that i can move. I am new to wxwidgets and wondering if there is a way to move a box
<p>The Image is what I currently have made, I plan to make an Elevator that can go up and down. I am unsure of how I would move a box such that it stays at the same x cords but changes the y cords. Any help is appreciated.</p> <p>This is for a project I am doing. The specifications state</p> <pre><code> &quot;In this project, the group is required to develop a programme that simulates the operation of arrays (columns) of elevators running over a multi‐storey building. The program (application) should be able to cope with user defined number of elevators and number of storeys along with an ability for a user to simulate or represent elevator passengers making request for elevator service to particular floors. The program should have a user interface that displays the elevators’ states allows user input and ideally shows (simulates) the vertical movement of each elevator. &quot; </code></pre> <p><a href="https://i.stack.imgur.com/rnte7.png" rel="nofollow noreferrer">Simulation Plane</a></p> <p>I am looking for something that will move the &quot;Elevator A&quot; box with the buttons up or down, along with a box inside the elevator shaft, both move up and down in unison. The code should do this automatically hopefully without having to drag the boxes and buttons with a mouse.</p> <p>cMain.hpp (Updated)</p> <pre><code>#pragma once #ifndef _cMain_ #define _cMain_ #include &lt;wx/frame.h&gt; #include &lt;wx/wx.h&gt; class cMain : public wxFrame { public: cMain(wxWindow* parent, wxWindowID id, const wxString&amp; title, const wxPoint&amp; pos = wxDefaultPosition, const wxSize&amp; size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString&amp; name = wxASCII_STR(wxFrameNameStr)); ~cMain(); wxStaticBox* m_box1 = nullptr; wxStaticBox* m_box2 = nullptr; wxStaticBox* m_box3 = nullptr; wxButton* m_btng = nullptr; wxButton* m_btn1 = nullptr; wxButton* m_btn2 = nullptr; wxButton* m_btn3 = nullptr; wxButton* m_btn_up = nullptr; wxButton* m_btn_down = nullptr; wxListBox* m_list1 = nullptr; void Ground_Button(wxCommandEvent&amp; evt); void Level_1_Button(wxCommandEvent&amp; evt); void Level_2_Button(wxCommandEvent&amp; evt); void Level_3_Button(wxCommandEvent&amp; evt); void Call_Up_Button(wxCommandEvent&amp; evt); void Call_Down_Button(wxCommandEvent&amp; evt); DECLARE_EVENT_TABLE(); }; #endif /* */ </code></pre> <p>cMain.cpp (Updated)</p> <pre><code>#include &quot;cMain.h&quot; #include &quot;id.h&quot; #include &lt;wx/dc.h&gt; #include &lt;wx/graphics.h&gt; #include &lt;wx/dcbuffer.h&gt; #include &lt;wx/event.h&gt; #include &lt;iostream&gt; #include &quot;cElevator.h&quot; using namespace std; cElevator e; wxBEGIN_EVENT_TABLE(cMain, wxFrame) wxEND_EVENT_TABLE(); cMain::cMain(wxWindow* parent, wxWindowID id, const wxString&amp; title, const wxPoint&amp; pos, const wxSize&amp; size, long style , const wxString&amp; name) : wxFrame(parent,id,title,pos,size,style,name) { this-&gt;SetBackgroundColour(*wxWHITE); m_box1 = new wxStaticBox(this, wxID_ANY, &quot;Call 1&quot;, wxPoint(252, 530), wxSize(50, 80)); m_btn_up = new wxButton(this, wxID_ANY, &quot;/\\&quot;, wxPoint(265, 547), wxSize(25, 25)); m_btn_down = new wxButton(this, wxID_ANY, &quot;\\/&quot;, wxPoint(265, 575), wxSize(25, 25)); //Inner Panel m_box2 = new wxStaticBox(this, wxID_ANY, &quot;Elevator A&quot;, wxPoint(164, 530), wxSize(80, 80)); m_btng = new wxButton(this, wxID_ANY, wxString(&quot;G&quot;), wxPoint(177, 575), wxSize(25, 25)); m_btn1 = new wxButton(this, wxID_ANY, wxString(&quot;1&quot;), wxPoint(177, 547), wxSize(25, 25)); m_btn2 = new wxButton(this, wxID_ANY, wxString(&quot;2&quot;), wxPoint(207, 575), wxSize(25, 25)); m_btn3 = new wxButton(this, wxID_ANY, wxString(&quot;3&quot;), wxPoint(207, 547), wxSize(25, 25)); //Elevator Shafts //m_box3 = new wxStaticBox(panel, wxID_ANY, &quot;&quot;, wxPoint(80, 10), wxSize(80, 600)); //Other m_list1 = new wxListBox(this, wxID_ANY, wxPoint(200, 10), wxSize(100, 100)); m_btn_up-&gt;Bind(wxEVT_BUTTON, &amp;cMain::Call_Up_Button, this); m_btn_down-&gt;Bind(wxEVT_BUTTON, &amp;cMain::Call_Down_Button, this); m_btng-&gt;Bind(wxEVT_BUTTON, &amp;cMain::Ground_Button, this); m_btn1-&gt;Bind(wxEVT_BUTTON, &amp;cMain::Level_1_Button, this); m_btn2-&gt;Bind(wxEVT_BUTTON, &amp;cMain::Level_2_Button, this); m_btn3-&gt;Bind(wxEVT_BUTTON, &amp;cMain::Level_3_Button, this); } void cMain::Ground_Button(wxCommandEvent&amp; evt) { e.GLevel = true; m_list1-&gt;AppendString(&quot;Going to Ground Level&quot;); evt.Skip(); } void cMain::Level_1_Button(wxCommandEvent&amp; evt) { m_list1-&gt;AppendString(&quot;Going to Level 1&quot;); evt.Skip(); } void cMain::Level_2_Button(wxCommandEvent&amp; evt) { m_list1-&gt;AppendString(&quot;Going to Level 2&quot;); evt.Skip(); } void cMain::Level_3_Button(wxCommandEvent&amp; evt) { m_list1-&gt;AppendString(&quot;Going to Level 3&quot;); evt.Skip(); } void cMain::Call_Up_Button(wxCommandEvent&amp; evt) { m_list1-&gt;AppendString(&quot;Going to Up&quot;); //evt.Skip(); } void cMain::Call_Down_Button(wxCommandEvent&amp; evt) { m_list1-&gt;AppendString(&quot;Going Down&quot;); //evt.Skip(); } cMain::~cMain() { } </code></pre> <p>cElevator.hpp</p> <pre><code>#include &lt;wx/wx.h&gt; class cElevator : public wxFrame { public: cElevator(wxWindow* parent, wxWindowID id, const wxString&amp; title, const wxPoint&amp; pos = wxDefaultPosition, const wxSize&amp; size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString&amp; name = wxASCII_STR(wxFrameNameStr)); ~cElevator(); bool GLevel; void OnPaint(wxPaintEvent&amp; evt); wxDECLARE_EVENT_TABLE(); }; </code></pre> <p>cElevator.cpp</p> <pre><code>#include &quot;cMain.h&quot; #include &quot;cElevator.h&quot; #include &lt;wx/dc.h&gt; #include &lt;wx/graphics.h&gt; #include &lt;wx/dcbuffer.h&gt; #include &lt;wx/event.h&gt; #include &lt;iostream&gt; using namespace std; wxBEGIN_EVENT_TABLE(cElevator,wxPanel) EVT_PAINT(cElevator::OnPaint) wxEND_EVENT_TABLE(); cElevator::cElevator(wxWindow* parent, wxWindowID id, const wxString&amp; title, const wxPoint&amp; pos, const wxSize&amp; size, long style, const wxString&amp; name) : wxFrame(parent,id,title,pos,size,style,name) { this-&gt;SetBackgroundColour(*wxBLACK); } void cElevator::OnPaint(wxPaintEvent&amp; evt) { wxClientDC cdc(this); wxBufferedDC dc(&amp;cdc); wxGraphicsContext* gc = wxGraphicsContext::Create(dc); // make a path that contains a circle and some lines gc-&gt;SetPen(*wxWHITE_PEN); wxGraphicsPath path = gc-&gt;CreatePath(); path.CloseSubpath(); path.AddRectangle(80.0, 10.0, 80.0, 800.0); path.MoveToPoint(80, 600); path.AddLineToPoint(160, 600); path.MoveToPoint(80, 400); path.AddLineToPoint(160, 400); path.MoveToPoint(80, 200); path.AddLineToPoint(160, 200); //path.AddRectangle(90, 740, 60, 65); //path.AddRectangle(90, 530, 60, 65); //path.AddRectangle(90, 330, 60, 65); //path.AddRectangle(90, 130, 60, 65); gc-&gt;StrokePath(path); delete gc; } cElevator::~cElevator() { } </code></pre> <p>Paintting part</p> <pre><code>void cElevator::OnPaint(wxPaintEvent&amp; evt) { int CurrentPosy = 130; wxPaintDC dc(this); dc.DrawRectangle(80.0, 10.0, 80.0, 800.0);//overall rectangle for elevator shaft dc.Clear(); dc.SetPen(*wxWHITE); dc.SetBrush(*wxLIGHT_GREY_BRUSH); while (CurrentPosy != ExpectedPosy) { dc.DrawRectangle(90, CurrentPosy, 60, 65); //CurrentPosy--; // or currentPOs.y++; wxSleep(5); dc.Clear(); } dc.SetPen(wxNullPen); dc.SetBrush(wxNullBrush); </code></pre> <p>The ExpectedPosy is in the header file as an int, that should get a value when the ground button (or other level buttons) is pressed.</p>
3
3,619
How to setup CMake to build code which contains path-includes like #include <libdir/lib>?
<p>I am trying to migrate an old C/C++ sunstudio project to visual studio 2019. I need to build targets on a remote linux machine, so I cannot use the visual studio solution to build. After some unsuccessful attempts to use the old sunstudio makefiles, I have decided to use <strong>cmake</strong> to build the project.</p> <p>The problem is that the code references includes with relative paths, like this:</p> <pre><code>(tkamain.cxx): #include &lt;ukernel/inc/U.h&gt; #include &lt;monitor/inc/monitor.h&gt; </code></pre> <p>I don't want to touch the code, so how can I setup CMake to build this project properly with these specific include statements?</p> <p>The project structure looks like this.</p> <pre><code>tka |-mod ||-monitor ||'-inc ||-feedutils ||'-inc |'-ukernel | '-inc |-inc ||-foo.hxx |'-bar.hxx |-src ||-foo.cxx ||-bar.cxx ||-tkamain.cxx |'-CMakeLists.txt (CMakeB) '-CMakeLists.txt (CMakeA) </code></pre> <p>The CMakeLists.txt are newly created by me and are probably not correctly set up yet.</p> <p>The CMakeA file contains this:</p> <pre><code>project(tka) add_subdirectory(src) </code></pre> <p>The CMakeB file contains this:</p> <pre><code>include_directories(${PROJECT_SOURCE_DIR}/inc) include_directories(${PROJECT_SOURCE_DIR}/mod) add_executable(tkamain tkamain.cxx) </code></pre> <p>The commands in CMakeB seem not to be sufficient for my purposes, what am I missing? Or do I need more CMakeLists.txt files? </p> <p>The errors I am getting look like this:</p> <pre><code>[ 50%] Building CXX object src/CMakeFiles/tkamain.dir/tkamain.cxx.o /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:11:27: error: ukernel/inc/U.h: No such file or directory /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:14:33: error: monitor/inc/monitor.h: No such file or directory </code></pre> <p>I have tried to give more specific include paths, like this, but that didn't help either:</p> <pre><code>include_directories(${PROJECT_SOURCE_DIR}/mod/ukernel/inc) include_directories(${PROJECT_SOURCE_DIR}/mod/monitor/inc) </code></pre> <p>When I run make VERBOSE=1, I get the following:</p> <pre><code>/usr/local/bin/cmake -S/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src -B/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test --check-build-system CMakeFiles/Makefile.cmake 0 /usr/local/bin/cmake -E cmake_progress_start /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test/CMakeFiles /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test/CMakeFiles/progress.marks make -f CMakeFiles/Makefile2 all make[1]: Entering directory `/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test' make -f src/CMakeFiles/tkamain.dir/build.make src/CMakeFiles/tkamain.dir/depend make[2]: Entering directory `/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test' cd /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test &amp;&amp; /usr/local/bin/cmake -E cmake_depends "Unix Makefiles" /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test/src /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test/src/CMakeFiles/tkamain.dir/DependInfo.cmake --color= make[2]: Leaving directory `/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test' make -f src/CMakeFiles/tkamain.dir/build.make src/CMakeFiles/tkamain.dir/build make[2]: Entering directory `/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test' [ 50%] Building CXX object src/CMakeFiles/tkamain.dir/tkamain.cxx.o cd /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test/src &amp;&amp; /usr/bin/c++ -I/inc -g -o CMakeFiles/tkamain.dir/tkamain.cxx.o -c /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:11:27: error: ukernel/inc/U.h: No such file or directory /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:12:30: error: ukernel/inc/Ulib.h: No such file or directory /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:13:31: error: ukernel/inc/UExit.h: No such file or directory /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:14:33: error: monitor/inc/monitor.h: No such file or directory /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:31:26: error: tkacontrol.hxx: No such file or directory /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:24: error: expected ',' or ';' before 'U_OS' /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx: In function 'int main(int, char**)': /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:37: error: 'UkInit' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:39: error: 'TkaControl' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:39: error: 'tkaControl' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:39: error: expected type-specifier before 'TkaControl' /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:39: error: expected ';' before 'TkaControl' /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:41: error: 'UExitHandler' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:41: error: expected ';' before 'exithandler' /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:43: error: 'Monitor2Startup' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:45: error: 'evalarg_error' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:46: error: 'UEXIT_STOP' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:46: error: 'UExitMsg' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:49: error: 'UkMain' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:50: error: 'Monitor2Exit' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:59: error: 'UEXIT_STOP' was not declared in this scope /drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/src/src/tkamain.cxx:59: error: 'UExitMsg' was not declared in this scope make[2]: *** [src/CMakeFiles/tkamain.dir/tkamain.cxx.o] Error 1 make[2]: Leaving directory `/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test' make[1]: *** [src/CMakeFiles/tkamain.dir/all] Error 2 make[1]: Leaving directory `/drive/new/home/mwe/.vs/tka/eb2f2a43-555a-3934-8996-0095b1bcc780/out/build/Linux-Debug-test' make: *** [all] Error 2 </code></pre>
3
3,561
Roslyn can't find IDictionary.Add interface implementation member
<p>Why Roslyn in following example can't find IDictionary.Add interface member implementation in Dictionary type?</p> <p>IDictionary.Add and Dictionary.Add correctly resolve by Roslyn, but then i can't find implementation IDictionary.Add method in Dictionary type.</p> <p><strong>Update</strong> I added second code example with correct code.</p> <p>VS2015, Roslyn 1.1.1:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; namespace RoslynSymbolsTest { public class InterfaceMemberImplemnentationTest { public void Run() { string solutionPath = @"..\..\..\RoslynSymbolsTest.sln"; MSBuildWorkspace workspace = MSBuildWorkspace.Create(); Solution solution = workspace.OpenSolutionAsync(solutionPath).Result; var project = solution.Projects.Where(p =&gt; p.Name == "RoslynSymbolsTest").Single(); var document = project.Documents.Where(d =&gt; d.Name == "InterfaceMemberImplemnentationTest.cs").Single(); var semanticModel = document.GetSemanticModelAsync().Result; // IDictionary.Add IMethodSymbol _idictionaryAddMethodSymbol = ResolveMethod(semanticModel, typeof(IDictionary&lt;,&gt;), "Add"); // ok // Dictionary.Add IMethodSymbol _dictionaryAddMethodSymbol = ResolveMethod(semanticModel, typeof(Dictionary&lt;,&gt;), "Add"); // ok var implementationMethodSymbol = _dictionaryAddMethodSymbol.ContainingType.FindImplementationForInterfaceMember(_idictionaryAddMethodSymbol); // null } private ITypeSymbol ResolveType(SemanticModel semanticModel, Type type) { string[] names = type.FullName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); INamespaceOrTypeSymbol scope = null; for (int i = 0; i != names.Count(); ++i) { string metadataName = names[i]; string name = metadataName; int index = name.IndexOf('`'); int numberOfGenericTypes = 0; if (index != -1) { string sNumber = name.Substring(index + 1); if (!int.TryParse(sNumber, out numberOfGenericTypes)) { return null; } name = name.Substring(0, index); } IEnumerable&lt;ISymbol&gt; symbols = semanticModel.LookupNamespacesAndTypes(0, scope, name); if (numberOfGenericTypes != 0) { symbols = symbols.Where(s =&gt; s.MetadataName == metadataName); } if (symbols.Count() == 1) { scope = (INamespaceOrTypeSymbol)symbols.First(); } else { scope = null; break; } } return (ITypeSymbol)scope; } public IMethodSymbol ResolveMethod(SemanticModel semanticModel, Type type, string methodName) { ITypeSymbol typeSymbol = ResolveType(semanticModel, type); if (typeSymbol == null) { return null; } var members = typeSymbol.GetMembers(methodName); if (members.Length == 1 &amp;&amp; members[0] is IMethodSymbol) { return members[0] as IMethodSymbol; } return null; } } } </code></pre> <p>Fixed Example:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; namespace RoslynSymbolsTest { public class InterfaceMemberImplementationTest { class MyDisposable : IDisposable { public void Dispose() { } } public void Run() { string solutionPath = @"..\..\..\RoslynSymbolsTest.sln"; MSBuildWorkspace workspace = MSBuildWorkspace.Create(); Solution solution = workspace.OpenSolutionAsync(solutionPath).Result; var project = solution.Projects.Where(p =&gt; p.Name == "RoslynSymbolsTest").Single(); var document = project.Documents.Where(d =&gt; d.Name == "InterfaceMemberImplementationTest.cs").Single(); var semanticModel = document.GetSemanticModelAsync().Result; IMethodSymbol idictionaryAddMethodSymbol = ResolveMethod(semanticModel, typeof(IDictionary&lt;,&gt;), "Add"); IMethodSymbol idictionaryAddStringObjectMethodSymbol = ResolveMethod(semanticModel, typeof(IDictionary&lt;,&gt;), new Type[] { typeof(string), typeof(object) }, "Add"); IMethodSymbol idictionaryAddStringStringMethodSymbol = ResolveMethod(semanticModel, typeof(IDictionary&lt;,&gt;), new Type[] { typeof(string), typeof(string) }, "Add"); IMethodSymbol idictionaryGetItemMethodSymbol = ResolveMethod(semanticModel, typeof(IDictionary&lt;,&gt;), "get_Item"); IMethodSymbol dictionaryMethodSymbol = ResolveMethod(semanticModel, typeof(Dictionary&lt;,&gt;), "Add"); IMethodSymbol dictionaryStringObjectMethodSymbol = ResolveMethod(semanticModel, typeof(Dictionary&lt;,&gt;), new Type[] { typeof(string), typeof(object) }, "Add"); IMethodSymbol idisposableDisposeMethodSymbol = ResolveMethod(semanticModel, typeof(IDisposable), "Dispose"); IMethodSymbol myDisposableDisposeMethodSymbol = ResolveMethod(semanticModel, typeof(MyDisposable), "Dispose"); bool result1 = ImplementsInterfaceMember(dictionaryMethodSymbol, idictionaryAddMethodSymbol); bool result2 = ImplementsInterfaceMember(dictionaryMethodSymbol, idictionaryGetItemMethodSymbol); bool result3 = ImplementsInterfaceMember(dictionaryStringObjectMethodSymbol, idictionaryAddMethodSymbol); bool result4 = ImplementsInterfaceMember(dictionaryStringObjectMethodSymbol, idictionaryGetItemMethodSymbol); bool result5 = ImplementsInterfaceMember(dictionaryStringObjectMethodSymbol, idictionaryAddStringObjectMethodSymbol); bool result6 = ImplementsInterfaceMember(dictionaryStringObjectMethodSymbol, idictionaryAddStringStringMethodSymbol); bool result7 = ImplementsInterfaceMember(myDisposableDisposeMethodSymbol, idisposableDisposeMethodSymbol); } private static bool ImplementsInterfaceMember(IMethodSymbol implementationMethod, IMethodSymbol interfaceMethod) { if (!IsOpenMethod(interfaceMethod)) { if (implementationMethod.Equals(implementationMethod.ContainingType.FindImplementationForInterfaceMember(interfaceMethod))) { return true; } } else { INamedTypeSymbol interfaceTypeSymbol = interfaceMethod.ContainingType; INamedTypeSymbol interfaceConstructedFromTypeSymbol = interfaceTypeSymbol.ConstructedFrom; INamedTypeSymbol implementationTypeSymbol = implementationMethod.ContainingType; var implementedInterfaces = implementationTypeSymbol.AllInterfaces.Where(i =&gt; i.ConstructedFrom.Equals(interfaceConstructedFromTypeSymbol)); foreach (var implementedInterface in implementedInterfaces) { foreach (var implementedInterfaceMember in implementedInterface.GetMembers(interfaceMethod.Name)) { if (implementedInterfaceMember.OriginalDefinition.Equals(interfaceMethod)) { var exactImplementedInterfaceMember = implementationMethod.ContainingType.FindImplementationForInterfaceMember(implementedInterfaceMember); if (implementationMethod.Equals(exactImplementedInterfaceMember)) { return true; } } } } } return false; } private static bool IsOpenMethod(IMethodSymbol method) { bool result = method.OriginalDefinition.Equals(method); return result; } private ITypeSymbol ResolveType(SemanticModel semanticModel, Type type) { string[] names = type.FullName.Split(new[] { '.', '+' }, StringSplitOptions.RemoveEmptyEntries); INamespaceOrTypeSymbol scope = null; for (int i = 0; i != names.Count(); ++i) { string metadataName = names[i]; string name = metadataName; int index = name.IndexOf('`'); int numberOfGenericTypes = 0; if (index != -1) { string sNumber = name.Substring(index + 1); if (!int.TryParse(sNumber, out numberOfGenericTypes)) { return null; } name = name.Substring(0, index); } IEnumerable&lt;ISymbol&gt; symbols; if (i == 0) { symbols = semanticModel.LookupNamespacesAndTypes(0, scope, name); } else { symbols = scope.GetMembers(name).Where(m =&gt; m.Kind == SymbolKind.Namespace || m.Kind == SymbolKind.NamedType); } if (numberOfGenericTypes != 0) { symbols = symbols.Where(s =&gt; s.MetadataName == metadataName); } if (symbols.Count() == 1) { scope = (INamespaceOrTypeSymbol)symbols.First(); } else { scope = null; break; } } return (ITypeSymbol)scope; } private ITypeSymbol ResolveType(SemanticModel semanticModel, Type type, params Type[] typeParameters) { ITypeSymbol typeSymbol = ResolveType(semanticModel, type); if (typeSymbol == null) { return null; } ITypeSymbol[] typeParametersSymbols = new ITypeSymbol[typeParameters.Length]; for (int i = 0; i != typeParameters.Length; ++i) { ITypeSymbol typeParameterSymbol = ResolveType(semanticModel, typeParameters[i]); if (typeParameterSymbol == null) { return null; } typeParametersSymbols[i] = typeParameterSymbol; } INamedTypeSymbol constructedTypeSymbol = ((INamedTypeSymbol)typeSymbol).Construct(typeParametersSymbols); return constructedTypeSymbol; } public IMethodSymbol ResolveMethod(SemanticModel semanticModel, Type type, string methodName) { ITypeSymbol typeSymbol = ResolveType(semanticModel, type); if (typeSymbol == null) { return null; } var members = typeSymbol.GetMembers(methodName); if (members.Length == 1 &amp;&amp; members[0] is IMethodSymbol) { return members[0] as IMethodSymbol; } return null; } public IMethodSymbol ResolveMethod(SemanticModel semanticModel, Type type, Type[] typeParameters, string methodName) { ITypeSymbol typeSymbol = ResolveType(semanticModel, type, typeParameters); if (typeSymbol == null) { return null; } var members = typeSymbol.GetMembers(methodName); if (members.Length == 1 &amp;&amp; members[0] is IMethodSymbol) { return members[0] as IMethodSymbol; } return null; } } } </code></pre>
3
5,794
finding next/previous tv show from MySQL database
<p>I've become rather stuck with a situation I have. I have a database with fields id, showid, season, episode and some other arbitrary data. I have a php page to display information about episodes of shows which works by having the id as a get variable. What I wish to achieve is to have a link to the next episode and previous episode of this tv program however the shows aren't necessarily in order and so simply incrementing or decrementing the id will not help. So I would fetch the episodes and store then in <code>$rows</code> with the following <code>MySQL</code> query:</p> <p><code>SELECT id FROM episodes WHERE showid = $id ORDER BY season, episode;</code></p> <p>Now without having to loop through the array (which could be rather large for some shows) is there an easy way for me to find the next and previous episode? I'm sure there is I just can't think of it.</p> <p><strong>Edit:</strong> I have been thinking about this myself and nothing all that helpful has come through yet (although thanks for the help, its much appreciated). What I have thought of is to make a query to see if a higher episode exists of the same season, if not make another query to find the lowest episode of then next lowest season - or something along those lines - and then repeat for previous. What do you think?</p> <p><strong>Edit 2:</strong> I thought I would post my final code for future reference. Here I find the id's of the nex and previous shows (if they exist).</p> <p>Find the next episode:</p> <pre><code>try { // First check for a show of the same season but the next lowest episode number $stmt = $dbh-&gt;prepare("SELECT id FROM episodes WHERE showid = :show AND season = :s AND episode &gt; :e ORDER BY episode LIMIT 1;"); $stmt-&gt;execute($pars); $rows = $stmt-&gt;fetchAll(); if(count($rows) &gt; 0) { // If there is one this is our next id $nextid = $rows[0]['id']; } else { // Otherwise check for an episode of a higher season number $stmt = $dbh-&gt;prepare("SELECT id FROM episodes WHERE showid = :show AND season &gt; :s ORDER BY season, episode LIMIT 1;"); $stmt-&gt;execute($pars); $rows = $stmt-&gt;fetchAll(); if(count($rows) &gt; 0) { // If there is one this is our next id. $nextid = $rows[0]['id']; } // Otherwise no next id is set and so no next link will be created. } } catch(PDOException $e) { die("Error: " . $e-&gt;getMessage()); } </code></pre> <p>Find the previous episode:</p> <pre><code>try { // First check for an episode in same season of the next highest episode number. $stmt = $dbh-&gt;prepare("SELECT id FROM episodes WHERE showid = :show AND season = :s AND episode &lt; :e ORDER BY episode DESC LIMIT 1;"); $stmt-&gt;execute($pars); $rows = $stmt-&gt;fetchAll(); if(count($rows) &gt; 0) { // If one is found then this is our prev id. $previd = $rows[0]['id']; } else { // Otherwise check for an episode of a lower season number. $stmt = $dbh-&gt;prepare("SELECT id FROM episodes WHERE showid = :show AND season &lt; :s ORDER BY season DESC, episode DESC LIMIT 1;"); $stmt-&gt;execute($pars); $rows = $stmt-&gt;fetchAll(); if(count($rows) &gt; 0) { // If there is one this is our prev id. $previd = $rows[0]['id']; } // Otherwise no prev id is set and so no prev link will be created. } } catch(PDOException $e) { die("Error: " . $e-&gt;getMessage()); } </code></pre> <p>Then I have the following links:</p> <pre><code>if($previd) echo "&lt;a href=\"/tv/view/" . $previd . "/\"&gt;Previous Episode&lt;/a&gt;"; if($nextid) echo "&lt;a href=\"/tv/view/" . $nextid . "/\"&gt;Next Episode&lt;/a&gt;"; </code></pre>
3
1,313
Struts2 Dispatcher FilterMapping Cannot be Found
<p>I'm using the Tuckey URL re-write filter which works fine. However I'm trying to use Struts2 to implement a login system for my web app. So far I've been able to bypass my other service calls so they pass through struts (they are webservlets and I don't want to use struts for them). I can hit them, however I can't access my Login.jsp. I've tried all kinds of mixing and matching with no luck. Ultimately I want to be able to use my existing webservlets but route the user to the login page if there is not a valid session and not allow access to two pages if the user hasn't logged in. But right now I'm just trying to get the login screen to show up. I get them both working separately but can't messh them to work together.</p> <p>Any idea on how to make the login page show up?</p> <h2>Struts.xml</h2> <pre><code> &lt;struts&gt; &lt;constant name="struts.action.excludePattern" value="/InsertMessage, /AutoComplete"/&gt; &lt;constant name="struts.custom.i18n.resources" value="LoginAction"/&gt; &lt;package name="default" extends="struts-default" namespace="/"&gt; &lt;action name="Login" class="controls.LoginAction" &gt; &lt;result name="success"&gt;Listing.jsp&lt;/result&gt; &lt;result name="input"&gt;Login.jsp&lt;/result&gt; &lt;/action&gt; &lt;action name="InsertMessage"&gt; &lt;result&gt;/InsertMessage&lt;/result&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt; </code></pre> <h2>web.xml</h2> <pre><code> &lt;filter&gt; &lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.tuckey.web.filters.urlrewrite.UrlRewriteFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;confPath&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/urlrewrite.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; &lt;/filter-mapping&gt; &lt;filter&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;filter-class&gt; org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter &lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;/Listing&lt;/url-pattern&gt; &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; &lt;/filter-mapping&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;/MessageDetail&lt;/url-pattern&gt; &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; &lt;/filter-mapping&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;/Login&lt;/url-pattern&gt; &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; &lt;/filter-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;login.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; </code></pre> <h2>Login.jsp</h2> <pre><code>&lt;s:form action="Login"&gt; &lt;s:textfield name="userName" label="User Name" /&gt; &lt;s:password name="password" label="Password" /&gt; &lt;s:submit value="Login" /&gt; &lt;/s:form&gt; </code></pre> <h2>Error <code>Login.jsp</code></h2> <p>HTTP Status 500 - The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]</p> <p>The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - </p> <pre><code>[unknown location] org.apache.struts2.views.jsp.TagUtils.getStack(TagUtils.java:60) org.apache.struts2.views.jsp.StrutsBodyTagSupport.getStack(StrutsBodyTagSupport.java:44) org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:48) org.apache.jsp.Login_jsp._jspx_meth_s_005fhead_005f0(Login_jsp.java:111) org.apache.jsp.Login_jsp._jspService(Login_jsp.java:80) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:69) javax.servlet.http.HttpServlet.service(HttpServlet.java:847) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:365) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:309) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:242) javax.servlet.http.HttpServlet.service(HttpServlet.java:847) org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176) org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394) </code></pre>
3
2,342
Wrong css ">" selectors (by me)
<p>I am trying to design a chess board with css3, but it seems like my selectors are wrong. <a href="http://jsfiddle.net/loloof64/nxvse1hd/6/" rel="nofollow">Here is my JsFiddle </a></p> <p>So why can't I see the designed test blue and red borders around lines and cells ?</p> <p><strong>html</strong></p> <pre><code>&lt;body&gt; My chess board &lt;table class="chess_board"&gt; &lt;tr class="chess_line"&gt; &lt;td class="chess_cell black_cell white_piece"&gt;&lt;span&gt;&amp;#9812;&lt;/span&gt;&lt;/td&gt; &lt;td class="chess_cell white_cell white_piece"&gt;&lt;span&gt;&amp;#9813;&lt;/span&gt;&lt;/td&gt; &lt;td class="chess_cell black_cell white_piece"&gt;&lt;span&gt;&amp;#9814;&lt;/span&gt;&lt;/td&gt; &lt;td class="chess_cell white_cell white_piece"&gt;&lt;span&gt;&amp;#9815;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr class="chess_line"&gt; &lt;td class="chess_cell white_cell"&gt;&lt;span&gt;&amp;#9820;&lt;/span&gt;&lt;/td&gt; &lt;td class="chess_cell black_cell"&gt;&lt;span&gt;&amp;#9821;&lt;/span&gt;&lt;/td&gt; &lt;td class="chess_cell white_cell"&gt;&lt;span&gt;&amp;#9822;&lt;/span&gt;&lt;/td&gt; &lt;td class="chess_cell black_cell"&gt;&lt;span&gt;&amp;#9823;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; My another chess board ... to be drawn ! &lt;/body&gt; </code></pre> <p><strong>css</strong></p> <pre><code>table.chess_board &gt; tr.chess_line { background-color: blue; } table.chess_board &gt; tr.chess_line &gt; td.chess_cell { border: 2px solid red; /* font-family: serif; font-size: 2.3em; width: 1.0em; height: 1.0em; text-align: center; */ } table.chess_board &gt; tr.chess_line &gt; td.chess_cell &gt; span { position: relative; bottom: 0.1em; } table.chess_board &gt; tr.chess_line &gt; td.white_cell { background-color: rgb(217, 245, 2); } table.chess_board &gt; tr.chess_line &gt; td.black_cell { background-color: rgb(89, 34, 21); } table.chess_board &gt; tr.chess_line &gt; td.white_piece { color: rgb(179, 48, 63); } </code></pre> <p>Can anyone help ?</p>
3
1,064
Why doesn't nth:child work on my site when it worked on my boilerplate?
<p>I'm a web development student and I'm trying to use nth:child in order to code a section of a site that has images on the left and text on the right, and then the next section has text on the left and images on the right etc. Maybe it's a really simple mistake but I'm not sure why it's not working because my boilerplate worked. I'm new to stackoverflow so I'm not really sure how to format a post, so the CSS is under the HTML. I appreciate the help, thanks.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.character img { height: 200px; } .character { display: flex; align-items: center; } .character:nth-child(even) .characterDetails { order: 1; } .character:nth-child(even) .characterImage { order: 2; } .character:nth-child(odd) .characterDetails { order: 2; } .character:nth-child(odd) .characterImage { order: 1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="characters"&gt; &lt;div class="character"&gt; &lt;div class="characterImage"&gt; &lt;img src="images/user.png" alt="Placeholder Image" /&gt; &lt;/div&gt; &lt;div class="characterDetails"&gt; &lt;h2&gt;Character&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non ex mattis neque condimentum pharetra non ac urna. Aliquam eleifend id sapien id convallis. Duis gravida pharetra lorem ut fermentum. Mauris semper neque vel imperdiet convallis. Fusce volutpat mi nec elit blandit luctus. Morbi lorem elit, facilisis vitae mi id, tempus scelerisque erat. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.&lt;/p&gt;&lt;br&gt; &lt;p&gt;Aenean sed dui magna. Proin eleifend risus eget porta bibendum. Donec ut diam sed tellus tempor mattis. Mauris at pharetra eros. Donec in volutpat sapien, ut ullamcorper tortor. Morbi placerat massa enim, vel tempor ante facilisis non. Praesent sollicitudin ante vitae pellentesque pretium. Curabitur ut leo mattis, convallis nisi eu, hendrerit dolor. Nullam sed efficitur risus. Proin quis dui commodo, sollicitudin purus id, blandit lacus. Fusce porta auctor varius. Fusce a ultrices nibh. Curabitur semper turpis ex, sit amet suscipit mauris ultricies ut. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="characters"&gt; &lt;div class="character"&gt; &lt;div class="characterImage"&gt; &lt;img src="images/user.png" alt="Placeholder Image" /&gt; &lt;/div&gt; &lt;div class="characterDetails"&gt; &lt;h2&gt;Character&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non ex mattis neque condimentum pharetra non ac urna. Aliquam eleifend id sapien id convallis. Duis gravida pharetra lorem ut fermentum. Mauris semper neque vel imperdiet convallis. Fusce volutpat mi nec elit blandit luctus. Morbi lorem elit, facilisis vitae mi id, tempus scelerisque erat. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.&lt;/p&gt;&lt;br&gt; &lt;p&gt;Aenean sed dui magna. Proin eleifend risus eget porta bibendum. Donec ut diam sed tellus tempor mattis. Mauris at pharetra eros. Donec in volutpat sapien, ut ullamcorper tortor. Morbi placerat massa enim, vel tempor ante facilisis non. Praesent sollicitudin ante vitae pellentesque pretium. Curabitur ut leo mattis, convallis nisi eu, hendrerit dolor. Nullam sed efficitur risus. Proin quis dui commodo, sollicitudin purus id, blandit lacus. Fusce porta auctor varius. Fusce a ultrices nibh. Curabitur semper turpis ex, sit amet suscipit mauris ultricies ut. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
1,542
Updating notifications after being added
<p>I want to update the content for a reminder after it has been added before being received by the user. After setting a reminder through AlarmManager using the data stored in sqlite database, the notification from the reminder set only shows the data, title and description, that was first added, not any updated data stored corresponding to the ID as primary key.</p> <p>Things I have tried:</p> <ul> <li>cancelling the pending intent for the reminder then setting it again after updating the data stored in the database but it still displays the same result.</li> <li>using an activity for adding data to be stored in the database to set a reminder and using another activity for updating this data as an attempt to update the reminder content with the same ID issued. One result shows two notifications received, one with initial title and description, and the other with updated information.</li> </ul> <p>Currently, the methods I use to set and cancel a reminder is in my Adapter class for Recyclerview. I am stuck on updating although adding and cancel works fine.</p> <p>Update: Now I use two separate activities for the add and update reminder functions.</p> <p>For adding a reminder:</p> <pre><code>databaseManager.addReminder(titlePicked, descriptionPicked, timePicked, datePicked, dateTimePicked); startActivity(new Intent(getApplicationContext(), MainActivity.class)); setAlarm(); private void setAlarm() { AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class); intent.putExtra(&quot;DateTime&quot;, dateTimePicked); intent.putExtra(&quot;NotifID&quot;, remId); intent.putExtra(&quot;Title&quot;, titlePicked); intent.putExtra(&quot;Description&quot;, descriptionPicked); PendingIntent addIntent = PendingIntent.getBroadcast(this, remId, intent, 0); alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), addIntent); } </code></pre> <p>For updating a reminder:</p> <pre><code>databaseManager.updateReminder(remindId, titlePicked2, descriptionPicked2, timePicked, datePicked, dateTimePicked); startActivity(new Intent(getApplicationContext(), MainActivity.class)); updateAlarm(); private void updateAlarm() { AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class); intent.putExtra(&quot;DateTime&quot;, dateTimePicked); intent.putExtra(&quot;NotifID&quot;, remindId); intent.putExtra(&quot;Title&quot;, titlePicked2); intent.putExtra(&quot;Description&quot;, descriptionPicked2); PendingIntent updateIntent = PendingIntent.getBroadcast(this, remindId, intent, 0); alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Date.parse(dateTimePicked), updateIntent); } </code></pre> <p>Receiver class:</p> <pre><code>public class ReminderReceiver extends BroadcastReceiver { private static final String CHANNEL_ID = &quot;CHANNEL_REMIND&quot;; String DateTimeChoice, TitleChoice, DescriptionChoice; int notificationID; @Override public void onReceive(Context context, Intent intent) { DateTimeChoice = intent.getStringExtra(&quot;DateTime&quot;); notificationID = intent.getIntExtra(&quot;NotifID&quot;, 0); TitleChoice = intent.getStringExtra(&quot;Title&quot;); DescriptionChoice = intent.getStringExtra(&quot;Description&quot;); Intent mainIntent = new Intent(context, ViewReminder.class); mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent contentIntent = PendingIntent.getActivity(context, notificationID, mainIntent, 0); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) { // For API 26 and above CharSequence channelName = &quot;My Notification&quot;; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance); notificationManager.createNotificationChannel(channel); } NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(android.R.drawable.ic_dialog_info) .setContentTitle(TitleChoice) .setContentText(DescriptionChoice) .setContentIntent(contentIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setColor(context.getResources().getColor(R.color.purple_700)) .setAutoCancel(true); notificationManager.notify(notificationID, builder.build()); } </code></pre> <p>Adapter class:</p> <pre><code>int remindId = reminder.getReminderId(); databaseManager = new DatabaseManager(holder.view.getContext()); sqLiteDB = databaseManager.getWritableDatabase(); public void onClick(View view) { Reminder reminder = remindList.get(holder.getAdapterPosition()); PopupMenu popupMenu = new PopupMenu(view.getContext(), view); popupMenu.setGravity(Gravity.END); popupMenu.getMenu().add(&quot;Edit&quot;).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { Intent intent = new Intent(view.getContext(), UpdateReminderActivity.class); intent.putExtra(&quot;reminderId&quot;, remindId); intent.putExtra(&quot;title&quot;, reminder.getReminderTitle()); intent.putExtra(&quot;definition&quot;, reminder.getReminderDefinition()); view.getContext().startActivity(intent); return true; } }); </code></pre>
3
2,154
How to print ALL columns of MySQL table in Python?
<p>Here I want to print every column present in the MySQL table <strong>(PASSENGER)</strong>, but this code only gives 4-5 columns.</p> <p>The code:</p> <pre><code>import pandas as pd import mysql.connector as myq d = myq.connect(host=&quot;localhost&quot;, user=&quot;root&quot;, passwd=&quot;admin&quot;, database=&quot;air&quot;) df = pd.read_sql(&quot;select * from Passengers&quot;, d) print(df) </code></pre> <p>Output:</p> <pre><code> Ticket_Number Date Passenger ... Class Stat Announcement 0 1 1 1 ... 1 1 1 1 184784 1 1 ... 1 1 1 2 184785 1 1 ... 1 1 None 3 184787 9:12:2020 Jeet ... FIRST CLASS CONFIRMED None 4 184789 9:12:2020 Jeet ... FIRST CLASS CONFIRMED None 5 184790 9:12:2021 Jeet ... FIRST CLASS CONFIRMED None </code></pre> <p>This is what Python is returning to my code. Here I want all 12 columns.</p> <p>Desired output:</p> <pre><code>Ticket_Number Date Passenger Flight_Code Airline Departs_From Arrives_TO Departs Arrives Class Stat Announcement 1 1 1 1 1 1 1 1 1 1 1 1 184784 1 1 1 1 1 1 1 1 1 1 1 184785 1 1 1 1 1 1 1 1 1 1 none 184787 9:12:2020 Jeet CX131 Cathay Pacific London,UK Ahemdabad,India 04:40:00 18:20:00 FIRST CLASS CONFIRMED none 184789 9:12:2020 Jeet CX131 Cathay Pacific London,UK Ahemdabad,India 04:40:00 18:20:00 FIRST CLASS CONFIRMED none 184790 9:12:2021 Jeet QF248 Quantas London,UK Ahemdabad,India 23:50:00 13:50:00 FIRST CLASS CONFIRMED none </code></pre>
3
1,488
Kindly help to get office wise data row wise
<pre><code>select NUM_OFC_CODE,NUM_RO_CODE, case when TXT_MONTH='JAN' then 1 ELSE 0 end as JAN, case when TXT_MONTH='FEB' then 1 ELSE 0 end as FEB, case when TXT_MONTH='MAR' then 1 ELSE 0 end as MAR, case when TXT_MONTH='APR' then 1 ELSE 0 end as APR, case when TXT_MONTH='MAY' then 1 ELSE 0 end as MAY, case when TXT_MONTH='JUN' then 1 ELSE 0 end as JUN, case when TXT_MONTH='JUL' then 1 ELSE 0 end as JUL, case when TXT_MONTH='AUG' then 1 ELSE 0 end as AUG, case when TXT_MONTH='SEP' then 1 ELSE 0 end as SEP, case when TXT_MONTH='OCT' then 1 ELSE 0 end as OCT, case when TXT_MONTH='NOV' then 1 ELSE 0 end as NOV, case when TXT_MONTH='DEC' then 1 ELSE 0 end as DEC from LEG_OMBUDSMAN_NONMACT where NUM_YEAR=2019 group by NUM_OFC_CODE,TXT_MONTH,NUM_RO_CODE; </code></pre> <p>Result is showing as below:-</p> <pre><code>NUM_OFC_CODE NUM_RO_CODE JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC 280400 280000 0 0 0 0 0 0 0 1 0 0 282300 280000 0 0 0 0 0 0 0 1 0 0 0 281600 280000 0 0 0 0 0 0 0 1 0 0 0 280500 280000 0 0 0 0 0 0 1 0 0 0 0 280500 280000 0 0 0 1 0 0 0 0 0 0 0 281800 280000 0 0 0 0 0 0 0 1 0 0 0 282200 280000 0 0 0 0 0 0 0 1 0 0 0 280500 280000 0 0 0 0 1 0 0 0 0 0 0 280500 280000 0 0 0 0 0 1 0 0 0 0 0 280500 280000 0 0 0 0 0 0 0 1 0 0 0 281300 280000 0 0 0 0 0 0 0 1 0 0 0 </code></pre> <p>I want office wise data. If August data is present, Then It should show 1 else 0. Like wise for other months. But in my query Separate row is showing for separate months.</p>
3
1,053
'click' Event listener not working on small screen
<p>I have a table whose each row has an addEventlistener for click. The rows are selected fine on bigger screens, but in small screens some of the items cannot be selected. I am using plain JavaScript for this. I have the respective media queries defined so that should not be a problem in my opinion.</p> <p>This is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var table_row = document.querySelectorAll('.table-row'); //all table rows window.onload = () =&gt; { //clear the localstorage from previous sessions localStorage.clear(); table_row.forEach(element =&gt; { element.addEventListener('click', () =&gt; { //on click of a row id = element.getAttribute('data-id'); state = element.getAttribute('data-state'); if (state == 'off') { //unselected element.style.background = "#742173"; element.style.color = "white"; element.setAttribute('data-state', 'on'); //changed the appearance of current element if (prev_element != null) { //revert changes to last selection console.log('prev_element:' + prev_element.childNodes[1].innerText); prev_element.style.background = "#f0efed"; prev_element.style.color = "black"; prev_element.setAttribute('data-state', 'off'); } //setting current element ad prev_element prev_element = document.getElementById(id); console.log('prev_element:' + prev_element.childNodes[1].innerText); } }); }); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table align="center " id='space-table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Spacecraft name&lt;/td&gt; &lt;td&gt; Origin&lt;/td&gt; &lt;td&gt; Destination&lt;/td&gt; &lt;td&gt;Price per person&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr class="table-row" id='row1' data-id="row1" data-state="off"&gt; &lt;td&gt;ax12&lt;/td&gt; &lt;td&gt;Sector 3&lt;/td&gt; &lt;td&gt;Sector 5A-12&lt;/td&gt; &lt;td&gt;450&lt;/td&gt; &lt;/tr&gt; &lt;tr class="table-row" id='row2' data-id="row2" data-state="off"&gt; &lt;td&gt;ax13&lt;/td&gt; &lt;td&gt;Crater34&lt;/td&gt; &lt;td&gt;Sector 3&lt;/td&gt; &lt;td&gt;145&lt;/td&gt; &lt;/tr&gt; &lt;tr class="table-row" id='row3' data-id="row3" data-state="off"&gt; &lt;td&gt;ax14&lt;/td&gt; &lt;td&gt;Crater 34&lt;/td&gt; &lt;td&gt;Sector 3A-5&lt;/td&gt; &lt;td&gt;250&lt;/td&gt; &lt;/tr&gt; &lt;tr class="table-row" id='row4' data-id="row4" data-state="off"&gt; &lt;td&gt;ax15&lt;/td&gt; &lt;td&gt;Sector 5A-12&lt;/td&gt; &lt;td&gt;LM-36 &lt;/td&gt; &lt;td&gt;125&lt;/td&gt; &lt;/tr&gt; &lt;tr class="table-row" id='row5' data-id="row5" data-state="off"&gt; &lt;td&gt;ax16&lt;/td&gt; &lt;td&gt;Sector 5A-12&lt;/td&gt; &lt;td&gt;Crater 34&lt;/td&gt; &lt;td&gt;210&lt;/td&gt; &lt;/tr&gt; &lt;tr class="table-row" id='row6' data-id="row6" data-state="off"&gt; &lt;td&gt;ax17&lt;/td&gt; &lt;td&gt;Crater 34&lt;/td&gt; &lt;td&gt;LM-36&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
3
1,700
Discord Bot: cannot create POST request for create a message
<p>i have a problem while i am implementing discord bot in C/C++. My problem is when i when i want to create message in other way create POST request to create message with my BOT i do not recieve any answer whether the request was completed or not. When i create GET request with specifics which is necessary due to discord documentary everything is good and i recieve what i want. My code is:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;unistd.h&gt;`` #include &lt;bits/stdc++.h&gt; #include &lt;sys/socket.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;signal.h&gt; #include &lt;malloc.h&gt; #include &lt;netdb.h&gt; #include &lt;openssl/err.h&gt; /* errors */ #include &lt;openssl/ssl.h&gt; /* core library */ #include &lt;thread&gt; #define BuffSize 8096 using namespace std; SSL *ssl; int sock; int RecvPacket() { int len=100; char buf[1000000]; do { len=SSL_read(ssl, buf, 100); buf[len]=0; printf(&quot;%s\n&quot;,buf); // fprintf(fp, &quot;%s&quot;,buf); } while (len &gt; 0); if (len &lt; 0) { int err = SSL_get_error(ssl, len); if (err == SSL_ERROR_WANT_READ) return 0; if (err == SSL_ERROR_WANT_WRITE) return 0; if (err == SSL_ERROR_ZERO_RETURN || err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL) return -1; } } int SendPacket(const char *buf) { int len = SSL_write(ssl, buf, strlen(buf)); if (len &lt; 0) { int err = SSL_get_error(ssl, len); switch (err) { case SSL_ERROR_WANT_WRITE: return 0; case SSL_ERROR_WANT_READ: return 0; case SSL_ERROR_ZERO_RETURN: case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: default: return -1; } } } void log_ssl() { int err; while (err = ERR_get_error()) { char *str = ERR_error_string(err, 0); if (!str) return; printf(str); printf(&quot;\n&quot;); fflush(stdout); } } int main(int argc, char *argv[]){ struct sockaddr_in socket_address_IPv4; struct hostent *hos; int socket_invoke; string messageId; string username; char content[1024]; string messageBodyString; char messageBody[BuffSize]; char* response_2; char *token=(char*)malloc(sizeof(char) * strlen(argv[1])); char *url_uncompleted=(char*)malloc(sizeof(char) *300); char *ip=(char*)malloc(sizeof(char) *100); struct in_addr **addr_list; int i=0; strcpy(url_uncompleted,&quot;www.discord.com:443&quot;); char *url = strtok(url_uncompleted, &quot;:&quot;); strcpy(token,argv[1]); socket_invoke = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); if(socket &lt; 0){ fprintf(stderr,&quot;Unsuccessfull creation of seocket\n&quot;); } memset(&amp;socket_address_IPv4,0,sizeof(socket_address_IPv4)); socket_address_IPv4.sin_family=AF_INET; hos=gethostbyname(url); if(!hos){ printf(&quot;chyba pri gethostbyname\n&quot;); close(socket_invoke); exit(10); } addr_list = (struct in_addr **) hos-&gt;h_addr_list; for(int i = 0; addr_list[i] != NULL; i++) { //Return the first one; strcpy(ip , inet_ntoa(*addr_list[i]) ); break; } printf(&quot;IP adresa je: %s\n&quot;,ip); socket_address_IPv4.sin_addr.s_addr=inet_addr(ip); socket_address_IPv4.sin_port=htons(443); if(connect(socket_invoke,(struct sockaddr*)&amp;socket_address_IPv4,sizeof(socket_address_IPv4)) &lt;0) { fprintf(stderr,&quot;connection failed\n&quot;); free(token); free(url_uncompleted); free(ip); close(socket_invoke); } SSL_library_init(); SSLeay_add_ssl_algorithms(); SSL_load_error_strings(); const SSL_METHOD *meth = TLSv1_2_client_method(); SSL_CTX *ctx = SSL_CTX_new (meth); ssl = SSL_new (ctx); if (!ssl) { printf(&quot;Error creating SSL.\n&quot;); log_ssl(); return -1; } sock = SSL_get_fd(ssl); SSL_set_fd(ssl, socket_invoke); int err = SSL_connect(ssl); if (err &lt;= 0) { printf(&quot;Error creating SSL connection. err=%x\n&quot;, err); log_ssl(); fflush(stdout); return -1; } printf (&quot;SSL connection using %s\n&quot;, SSL_get_cipher (ssl)); snprintf(messageBody, 1024, &quot;{\&quot;content\&quot;:\&quot;hi\&quot;,\n\&quot;tts\&quot;: false}&quot;); sprintf(content, &quot;POST https://discord.com/api/v6/channels/760577856702644327/messages HTTP/1.1\r\nauthorization: Bot %s\r\nContent-Type: application/json\r\nContent-Length: 1024\r\nhost: %s\r\n%s\r\nConnection: keep-alive\r\n\r\n&quot;,token,&quot;discord.com&quot;,messageBody); printf(&quot;%s\n&quot;,content); SendPacket(content); RecvPacket(); printf(&quot;som tu\n&quot;); free(token); free(url_uncompleted); free(ip); close(socket_invoke); return 0; } </code></pre> <p>thank you for all advices</p>
3
2,615
Kivy - Draw Rectangle Around Text
<p>I'm brand new to Kivy and trying to make a UI for a project. I'm trying to develop an understanding for how everything gets sized in the different layouts.</p> <p>I'm having an issue where I have two labels side by side in a box layout (nested in another box layout). I want the 2nd label to have a rectangle drawn behind only the text. I can get 90% of the way there, but I'm stumbling over positioning the rectangle behind the text, since there is no &quot;self.texture_pos&quot; like there is &quot;self.texture_size&quot;.</p> <p>How can I dynamically draw a rectangle at the size and position of a label string, or am I doing this a really dumb way?</p> <p>My .KV, sorry for the funky colors, as I said I'm trying to understand how everything is positioned:</p> <pre><code>#:kivy 1.8.0 BoxLayout: size: root.size pos: root.pos id: foo_bar orientation: 'vertical' canvas.before: Color: rgb: .6, .6, .6 Rectangle: size: self.size StatusBarWidget: ProcessValWidget: ProcessSliderWidget: StartStopWidget: &lt;startstopwidget&gt;: BoxLayout: orientation: 'horizontal' Label: font_size: 70 center_x: root.width / 4 top: root.top - 50 text: &quot;2&quot; canvas.before: Color: rgba: 0,1,0,1 Rectangle: size: self.size pos: self.pos Label: font_size: 70 center_x: root.width * 3 / 4 top: root.top - 50 text: &quot;3&quot; canvas.before: Color: rgba: 0,0,1,1 Rectangle: size: self.size pos: self.pos &lt;processvalwidget&gt;: BoxLayout: orientation: 'horizontal' Label: id: lbl_pval font_size: 50 text: &quot;Pressure:&quot; text_size: self.size halign: 'right' valign: 'middle' canvas.before: Color: rgba: 1,0,0,1 Rectangle: size: self.size pos: self.pos Label: id: val_pval font_size: 50 text: &quot;100 PSI&quot; canvas.before: Color: rgba: 0,1,0,1 Rectangle: size: self.texture_size pos: self.pos &lt;processsliderwidget&gt;: BoxLayout: orientation: 'vertical' Slider: id: slider min: 0 max: 100 step: 1 orientation: 'horizontal' Label: text: str(slider.value) &lt;statusbarwidget&gt;: size_hint_y: None height: 50 canvas.before: Color: rgba: 0,0,0,1 Rectangle: size: self.size pos: self.pos Label: text: &quot;STATUS BAR&quot; text_size: self.size size_hint_x: None halign: 'left' valign: 'middle' padding_x: 5 </code></pre>
3
1,911
Why can threads change instance data if it is blocked in another thread?
<p>I began to study lock and immediately a question arose.</p> <p>It <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock" rel="nofollow noreferrer">docs.microsoft</a> says here:</p> <blockquote> <p>The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. <strong>Any other thread is blocked from acquiring the lock and waits until the lock is released</strong>.</p> </blockquote> <p>I made a simple example proving that another thread with a method without the lock keyword can easily change the data of an instance while that instance is occupied by a method using the lock from the first thread. It is worth removing the comment from the blocking and the work is done as expected. I thought that a lock would block access to an instance from other threads, even if they don't use a lock on that instance in their methods.</p> <p><strong>Questions</strong>:</p> <ol> <li><p>Do I understand correctly that locking an instance on one thread allows data from another thread to be modified on that instance, unless that other thread also uses that instance's lock? If so, what then does such a blocking generally give and why is it done this way?</p> </li> <li><p>What does this mean in simpler terms? <strong>While a lock is held, the thread that holds the lock can again acquire and release the lock</strong>.</p> </li> </ol> <hr /> <blockquote> <p>So code formatting works well.</p> </blockquote> <hr /> <pre><code>using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class A { public int a; } class Program { static void Main(string[] args) { A myA = new A(); void MyMethod1() { lock (myA) { for (int i = 0; i &lt; 10; i++) { Thread.Sleep(500); myA.a += 1; Console.WriteLine($&quot;Work MyMethod1 a = {myA.a}&quot;); } } } void MyMethod2() { //lock (myA) { for (int i = 0; i &lt; 10; i++) { Thread.Sleep(500); myA.a += 100; Console.WriteLine($&quot;Work MyMethod2 a = {myA.a}&quot;); } } } Task t1 = Task.Run(MyMethod1); Thread.Sleep(100); Task t2 = Task.Run(MyMethod2); Task.WaitAll(t1, t2); } } } </code></pre>
3
1,283
Error : You are trying to load a weight file containing 1 layers into a model with 14 layers
<p>Since due to having not enough of resources like GPU and Ram we are using Google Colab for training the model but still there are some limitations in it for example maximum time limit for Google Colab's GPU is only 12-hours. Still we trained the model in those 12- hours but the loss doesn't seem to be changing after 1st epoch, due to which we decide to use Auto-Colorize's code and there trained weight's file <strong>"colorize.hdf5"</strong> that is uploaded on GitHub (code available on github link: <a href="https://github.com/hvvashistha/Auto-Colorize" rel="nofollow noreferrer">https://github.com/hvvashistha/Auto-Colorize</a>) , but on loading those weights we are getting an error. </p> <p><strong>"You are trying to load a weight file containing 1 layers into a model with 14 layers</strong>." </p> <p><a href="https://i.stack.imgur.com/5qdIG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5qdIG.png" alt="enter image description here"></a></p> <p>We have tried to downgrade Keras version to 2.2.0 , 2.1.6 and 2.1.0 but the error didn't resolved. we are using the same model structure that been have provided on GitHub but still its giving that error.</p> <p><strong>Model :</strong> This is the model Architecture </p> <pre><code> #Inputs embed_input = Input(shape=(1000,)) encoder_input = Input(shape=(256, 256, 1,)) #Encoder encoder_output = Conv2D(64, (3,3), activation='relu', padding='same', strides=2, bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_input) encoder_output = Conv2D(128, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) encoder_output = Conv2D(128, (3,3), activation='relu', padding='same', strides=2, bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) encoder_output = Conv2D(256, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) encoder_output = Conv2D(256, (3,3), activation='relu', padding='same', strides=2, bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) encoder_output = Conv2D(512, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) encoder_output = Conv2D(512, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) encoder_output = Conv2D(256, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(encoder_output) #Fusion fusion_output = RepeatVector(32 * 32)(embed_input) fusion_output = Reshape(([32, 32, 1000]))(fusion_output) fusion_output = concatenate([encoder_output, fusion_output], axis=3) fusion_output = Conv2D(256, (1, 1), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(fusion_output) #Decoder decoder_output = Conv2D(128, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(fusion_output) decoder_output = UpSampling2D((2, 2))(decoder_output) decoder_output = Conv2D(64, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(decoder_output) decoder_output = UpSampling2D((2, 2))(decoder_output) decoder_output = Conv2D(32, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(decoder_output) decoder_output = Conv2D(16, (3,3), activation='relu', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(decoder_output) decoder_output = Conv2D(2, (3, 3), activation='tanh', padding='same', bias_initializer=TruncatedNormal(mean=0.0, stddev=0.05))(decoder_output) decoder_output = UpSampling2D((2, 2))(decoder_output) model = Model(inputs=[encoder_input, embed_input], outputs=decoder_output) model.compile(optimizer=RMSprop(lr=1e-3), loss='mse', metrics=['accuracy']) </code></pre> <p><strong>Test_image Function:</strong></p> <p>I am loading the weights this way.</p> <pre><code> test_images = getImages(testing_files) model.load_weights('/content/drive/My Drive/weights/orignalcolorize.hdf5') </code></pre> <p>Am I Loading the weights in a wrong way or is this some other issue.</p>
3
1,879
mat-icon doesn't show icon in dialog after closing and re-opening the dialog
<p>I have created a dynamic dialog component, which I can pass action buttons to, which then get displayed in the dialog header. By default, the dialog contains a close action button, and I'm passing an edit action to the dialog header. This edit action contains two buttons:</p> <ul> <li>one select button that changes the dialog content to an edit form if it had not been selected and that cancels the editing if it had been selected prior.</li> <li>a save button that only displays if the select button had been selected.</li> </ul> <p>Both of these buttons are mat-icon-buttons using a mat-icon. This works fine when I open the dialog for the first time, however the icons do not get displayed if I close and re-open the dialog. The close button icon is displayed but neither of the edit action buttons are.</p> <p>This is where I open the dialog:</p> <pre><code>&lt;div id=&quot;btn-add&quot;&gt; &lt;button mat-mini-fab (click)=&quot;add()&quot;&gt; &lt;mat-icon&gt;add&lt;/mat-icon&gt; &lt;/button&gt; &lt;/div&gt; &lt;wb-dialog [title]=&quot;selectedArea?.title&quot; [active]=&quot;!!selectedArea&quot; (onClose)=&quot;close()&quot;&gt; &lt;div actions&gt; &lt;wb-tab-button [tab]=&quot;dialogStatusEnum.EDIT&quot; [form]=&quot;areaForm&quot; icon=&quot;edit&quot; [active]=&quot;this.dialogStatus === dialogStatusEnum.EDIT&quot; (onSelect)=&quot;this.tab($event)&quot; (onSubmit)=&quot;saveArea()&quot;&gt;&lt;/wb-tab-button&gt; &lt;/div&gt; &lt;/wb-dialog&gt; </code></pre> <p>And its typescript code:</p> <pre><code>export class AreaComponent { public readonly dialogStatusEnum: typeof DialogStatus = DialogStatus; public selectedArea: Area | undefined; public areaForm: FormGroup; constructor(formBuilder: FormBuilder) { this.areaForm = formBuilder.group({}); } public add(): void { this.selectedArea = new Area(); this.isDialogLoading = false; } public close(): void { this.selectedArea = undefined; } public tab(tab: DialogStatus | undefined) { this.dialogStatus = tab || this.dialogStatusEnum.EDIT; } public saveArea() { // TODO! } } </code></pre> <p>This is the dialog:</p> <pre><code>&lt;div class=&quot;mat-dialog-wrapper&quot; [ngClass]=&quot;{'mat-hidden': !active}&quot;&gt; &lt;mat-card *ngIf=&quot;active&quot;&gt; &lt;mat-card-header&gt; &lt;mat-card-title *ngIf=&quot;title&quot; [ngClass]=&quot;{'mat-placeholder': !!title}&quot;&gt;{{title || 'no title'}}&lt;/mat-card-title&gt; &lt;ng-content select=&quot;[actions]&quot;&gt;&lt;/ng-content&gt; &lt;button mat-icon-button (click)=&quot;close()&quot; class=&quot;mat-card-header-action&quot;&gt;&lt;mat-icon&gt;close&lt;/mat-icon&gt;&lt;/button&gt; &lt;/mat-card-header&gt; &lt;ng-content select=&quot;[content]&quot;&gt;&lt;/ng-content&gt; &lt;/mat-card&gt; &lt;/div&gt; </code></pre> <p>And the component code:</p> <pre><code>export class DialogComponent { @Input() title: string | undefined; @Input() active: boolean; @Output() onClose: EventEmitter&lt;void&gt;; constructor() { this.active = false; this.onClose = new EventEmitter&lt;void&gt;(); } public close(): void { this.onClose.emit(); } } </code></pre> <p>And here's the button:</p> <pre><code>&lt;button *ngIf=&quot;active&quot; mat-icon-button (click)=&quot;submit()&quot; [disabled]=&quot;form.invalid&quot;&gt;&lt;mat-icon&gt;save&lt;/mat-icon&gt;&lt;/button&gt; &lt;button mat-icon-button (click)=&quot;select()&quot; [ngClass]=&quot;{'mat-active': active}&quot;&gt; &lt;mat-icon *ngIf=&quot;active&quot;&gt;block&lt;/mat-icon&gt; &lt;mat-icon *ngIf=&quot;!active&quot;&gt;{{icon}}&lt;/mat-icon&gt; &lt;/button&gt; </code></pre> <p>And its component:</p> <pre><code>export class TabButtonComponent { @Input() tab!: DialogStatus; @Input() form!: FormGroup; @Input() icon: string; @Input() active!: boolean; @Output() onSelect: EventEmitter&lt;DialogStatus | undefined&gt;; @Output() onSubmit: EventEmitter&lt;void&gt;; constructor() { this.onSelect = new EventEmitter&lt;DialogStatus | undefined&gt;(); this.onSubmit = new EventEmitter&lt;void&gt;(); } public select(): void { this.onSelect.emit(this.active ? undefined : this.tab); } public submit(): void { this.onSubmit.emit(); } } </code></pre> <p>The only similar thing I found is this question <a href="https://stackoverflow.com/questions/55797323/message-wont-display-a-second-time-after-being-closed">message-wont-display-a-second-time-after-being-closed</a>. However, all my bindings work, the click event handlers, the dynamic mat-active CSS class, all of the elements exist in my DOM, the buttons as well as the icons and I couldn't find any difference in the CSS when I compare the first with a subsequent dialog call. The only issue I have is that the icons are not being displayed and I can't figure out why that is or how to fix it.</p> <p>If I place the tab button directly in the dialog instead of inserting it from the parent this issue does not occur.</p>
3
2,327
How to force CLion using a custom MSVC version?
<h1>The problem</h1> <p>I use CLion 2022.2, Visual Studio 2022, and CMake 3.23. I want to use the toolset of version 14.31.17.1, which is older than the newest one.</p> <h1>Configure</h1> <p>I configure the CMake project with a <code>CMakeLists.txt</code> file</p> <pre><code>project(test_project) add_executable(test_project main.cpp) </code></pre> <p>In CLion, I specify generator Visual Studio 2022 and a toolset 14.31.17.1. The command executed is</p> <pre><code>&quot;C:\Program Files\CMake\bin\cmake.exe&quot; -G &quot;Visual Studio 17 2022&quot; -T version=14.31.17.1 -S F:\test_project -B F:\test_project\build </code></pre> <p>Nevertheless, logs say</p> <pre><code>-- The C compiler identification is MSVC 19.33.31629.0 -- The CXX compiler identification is MSVC 19.33.31629.0 </code></pre> <p>When I clear the cache directory and execute the same command in CLion Terminal (copy and paste it with the <code>.</code> or <code>&amp;</code> prefix), I get what I want</p> <pre><code>-- The C compiler identification is MSVC 19.31.31107.0 -- The CXX compiler identification is MSVC 19.31.31107.0 </code></pre> <p>Note: toolset 14.31.31103 contains MSVC 19.31.31107.0 while toolset 14.33.31629 contains MSVC 19.33.31629.0. So I conclude that something goes wrong.</p> <p>After this, I can modify the project and execute the &quot;Reload CMake Project&quot;, and CLion does it well because the versions of compilers are already configured.</p> <p>Specifying C and C++ compilers for the toolchain (File | Settings | Build, Execution, Deployment | Toolchains) doesn't help.</p> <p>When I remove the latest toolset using Visual Studio Installer, it also automatically removes C++ CMake Tools for Windows, which doesn't allow me to use CMake with Visual Studio.</p> <h1>Build</h1> <p>My <code>main.cpp</code> file is</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; int main() { std::cout &lt;&lt; _MSC_VER &lt;&lt; std::endl; return 0; } </code></pre> <p>When I configure the project (no matter with CLion or manually) and build it using CLion GUI, I get the answer</p> <pre><code>1933 </code></pre> <p>Although, if I use the same command as CLion, namely</p> <pre><code>&quot;C:\Program Files\CMake\bin\cmake.exe&quot; --build F:\test_project\build --target test_project --config Debug </code></pre> <p>I get what I need</p> <pre><code>1931 </code></pre> <p>The strange part is that I get the correct result using Terminal even after configuring the project using CLion GUI. Also, I can set up the project in Terminal to use the newer toolset (which is the default) and have the <code>1933</code> printed.</p> <p>Also, when I debug the code using CLion, the Evaluate says that <code>_MSC_VER</code> is <code>1933</code> but the application still prints <code>1931</code>. When I create a variable <code>int x{_MSC_VER};</code>, the debugger shows that <code>x</code> equals <code>1931</code>.</p> <h1>Summary</h1> <p>If I use CLion GUI to configure or build the project or to do both things, it uses MSVC 19.33.31629.0. If I configure and build the project in CLion's Terminal using the same commands CLion shows me when configuring and building the project, I can use MSVC 19.31.31107.0.</p> <p>Am I missing something? Does CLion specify environment variables I should override? Is it possible to choose the MSVC version I need using CLion?</p>
3
1,127
xamarin forms - image wrapped in frame(with property cornerRadius set) not showing round corners
<p>I am trying to create layout similar to Android cardview. </p> <p>My progress for now.</p> <p><a href="https://i.stack.imgur.com/69vuH.png" rel="nofollow noreferrer">image1</a></p> <p>As you can see It looks guide well. However when I change Image property Aspect="Fill" to Aspect="AspectFill" images would lost round corners. </p> <p><a href="https://i.stack.imgur.com/1Qv3U.png" rel="nofollow noreferrer">image2</a></p> <p>My code</p> <pre><code>&lt;Frame VerticalOptions="Start" Margin="8" CornerRadius="10" Padding="0" BackgroundColor="White" IsClippedToBounds="False"&gt; &lt;StackLayout Spacing="0"&gt; &lt;Image HeightRequest="150" Source="{Binding ImageUrl}" Aspect="AspectFill" /&gt; &lt;StackLayout Spacing="1" Margin="8" &gt; &lt;Label FontFamily="{StaticResource MontserratMedium}" TextColor="Black" Text="{Binding Title}"&gt; &lt;/Label&gt; &lt;StackLayout Orientation="Horizontal" &gt; &lt;Label FontFamily="{StaticResource MontserratMedium}" FontSize="13" TextColor="{StaticResource TextColorDate}" Text="Price"&gt; &lt;/Label&gt; &lt;Label FontFamily="{StaticResource MontserratBold}" FontSize="13" HorizontalOptions="EndAndExpand" TextColor="{StaticResource TextColorCash}" Text="{Binding Price,StringFormat='{0}K'}"&gt; &lt;/Label&gt; &lt;/StackLayout&gt; &lt;/StackLayout&gt; &lt;/StackLayout&gt; &lt;/Frame&gt; </code></pre> <p>Is there solution to have Image with property Aspect="AspectFill" and with rounded corners?</p>
3
1,257
How to dynamically adjust the number of rows in a table to pad table elements in bootstrap?
<p>I currently have a balance sheet table. On the left hand side is all the assets and the right hand is all the liabilities. There are short and long-term assets and short and long term liabilities. Currently my table looks like:</p> <pre><code>Assets Liabilities Short-term Long-term Cash Bond 1 Accounts Receivable Bond 2 Long-term Plants </code></pre> <p>The number of items under short/long-term asset/liabilities will change over time. So I'm looking for a solution to automatically adjust to the number of items I might have under each category. Is there a easy way in bootstrap to dynamically pad the column such that rows of similar qualities are aligned or do I need to pre-process this in Django first before outputting the results? like this?</p> <pre><code>Assets Liabilities Short-term Cash Accounts Receivable Long-term Long-term Plants Bond 1 Bond 2 </code></pre> <p>Here is the html:</p> <pre><code>&lt;div id="balance_sheet" class="container-fluid"&gt; &lt;div class="container-fluid col-sm-6 right-side"&gt; &lt;table style="width:100%"&gt; &lt;tr&gt; &lt;th&gt; Assets &lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;{{ account_receivable_title }}&lt;/th&gt; &lt;th&gt;Balance&lt;/th&gt; &lt;/tr&gt; {% for account_receivable in account_receivables %} &lt;tr&gt; &lt;td&gt;{{ account_receivable.name }}&lt;/td&gt; &lt;td&gt;${{ account_receivable.balance }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;tr&gt; &lt;th&gt;{{ account_plant_title }}&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; {% for account_plant in account_plants %} &lt;tr&gt; &lt;td&gt;{{ account_plant.name }}&lt;/td&gt; &lt;td&gt;${{ account_plant.value }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;tfoot&gt; &lt;tr&gt; &lt;td&gt;{{ account_total_name }}&lt;/td&gt; &lt;td&gt;${{ user_asset_total }}&lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;/table&gt; &lt;/div&gt; &lt;p&gt; &lt;p&gt; &lt;div class="container-fluid col-sm-6 left-side"&gt; &lt;table style="width:100%"&gt; &lt;tr&gt; &lt;th&gt; Liabilities&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;{{ account_credit_title }}&lt;/th&gt; &lt;th&gt;Balance&lt;/th&gt; &lt;/tr&gt; {% for account_credit in account_credit %} &lt;tr&gt; &lt;td&gt;{{ account_credit.name }}&lt;/td&gt; &lt;td&gt;${{ account_credit.balance }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;tr&gt; &lt;th&gt;{{ account_bond_title }}&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; {% for account_bond in account_bonds %} &lt;tr&gt; &lt;td&gt;{{ account_bond.name }}&lt;/td&gt; &lt;td&gt;${{ account_bond.balance }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;tfoot&gt; &lt;tr&gt; &lt;td&gt;{{ account_total_name }}&lt;/td&gt; &lt;td&gt;${{ user_liability_total }}&lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
3
1,641