date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/15
776
2,139
<issue_start>username_0: I have 3 tables A ,B ,C TABLE A ``` TABLE_NAME|table_number soho 20 foho 30 joho 40 ``` TABLE B ``` TABLE_ID | TABLE_NAME 1 soho 2 foho 3 joho ``` TABLE C ``` TABLE_ID | TABLE_VALUES 1 xx 1 yy 2 hh 3 no 3 bb ``` what I want to do is pass table\_name as `:paramter` from and get `table_values` from table c, like this if i pass soho ``` TABLE_NAME| TABLE_VALUES SOHO xx SOHO yy ``` this is my try but I get the `table_value` for all tables ``` select a.table_name , c.table_value from a , b , c where a.table_name= :myParamter and b.table_id= c.table_id ``` the output of my query is like this ``` ABLE_NAME| TABLE_VALUES SOHO xx SOHO yy SOHO hh SOHO no SOHO bb ```<issue_comment>username_1: ``` select b.table_name , c.table_value from b inner join c on b.table_id= c.table_id where b.table_name= :myParamter ``` Upvotes: 3 <issue_comment>username_2: > > Table DDL > > > ``` CREATE TABLE TABLEA ( TABLE_NAME VARCHAR2(64), TABLE_NUMBER NUMBER(18) ); CREATE TABLE TABLEB ( TABLE_ID NUMBER(18), TABLE_NAME VARCHAR2(64) ); CREATE TABLE TABLEC ( TABLE_ID NUMBER(18), TABLE_VALUES VARCHAR2(10) ); ``` > > Data Inserts > > > ``` INSERT INTO TABLEA VALUES('soho',20); INSERT INTO TABLEA VALUES('foho',30); INSERT INTO TABLEA VALUES('joho',40); INSERT INTO TABLEB VALUES(1,'soho'); INSERT INTO TABLEB VALUES(2, 'foho'); INSERT INTO TABLEB VALUES(3, 'joho'); INSERT INTO TABLEC VALUES(1, 'xx'); INSERT INTO TABLEC VALUES(1,'yy'); INSERT INTO TABLEC VALUES(2, 'hh'); INSERT INTO TABLEC VALUES(3, 'no'); INSERT INTO TABLEC VALUES(3, 'bb'); ``` > > Query - > > > ``` select b.table_name, c.table_values from tableb b inner join tablec c on b.table_id = c.table_id inner join tablea a on a.table_name = b.table_name and b.table_name = 'soho' ; ``` > > Output > > > ``` TABLE_NAME,TABLE_VALUES soho,yy soho,xx ``` Upvotes: 1
2018/03/15
890
2,446
<issue_start>username_0: Please check the example bellow. On bottom in javascript section you will see a datatables framework function cell().data() used to change first < td > text but there i didn't selected any of specific < td > so by default this changing the text of first < td >. But my goal is i want to select my "< td >" with "$row.find('td:eq(2)'))" jquery function. But keep in mind i must have to use the cell().data() function to change text. In short actually i wanted to control cell.().data() with jquery eq selector. How can i do it? Note: I am using [datatables framework](https://datatables.net/reference/api/cell().data()) on this example ``` Demo | Name | Position | Office | Age | Start date | Salary | | --- | --- | --- | --- | --- | --- | | <NAME> | System Architect | Edinburgh | 61 | 2011/04/25 | $320,800 | | <NAME> | Accountant | Tokyo | 63 | 2011/07/25 | $170,750 | | <NAME> | Junior Technical Author | San Francisco | 66 | 2009/01/12 | $86,000 | | <NAME> | Senior Javascript Developer | Edinburgh | 22 | 2012/03/29 | $433,060 | $(document).ready(function() { $('#example').DataTable(); //$row.find('td:eq(2)')); var table = $('#example').DataTable(); table.cell().data("fooo"); }); ```<issue_comment>username_1: ``` select b.table_name , c.table_value from b inner join c on b.table_id= c.table_id where b.table_name= :myParamter ``` Upvotes: 3 <issue_comment>username_2: > > Table DDL > > > ``` CREATE TABLE TABLEA ( TABLE_NAME VARCHAR2(64), TABLE_NUMBER NUMBER(18) ); CREATE TABLE TABLEB ( TABLE_ID NUMBER(18), TABLE_NAME VARCHAR2(64) ); CREATE TABLE TABLEC ( TABLE_ID NUMBER(18), TABLE_VALUES VARCHAR2(10) ); ``` > > Data Inserts > > > ``` INSERT INTO TABLEA VALUES('soho',20); INSERT INTO TABLEA VALUES('foho',30); INSERT INTO TABLEA VALUES('joho',40); INSERT INTO TABLEB VALUES(1,'soho'); INSERT INTO TABLEB VALUES(2, 'foho'); INSERT INTO TABLEB VALUES(3, 'joho'); INSERT INTO TABLEC VALUES(1, 'xx'); INSERT INTO TABLEC VALUES(1,'yy'); INSERT INTO TABLEC VALUES(2, 'hh'); INSERT INTO TABLEC VALUES(3, 'no'); INSERT INTO TABLEC VALUES(3, 'bb'); ``` > > Query - > > > ``` select b.table_name, c.table_values from tableb b inner join tablec c on b.table_id = c.table_id inner join tablea a on a.table_name = b.table_name and b.table_name = 'soho' ; ``` > > Output > > > ``` TABLE_NAME,TABLE_VALUES soho,yy soho,xx ``` Upvotes: 1
2018/03/15
2,085
7,546
<issue_start>username_0: I'm trying to make a simple upload app with springboot and it works fine until i try to upload 10Mb+ files, i receive this message on my screen: ``` There was an unexpected error (type=Internal Server Error, status=500). Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (14326061) exceeds the configured maximum (10485760) ``` I've done some research, and nothing have worked until now. I'll leave here below the things i've tried so far. put this code(In various ways) in my "application.yml" ``` multipart: maxFileSize: 51200KB maxRequestFile: 51200KB ``` I've also tried this in my principal class: ``` @Bean public TomcatEmbeddedServletContainerFactory containerFactory() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { @Override public void customize(Connector connector) { ((AbstractHttp11Protocol) connector.getProtocolHandler()).setMaxSwallowSize(-1); } }); return factory; } ``` And some strange thing. If i enter in my tomcat web.xml, the multipart-config is: ``` 52428800 52428800 0 ``` So where the hell this "...configured maximum (10485760)" is coming from ? (Sidenote: I'm using netbeans 8.1 and springboot 1.5). Thx guys.(And sorry for the english s2) Since asked, this is my application.yml ``` server: port: 9999 context-path: /client logging: level: org.springframework.security: DEBUG endpoints: trace: sensitive: false spring: thymeleaf: cache: false multipart: maxFileSize: 51200KB maxRequestFile: 51200KB ################################################################################# security: basic: enabled: false oauth2: client: client-id: acme2 client-secret: acmesecret2 access-token-uri: http://localhost:8080/oauth/token user-authorization-uri: http://localhost:8080/oauth/authorize resource: user-info-uri: http://localhost:8080/me # ```<issue_comment>username_1: ``` spring: http: multipart: enabled: true max-file-size: 50MB max-request-size: 50MB ``` or ``` spring.http.multipart.max-file-size=50MB spring.http.multipart.max-request-size=50MB ``` Reference [here](https://spring.io/guides/gs/uploading-files/) Hope it will works Upvotes: 5 [selected_answer]<issue_comment>username_2: For SpringBoot 1.5.7 till 2.1.2 the property need to set in application.properties file are: ``` spring.http.multipart.max-file-size=100MB spring.http.multipart.max-request-size=100MB ``` Also make sure you have application.properties file in "resources" folder. Upvotes: 2 <issue_comment>username_3: For configuring CommonsMultipartResolver Define a bean with bean name as **MultipartFilter.DEFAULT\_MULTIPART\_RESOLVER\_BEAN\_NAME** As the default spring boot's default MultipartFilter looks for resolver with default bean name. ``` @Bean(name = MultipartFilter.DEFAULT_MULTIPART_RESOLVER_BEAN_NAME) protected MultipartResolver getMultipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20971520); multipartResolver.setMaxInMemorySize(20971520); return multipartResolver; } ``` Upvotes: 0 <issue_comment>username_4: Following are the ways based on version, 1'st : ``` spring.servlet.multipart.max-file-size=1000MB spring.servlet.multipart.max-request-size=1000MB ``` 2'nd : ``` spring.http.multipart.max-file-size=50MB spring.http.multipart.max-request-size=50MB ``` 3'rd : ``` multipart.enabled=true multipart.max-file-size=100MB multipart.max-request-size=100MB ``` Upvotes: 3 <issue_comment>username_5: ```yaml spring: servlet: multipart: enabled: true file-size-threshold: 200KB max-file-size: 500MB max-request-size: 500MB ``` Upvotes: 2 <issue_comment>username_6: In SpringBoot 2.6.3 setting "spring.http.multipart.max-file-size" did not work. Following did work for me: ``` spring: servlet: multipart: max-file-size: 50MB max-request-size: 50MB ``` Upvotes: 1 <issue_comment>username_7: I also had this problem and I don't know why setting properties spring.http.multipart.max-file-size=20MB and spring.http.multipart.max-request-size=20MB in application.properties didn't work. To change max file size I've followed this guide <https://www.baeldung.com/spring-maxuploadsizeexceeded> So I've added this to my principal class: ``` @Bean public MultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20000000); return multipartResolver; } ``` and then, to handle MaxUploadSizeExceededException, I've copied this ``` @ControllerAdvice public class FileUploadExceptionAdvice { @ExceptionHandler(MaxUploadSizeExceededException.class) public ModelAndView handleMaxSizeException( MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response) { ModelAndView modelAndView = new ModelAndView("file"); modelAndView.getModel().put("message", "File too large!"); return modelAndView; } } ``` and wrote this simple file.html template: ``` Title ### ``` After adding this code I've seen in logs that the MaxUploadSizeExceededException error was handled, but in browser I still got error. The solution was adding this to application.properties: ``` server.tomcat.max-swallow-size=60MB ``` like in this tutorial: <https://www.youtube.com/watch?v=ZZMcg6LHC2k> Upvotes: 0 <issue_comment>username_8: For me the following worked in `application.properties` of a Spring Boot 3 application (v3.0.5). This should be also the correct properties according to the [following guide / reference of spring.io](https://spring.io/guides/gs/uploading-files/) and as well here at the [source code documentation](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/web/servlet/MultipartProperties.html) and the related Spring Boot [Multipart Auto Configuration](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.html). ``` spring.servlet.multipart.max-file-size=128MB spring.servlet.multipart.max-request-size=128MB ``` I had **NOT** to add any special `@Bean`configuration. According to the [Multipart Auto Configuration](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.html) documentation: ``` Auto-configuration for multipart uploads. Adds a StandardServletMultipartResolver if none is present, and adds a multipartConfigElement if none is otherwise defined. The ServletWebServerApplicationContext will associate the MultipartConfigElement bean to any Servlet beans. ``` the following did **NOT** work (may be it worked in an earlier version of Spring boot). ``` #spring.http.multipart.enabled=true #spring.http.multipart.max-file-size=128MB #spring.http.multipart.max-request-size=128MB ``` Upvotes: 0
2018/03/15
298
1,268
<issue_start>username_0: When I try to signup for a Google Cloud free trial, I get the following error after the page which checks your details and payment method: An unexpected error has occurred. Please try again later. [OR-BSBBF-01] On this page it shows my payment profile which is correct and works for other Google services such as google Express etc.<issue_comment>username_1: As stated in the documentation, to sign up for the 12-month, $300 free trial, a ***credit card or bank account*** is needed so Google can verify your identity. You will not be charged or billed during free trial. Here is the [**link**](https://cloud.google.com/free/docs/frequently-asked-questions) where you can check this information. Upvotes: 2 <issue_comment>username_2: The issue is likely that you are using a prepaid card, which G Cloud unfortunately does not accept. Upvotes: 1 <issue_comment>username_3: My old address was listed on my payments profile. I created a new profile with the correct address and this solved the issue. [After going around in circles, it appears my old address could only be updated by contacting Google directly despite their online instructions to the contrary. Instead of waiting to speak to Google, I just created a new profile.] Upvotes: 0
2018/03/15
2,023
7,499
<issue_start>username_0: I have this Android code : ``` package com.example.webtestconnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ private Button login; private EditText username, password; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); login = (Button) findViewById(R.id.ok); username = (EditText) findViewById(R.id.name); password = (EditText) findViewById(R.id.password); login.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String mUsername = username.getText().toString(); String mPassword = password.getText().toString(); tryLogin(mUsername, mPassword); } }); } protected void tryLogin(String mUsername, String mPassword) { HttpURLConnection connection; OutputStreamWriter request = null; URL url = null; String response = null; String parameters = "username="+mUsername+"&password="+mPassword; try { url = new URL("http://welovelamacompany.altervista.org/test2.php"); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); request = new OutputStreamWriter(connection.getOutputStream()); request.write(parameters); request.flush(); request.close(); String line = ""; InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Response from server after login process will be stored in response variable. response = sb.toString(); // You can perform UI operations here Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show(); isr.close(); reader.close(); } catch(IOException e) { // Error } } } ``` And this is the php page code: ``` php //impostazioni server phpmyadmin per poter accedere al db $servername = "servername"; $username = "username"; $password = "<PASSWORD>"; $databasename = "my_databasename"; $Nome_Giocatore = $_POST['username']; $PasswordGiocatore = $_POST['password']; try { $conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password); //imposto una modalità di eccezzione errore $conn-setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //stampo che la connessione è riuscita $sql=$conn->query("SELECT Password_Giocatore FROM Giocatori WHERE Nome_Giocatore=\"$Nome_Giocatore\""); $control = $sql->fetch(); $controllo=$control['Password_Giocatore']; if (password_verify($PasswordGiocatore, $controllo)){ echo "Success"; } else { echo "Error"; } $conn->exec($sql); } catch(PDOException $e){ //stampo che la connessione è fallita e l'errore che ha causato il fallimento echo "Qualcosa è andato storto :(. Errore: ".$e->getMessage(); } $conn = null; ?> ``` But when I run it it give me this error: > > E/AndroidRuntime: FATAL EXCEPTION: main > Process: com.example.webtestconnection, PID: 23550 > android.os.NetworkOnMainThreadException > at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166) > at java.net.InetAddress.lookupHostByName(InetAddress.java:385) > at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) > at java.net.InetAddress.getAllByName(InetAddress.java:214) > at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28) > at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216) > at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122) > at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390) > at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343) > at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289) > at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) > at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89) > at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197) > at com.example.webtestconnection.MainActivity.tryLogin(MainActivity.java:62) > at com.example.webtestconnection.MainActivity$1.onClick(MainActivity.java:40) > at android.view.View.performClick(View.java:4633) > at android.view.View$PerformClick.run(View.java:19270) > at android.os.Handler.handleCallback(Handler.java:733) > at android.os.Handler.dispatchMessage(Handler.java:95) > at android.os.Looper.loop(Looper.java:136) > at android.app.ActivityThread.main(ActivityThread.java:5476) > at java.lang.reflect.Method.invokeNative(Native Method) > at java.lang.reflect.Method.invoke(Method.java:515) > at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) > at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) > at dalvik.system.NativeStart.main(Native Method) > > > Why? How can I fix it? Thanks for help P.S. I have the internet permission in the manifest<issue_comment>username_1: You are trying to run a http connection on the main thread. This in Android is absolutely forbidden, because you undermine the app's responsiveness. You should run your connection into an [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask.html) Upvotes: 0 <issue_comment>username_2: Please use [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask.html) to make an API call, you are getting exception because you are calling it on MainThread. ``` class LoginTask extends AsyncTask { private Exception exception; protected YourResponse doInBackground(String... urls) { try { URL url = new URL(urls[0]); //your login code } catch (Exception e) { this.exception = e; } } protected void onPostExecute(YourResponse response) { // TODO: check this.exception // TODO: do something with the feed } } ``` and add this line in your code ``` new LoginTask().execute(url); ``` **EDITED** You can below libraries for Network calls, easier and optimized for Network calls 1. [Retrofit](http://square.github.io/retrofit/) 2. [Volley](https://github.com/google/volley) Upvotes: 3 [selected_answer]
2018/03/15
565
2,360
<issue_start>username_0: I am trying to do this while building build in ionic, but the location is on IOS and does not work with geolocation in ionic 2 app. I have installed ionic cordova plugin add cordova-plugin-geolocation and In android devices it is working when the location service is made on. When the location service is made off its not working. In iOS devices both scenarios not working. Need some help!! ``` import { Geolocation } from '@ionic-native/geolocation'; ``` In Providers I have mentioned Geolocation; In home.ts I imported Geolocation. To get the current location I Have written the following code ``` getCurrentLocation(){ this.geolocation.getCurrentPosition().then((position) => { let loc = { placeId: null, name:null, lat:null, long:null, } var lat = position.coords.latitude; var lng = position.coords.longitude; var latlng = new google.maps.LatLng(lat, lng); var geocoder = geocoder = new google.maps.Geocoder(); } ```<issue_comment>username_1: If location on IOS do not work with geolocation Since iOS 10 it's mandatory to add a NSLocationWhenInUseUsageDescription entry in the info.plist. NSLocationWhenInUseUsageDescription describes the reason that the app accesses the user's location. When the system prompts the user to allow access, this string is displayed as part of the dialog box. To add this entry you can pass the variable GEOLOCATION\_USAGE\_DESCRIPTION on plugin install. Example: cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION\_USAGE\_DESCRIPTION="your usage message" If you don't pass the variable, the plugin will add an empty string as value. To solve your problem, try: Uninstall the plugin: cordova plugin remove cordova-plugin-geolocation Reinstall with: cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION\_USAGE\_DESCRIPTION="my\_project would like to use your location" platform/ios/{project}/{project}/project.info.plist This will automatically add entry in the info.plist file Upvotes: 4 [selected_answer]<issue_comment>username_2: You can also manually edit the platform/ios/{project}/{project}/project.info.plist file and add the following lines ``` NSLocationWhenInUseUsageDescription Location is needed because [your reason] ``` Upvotes: 1
2018/03/15
464
1,520
<issue_start>username_0: I have a problem with some PHP code defined at the top of a layout file (default.htm) which does not executes. It is just printed verbatim on the page. The layout file is the default layout for a plugin. Here is the source file (default.htm) : ``` title = "default" == use Config; function onStart() { $this['select2_Api_Url'] = Config::get('tudordanes.select2::select2_Api_Url'); } ? == Code de loi: Choisir un code Numero: Numero d'article {% put scripts %} $(document).ready(function() { console.log('ready!'); console.log('{{ cfg\_API\_URL }}'); {% endput %} ```<issue_comment>username_1: Are you sure you have **and is uncommented** the: ``` AddType application/x-httpd-php .htm ``` in your `httpd.conf` file? "short tags" is a bad habit, if you really need to use them make shure you have and is uncommented: ``` short_open_tag=On ``` in your `php.ini` Upvotes: 0 <issue_comment>username_2: Actually, your default.htm file is in the component named 'select2' in 'tudordanes' plugin. And the rule is that you cannot access PHP code section in components. Please refer [Building components instructions](https://octobercms.com/docs/plugin/components#page-cycle) for the better explanation. As per code in question, you can do with that is define onRun() function in your Select2.php file. ``` use Config; public function onRun() { $this->page['select2_Api_Url'] = Config::get('tudordanes.select2::select2_Api_Url'); } ``` Upvotes: 2 [selected_answer]
2018/03/15
405
1,328
<issue_start>username_0: What is the difference between the top two system images entries currently in this Android Studio dialog: [![Android Studio System Images](https://i.stack.imgur.com/f5WBk.png)](https://i.stack.imgur.com/f5WBk.png) You can see that neither **Oreo**, **API 27**, or **P** or listed in the "API level distribution chart." [![Android Platform/API Version Distribution](https://i.stack.imgur.com/9hNX7.png)](https://i.stack.imgur.com/9hNX7.png)<issue_comment>username_1: > > What is the difference between the top two system images entries currently in this Android Studio dialog > > > Android P is the P Developer Preview, currently Developer Preview 1. API Level 27 is [Android 8.1](https://developer.android.com/about/versions/oreo/android-8.1.html). Upvotes: 4 [selected_answer]<issue_comment>username_2: [Android P](https://developer.android.com/preview/index.html) is preview 1(initial release, alpha) of the next version of Android. Whereas API 27 is the [Go Edition](https://developer.android.com/about/versions/oreo/android-8.1.html#safebrowsing) of the android Oreo(Android 8.1). [![enter image description here](https://i.stack.imgur.com/eanfF.png)](https://i.stack.imgur.com/eanfF.png) [API LEVEL DISTRIBUTION CHART](https://developer.android.com/about/dashboards/index.html) Upvotes: 2
2018/03/15
518
1,788
<issue_start>username_0: I'm working on a Laravel 5.6 app and have the following two API routes: ``` Route::resource('/partners', 'API\Partners\PartnersController'); Route::resource('/partners/{id}/sales-team', 'API\Partners\SalesTeamController'); ``` In both of the controllers I am referencing a custom middleware 'VerifyUserOwnsTeam' in the construct method. To get the resource ID from the request in the middleware I previously had: ``` $request->route('partner') ``` This worked a URL such as: ``` /api/partners/1 ``` However, I am now calling a new end point such as: ``` /api/partners/1/sales-team ``` In my middleware the request route param for partner is null. If I change the reference to be: ``` $request->route('id') ``` Then it works for the latter endpoint, but fails on the first for a null value. Any idea how to get this consistent?<issue_comment>username_1: you need to change your first route to accept an id: ``` Route::resource('/partners/{id?}', 'API\Partners\PartnersController'); ``` Upvotes: 0 <issue_comment>username_2: For all searchers: For resources in edit/update/delete actions you can access id of the model inside Request classes using ``` $this->get('id') ``` Upvotes: -1 <issue_comment>username_3: I use laravel 8 and got solved in my case. I have put the param **id** from the router to function in my controller. Then passing the **id** with compact function to use on my view. Here's the code example My router: ``` Route::resource('stock/{id}', StockController::class); ``` My controller: ``` public function index($id, Request $request) { return View::make("pages.stock.index", compact('id')); } ``` My view: ``` {{$id}} ``` Idk this is works or not for your case, but I hope you get some clue. Upvotes: 1
2018/03/15
482
1,692
<issue_start>username_0: I have an existing Factory (order), and I am trying to make a new factory that effectively inherits from it. It looks like this: ``` factory :order_with_domain, :parent => :order do |o| o.order_provider 'DomainNameHere' end ``` Upon doing that and running the specs with `order_with_domain`, I am greeted by this: ``` undefined method `order_provider=' for # Did you mean? order\_provider ``` I receive this same error if I try and place `order_provider` in the parent Factory. Any helps is much appreciated. Thanks.<issue_comment>username_1: Assuming your model has an `order_provider` attribute or `order_provider=` method, as @moveson commented above. I would use [`traits`](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#traits). Something like this: ``` factory :order do # ... original factory stuff trait :with_domain do order_provider 'DomainNameHere' end end ``` Then to use it: ``` order_with_domain = FactoryBot.create(:order, :with_domain) ``` Upvotes: 0 <issue_comment>username_2: Try running `rails c test` then check if your column is present. If not then it's an issue with your test database and you need to run your migrations in the test environment using `RAILS_ENV=test rake db:migrate`. If nothing happens, delete your `schema.rb` then run the migrations command again. Upvotes: 3 <issue_comment>username_3: Try putting the value in curly braces like so: ```rb factory :order_with_domain, :parent => :order do |o| o.order_provider { 'DomainNameHere' } end ``` Here is the reason [on thoughtbot](https://thoughtbot.com/blog/deprecating-static-attributes-in-factory_bot-4-11) Upvotes: 2
2018/03/15
1,796
6,506
<issue_start>username_0: I'm trying to understand how php works but I have problems with understanding syntax and arrays/objects. 1. I know that code igniter uses $\_POST only and keeps form data in an array but how to access it in a view? I have some more questions in the comments inside below code: I understand the concept of MVC but below code is all-in-one. ``` php //database - formvalidation //controller - form //model - form //model methods - add //view form/add.php class Form extends CI_Controller { public function __construct() { parent::__construct(); $this-load->model( 'Form_model' ); $this->load->library( array( 'form_validation' ) ); } //controller > add public function add() { if ( $this->form_validation->run() == FALSE ) { //displaying form if validation doesn't run $this->load->view( 'form/add' ); } else { //inserting data from the form into the database //I dont understand what happens here and how to access keys in the view :/ $data = array( 'username' => $this->input->post( 'username' ), ); $this->Form_model->add( $data ); // passing data array to the view $this->load->view( 'form/success' ); //loading success page } } //Form model > add var $table = 'formvalidation'; public function add( $data ) { $this->db->insert( $this->table, $data ); return $this->db->insert_id(); } //Form model > get all items //how can I use this function to display data in the view? public function get_all() { return $this->db->get( $this->table )->result_array(); } } ?> //view ? php echo form_open('form/add',array('class'='pure-form', 'style'=>'width:50%')); ?> php echo form_error('username'); ? php foreach($asd as $a){ //What if I don't want to use foreach loop? //How can i display field values in the view? ? php } ? //Can you show me simple example of using objects and arrays to display data in the view? ? ```<issue_comment>username_1: If validation fails you want to repopulate the fields with the post data so that the user doesn't have to re-enter data for inputs that didn't fail. You can do this by using the `set_value($fieldname)` method in the form view. ``` php echo form_open('form/add',array('class'='pure-form', 'style'=>'width:50%')); ?> php echo form_error('username'); ? ``` Now if a validation error occurs whatever the user posted will appear in the `username` field. --- In this function: ``` public function get_all() { return $this->db->get( $this->table )->result_array(); } ``` You are using `result_array()`. `result_array()` is different than `row_array()` in that all the users in the table will be returned as an array (as long as you don't have a unique where condition) e.g. `array( 0 => array('username'=>'bob'), 1 => array('username'=>'jeff'));`. Thus you can generate a table or whatever of all of the users: In controller: `$this->load->view('form/success', array('users' => $this->form_model->get_all());` In view: ``` foreach ($users as $user) { echo $user['username']; } ``` Echos: <NAME> But I think you want to just get the user you just added... In which case a model function like this will work nicely: ``` public function get_one($id) { $this->db->where('id', $id); return $this->db->get( $this->table )->row_array(); } ``` And then in controller: ``` if ($this->form_validation->run() == FALSE) { $this->load->view('form/add'); } else { $data = array( 'username' => $this->input->post('username'), ); $id = $this->Form_model->add($data); $user = $this->Form_model->get_one($id); $this->load->view('form/success', array('user' => $user)); } ``` and in view: ``` echo $user['username']; ``` --- Objects generated from `result()` and `row()` are the same as their counterparts `result_array()` and `row_array()`, respectively, with the exception that objects are accessed via `->` rather than `[$somekey]`. In the last example had you passed an object by using `row()` instead of `row_array()` in `get_one()` you would access it in the view like: `$user->username;`. Assigning data to the view is usually handled in the above method, but for more info you can [view the docs.](https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view) Upvotes: 2 [selected_answer]<issue_comment>username_2: Ok. I was confusing post values with database functions values. Now that subject is a little bit brighter to me. Look below: I didn't know where to find the information in the user guide :/ ``` php defined( 'BASEPATH' )OR exit( 'No direct script access allowed' ); class Lol extends CI_Controller { function __Construct() { parent::__Construct(); //loading helpers, models, libraries $this-load->database(); $this->load->helper( array( 'form' ) ); $this->load->library( array( 'form_validation' ) ); } //form remembers the username field value public function index() { echo form_open( 'lol' ); $val = set_value('username'); echo form_input( 'username', $val ); echo form_submit( 'submit', 'Submit' ); echo form_close(); } public function validation() { //setting up the form validation $this->form_validation->set_rules( 'username', 'Username', 'required|min_length[3]' ); //displaying form if validation doesn't run if ( $this->form_validation->run() == FALSE ) { echo form_error( 'username' ); echo form_open( 'lol/validation' ); $val = set_value('username'); echo form_input( 'username', $val ); echo form_submit( 'submit', 'Submit' ); echo form_close(); } //inserting data from the form into the database else { echo "username is ok"; } } //getting field value from database in two ways: array and object. Your pick. public function database() { echo form_open( 'lol' ); $val = $this->get_all(); //echo form_input( 'username', $val->username ); // object echo form_input( 'username', $val['username'] ); //array echo form_submit( 'submit', 'Submit' ); echo form_close(); } //getting database data public function get_all() { //return $this->db->get('formvalidation')->row(); //object return $this->db->get('formvalidation')->row_array(); //array } } ``` Upvotes: 0
2018/03/15
524
1,681
<issue_start>username_0: I have two tables, first one serves as a search functionality utilizing datepicker, and the second holds the `thead` and `tbody` which holds the actual header and rows for my data. I tried following <http://jsfiddle.net/wLcjh/255/> ``` var tableOffset = $("#table-1").offset().top; var $header = $("#table-1 > thead"); var $fixedHeader = $("#header-fixed").append($header.clone()); console.log(tableOffset); console.log($header); console.log($fixedHeader); console.log($fixedHeader.is(":hidden")); $(window).bind("scroll", function () { var offset = $(this).scrollTop(); if (offset >= tableOffset && $fixedHeader.is(":hidden")) { $fixedHeader.show(); $.each($header.find('#tr1 > th'), function (ind, val) { var original_width = $(val).width(); $($fixedHeader.find('#tr1 > th')[ind]).width(original_width); }); } }); ``` However, it had no effect on my page whatsoever. Is it even possible to accomplish?<issue_comment>username_1: How about doing this with plain CSS using [postion:sticky](https://css-tricks.com/position-sticky-2/)? ```css body { height: 1000px; } thead tr th{ background: white; position: sticky; top: 0; } ``` ```html | Col1 | Col2 | Col3 | | --- | --- | --- | | info000000 | info | info | | info | infolllllllllllll | info | | info | info | info00000000 | ``` Upvotes: 2 <issue_comment>username_2: You can apply `position: fixed;` CSS on header container to keep position fix. Plese check below code:: ``` .header-container-fixed { left: 0; position: fixed; right: 0; top: 0; width: 100%; z-index: 1; } ``` Upvotes: 0
2018/03/15
630
1,933
<issue_start>username_0: I have two arrays data I'm just trying to get the data of array two based on the same ID example ``` import React from 'react'; const data = [ { "userId": 1, "id": 1, "title": "One", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "Two", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, ] const dataTwo = [ { "id": 1, "color": "red" }, { "id": 2, "color": "blue" }, ] class App extends React.Component { render() { return ( {data.map((tweet)=> * {tweet.title} **Color:** I want to put the color here )} ); } } export default App; ``` if id of dataTwo `===` id of data so I want to get the color for the same item<issue_comment>username_1: You can use `Array.prototype.find`: ``` {data.map((tweet)=> { const { color = "default-color" } = dataTwo.find(item => item.id === tweet.id) || {}; return * {tweet.title} **Color:** { color } })} ``` Or you can change `dataTwo` so that it is an object (map): ``` const dataTwo = { 1: "red" 2: "blue" }; ``` And then access it directly: ``` {data.map((tweet)=> * {tweet.title} **Color:** { dataTwo[tweet.id] || 'default-color' } )} ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Create a object of dataTwo with key as id and value as color. Use this object to get color while looping ``` var dataTwoObj = {}; dataTwo.reduce((data)=>{ dataTwoObj[data.id] = data.color; }); data.map((tweet)=> { const color = dataTwoObj[item.id]; * {tweet.title} **Color:** { color } ) ``` Upvotes: 1
2018/03/15
527
2,033
<issue_start>username_0: I am doing a project on an application where by I need to discover other devices based on my current location. These devices I want to filter in a way whereby they are classified by North/South/East/West of my device pointing direction. I read some article saying converting compass bearing into lat & long but how do I know the lat & long is to my right or left ? north or south ?<issue_comment>username_1: So I am assuming you have Latitude and Longitude coordinates. Latitude denotes North and South of the equator and longitude denotes East and West of the Prime Meridian. If you want to convert latitutde-longitude to East-West-North-South direction you can use this scheme. Positive latitude means North of the equator, and Positive longitude means East of the Prime Meridian and vice versa. So in short ``` +,+ -> North/East +,- -> North/West -,+ -> South/East -,- -> South/West ``` Using this key you can find out relative direction of any lat-lon pair from your base location. **Edit** **Example** If your location is `(50,50)` and some other device has location `(60,60)` that means the other device is 10 degrees North and 10 degrees East to your relative location. You can easily implement this logic in android. Upvotes: 0 <issue_comment>username_2: The Android Maps Util library has a function to calculate the bearing between 2 `LatLng` Objects. Include the Android Maps library if you don't have it already ``` implementation 'com.google.maps.android:android-maps-utils:0.5' ``` Compare your current `LatLng` with the `LatLng` of the other device. ``` LatLng myLocation; LatLng otherPhone; double heading = SphericalUtil.computeHeading(myLocation, otherPhone); ``` Now you can use the heading however you want, the double represents the heading from one LatLng to another LatLng. Headings are expressed in degrees clockwise from North within the range [-180,180). Documentation can be found [here](http://googlemaps.github.io/android-maps-utils/javadoc/) Upvotes: 1
2018/03/15
1,939
7,439
<issue_start>username_0: As the title says I would like to find all strings with Roslyn and be able to manipulate them. I have created a program that can get all classes and local declarations but I would have hoped there was some way to extract strings. In an optimal world I would like to be able to get a key value pair for the following strings as well and avoid `int i = 0;` and `var i2 = 0;`. ``` var test = "test"; string test1 = "testing"; String test2 = "testing 2"; ``` What I currently have: ``` { class Program { static void Main(string[] args) { var workspace = MSBuildWorkspace.Create(); SyntaxTree tree = CSharpSyntaxTree.ParseText( @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { var test = ""test""; string test1 = ""testing""; String test2 = ""testing 2""; int i = 0; var i2 = 0; } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var classVisitor = new ClassVirtualizationVisitor(); classVisitor.Visit(root); var classes = classVisitor.Classes; var localDeclaration = new LocalDeclarationVirtualizationVisitor(); localDeclaration.Visit(root); var localDeclarations = localDeclaration.LocalDeclarations; } } class LocalDeclarationVirtualizationVisitor : CSharpSyntaxRewriter { public LocalDeclarationVirtualizationVisitor() { LocalDeclarations = new List(); } public List LocalDeclarations { get; set; } public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node); LocalDeclarations.Add(node); return node; } } class ClassVirtualizationVisitor : CSharpSyntaxRewriter { public ClassVirtualizationVisitor() { Classes = new List(); } public List Classes { get; set; } public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node); Classes.Add(node); // save your visited classes return node; } } } ``` Example program: ``` using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { var test = "test"; string test1 = "testing"; String test2 = "testing 2"; int i = 0; var i2 = 0; } } } ``` Using `Strings v2.53` from `SysInternals` I get the following strings below for the `.exe` and I would like to get the same from Roslyn. <https://learn.microsoft.com/sv-se/sysinternals/downloads/strings> ``` !This program cannot be run in DOS mode. .text `.rsrc @.reloc BSJB v4.0.30319 #Strings #US #GUID #Blob T.#] mscorlib HelloWorld DebuggableAttribute TargetFrameworkAttribute CompilationRelaxationsAttribute RuntimeCompatibilityAttribute ObfuscationConsoleApp.exe System.Runtime.Versioning Program System Main ObfuscationConsoleApp .ctor System.Diagnostics System.Runtime.CompilerServices DebuggingModes args Object test testing testing 2 z\V WrapNonExceptionThrows .NETFramework,Version=v4.6.1 FrameworkDisplayName .NET Framework 4.6.1 RSDS g1M |EF\R} C:\Users\Oscar\source\repos\ObfuscationConsoleApp\ObfuscationConsoleApp\obj\Debug\ObfuscationConsoleApp.pdb \_CorExeMain mscoree.dll VS\_VERSION\_INFO VarFileInfo Translation StringFileInfo 000004b0 FileDescription FileVersion 0.0.0.0 InternalName ObfuscationConsoleApp.exe LegalCopyright OriginalFilename ObfuscationConsoleApp.exe ProductVersion 0.0.0.0 Assembly Version 0.0.0.0 xml version="1.0" encoding="UTF-8" standalone="yes"? ```<issue_comment>username_1: A big thank you too @MarcGravell and the service at <http://roslynquoter.azurewebsites.net/> (make sure to check the checkbox "Keep redundant API calls") or <https://github.com/KirillOsenkov/RoslynQuoter>. Final code to print key value pair for strings: ``` var localDeclaration = new LocalDeclarationVirtualizationVisitor(); localDeclaration.Visit(root); var localDeclarations = localDeclaration.LocalDeclarations; foreach (var localDeclarationStatementSyntax in localDeclarations) { foreach (VariableDeclaratorSyntax variable in localDeclarationStatementSyntax.Declaration.Variables) { var stringKind = variable.Initializer.Value.Kind(); if (stringKind == SyntaxKind.StringLiteralExpression) { Console.WriteLine($"Key: {variable.Identifier.Value} Value:{variable.Initializer.Value}"); } } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Based on the accepted answer this has helped me: ``` using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace CodeScanner { class StringsCollector : CSharpSyntaxWalker { public List \_strings = new List(); public override void VisitLiteralExpression(LiteralExpressionSyntax node) { if (node.IsKind(SyntaxKind.StringLiteralExpression)) { // StringLiteralToken stringLiteralToken = node.Token; // Console.WriteLine(node.Token.Value); \_strings.Add((string) node.Token.Value); } } } class Program { const string programText = @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace TopLevel { using Microsoft; using System.ComponentModel; namespace Child1 { using Microsoft.Win32; using System.Runtime.InteropServices; class Foo { } } namespace Child2 { using System.CodeDom; using Microsoft.CSharp; class Bar { public string test = ""str1\n\t""; public void test() { Console.WriteLine(""str2""); } } } }"; private const string \_rootDir = @""; static List GetAllCSharpCode(string folder) { List result = new List(); result.AddRange(Directory.GetFiles(folder, "\*.cs")); foreach (var directory in Directory.GetDirectories(folder).Where(d => !SkipDirectory(d))) { result.AddRange(GetAllCSharpCode(directory)); } return result; } private static string[] skippedDirs = new string[] {"obj", "packages"}; static bool SkipDirectory(string directory) { var lcDir = directory.ToLower(); return skippedDirs.Any(sd => directory.EndsWith("\\" + sd)); } static void Main(string[] args) { //PrintStrings(GetStrings(programText)); //Console.WriteLine("Hello World!"); var allCSharpFiles = GetAllCSharpCode(\_rootDir); PrintStrings(allCSharpFiles); allCSharpFiles.ForEach(f => { Console.WriteLine(f); PrintStrings(GetStrings(File.ReadAllText(f))); }); } static void PrintStrings(List list) { list.ForEach(Console.WriteLine); } private static List GetStrings(string sourceCode) { SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); var collector = new StringsCollector(); collector.Visit(root); return collector.\_strings; } } } ``` Of course the code can be tweaked to cater for other requirements. Upvotes: 1
2018/03/15
744
3,077
<issue_start>username_0: I have UICollectionView, i am selected cell with didSelectItemAt and deselect with didDeselectItemAt but selected cells are replaced [![enter image description here](https://i.stack.imgur.com/pgk9W.gif)](https://i.stack.imgur.com/pgk9W.gif) <https://im4.ezgif.com/tmp/ezgif-4-2715e62591.gif> ``` func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) // print(indexPath) let collectionActive: UIImageView = { let image=UIImageView(image: #imageLiteral(resourceName: "collectionActive")) image.contentMode = .scaleAspectFill return image }() if cell?.isSelected == true { cell?.backgroundView = collectionActive } } func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { return true } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) let collectionInactive: UIImageView = { let image=UIImageView(image: #imageLiteral(resourceName: "collectionInactive")) image.contentMode = .scaleAspectFill return image }() if cell?.isSelected == false { cell?.backgroundView = collectionInactive } } ```<issue_comment>username_1: Try the following code. In "didSelectItemAt" function add converse condition also: ``` if cell?.isSelected == true { cell?.backgroundView = collectionActive } else { cell?.backgroundView = collectionInactive } ``` Similarly, in "didDeselectItemAt" add this condition: ``` if cell?.isSelected == false { cell?.backgroundView = collectionInactive } else { cell?.backgroundView = collectionActive } ``` This problem occurs whenever we are reusing the cells. Above code might help you!! Upvotes: 0 <issue_comment>username_2: I have also worked on same things, I have following solution for that. You need to create array of indexPath which will store selected indexPath. ``` var arrSelectedIndexPath = [IndexPath]() ``` In `cellForRowAtItem` method add following code which will check if arrSelectedIndexPath contains indexPath then display selected active background else display inactive background. ``` if arrSelectedIndexPath.contains(indexPath) { cell?.backgroundView = collectionActive } else { cell?.backgroundView = collectionInactive } ``` In `didSelect` method you need to add following code which also same as above logic, but just add or remove indexPath. ``` if arrSelectedIndexPath.contains(indexPath) { cell?.backgroundView = collectionInactive arrSelectedIndexPath.remove(at: arrSelectedIndexPath.index(of: indexPath)!) } else { cell?.backgroundView = collectionInactive arrSelectedIndexPath.append(indexPath) } ``` I hope this solution work for you. Upvotes: 2 [selected_answer]
2018/03/15
590
2,018
<issue_start>username_0: I want to remove the last specific word from each sentence within some classes. Example: ``` Active speakers hire Passive speakers hire ``` I want to remove the word "hire" from every paragraph that has the "remove" class attached to it. I understand that this can be done individually using the following code: ``` var str = "Active speakers hire"; var lastIndex = str.lastIndexOf(" "); str = str.substring(0, lastIndex); ``` But how to do that in the external jquery file based on the classes? I don't want to type in the js code individually for each paragraph. Thanks<issue_comment>username_1: You can try this using [`text-function`](http://api.jquery.com/text/#text-function) like: ```js $('.remove').text(function(i, txt) { return txt.substring(0, txt.lastIndexOf(" ")); }); ``` ```html Active speakers hire Passive speakers hire ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can use jQuery's [.each](https://api.jquery.com/each/) function. ``` $(".remove").each(function() { var str = this.html() var lastIndex = str.lastIndexOf(" "); this.html(str.substring(0, lastIndex)); }); ``` Upvotes: 1 <issue_comment>username_3: No jQuery necessary: ```js var items = document.getElementsByClassName('remove'); [].forEach.call(items, item => { var newText = item.innerHTML.split(' '); newText.pop(); item.innerHTML = newText.join(' '); }); ``` ```html Active speakers hire Passive speakers hire ``` Upvotes: 0 <issue_comment>username_4: Solution below won't work in IE due to [NodeList.forEach()](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach), but it has no dependencies. ``` const process = node => { let str = node.innerHTML node.innerHTML = str.split(' ').slice(0, -1).join(' ') } document.querySelectorAll('.remove').forEach(process) ``` To make it work in IE you'll have to iterate nodelist in other way, but I think it's not a problem. [Fiddle](https://jsfiddle.net/Lxuxtaf2/10/) Upvotes: 0
2018/03/15
708
2,264
<issue_start>username_0: I'm trying to create an OTRS ticket. Web service type `HTTP:REST`. ``` var data = { Ticket: { Title: "123123", TypeID: "2", QueueID: "1", State: "open", PriorityID: "2", ServiceID: "1" }, Article: { Subject: "123123", Body: "Trololo", ContentType: "text/plain; charset=utf8" }, SessionID: 123 }; $.ajax({ url: url, type: 'POST', dataType: 'json', data: JSON.stringify(data), success: function(res) { ... }, error: function(res) { ... } }); ``` And after submitting I got an error: `Could not read input data`. If I try change method to GET and change the data type to JS obj I've got another ``` error: ErrorCode:"TicketCreate.MissingParameter" ErrorMessage:"TicketCreate: Ticket parameter is missing in or not valid!" ``` What am I doing wrong?<issue_comment>username_1: You can try this using [`text-function`](http://api.jquery.com/text/#text-function) like: ```js $('.remove').text(function(i, txt) { return txt.substring(0, txt.lastIndexOf(" ")); }); ``` ```html Active speakers hire Passive speakers hire ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can use jQuery's [.each](https://api.jquery.com/each/) function. ``` $(".remove").each(function() { var str = this.html() var lastIndex = str.lastIndexOf(" "); this.html(str.substring(0, lastIndex)); }); ``` Upvotes: 1 <issue_comment>username_3: No jQuery necessary: ```js var items = document.getElementsByClassName('remove'); [].forEach.call(items, item => { var newText = item.innerHTML.split(' '); newText.pop(); item.innerHTML = newText.join(' '); }); ``` ```html Active speakers hire Passive speakers hire ``` Upvotes: 0 <issue_comment>username_4: Solution below won't work in IE due to [NodeList.forEach()](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach), but it has no dependencies. ``` const process = node => { let str = node.innerHTML node.innerHTML = str.split(' ').slice(0, -1).join(' ') } document.querySelectorAll('.remove').forEach(process) ``` To make it work in IE you'll have to iterate nodelist in other way, but I think it's not a problem. [Fiddle](https://jsfiddle.net/Lxuxtaf2/10/) Upvotes: 0
2018/03/15
791
3,009
<issue_start>username_0: I'm working on an application to capture images but I'd like to rotate a JPEG image before saving it, I already saw this link : [Android Rotate Picture before saving](https://stackoverflow.com/questions/9606046/android-rotate-picture-before-saving) This is what I'm doing right now. ``` ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer(); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(mImageFileName); fileOutputStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } ``` I tried this to rotate the image like this : ``` // Bytes array to bitmap and matrix rotation Bitmap sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); Matrix m = new Matrix(); m.setRotate((float)90, sourceBitmap.getWidth(), sourceBitmap.getHeight()); Bitmap targetBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m, true); // Bitmap to bytes array int size = targetBitmap.getRowBytes() * targetBitmap.getHeight(); ByteBuffer targetByteBuffer = ByteBuffer.allocate(size); targetBitmap.copyPixelsToBuffer(targetByteBuffer); bytes = targetByteBuffer.array(); ``` But when I look into the file into my gallery, I cannot read it, the image seems broken. EDIT: Doesn't work on Android 7.1.1 :/ Any idea ? Can I do something similar for a video record?<issue_comment>username_1: You are Coverting Your `Bitmap` to `bytes array`, Now You stop That way save `Bitmap` directly to `File` ``` Bitmap sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); Matrix m = new Matrix(); m.setRotate((float)90, sourceBitmap.getWidth(), sourceBitmap.getHeight()); Bitmap rotatedBitmap= Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m, true); // Save Bitmap directly to the file String filename = "hello.jpg"; File sd = Environment.getExternalStorageDirectory(); File dest = new File(sd, filename); try { FileOutputStream out = new FileOutputStream(dest); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } ``` Upvotes: 2 <issue_comment>username_2: This little change apparently did the trick ! Thanks Nikunj ! ``` ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer(); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); Matrix matrix = new Matrix(); matrix.setRotate((float)90, bitmap.getWidth(), bitmap.getHeight()); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(mImageFileName); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } ``` Upvotes: 0
2018/03/15
716
2,771
<issue_start>username_0: I'm in the situation where I need to make 5 http calls that can be executed in parallel + another http call that need to be executed after these five. I used forkJoin for the first 5, but I don't have any idea how to chain flatMap (or other function). ``` forkJoin( firstObservable, secondObservable, thirdObservable, ..) .subscribe(results => { this.myComposedObject = results[0]; let secondResult = results[1]; let thirdResult = results[2]; [...] // !!! AT THIS POINT I WOULD NEED TO MAKE AN EXTRA CALL! // results[1] contains data I need to make the extra call // this.myComposedObject.second = secondResult; this.myComposedObject.third = thirdResult; }); ``` I do this operation within a component, so at the end I assign data to myComposedObject.<issue_comment>username_1: Like you said to make 5 parallel requests you can use `forkJoin`. Then you want to make another request when the previous 5 complete so you'll chain it with the `concatMap` operator (or `mergeMap` would work here as well). Then you need to work with all the results combined so you can use `map` to add the last result to the the same array as the previous five. ``` forkJoin( firstObservable, secondObservable, thirdObservable, ... ) .concatMap(firstFiveResults => makeAnotherCall(firstFiveResults[1]) .map(anotherResult => [...firstFiveResults, anotherResult]) ) .subscribe(allResults => { this.myComposedObject.second = allResults[1]; this.myComposedObject.third = allResults[2]; // allResults[5] - response from `makeAnotherCall` .... }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Thanks, that pointed me to the right direction. I had some problem with results types. When I tried to assign ``` this.myComposedObject.second = allResults[1]; ``` compiler complains about type conversion, so I'll report my solution here for other people. In order to get rid of this problem you take advantage of "destructuring" (more info here: <https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment>) ``` forkJoin( firstObservable, secondObservable, thirdObservable, ... ) .concatMap(firstFiveResults => makeAnotherCall(firstFiveResults[1]) .map(anotherResult => [...firstFiveResults, anotherResult]) ) .subscribe((allResults: [ TypeA, <-- type returned from firstObservable TypeB, TypeC, TypeD, TypeE ]) => { this.myComposedObject.second = allResults[1]; this.myComposedObject.third = allResults[2]; // allResults[5] - response from `makeAnotherCall` .... }); ``` Upvotes: 0
2018/03/15
679
2,570
<issue_start>username_0: I'm currently migrating a project from Windows Phone 8.1 to UWP, and I'm having problems with a XAML line that doesn't rotate when renderTransform compositeTransform rotation in code, but happens in if change is made in XAML. In Windows Phone 8.1 it worked without any problem. Here's XAML part: ``` ``` This line is drawn **inside a Map Control**. And then changed in code (but veen I change Rotation value to 0 it doesn't rotate. Here's the C# code that should rotate the XAML line above: `lineMilestoneHelperAzimuth.Rotation = azimuth;` As you have seen, I've tried with RotateTransform also, but it didn't work. Any idea why it happens? Thank you<issue_comment>username_1: Like you said to make 5 parallel requests you can use `forkJoin`. Then you want to make another request when the previous 5 complete so you'll chain it with the `concatMap` operator (or `mergeMap` would work here as well). Then you need to work with all the results combined so you can use `map` to add the last result to the the same array as the previous five. ``` forkJoin( firstObservable, secondObservable, thirdObservable, ... ) .concatMap(firstFiveResults => makeAnotherCall(firstFiveResults[1]) .map(anotherResult => [...firstFiveResults, anotherResult]) ) .subscribe(allResults => { this.myComposedObject.second = allResults[1]; this.myComposedObject.third = allResults[2]; // allResults[5] - response from `makeAnotherCall` .... }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Thanks, that pointed me to the right direction. I had some problem with results types. When I tried to assign ``` this.myComposedObject.second = allResults[1]; ``` compiler complains about type conversion, so I'll report my solution here for other people. In order to get rid of this problem you take advantage of "destructuring" (more info here: <https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment>) ``` forkJoin( firstObservable, secondObservable, thirdObservable, ... ) .concatMap(firstFiveResults => makeAnotherCall(firstFiveResults[1]) .map(anotherResult => [...firstFiveResults, anotherResult]) ) .subscribe((allResults: [ TypeA, <-- type returned from firstObservable TypeB, TypeC, TypeD, TypeE ]) => { this.myComposedObject.second = allResults[1]; this.myComposedObject.third = allResults[2]; // allResults[5] - response from `makeAnotherCall` .... }); ``` Upvotes: 0
2018/03/15
575
1,905
<issue_start>username_0: I tried this command, but it works only to a certain extent. Input file content: ``` this is begin not sure what is wrong end and why not ``` Command: ``` cat file | sed 's/.*begin \(.*\)end/\1/' ``` Output: ``` not sure what is wrong and why not ``` Desired output (please see notes below): ``` not sure what is wrong ``` 1. My sed command searches for the first pattern and second pattern, but omits the second pattern and prints the text. However, it also prints the rest of the line, `why not`. I do not want to print what comes after the second pattern, only what is between the two patterns. I am not sure how to do this. 2. What if there are two `end` on the same line? Can someone provide and explain the command?<issue_comment>username_1: The problem is that you are only substituting what was matched, not the other text after `end`. Just add a `.*`: ``` txt='this is begin not sure what is wrong end and why not' sed 's/.*begin \(.*\)end.*/\1/' <<< "$txt" ``` Gives: ``` not sure what is wrong ``` Upvotes: 0 <issue_comment>username_2: Following `sed` may help you on same. ``` echo "this is begin not sure what is wrong end and why not" | sed 's/.*begin //;s/ end.*//' ``` Upvotes: 0 <issue_comment>username_3: For your current input you may use this `sed`: ``` sed 's/.*begin \(.*\) end.*/\1/' file ``` ``` not sure what is wrong ``` Difference is use of `.*` after `end` that matches text after last `end` and discards in substitution. --- However for your 2nd part if there are two `end` words, `sed` command won't work correctly as it will find last `end` due to **greedy matching** of `.*`. e.g if your input is: ``` this is begin not sure what is wrong end and why not end ``` Then following `awk` would work better: ``` awk -F 'begin | end' '{print $2}' file ``` ``` not sure what is wrong ``` Upvotes: 3 [selected_answer]
2018/03/15
1,109
2,949
<issue_start>username_0: I have dictionary in format `"site_mame": (side_id, frequency)`: ``` d=[{'fpdownload2.macromedia.com': (1, 88), 'laposte.net': (2, 23), 'www.laposte.net': (3, 119), 'www.google.com': (4, 5441), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}] ``` Is there a smart way to filter dictionary d by value so that I have only those positions, where frequency is less than 100? For example: ``` d=[{'fpdownload2.macromedia.com': (1, 88), 'laposte.net': (2, 23), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}] ``` I don't want to use loops, just looking for smart and efficient solution...<issue_comment>username_1: You can use a dictionary comprehension to do the filtering: ``` d = { 'fpdownload2.macromedia.com': (1, 88), 'laposte.net': (2, 23), 'www.laposte.net': (3, 119), 'www.google.com': (4, 5441), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88), } d_filtered = { k: v for k, v in d.items() if v[1] < 100 } ``` Upvotes: 1 <issue_comment>username_2: What you want is a dictionary comprehension. I'll show it with a different example: ``` d = {'spam': 120, 'eggs': 20, 'ham': 37, 'cheese': 101} d = {key: value for key, value in d.items() if value >= 100} ``` If you don't already understand list comprehensions, this probably looks like magic that you won't be able to maintain and debug, so I'll show you how to break it out into an explicit loop statement that you should be able to understand easily: ``` new_d = {} for key, value in d.items(): if value >= 100: new_d[key] = value ``` If you can't figure out how to turn that back into the comprehension, just use the statement version until you learn a bit more; it's a bit more verbose, but better to have code you can think through in your head. Your problem is slightly more complicated, because the values aren't just a number but a tuple of two numbers (so you want to filter on `value[1]`, not `value`). And because you have a list of one dict rather than just a dict (so you may need to do this for each dict in the list). And of course my filter test isn't the same as yours. But hopefully you can figure it out from here. Upvotes: 0 <issue_comment>username_3: You can use a dictionary comprehension with unpacking for a more Pythonic result: ``` d=[{'fpdownload2.macromedia.com': (1, 88), 'laposte.net': (2, 23), 'www.laposte.net': (3, 119), 'www.google.com': (4, 5441), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}] new_data = [{a:(b, c) for a, (b, c) in d[0].items() if c < 100}] ``` Output: ``` [{'laposte.net': (2, 23), 'fpdownload2.macromedia.com': (1, 88), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}] ``` Upvotes: 3 [selected_answer]
2018/03/15
517
1,650
<issue_start>username_0: I want to sum up `myArray` where i declared `var sumUpArray = 0`. It return the correct sum of `myArray` which is 6. ```js var myArray = [1, 2, 3]; var sumUpArray = 0; for (i = 0; i < myArray.length; i++) { sumUpArray = sumUpArray + myArray[i]; } console.log(sumUpArray); ``` But when I declared `var sumUpArray;` it return `NaN`. ```js var myArray = [1, 2, 3]; var sumUpArray; for (i = 0; i < myArray.length; i++) { sumUpArray = sumUpArray + myArray[i]; } console.log(sumUpArray); ``` What is the difference between the two declaration of variable?<issue_comment>username_1: Because when you use `var sumUpArray`, `sumUpArray` is `undefined`, not 0. `undefined` + any number will return `NaN`. Upvotes: 0 <issue_comment>username_2: In the first example you declared the variable but didn't assign any value, so it starts out as `undefined`. I think you maybe expected it to be auto-assigned to 0, which it does not. Then you tried to add some numbers to it, but `undefined + {anyNumber} = NaN`. Upvotes: 1 [selected_answer]<issue_comment>username_3: `var name;` is declared but not assigned or initialized or defined and hence is `undefined` however `var name=0;` is assigned a value '0'. typeof(name) will tell you that both are having different types. Upvotes: 0 <issue_comment>username_4: When you declare variable ``` var sumUpArray; ``` is the same as ``` var sumUpArray = undefined; ``` So you try add integer to undefined results NaN ``` sumUpArray = sumUpArray + myArray[i]; sumUpArray = undefined + myArray[i]; // NaN ``` BTW: use `let` and `const` to declare variables. Upvotes: 1
2018/03/15
573
1,811
<issue_start>username_0: I am receiving error: > > AppName won't run unless you update Google Play services. > > > Update > > > Emulator is not showing option for updating Google Play Services. --- Configurations -------------- **Emulator:** * Android 8.1 (Oreo) * Google APIs Intel x86 Atom System Image. **Following is installed:** * Build tools 27.0.3 * Android Emulator 27.2.0 * Google Play Services (Version 48) Android Studio 3.1 Canary 9 running on Ubuntu. Tried many solutions on this website but no success.<issue_comment>username_1: You Use That Emulator Which have Playstore Like this shown in Image. [![enter image description here](https://i.stack.imgur.com/T2hqt.png)](https://i.stack.imgur.com/T2hqt.png) Upvotes: 2 [selected_answer]<issue_comment>username_2: Now even better solution exist: using AVD image with build-in Google Play Services. It will enable you to use Google Services including Google Play. Also you will be able update it without re-creating AVD image. [![enter image description here](https://i.stack.imgur.com/uPHxd.jpg)](https://i.stack.imgur.com/uPHxd.jpg) For further information check this post <https://www.google.com.pk/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/14536595/how-to-download-google-play-services-in-an-android-emulator&ved=2ahUKEwjwz76G5u7ZAhUMCuwKHdVFAH4QFjADegQIBxAB&usg=AOvVaw1NNhhmar8bv8PoXT5o9B0q> Upvotes: 1 <issue_comment>username_3: You must have an Emulator with Google APIs included. Depending in the version of Google Play Services libraries used in your project you may require a higher API level emulator with Google API included. An emulator with Android 8.0 (API level 26) with Google API (Google Play) included should be enough. [Like this image](https://i.stack.imgur.com/OI6iJ.png) Upvotes: 0
2018/03/15
363
1,173
<issue_start>username_0: I'm using the following function to check whether the date is in the past, but I want to exclude today’s date from it as it returns true for today's date also. For example, if I pass today's date 2018-03-15, it returns true when it shouldn't. ``` function is_date_in_past($date):bool { return !empty($date) && (strtotime($date) < time()); } ``` Can anybody please help me with this, that how to exclude today's date from being recognised as past date? Thanks in advance.<issue_comment>username_1: Use [`DateTime`](http://php.net/manual/en/class.datetime.php) objects. They are easier to use than the old [date & time functions](http://php.net/manual/en/ref.datetime.php) and the code is more clear. ``` function is_date_in_past($date) { return new DateTime($date) < new DateTime("today"); } ``` Upvotes: 3 <issue_comment>username_2: If you'd like to use old date/time functions, you can do like that: ``` function is_date_in_past(string $date) :bool { return !empty($date) && strtotime($date) < strtotime(date('Y-m-d')); } ``` but better to consider to use <https://stackoverflow.com/a/49305230/9254020> variant Upvotes: 1
2018/03/15
733
2,933
<issue_start>username_0: I am not able to bind the request header values into a POJO class. Here is an explanation: I want to bind the value of "isKidsProfile" into "DetailCO" but it is not binding. On the other hand, it is working if I am binding it into a variable only. // consider header value in request is: key:isKidsProfile and value:true/false ``` @RequestMapping(value = "/api/v1/detail/{id}", method = RequestMethod.GET) public ResponseDTO fetchDetailForKidsProfileUser( @RequestHeader DetailCO detailCO, @RequestHeader boolean isKidsProfile) { sout(detailCO.isKidsProfile); // not bind in object sout(isKidsProfile); // bind in variable return new ResponseDTO(); } ``` class DetailCO { private boolean isKidsProfile; ``` //getters ans setters ``` } There are more values so it will be good to bind in POJO rather than creating multiple variables. Please suggest.<issue_comment>username_1: This is what I have used for my use case where I needed to parse all Parameters. You may use [RequestHeaderMethodArgumentResolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolver.html) if it's just the headers. *Create a configuration* ``` @Configuration public class IRSConfig implements WebMvcConfigurer { @Autowired private IRSArgumentResolver irsArgumentResolver; @Override public void addArgumentResolvers(List resolvers) { resolvers.add(irsArgumentResolver); } } ``` --- *Create POJO class for encapsulating your data and sending to RequestHandler* ``` public class MyRequestParams { private String first; private String second; public void setFirst(String first) { this.first = first; } public void setSecond(String second) { this.second = second; } public String getFirst() { return first; } public String getSecond() { return second; } } ``` --- *Create an argument resolver* ``` @Component public final class IRSArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterType().equals(MyRequestParams.class); } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { MyRequestParams requestParams = new MyRequestParams(); requestParams.setFirst(nativeWebRequest.getParameter("x-et-participant-id")); requestParams.setSecond(nativeWebRequest.getHeader("Authorization")); return requestParams; } } ``` Upvotes: 1 <issue_comment>username_2: You should be able to [register](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-config-conversion) a `Converter`. Upvotes: 0
2018/03/15
542
2,046
<issue_start>username_0: I used to use the "`execute_command`" found in the former awesome wiki. This command uses `io.popen` and the `lines` method to return the command's result. Now, the doc's advice is to avoid `io.popen`. My rc.lua uses `io.popen` to assign hostname's computer to a variable ordinateur (I'm trying to maintain a unique rc.lua for two quite different computers). I used to have this line : ordinateur=execute\_command( "hostname" ) I replace it with : ``` awful.spawn.easy_async_with_shell( "hostname" , function(stdout,stderr,reason,exit_code) ordinateur = stdout end) ``` Further in the script, I have tests like if ordinateur == "asus" then .... But it fails. Actually ordinateur is nil I think the rc.lua is read before ordinateur gets its assignment, right ? So, what can I do ? I'm thinking replace the command with the reading of the `/etc/hostname` file, is that better ? How am I going to do this with awful.spawn.\* commands ? Thank you David<issue_comment>username_1: If at all possible, use LuaSocket. ``` > socket = require "socket" > print(socket.dns.gethostname()) myhost ``` Another option is to run `hostname` from the script that launches the window manager, and store the result in an environment variable. Who knows, if you're lucky, it's already in there?! ``` > print(os.getenv("HOSTNAME") or os.getenv("HOST")) myhost ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: It fails later in the script because the command is asynchronous. This means it Awesome keeps going during the command execution and the result will be available later. This is the whole point of not using `io.popen`. `io.popen` will *stop* everything [related to X11, including all applications] on your computer while it is being executed. You need to modify your code so all things that access `ordinateur` do so *after* the callback has been called. The easiest way to do so is adding that code in the callback. Upvotes: 0
2018/03/15
1,466
4,942
<issue_start>username_0: I have a binary object that was generated on an SGI 64bit machine using a MIPSpro compiler. I am trying to read this binary object on a 64bit x86\_64 machine running RHEL 6.7. The structure of the object is something like like ``` class A { public: A(){ a_ = 1; } A(int a){ a_ = a; } virtual ~A(); protected: int a_; }; class B : public A { public: // Constructors, methods, etc B(double b, int a){ b_ = b; a_ = a; } virtual ~B(); private: double b_; }; A::~A(){} B::~B(){} ``` After reading the binary file, a swapping the bytes (due to the endianness) I find that `b` is correct but `a` is misaligned, indicating the data is misaligned with my current build. I have two question about this. Firstly, how does the MIPS Pro compiler align its fields and how is that different to the way `gcc` does it. I am interested in the case of inherited classes. Secondly, is there an option in `gcc` or C++ that can force the alignment to be the same as the way MIPS does it? **Update 1**: For additional clarification, the code was compiled on MIPS ABI n64. I have access to the original C++ source code but I can't change it on the MIPS machine. I am constrained to reading the binary on x86\_64. **Update 2**: I ran sizeof commands before and after adding a `virtual` destructor to both my classes on both machines. On MIPS and x86\_64, the output before the virtual directive was ``` size of class A: 4 size of class B: 16 ``` After adding the `virtual` method, on SGI MIPS the output is ``` size of class A: 8 size of class B: 16 ``` and on x86-64 Linux: ``` size of class A: 16 size of class B: 24 ``` Looks like the way virtual method (or is it just methods in general?) is processed on these machines is different. Any ideas why or how to get around this problem?<issue_comment>username_1: Reverse engineering: Write some different objects instances into several files. With a hexadecimal editor look for the differences. At least you get the positions in the binary file for each value. Finally, handle endianess. Upvotes: 1 <issue_comment>username_2: Hoping to make the binary layouts of the two structures match *with inheritance* ***and*** *having virtual methods* ***and*** *across different endianness* looks to me like a lost cause (and I don't even know how you managed to make `fwrite`/`fread` serialization work even on the same architecture - overwriting the vtable address is a recipe for disaster - even on "normal" architectures nothing guarantees you that they'll be located in the same address *even across multiple runs of the exact same binary*). Now, if this serialization format is already written in stone and you have to deal with it, I'd avoid completely the "match the binary layout" way; you are going to get mad and get a terribly fragile result. Instead, first find out the exact binary layout of the source data once for all; you can do it easily using [`offsetof`](http://en.cppreference.com/w/cpp/types/offsetof) over all members on the MIPS machine, or even just by printing the address of each member and computing the relevant differences. Now that you have the binary layout, write some architecture-independent deserialization code. Let's say you found out that you found out that `A` is made of: * 0x00: vptr (8 bytes); * 0x08: `a_` (4 bytes); * 0x0c: (padding) (4 bytes) and `B` is made of: * 0x00: vptr (8 bytes); * 0x08: `A::a_` (4 bytes); * 0x0c: (padding) (4 bytes); * 0x10: `b_` (8 bytes). then you'll write out code that deserializes *manually* each of these fields in a given structure. For example: ``` typedef unsigned char byte; uint32_t read_u32_be(const byte *buf) { return uint32_t(buf[0])<<24 | uint32_t(buf[1])<<16 | uint32_t(buf[2])<<8 | uint32_t(buf[3]); } int32_t read_i32_be(const byte *buf) { // assume 2's complement in unsigned -> signed conversion return read_u32_be(buf); } double read_f64_be(const byte *buf) { static_assert(sizeof(double)==8); double ret; std::reverse_copy(buf, buf+8, (byte*)&ret); return ret; } void read_A(const byte *buf, A& t) { t.a_ = read_i32_be(buf+8); } void read_B(const uint8_t *buf, B& t) { read_A(buf, t); t.b_ = read_f64_be(buf+0x10); } ``` Notice that this isn't wasted effort, as you'll soon need this code even for the MIPS version if you happen to change compiler, compilation settings or anything else that may affect the binary layout of your classes. BTW, the generation of this code can potentially be automated, as [it's all data that is available in the debug information](https://wiki.antiguru.de/doku.php/info/c_memory_structure); so, if you have many structures in this criminal serialization format you can semi-automatically generate the deserialization code (and move them to something saner for the future). Upvotes: 3
2018/03/15
983
3,376
<issue_start>username_0: I want to find and active inactive object: Main Menu. I try this code, but it isn't working. What am I doing wrong? ``` if (Input.GetKey(KeyCode.Escape)) { this.gameObject.SetActive(false); GameObject.Find("Main Menu").SetActive(true); } ```<issue_comment>username_1: Reverse engineering: Write some different objects instances into several files. With a hexadecimal editor look for the differences. At least you get the positions in the binary file for each value. Finally, handle endianess. Upvotes: 1 <issue_comment>username_2: Hoping to make the binary layouts of the two structures match *with inheritance* ***and*** *having virtual methods* ***and*** *across different endianness* looks to me like a lost cause (and I don't even know how you managed to make `fwrite`/`fread` serialization work even on the same architecture - overwriting the vtable address is a recipe for disaster - even on "normal" architectures nothing guarantees you that they'll be located in the same address *even across multiple runs of the exact same binary*). Now, if this serialization format is already written in stone and you have to deal with it, I'd avoid completely the "match the binary layout" way; you are going to get mad and get a terribly fragile result. Instead, first find out the exact binary layout of the source data once for all; you can do it easily using [`offsetof`](http://en.cppreference.com/w/cpp/types/offsetof) over all members on the MIPS machine, or even just by printing the address of each member and computing the relevant differences. Now that you have the binary layout, write some architecture-independent deserialization code. Let's say you found out that you found out that `A` is made of: * 0x00: vptr (8 bytes); * 0x08: `a_` (4 bytes); * 0x0c: (padding) (4 bytes) and `B` is made of: * 0x00: vptr (8 bytes); * 0x08: `A::a_` (4 bytes); * 0x0c: (padding) (4 bytes); * 0x10: `b_` (8 bytes). then you'll write out code that deserializes *manually* each of these fields in a given structure. For example: ``` typedef unsigned char byte; uint32_t read_u32_be(const byte *buf) { return uint32_t(buf[0])<<24 | uint32_t(buf[1])<<16 | uint32_t(buf[2])<<8 | uint32_t(buf[3]); } int32_t read_i32_be(const byte *buf) { // assume 2's complement in unsigned -> signed conversion return read_u32_be(buf); } double read_f64_be(const byte *buf) { static_assert(sizeof(double)==8); double ret; std::reverse_copy(buf, buf+8, (byte*)&ret); return ret; } void read_A(const byte *buf, A& t) { t.a_ = read_i32_be(buf+8); } void read_B(const uint8_t *buf, B& t) { read_A(buf, t); t.b_ = read_f64_be(buf+0x10); } ``` Notice that this isn't wasted effort, as you'll soon need this code even for the MIPS version if you happen to change compiler, compilation settings or anything else that may affect the binary layout of your classes. BTW, the generation of this code can potentially be automated, as [it's all data that is available in the debug information](https://wiki.antiguru.de/doku.php/info/c_memory_structure); so, if you have many structures in this criminal serialization format you can semi-automatically generate the deserialization code (and move them to something saner for the future). Upvotes: 3
2018/03/15
402
1,397
<issue_start>username_0: I put the spinner on the page and I see nothing at all. There are no console of errors or anything like that. Here is my code: ``` import React, { Component } from 'react'; import { Spin } from 'antd'; import './App.css'; class App extends Component { render() { return ( ); } } export default App; ```<issue_comment>username_1: I believe you have forgotten to import the CSS for AndD. ``` @import '~antd/dist/antd.css'; ``` <https://ant.design/docs/react/use-with-create-react-app> Upvotes: 2 <issue_comment>username_2: The accepted answer imports all of the library styles. Here's a preferred way to do so ``` import Spin from 'antd/es/spin'; import 'antd/es/spin/style/css'; ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: The proposed solution by @username_2 doesn't explain that why one should import the CSS at the component level. Probably this is the reason [Remove global Styles](https://github.com/ant-design/ant-design/issues/9363) But I would like to add that the proposed solution by @username_2 still doesn't work. Which is to import the component level CSS only like this ``` import 'antd/es/spin/style/css'; ``` The above CSS still continues adding some global styles and disturbs my styling. Instead importing the CSS with this method worked for me ``` import 'antd/lib/spin/style/index.css'; ``` Upvotes: 0
2018/03/15
813
2,492
<issue_start>username_0: I have a table storing Device details. For simplicity, the columns are: ``` Id (Primary Key) Name (varchar) StatusId (Foreign Key to Status table). ``` The Status table has two columns: ``` Id (Primary Key) State (varchar) ``` and two rows: ``` [Id | State] 1 | Active 2 | Inactive ``` I would like to allow multiple devices in the Devices table with the same Name, but only one of them can have status Active at any time. That is to say, this should be allowed in the Devices table: ``` [Id | Name | StatusId] 10 | Mobile001 | 1 11 | Mobile001 | 2 12 | Mobile001 | 2 20 | Tablet001 | 1 21 | Tablet002 | 2 22 | Tablet002 | 1 23 | Tablet003 | 2 ``` But this should not be allowed: ``` [Id | Name | StatusId] 10 | Mobile001 | 1 <-- wrong 11 | Mobile001 | 1 <-- wrong 12 | Mobile001 | 2 20 | Tablet001 | 1 21 | Tablet002 | 1 <-- wrong 22 | Tablet002 | 1 <-- wrong 23 | Tablet003 | 2 ``` Is there a way how to create a constraint in T-SQL to reject inserts and updates that violate this rule? And is there a way how to do it in EF code first using EntityTypeConfigurations and Fluent API, possibly via IndexAnnotation or IndexAttributes? Thanks.<issue_comment>username_1: One method, as @ZoharPeled just commented is using a filtered unique index. As you are only allowed one Active Device of a specific name, this can be implemented as below: ``` USE Sandbox; GO --Create sample table CREATE TABLE Device (ID int IDENTITY(1,1), [name] varchar(10), [StatusID] int); --Unique Filtered Index CREATE UNIQUE INDEX ActiveDevice ON Device ([name], [StatusID]) WHERE StatusID = 1; GO INSERT INTO Device ([name], StatusID) VALUES ('Mobile1', 1); --Works GO INSERT INTO Device ([name], StatusID) VALUES ('Mobile1', 0); --Works GO INSERT INTO Device ([name], StatusID) VALUES ('Mobile2', 1); --Works GO INSERT INTO Device ([name], StatusID) VALUES ('Mobile1', 1); --Fails GO UPDATE Device SET StatusID = 1 WHERE ID = 2; --Also fails GO SELECT * FROM Device; GO DROP TABLE Device; ``` Any questions, please do ask. Upvotes: 1 <issue_comment>username_2: In EF CF You could achieve it by setting an unique index like described in [this answer](https://stackoverflow.com/questions/22618237/how-to-create-index-in-entity-framework-6-2-with-code-first/47031294#47031294). ``` modelBuilder.Entity() .HasIndex(d => new { d.Name, d.StatusId }) .IsUnique(); ``` Upvotes: 0
2018/03/15
1,079
4,378
<issue_start>username_0: I have JPA entity Customer having say 50 fields and I would like to update it from the end user using html form. I am passing one instance of entity to html page form (using thymeleaf), this form is having only 20 fields out of 50 (including ID field). Now once the form is submitted, **I would like to update 20 fields from data received using form to the database. I am not getting solution for above issue. One solution is to update individual field but I don't think it is good solution.** ``` @Entity public class Customer { ... 50 fields } ``` My get method: ``` @GetMapping(value = "customer") public String customer(Model model) { Customer customer = null; Optional optional = customer Repo.findById(customerId); if (optional.isPresent()) { customer = optional.get(); } model.addAttribute("customer", Customer); return "customer"; } ``` Html form: ``` ----20 fields which I would like to get update from user are here @PostMapping(value = "updateCustomer") public String updateCustomer(Model model, @ModelAttribute Customer customer) { if(customer==null) { System.out.println("Customer object is null"); } else { customerRepo.save(customer); } return "savedCustomer"; } ``` In the post method when I get customer object it is having only 20 fields data not 50(Customer entity is having total fields) because html form is having only 20 fields for update. How to update the old customer object having 50 fields using the new customer object having updated 20 fields.?<issue_comment>username_1: There are three ways in the past that I solved this problem 1) have the page GET the Customer object in question, use the object to pre-populate the form, and then POST the changed customer object. The benefit is that the user changing the Customer sees all info related to the Customer, and you have a easy merge on the backend. The drawback is an additional REST call. 2) Create a DTO, and transfer non-null fields from the DTO to the entity. The benefit is you don't have to update all the fields in the form, and no extra network call. the drawback is that it's a pure pain in the rear end. 3) Create a DTO, and make it an entity to save. The benefit is that it's a easy merge back to the database, nothing prevents you from mapping the same table and fields to multiple entities. The drawback is that you have to worry about concurrency issues, which may just not work in your workflow, and the DTO is basically specific per form. Upvotes: 1 <issue_comment>username_2: To make partial updates to entity, you either need to use `Criteria` API or `JPQL` query ... this is called projection in JPA, [here is a quick example](https://www.objectdb.com/java/jpa/query/jpql/update) , Note : You might not be able to use this feature if you are using an old version of JPA query parser (no `JPQL` updates) + old version of JPA (when no `CriteriaUpdate` lib was there) you will then need to fetch the object from DB with the id passed from the client, update the 20 properties from the client and save the changes back Upvotes: 0 <issue_comment>username_3: Below solution worked for me: **Helper Class:** public class BeanCopy { ``` private static final Set> primitiveTypes = new HashSet>( Arrays.asList(Boolean.class, Character.class, Byte.class, Short.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class, String.class, Date.class)); public static void nullAwareBeanCopy(Object dest, Object source) throws IllegalAccessException, InvocationTargetException { new BeanUtilsBean() { @Override public void copyProperty(Object dest, String name, Object value) throws IllegalAccessException, InvocationTargetException { if(value != null && (primitiveTypes.contains(value.getClass()) )) { super.copyProperty(dest, name, value); } } }.copyProperties(dest, source); } ``` } This is how I copied and forced changes to database: ``` try { BeanCopy.nullAwareBeanCopy(DBcustomer,customer); customerRepo.save(DBcustomer); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } ``` **Please let me know any better solution is available for the above problem.** Upvotes: 1 [selected_answer]
2018/03/15
351
1,327
<issue_start>username_0: I am using Symfony 3.4. Suddenly, whenever I try to run my tests (phpunit) in /tests, I get the following error: ``` RuntimeException : Unable to guess the Kernel directory. ``` My test class looks something like: ``` class PaymentCreditTest extends KernelTestCase { /** @var PaymentRepository */ public $paymentRepository; /** * {@inheritDoc} */ protected function setUp() { $this->paymentRepository = self::bootKernel()->getContainer()->get('chaku.repository.payment'); } public function test_canRetrieveDeadFreightNetAmount() { /** @var Payment $payment */ $payment = $this->paymentRepository->findOneBy(['id' => 1000002]); // just to see payment object dump($payment); } } ``` This is what my phpunit.xml.dist looks like: ``` xml version="1.0" encoding="UTF-8"? tests src src/\*Bundle/Resources src/\*/\*Bundle/Resources src/\*/Bundle/\*Bundle/Resources ``` Any help with this will be well appreciated.<issue_comment>username_1: I think I had the exact same issue few weeks ago, can you try adding `KERNEL_DIR`: ``` ``` Upvotes: 2 <issue_comment>username_2: ./vendor/bin/simple-phpunit -c app/ add the Appkernel directory which is app while executing the command for testing. Upvotes: 0
2018/03/15
658
2,596
<issue_start>username_0: I would like to know how to gitignore files but only on local, without pushing it (because the other people working on the project should not get this update of gitignore of files I added there. To be simple, after a git status I only have : ``` modified: .gitignore ``` because I added my files to ignore to my gitignore but well now I want the line above gone without pushing it.<issue_comment>username_1: `.gitignore` file contains the list of files & folders that are to be prevented from getting committed/pushed to the remote repo. But, it is always acceptable to commit & push `.gitignore` file. And it is a very common practise. So, commit the `.gitignore` file and move ahead with your code. Read this [thread](https://stackoverflow.com/questions/5765645/should-you-commit-gitignore-into-the-git-repos) for reference/good practises about committing `.gitignore` file. Upvotes: 0 <issue_comment>username_2: Gitignore file should be committed because in most cases what you ignore would be ignored by other developers in the team too. But if you absolutely need to exclude it from being tracked for local changes, you could do the following: `git update-index --assume-unchanged .gitignore` This will make it "disappear" from the modified list. Though if someone else changes it, you will not get the changes on pulling. You'll then need to do the below to bring it back to tracked list and do a pull again: `git update-index --no-assume-unchanged .gitignore` Upvotes: 4 <issue_comment>username_3: For local ignores [you should use the `.git/info/exclude` file](https://git-scm.com/docs/gitignore#_description), not `.gitignore`: > > Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user’s workflow) should go into the `$GIT_DIR/info/exclude` file. > > > The two files accept the same format. Upvotes: 8 [selected_answer]<issue_comment>username_4: Another option in VSCode is to use [Git Exclude](https://marketplace.visualstudio.com/items?itemName=boukichi.git-exclude) extension which basically add any file/folder using right click to your .git/info/exclude file Upvotes: 2 <issue_comment>username_5: To exclude files without .gitignore ``` git update-index --assume-unchanged project/file.php ``` to remove file from exclude ``` git update-index --no-assume-unchanged project/file.php ``` this will help to ignore git file locally without adding it into .gitignore file Upvotes: -1
2018/03/15
676
2,579
<issue_start>username_0: `var intervalID = setInterval(funkey2, inter)();` In the Chrome console, I get this error: [![enter image description here](https://i.stack.imgur.com/QRiuj.jpg)](https://i.stack.imgur.com/QRiuj.jpg) but when I don't have line 24, the function never runs. The stop button doesn't work for some reason. I'm using `setInterval` for the first time so thanks for the help.<issue_comment>username_1: `.gitignore` file contains the list of files & folders that are to be prevented from getting committed/pushed to the remote repo. But, it is always acceptable to commit & push `.gitignore` file. And it is a very common practise. So, commit the `.gitignore` file and move ahead with your code. Read this [thread](https://stackoverflow.com/questions/5765645/should-you-commit-gitignore-into-the-git-repos) for reference/good practises about committing `.gitignore` file. Upvotes: 0 <issue_comment>username_2: Gitignore file should be committed because in most cases what you ignore would be ignored by other developers in the team too. But if you absolutely need to exclude it from being tracked for local changes, you could do the following: `git update-index --assume-unchanged .gitignore` This will make it "disappear" from the modified list. Though if someone else changes it, you will not get the changes on pulling. You'll then need to do the below to bring it back to tracked list and do a pull again: `git update-index --no-assume-unchanged .gitignore` Upvotes: 4 <issue_comment>username_3: For local ignores [you should use the `.git/info/exclude` file](https://git-scm.com/docs/gitignore#_description), not `.gitignore`: > > Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user’s workflow) should go into the `$GIT_DIR/info/exclude` file. > > > The two files accept the same format. Upvotes: 8 [selected_answer]<issue_comment>username_4: Another option in VSCode is to use [Git Exclude](https://marketplace.visualstudio.com/items?itemName=boukichi.git-exclude) extension which basically add any file/folder using right click to your .git/info/exclude file Upvotes: 2 <issue_comment>username_5: To exclude files without .gitignore ``` git update-index --assume-unchanged project/file.php ``` to remove file from exclude ``` git update-index --no-assume-unchanged project/file.php ``` this will help to ignore git file locally without adding it into .gitignore file Upvotes: -1
2018/03/15
1,012
3,313
<issue_start>username_0: **Scenario:** I have a table `Browsers` which is populated every time a browser is opened along with the associated date: ``` BrowserName Date ------------------------------------- Firefox? 8/20/2017 Firefox 8/20/2017 Google Chrome 8/20/2017 Google Chrome 8/20/2017 Google Chrome 8/20/2017 Opera 8/20/2017 Internet Explorer 8/20/2017 Internet Explorer 8/20/2017 ``` If I did a count as such: ``` SELECT COUNT (BrowserName) AS [Count Of Uses], BrowserName AS [Browser], Date FROM BROWSERS GROUP BY Date, BrowserName ``` I get a result something like this: ``` Count Of Uses Browser Date -------------------------------------------------- 1 Firefox? 8/20/2017 1 Firefox 8/20/2017 3 Google Chrome 8/20/2017 2 Internet Explorer 8/20/2017 1 Opera 8/20/2017 ``` **Question:** notice how there are two entries for `Firefox` (`Firefox` and `Firefox?`). How can I combine those into one count for `Firefox`, so that my end result would be like this: ``` Count Of Uses Browser Date -------------------------------------------------- 2 Firefox 8/20/2017 3 Google Chrome 8/20/2017 2 Internet Explorer 8/20/2017 1 Opera 8/20/2017 ``` Thanks.<issue_comment>username_1: You can use `case`: ``` SELECT Date, (CASE WHEN BrowserName LIKE 'Firefox%' THEN 'Firefox' ELSE BrowserName END) as Browser, COUNT(*) AS [Count Of Uses] FROM BROWSERS GROUP BY Date, (CASE WHEN BrowserName LIKE 'Firefox%' THEN 'Firefox' ELSE BrowserName END) ; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: If you only need to handle this particular case: ``` SELECT COUNT (*) AS [Count Of Uses], replace(BrowserName, 'FireFox?', 'Firefox') AS [Browser], Date FROM BROWSERS GROUP BY 2,3 ``` If you have multiple similar variations, nest `replace()` calls: ``` replace(replace(BrowserName, 'FireFox?', 'Firefox'), 'Internet Exploder', 'Internet Explorer') AS [Browser] ``` Upvotes: 2 <issue_comment>username_3: If you need to handle ? in general ``` declare @T table (browser varchar(40), dt date); insert into @T values ('Firefox?', '8/20/2017') , ('Firefox', '8/20/2017') , ('Google Chrome', '8/20/2017') , ('Google Chrome', '8/20/2017') , ('Google Chrome?', '8/20/2017') , ('Opera', '8/20/2017') , ('Internet Explorer', '8/20/2017') , ('Internet Explorer',' 8/20/2017') , ('Internet Explorer', '8/21/2017') , ('Internet Explorer',' 8/21/2017'); with cte as ( select t.dt, t.browser , SUBSTRING(REVERSE(t.browser),1,1) as f , case when SUBSTRING(reverse(t.browser), 1, 1) = '?' then substring(t.browser, 1, LEN(t.browser ) -1) else t.browser end as browserT from @T t ) select cte.dt as [date], cte.browserT as browswer, count(*) as [count] from cte group by cte.dt, cte.browserT order by cte.dt, cte.browserT; ``` Upvotes: 1
2018/03/15
799
2,868
<issue_start>username_0: I'm wondering how I can mock some private variable in a class with Groovy/Spock. Let's say we have this code: ``` public class Car { private Engine engine; public void drive(){ System.out.println("test"); if (engine.isState()) { // Do something } else { // Do something } } } ``` In Mockito I can write: ``` @Mock private Engine engine; @InjectMocks private Car car = new Car(); @Test public void drive() { when(engine.isState()).thenReturn(true); car.drive(); } ``` But I don't know how to do the same in Spock. What is the equivalent of `@InjectMocks` in Spock?<issue_comment>username_1: This is more a Groovy than a Spock question. In Groovy you can just call a constructor naming the private member and thus inject it. But this is ugly, you should rather refactor for testability via dependency injection as <NAME> already said. But for what it is worth, here is how you can (but shouldn't) do it: ```java package de.scrum_master.stackoverflow; public class Engine { private boolean state; public boolean isState() { return state; } } ``` ```java package de.scrum_master.stackoverflow; public class Car { private Engine engine; public void drive(){ System.out.println("driving"); if(engine.isState()) { System.out.println("true state"); } else { System.out.println("false state"); } } } ``` ```java package de.scrum_master.stackoverflow import spock.lang.Specification class CarTest extends Specification { def "Default engine state"() { given: def engine = Mock(Engine) def car = new Car(engine: engine) when: car.drive() then: true } def "Changed engine state"() { given: def engine = Mock(Engine) { isState() >> true } def car = new Car(engine: engine) when: car.drive() then: true } } ``` BTW, `then: true` is because your method returns `void` and I don't know which other things you want to check. The test is green and the console log looks like this: ```none driving false state driving true state ``` Upvotes: 2 <issue_comment>username_2: I'd suggest to put the `Engine` into the car when it is constructed: ``` public class Car { private final Engine engine; public Car(final Engine engine) { this.engine = engine } // ... } ``` Then you can just mock the engine like this using JUnit as in your example: ``` @Mock private Engine engine; private Car car = new Car(engine); @Test public void drive() { when(engine.isState()).thenReturn(true); car.drive(); } ``` Or using Spock: ``` private Engine engine = Mock(); private Car car = new Car(engine); def "test drive"() { given: engine.isState() >> true expect: car.drive(); } ``` Upvotes: 0
2018/03/15
684
2,300
<issue_start>username_0: I have a nginx-container with the following location and upstream configuration: ``` upstream jenkins-docker { server jenkins:8080 fail_timeout=0; } # configuration file /etc/nginx/conf-files/jenkins-location.conf: location /jenkins/ { sendfile off; proxy_pass http://jenkins-docker; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_max_temp_file_size 0; #this is the maximum upload size client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_request_buffering off; # Required for HTTP CLI commands in Jenkins > 2.54 } ``` Jenkins is in a docker container aswell. They are both connected to a docker bridge network. Inside nginx-container I can do: curl jenkins:8080: ``` window.location.replace('/login?from=%2F'); Authentication required ``` nginx can communicate with jenkins. In jenkins->manage Jenkins -> Configure System under "Jenkins Location" I changed the "Jenkins URL" to <http://myIP/jenkins> When I type into my Browser myIp/jenkins it get redirect to <http://myIp/login?from=%2Fjenkins%2F> which results in a 404 When I change the location in nginx "location /jenkins/ {" just to "/" it works like a charm. Thats why I tried it with a rewrite: ``` rewrite ^/jenkins(.*) /$1 break; ``` When I do this I can access the jenkins dashboar with myIp/jenkis. But when I click on a menu item I get a 404<issue_comment>username_1: You also need to set the `--prefix` command on your jenkins installation. You can do this in the `jenkins.xml` config file or by altering your command line arguments to include `--prefix=/jenkins`. The arguments can be seen at <https://wiki.jenkins.io/display/JENKINS/Starting+and+Accessing+Jenkins> Upvotes: 3 [selected_answer]<issue_comment>username_2: set an enviroment variable like this: `JENKINS_OPTS="--prefix=/jenkins"`. If you are using docker-compose, something like this: ``` environment: - JENKINS_OPTS="--prefix=/jenkins" ``` Upvotes: 2
2018/03/15
1,053
3,735
<issue_start>username_0: I've seen lots of questions/answers regarding detecting if an HTML element is scrollable (e.g. [Detect scrollbar dynamically](https://stackoverflow.com/questions/33805052/detect-scrollbar-dynamically) ). I need something similar, but not quite the same. I have a div set to `overflow-y: scroll;`. On a desktop browser it shows the vertical scrollbar; that's fine. On an iPad, there is no vertical scrollbar; but you can scroll it by touch. The *problem* I'm having is that it's not always *visually obvious* on an iPad that the div can be scrolled. The Div simply contains a list; and sometimes my users think they're seeing the entire list and don't realize there's more if they scroll. I'm thinking that if I can somehow detect if there is a **visible scrollbar** -- not simply if it's scrollable or not -- I can add a background image or similar visual cue for the mobile users who don't have the scrollbar. But I don't want a redundant cue if there's already a scrollbar. I'm open either to JavaScript/PHP solutions to detect the scrollbar, or other ways (CSS?) to "cue" the fact that a section can be scrolled. Any ideas?<issue_comment>username_1: JS solution: Compare the height (offsetHeight or clientHeight) of the element wrapping the content and the list itself -- then execute code accordingly. If you want to detect a scrollbar, this stackoverflow answer may help: [Hide scroll bar, but while still being able to scroll](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-while-still-being-able-to-scroll#answer-16671476) Where you can do `Element.offsetWidth - Element.clientWidth` to get a scrollbar's width (it should return 0 if there is no scrollbar). This Stack Overflow answer goes into detail about offset vs. client: [What is offsetHeight, clientHeight, scrollHeight?](https://stackoverflow.com/questions/22675126/what-is-offsetheight-clientheight-scrollheight#answer-22675563) ```js const listWrapper = document.getElementById('list-wrapper'), container = document.getElementById('container'), list = document.getElementById('list'); // compare the height of the target element ( listWrapper or list ) // against the element containing the element ( container ) if( list.offsetHeight > container.offsetHeight ){ // if the list is longer, add a class to the containing element container.className = 'overflowed'; } console.log( container.offsetHeight - container.clientHeight ); console.log( listWrapper.offsetHeight - listWrapper.clientHeight ); ``` ```css #container{ height: 150px; width: 150px; overflow-y: scroll; border: solid 1px red; } #container.overflowed{ background: linear-gradient(transparent 85%, rgba(0,0,0,0.25) ); } ``` ```html * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde ``` Upvotes: 2 <issue_comment>username_2: Based on username_1's hint about comparing offsetWidths, here's a working solution I came up with. Elements with the `vscroll` class are styled `overflow-y: scroll;`. ``` $(document).ready(function () { var scrollables = document.getElementsByClassName('vscroll'); if( scrollables.length && 0 === scrollables[0].offsetWidth - scrollables[0].clientWidth ) { for ( const scrollable of scrollables ) { scrollable.style.background = 'url("/images/updnarrows_75.png") no-repeat 60% 50%'; } } }); ``` The image is a set of faded up/down arrows that appear centered in the background of the div. Upvotes: 1 [selected_answer]
2018/03/15
993
3,425
<issue_start>username_0: I have been following the [official documentation](https://www.zetetic.net/sqlcipher/sqlcipher-for-android/) in order to start using SQLCipher Community Edition in the apps I´m developing. So, I made a proper gradle import as following: ``` compile 'net.zetetic:android-database-sqlcipher:3.5.9@aar' ``` I added the ``` @Override public void onCreate() { super.onCreate(); SQLiteDatabase.loadLibs(this); } ``` in the MainApplication.java. As my apps are already released, I have placed as well some migration code in onUpgrade() method in my instance of SQLiteOpenHelper class. Unfortunately, although I upgraded the DB version number, I do the call: `getInstance().getReadableDatabase("testKey");` neither onUpgrade(), nor onCreate() methods won´t be called. Did I miss something in the configuration?<issue_comment>username_1: JS solution: Compare the height (offsetHeight or clientHeight) of the element wrapping the content and the list itself -- then execute code accordingly. If you want to detect a scrollbar, this stackoverflow answer may help: [Hide scroll bar, but while still being able to scroll](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-while-still-being-able-to-scroll#answer-16671476) Where you can do `Element.offsetWidth - Element.clientWidth` to get a scrollbar's width (it should return 0 if there is no scrollbar). This Stack Overflow answer goes into detail about offset vs. client: [What is offsetHeight, clientHeight, scrollHeight?](https://stackoverflow.com/questions/22675126/what-is-offsetheight-clientheight-scrollheight#answer-22675563) ```js const listWrapper = document.getElementById('list-wrapper'), container = document.getElementById('container'), list = document.getElementById('list'); // compare the height of the target element ( listWrapper or list ) // against the element containing the element ( container ) if( list.offsetHeight > container.offsetHeight ){ // if the list is longer, add a class to the containing element container.className = 'overflowed'; } console.log( container.offsetHeight - container.clientHeight ); console.log( listWrapper.offsetHeight - listWrapper.clientHeight ); ``` ```css #container{ height: 150px; width: 150px; overflow-y: scroll; border: solid 1px red; } #container.overflowed{ background: linear-gradient(transparent 85%, rgba(0,0,0,0.25) ); } ``` ```html * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde * abcde ``` Upvotes: 2 <issue_comment>username_2: Based on username_1's hint about comparing offsetWidths, here's a working solution I came up with. Elements with the `vscroll` class are styled `overflow-y: scroll;`. ``` $(document).ready(function () { var scrollables = document.getElementsByClassName('vscroll'); if( scrollables.length && 0 === scrollables[0].offsetWidth - scrollables[0].clientWidth ) { for ( const scrollable of scrollables ) { scrollable.style.background = 'url("/images/updnarrows_75.png") no-repeat 60% 50%'; } } }); ``` The image is a set of faded up/down arrows that appear centered in the background of the div. Upvotes: 1 [selected_answer]
2018/03/15
692
2,140
<issue_start>username_0: I have an array, say `["a","b","c"]`, and I want to turn this into an object which has the array values as keys and a default value that I can set. So if the default value is `true`, I'd like my output to be `{a:true, b:true, c:true}`. Is there a more concise version of the code below to achieve this? ``` var myObject = {}; ["a","b","c"].forEach(x => myObject[x] = true); ``` I feel like there's a succinct Lodash or ES6 way to do this but I can't think of it.<issue_comment>username_1: Standard with [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) and [`Array#map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) ```js var array = ["a", "b", "c"], object = Object.assign(...array.map(k => ({ [k]: true }))); console.log(object); ``` Or with lodash and [`_.set`](https://lodash.com/docs/#set) ```js var array = ["a", "b", "c"], object = array.reduce((o, k) => _.set(o, k, true), {}); console.log(object); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` var myarray = ["a", "b", "c"]; var result = myarray.reduce((obj, item) => { obj[item] = true; return obj; }, {}); ``` Arguably no more concise than your version though. Upvotes: 1 <issue_comment>username_3: You can use [`_.zipObjects()`](https://lodash.com/docs/4.17.5#zipObject) with the array of keys, and a 2nd array you [fill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) with the default value: ```js const keys = ["a","b","c"]; const object = _.zipObject(keys, [...keys].fill(true)); console.log(object); ``` Upvotes: 0 <issue_comment>username_4: Here's a function I created which can help you with this problem: ```js function arrToObj(arr, defaultVal) { let newObj = {}; Object.keys(arr).forEach((item) => { newObj = { ...newObj, [item]: defaultVal }; }); return newObj; } ``` So now if you pass `arr=['a','b',c']` and `defaultVal=true` to this function You will get `{'a':true, 'b':true, 'c':true}` Upvotes: 0
2018/03/15
1,042
3,193
<issue_start>username_0: [Current vs Desired](https://i.stack.imgur.com/yAqFM.png) Currently this input field is created by giving the label a white background but its conflicting when the input field is on different colored backgrounds. Is there any way to have the border length to no longer need a background color. <https://codepen.io/ehaliseda/pen/OvJOVG?editors=1100> ``` Email .md-form.form-sm input { font-size: 1rem; } .md-form, .md-form .btn { margin-bottom: 0.8rem; margin-top: -17px; } .bg-input{ background-color: white !important; border: 1px solid #bdbdbd !important; border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-bottom-color: #4285f4; } input[type=text]:focus:not([readonly]){ box-shadow: 0px 2px 0px 0px #4285f4; } label{ margin-left: 12px; padding-left: 5px; padding-right: 5px; border-top-right-radius: 2px; border-top-left-radius: 2px; z-index: 5; position: relative; background-color: white; } .md-form input::-webkit-input-placeholder{ opacity: 0; } .md-form input:focus::-webkit-input-placeholder{ opacity: 1; color: #bdbdbd; } .input-wrapper{ height: auto; margin-bottom: 1.5rem; } input[type=text]{ color: #626262; } input[type=text]:focus{ color: #626262; } #bg-red{ background-color:red; padding:20px; } ```<issue_comment>username_1: Standard with [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) and [`Array#map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) ```js var array = ["a", "b", "c"], object = Object.assign(...array.map(k => ({ [k]: true }))); console.log(object); ``` Or with lodash and [`_.set`](https://lodash.com/docs/#set) ```js var array = ["a", "b", "c"], object = array.reduce((o, k) => _.set(o, k, true), {}); console.log(object); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` var myarray = ["a", "b", "c"]; var result = myarray.reduce((obj, item) => { obj[item] = true; return obj; }, {}); ``` Arguably no more concise than your version though. Upvotes: 1 <issue_comment>username_3: You can use [`_.zipObjects()`](https://lodash.com/docs/4.17.5#zipObject) with the array of keys, and a 2nd array you [fill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) with the default value: ```js const keys = ["a","b","c"]; const object = _.zipObject(keys, [...keys].fill(true)); console.log(object); ``` Upvotes: 0 <issue_comment>username_4: Here's a function I created which can help you with this problem: ```js function arrToObj(arr, defaultVal) { let newObj = {}; Object.keys(arr).forEach((item) => { newObj = { ...newObj, [item]: defaultVal }; }); return newObj; } ``` So now if you pass `arr=['a','b',c']` and `defaultVal=true` to this function You will get `{'a':true, 'b':true, 'c':true}` Upvotes: 0
2018/03/15
325
1,418
<issue_start>username_0: I'm trying to implement spring security and the default login page is being displayed even though i have login page with url defined in controller as "/login" Spring boot version : 2.0 Spring version: 5.0 Have two classes one for spring MVC config and another for Spring Web Config Please let me know.<issue_comment>username_1: You need to change the configure method within your spring security like the following: ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp"); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can direct to jsp directly or to a controller managed url In the configuration class:- ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp"); } ``` Or like this:- ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login"); } ``` And creating a url **`/login`** in your **`@Controller`** class Upvotes: 0
2018/03/15
323
1,443
<issue_start>username_0: i would like to know how to get the last X and Y coordinate value of the ACTION\_UP motion event, since this motion event returns the last release point as well as any intermediate points since the last down event. I would like to uniquely store the last X and Y coordinates (the last x and y before the user releases his finger)<issue_comment>username_1: You need to change the configure method within your spring security like the following: ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp"); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can direct to jsp directly or to a controller managed url In the configuration class:- ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp"); } ``` Or like this:- ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login"); } ``` And creating a url **`/login`** in your **`@Controller`** class Upvotes: 0
2018/03/15
344
1,500
<issue_start>username_0: i am having spring application with angular JS UI.in my application, i am returning pojo object as JSON to the UI. when returning to UI, pojo fields first letter will be changed to Upper case.For example, parameter "name" is changed to "Name" in json object.But its expecting "name".Due to this we are not able to map the fields in UI component.Could you please help me to resolve this.<issue_comment>username_1: You need to change the configure method within your spring security like the following: ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp"); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can direct to jsp directly or to a controller managed url In the configuration class:- ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp"); } ``` Or like this:- ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login"); } ``` And creating a url **`/login`** in your **`@Controller`** class Upvotes: 0
2018/03/15
1,747
5,152
<issue_start>username_0: I have a csv file and want to import part of it into my Mysql database. From [this question](https://stackoverflow.com/questions/6605765/importing-a-csv-into-mysql-via-command-line), I tried this command in my Mysql command line ``` load data local infile 'mycsv.csv’ into table mytable fields terminated by ',' enclosed by '"' lines terminated by '\n' (entity_ticker,harvested_at, entity_sector,entity_competitors,story_type,story_source,event,entity_sentiment,event_sentiment,event_relevance,entity_relevance,entity_industry) ``` Those in bracket is the columns I want to put in my table. The order is same to my table but not same to csv file. And the mysql didn't do anything like this: ``` mysql> load data local infile '2013first1000.csv’ into table news_dataset fields terminated by ',' enclosed by '"' lines terminated by '\n' (entity_ticker,harvested_at, entity_sector,entity_competitors,story_type,story_source,event,entity_sentiment,event_sentiment,event_relevance,entity_relevance,entity_industry) "> "> "> "> ``` This is the first two row of my file opened in txt: > > signal\_id,story\_id,story\_group\_id,new\_story\_group,story\_group\_count,source\_id,author\_id,story\_type,story\_source,templated\_story\_score,story\_traffic,story\_group\_traffic\_sum,story\_group\_exposure,entity\_sentiment,event\_sentiment,story\_sentiment,story\_group\_sentiment\_avg,story\_group\_sentiment\_stdev,entity\_name,entity\_ticker,entity\_exchange,entity\_relevance,entity\_country,entity\_indices,entity\_industry,entity\_region,entity\_sector,entity\_competitors,entity\_type,entity\_composite\_figi,entity\_exch\_code,entity\_figi,entity\_market\_sector,entity\_security\_description,entity\_security\_type,entity\_share\_class\_figi,entity\_unique\_id,entity\_unique\_id\_fut\_opt,entity\_author\_republish\_score,entity\_author\_timeliness\_score,entity\_source\_republish\_score,entity\_source\_timeliness\_score,event,event\_group,event\_relevance,event\_author\_republish\_score,event\_author\_timeliness\_score,event\_source\_republish\_score,event\_source\_timeliness\_score,event\_impact\_pct\_change\_avg,event\_impact\_pct\_change\_stdev,event\_impact\_pos,event\_impact\_neg,event\_impact\_gt\_mu\_add\_sigma,event\_impact\_lt\_mu\_sub\_sigma,event\_impact\_gt\_mu\_pos\_add\_sigma\_pos,event\_impact\_lt\_mu\_neg\_sub\_sigma\_neg,event\_impact\_gt\_mu\_pos\_add\_2sigma\_pos,event\_impact\_lt\_mu\_neg\_sub\_2sigma\_neg,event\_impact\_gt\_1pct\_pos,event\_impact\_lt\_1pct\_neg,overall\_source\_timeliness\_score,overall\_source\_republish\_score,overall\_author\_republish\_score,overall\_author\_timeliness\_score,harvested\_at > 5a431613914455535dd2f7e3,59a8c0cb631131661f7cca72,629355b4-5ef4-45ab-872a-9fd1809ca49d,f,552,hW9kPL6pMO0suREcwfIObD7SjwY=,A/mu8VqEc7agwge3hbjXgdFfDeA=,news,broadcastengineering.com,,11548,308325207322,high,31.2,33.35,31.2,36.9,38.9,Sony > Corp Ord,SNE,NYSE,100,N/A,[],Consumer > Electronics/Appliances,N/A,Consumer > Non-Durables,"[""MSFT"",""IBM"",""INTC"",""4331"",""NOKIA"",""HPQ"",""DIS"",""MSI"",""AAPL"",""PHG""]",US\_EQUITY,BBG000BT7ZK6,UN,BBG000BT81N7,Equity,SNE,ADR,BBG001S5W6H8,EQ0010136500009000,,0,70.2,0.9566,40.4852,Employment > Actions - General,Employment > Actions,50.8,,,0,32.5118,,,,,,,,,,,,,53.7511,0.53,0,64.2908,2013-08-01T00:00:03.000Z > > > Could you tell me how to do this?<issue_comment>username_1: 1) 'The order is same to my table but not same to csv file.'-Make the order same then whats the purpose of using csv import? use this- ``` load data local infile 'mycsv.csv' into table mytable fields terminated by ',' enclosed by ' ' lines terminated by '\n' ``` 2) still want to ignore columns- From Mysql docs: You can also discard an input value by assigning it to a user variable and not assigning the variable to a table column: ``` LOAD DATA INFILE 'file.txt' INTO TABLE t1 (column1, @dummy, column2, @dummy, column3); ``` 3)to skip first row- use Ignore 1 lines Upvotes: 3 [selected_answer]<issue_comment>username_2: From the [documentation](https://dev.mysql.com/doc/refman/5.7/en/load-data.html) > > You must also specify a column list if the order of the fields in the > input file differs from the order of the columns in the table. > Otherwise, MySQL cannot tell how to match input fields with table > columns. > > > In other words, your column list must match the order in the CSV file for this to work. To ignore columns within the csv you would assign them to a variable in your column list and then not do any further processing on them. If your csv has 4 columns and you only want the first and third columns the column list would look like `(first_col, @dummy, third_col, @dummy)` In your case, you can copy the header line and change any column name you don't want into the word @dummy. You'll also be wanting to add `IGNORE 1 LINES` directly before your column list so that you can skip over the first row with the column names. Upvotes: 1 <issue_comment>username_3: Some times you may need to use 'COLUMNS TERMINATED BY' instead 'FIELDS TERMINATED BY' Upvotes: 0
2018/03/15
613
1,200
<issue_start>username_0: I have a df like ``` ind1.id ind2.id group wang 02_1 02_1 1205 -0.2999 02_1 02_11 1205 -0.1688 02_1 02_12 1205 -0.0873 02_1 02_13 1205 -0.0443 02_1 02_14 1205 -0.1415 ``` and I would like to split the group column so that it is like this ``` ind1.id ind2.id group1 group2 wang 02_1 02_1 12 05 -0.2999 02_1 02_11 12 05 -0.1688 02_1 02_12 12 05 -0.0873 02_1 02_13 12 05 -0.0443 02_1 02_14 12 05 -0.1415 ``` I've messed around with strsplit and stuff but haven't managed to get every far. Thanks.<issue_comment>username_1: try: ``` library(tidyverse) df %>% as_tibble() %>% separate(group, c("group1", "group2"), sep = "0") ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Similar, cut after first two digits. ``` df %>% separate(group,c("group1","group2"),sep = "(?<=^\\d\\d)",remove=T) ``` Result: ``` ind1.id ind2.id group1 group2 wang 1: 02_1 02_1 12 05 -0.2999 2: 02_1 02_11 12 05 -0.1688 3: 02_1 02_12 12 05 -0.0873 4: 02_1 02_13 12 05 -0.0443 5: 02_1 02_14 12 05 -0.1415 ``` Upvotes: 0
2018/03/15
1,105
3,525
<issue_start>username_0: I'm currently trying to write an Oracle query which gets the number of allocation, per hour, per user. I've come up with the following, which does just this. ``` SELECT DISTINCT USER_CODE, TO_CHAR(TAUDIT.ENTERED, 'HH24') Hour, COUNT(TO_CHAR(TAUDIT.ENTERED, 'HH24')) OVER (PARTITION BY TO_CHAR(TAUDIT.ENTERED, 'HH24'), USER_CODE ORDER BY TO_CHAR(TAUDIT.ENTERED, 'HH24')) Allo_Count FROM TAUDIT WHERE TAUDIT.ACTION LIKE 'Job Allocated event: All%' AND TO_CHAR(TAUDIT.ENTERED, 'DD.MM.YY') = TO_CHAR(( SYSDATE - INTERVAL '1' day), 'DD.MM.YY') ``` This produces a list in the following format: ``` User_Code Hour Allo_Count --------- ---- ---------- CE 09 1 TB 09 3 CE 10 1 TB 10 4 ``` What I'm now trying to achieve is a the ability to rank the result by Allo\_Count, so that I can then select only the highest count for each hour. As I have little experience with oracle, I've been going over countless posts as well as the Oracle online documentation to try to understand and work this out, however I don't seem to be able to get around the issue of using the COUNT() within the order by ranking. I added in the following line, to the query to try and get the RANK in the output ``` Rank() OVER (Partition by TO_CHAR(TAUDIT.ENTERED, 'HH24') Order by COUNT(TO_CHAR(TAUDIT.ENTERED, 'HH24'))DESC) as 'Allo_Rank' ``` However this gives me a "Not a single-group group function" error, so clearly this isn't the way. From articles and posts I've read I'm pretty sure once I've ironed this out, I can surround the query with ``` SELECT * FROM (QUERY) WHERE Allo_Rank = 1 ``` But it's just getting over this hurdle in the first place. Any advice or tips on how to finish this query are appreciated, because right now, my head is fried!<issue_comment>username_1: Why are you using `select distinct`? Use `group by`. And don't do date comparisons using strings. So, this appears to be what you want: ``` SELECT USER_CODE, TO_CHAR(t.ENTERED, 'HH24') Hour, COUNT(*) as Allo_Count FROM TAUDIT t WHERE t.ACTION LIKE 'Job Allocated event: All%' AND TRUNC(t.ENTERED) = TRUNC(SYSDATE - INTERVAL '1' day) GROUP BY USER_CODE, TO_CHAR(t.ENTERED, 'HH24'); ``` For the ranking: ``` SELECT USER_CODE, TO_CHAR(t.ENTERED, 'HH24') as Hour, COUNT(*) as Allo_Count, RANK() OVER (PARTITION BY TO_CHAR(t.ENTERED, 'HH24') ORDER BY COUNT(*)) as ranking FROM TAUDIT t WHERE t.ACTION LIKE 'Job Allocated event: All%' AND TRUNC(t.ENTERED) = TRUNC(SYSDATE - INTERVAL '1' day) GROUP BY USER_CODE, TO_CHAR(t.ENTERED, 'HH24'); ``` Upvotes: 1 <issue_comment>username_2: Based on Gordon's answer, I've solved the issue including "Partition By" in the query. Below is the updated query: ``` SELECT USER_CODE, TO_CHAR(t.ENTERED, 'HH24') Hour, COUNT(*) as Allo_Count, RANK() OVER (PARTITION BY TO_CHAR(t.ENTERED, 'HH24') ORDER BY COUNT(*)) as ranking FROM TAUDIT t WHERE t.ACTION LIKE 'Job Allocated event: All%' AND TRUNC(t.ENTERED) = TRUNC(SYSDATE - INTERVAL '1' day) GROUP BY USER_CODE, TO_CHAR(t.ENTERED, 'HH24') ``` Which provides the following result set ``` User Hour Count Ranking ---- ---- ----- ------- CE 07 1 1 TB 09 1 1 CE 09 3 2 TB 10 1 1 CE 10 4 2 ``` Hopefully that's the right way to go about it, but please feel free to let me know if not Upvotes: 1 [selected_answer]
2018/03/15
806
3,371
<issue_start>username_0: I'm working with a BLE device which I need to verify. The BLE code I'm using is below ``` //Pragma Bluetooth Methods func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn { central.scanForPeripherals(withServices: nil, options: nil) } else { print("Bluetooth not available.") } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){ if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String { if peripheralName == "test-device1" { self.manager.stopScan() self.peripheral = peripheral self.peripheral.delegate = self self.manager.connect(peripheral, options: nil) } } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { peripheral.discoverServices(nil) } private func peripheral(peripheral: CBPeripheral, didDiscoverServices error: Error?) { for service in peripheral.services! { let thisService = service as CBService if service.uuid == SERVICE_UUID { peripheral.discoverCharacteristics( nil, for: thisService ) } } } ``` The process follows the anticipated route by passing through didDiscover and verifying the name as 'test-device1'. However, although it goes through the didConnect method and runs peripheral.discoverServices(nil) it never reaches the didDiscoverServices method. I've stepped through it several times and it always stops at didConnect(). What am I missing?<issue_comment>username_1: Method from the [doc](https://developer.apple.com/documentation/corebluetooth/cbperipheraldelegate/1518744-peripheral): ``` func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) ``` Yours: ``` func peripheral(peripheral: CBPeripheral, didDiscoverServices error: Error?) ``` Erase it and rewrite it letting XCode autocompletion helps you, copy/paste it from the doc, or just add a `_` that is missing. The method is optional, internally CoreBluetooth framework check if the delegates responds to the selector (`respondsToSelector()`) and the selector includes that "\_" which yours doesn't have. So it won't match and it won't call it because it's not the same. Upvotes: 2 [selected_answer]<issue_comment>username_2: if this is not working func peripheral(\_ peripheral: CBPeripheral, didDiscoverServices error: Error?) then first try to scan BLE device using BLE Scanner iOS, if in that app it shows the services then the issue in your code otherwise if BLE Scanner shows 0 service then the issue is inside the Peripheral device, or you can check the services by using print(peripheral.services) after connecting to peripheral if it print nil then discoverServices not called, other wise it call. or you can restart your iPhone sometime data stored into cache. Upvotes: 0 <issue_comment>username_3: I hit the same. Eventually learned that you have to set the delegate to self before making the call to discover services. Code as follows. ```swift peripheral.delegate = self peripheral.discoverServices(nil) ``` It has been 4 years since this question, hopefully becomes useful to someone. Upvotes: 1
2018/03/15
447
1,393
<issue_start>username_0: Currently getting this everytime I run my Pipeline: `Permission denied (publickey).` Steps so far: On Mac: * cd ~/.ssh * ssh-keygen -t rsa -N '' -f my\_ssh\_key * base64 < my\_ssh\_key * ssh-copy-id -i my\_ssh\_key.pub root@xxx.xxx.xxx.xxx * cd /my/repo/path * ssh-keyscan -t rsa server.domain.com > my\_known\_hosts On BitBucket > > Repo >> Settings >> SSH Key >> Use my own > > > * Pasted result of base64 < my\_ssh\_key into Private * Pasted my\_ssh\_key.pub into Public. Run Pipeline > > * ssh root@xxx.xxx.xxx.xxx ls -l /var/www > > > Permission denied (publickey). > > > **pipeline.yml** ``` image: node:6.9.4 pipelines: default: - step: caches: - node script: - ssh root@xxx.xxx.xxx.xxx ls -l /var/www ```<issue_comment>username_1: You may have just left it off the list of things you've done, but it looks like you haven't told Digital Ocean to authorize that public key for that user. Sign onto the DO droplet, copy the .pub file you've uploaded into ~/.ssh/authorized\_keys, and try again. Upvotes: 1 <issue_comment>username_2: Adding your system public SSH key to `~/.ssh/authorized_keys` tells your Digital ocean droplet to authorize your local machine to get acess. You also need to add your SSH key on your Digital Ocean Account. Go to: **Accounts > Security > Add SSH Keys** Upvotes: 2
2018/03/15
875
3,131
<issue_start>username_0: Currently i am fetching memory issue because i am loading direct image in Flatlist of React Native. Issue is that due to high resolutions images memory limit reached and app get crashed on iPhone. Is there any way i can fetch direct thumb url like image url (e.g. url: 'assets-library://asset/asset.JPG?id=5BECA80C-33B3-46A0-AE44-CF28A838CECF&ext=JPG',) ? Currently i am using 'React-native-photo-framework'.<issue_comment>username_1: `getAssets` takes a `prepareForSizeDisplay` prop. This uses `PHCachingImageManager` to request images of assets at a specified size. Example: ``` RNPhotosFramework.getAssets({ startIndex: 0, endIndex: 100, prepareForSizeDisplay: Rect(100,100), fetchOptions: { sourceTypes: ['userLibrary'], sortDescriptors: [{ key: 'creationDate', ascending: true, }] } }).then((response) => console.log(response.assets)); ``` When the user taps the row in your `FlatList`, you can then fetch the full-size asset. Don't fetch the full-size asset until you need to display it. Upvotes: 1 <issue_comment>username_2: Finally i have my own solution for this question. I have tried all ways to resolve but i am not able to resolve it. Lastly i come to know that new Photo Library provide options to fetch resized image but thats what not working with [react-native-photos-framework](https://github.com/olofd/react-native-photos-framework). My native experience will help me to resolve my issue, hope this will help you. [Here](https://www.logisticinfotech.com/blog/react-native-import-resized-image-photo-gallery) is link with detail description and code. Let me add here code snippets. Import Native Photo Library ``` #import CGSize retinaSquare = CGSizeMake(600, 600); PHImageRequestOptions \*cropToSquare = [[PHImageRequestOptions alloc] init]; cropToSquare.resizeMode = PHImageRequestOptionsResizeModeExact; cropToSquare.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic; [cropToSquare setSynchronous:YES]; NSURL \*imageurl = [NSURL URLWithString:@"youimagepath"]; PHFetchResult\* asset =[PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObjects:imageurl, nil] options:nil]; [[PHImageManager defaultManager] requestImageForAsset:(PHAsset \*)[asset objectAtIndex:0] targetSize:retinaSquare contentMode:PHImageContentModeAspectFit options:cropToSquare resultHandler:^(UIImage \*fetchedImage, NSDictionary \*info) { NSData \*imageData = UIImageJPEGRepresentation(fetchedImage,0.65); NSArray \*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970]; NSString \*filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%0.0f.jpg", timeStamp\*1000]]; NSError \*error = nil; [imageData writeToFile:filePath options:NSDataWritingAtomic error:&error]; NSURL\* fileUrl = [NSURL fileURLWithPath:filePath]; if(error){ fileUrl = imageurl; } NSString \*resizedImagePath = [NSString stringWithFormat:@"%@",fileUrl]; }]; ``` Upvotes: 1 [selected_answer]
2018/03/15
676
2,843
<issue_start>username_0: I've been racking my brain on this and am stuck. In the Excel NativeTimeline slicer I want to capture when a user switches from Months to Quarters so I can then update the time series chart on the dashboard. I can't seem to find a way to hook into this though as the change is only effecting what is displayed, nothing in the pivot table (otherwise I could use an event trigger there). I've tried adding it to a custom class and setting it to a public withevents object, but that didn't work. Any other ideas on how I can capture this? Here's the the code to switch to Quarters and then Months. ``` ActiveWorkbook.SlicerCaches("NativeTimeline_WeekBeginDate").Slicers("WeekBeginDate").TimelineViewState.Level = xlTimelineLevelQuarter ActiveWorkbook.SlicerCaches("NativeTimeline_WeekBeginDate").Slicers("WeekBeginDate").TimelineViewState.Level = xlTimelineLevelMonths ```<issue_comment>username_1: I think your only hope is to deselect the "Time Level" option so users can't change it on the TimeLine, and instead add a toggle button that lets the user select the time level there, then use their selection to not only change the time level on the TimeLine but also change your time series chart. Upvotes: 1 <issue_comment>username_2: In case others come across this, there currently is no way to capture this event so this is the best work around I could come up with. I capture the pivot table change event, check the Level for the Timeline slicer, and then update the pivot table as needed. The only problem with this is that it is not triggered when the user changes the time level, only after the change the time filter. ``` Private Sub Worksheet_PivotTableChangeSync(ByVal Target As PivotTable) Application.EnableEvents = False If Target = "PivotTable4" Then On Error Resume Next 'this will throw an error if a month/quarter is selected with no data If ThisWorkbook.SlicerCaches("NativeTimeline_WeekDate").Slicers("WeekDate").TimelineViewState.Level = xlTimelineLevelQuarters Then 'change times series chart to quarters ptDashboard.PivotTables("PivotTable4").PivotFields("WeekDate").LabelRange.Group _ Start:=True, End:=True, Periods:=Array(False, False, False, False, False, True, True) 'group by quarter & year ElseIf ThisWorkbook.SlicerCaches("NativeTimeline_WeekDate").Slicers("WeekDate").TimelineViewState.Level = xlTimelineLevelMonths Then 'change times series chart to months ptDashboard.PivotTables("PivotTable4").PivotFields("WeekDate").LabelRange.Group _ Start:=True, End:=True, Periods:=Array(False, False, False, False, True, False, True) 'group by months & year End If On Error GoTo 0 End If Application.EnableEvents = True End Sub ``` Upvotes: 0
2018/03/15
645
2,593
<issue_start>username_0: I would like to get position X or Y of view (ie button) programmatically but in solutions from link (<https://blog.takescoop.com/android-view-measurement-d1f2f5c98f75>) returned values are wrong. I need this to restrain y in animation for clamp function. Also I have problems to get height and width programmatically. I can get view like here (<https://stackoverflow.com/a/24035591/9498656> by view.post(new Runnable()) but like before values are wrong. [problem: animated view with restrictions on other view Y](https://i.stack.imgur.com/qLZIP.png) Could someone explain how get X Y height width for different screens?<issue_comment>username_1: I think your only hope is to deselect the "Time Level" option so users can't change it on the TimeLine, and instead add a toggle button that lets the user select the time level there, then use their selection to not only change the time level on the TimeLine but also change your time series chart. Upvotes: 1 <issue_comment>username_2: In case others come across this, there currently is no way to capture this event so this is the best work around I could come up with. I capture the pivot table change event, check the Level for the Timeline slicer, and then update the pivot table as needed. The only problem with this is that it is not triggered when the user changes the time level, only after the change the time filter. ``` Private Sub Worksheet_PivotTableChangeSync(ByVal Target As PivotTable) Application.EnableEvents = False If Target = "PivotTable4" Then On Error Resume Next 'this will throw an error if a month/quarter is selected with no data If ThisWorkbook.SlicerCaches("NativeTimeline_WeekDate").Slicers("WeekDate").TimelineViewState.Level = xlTimelineLevelQuarters Then 'change times series chart to quarters ptDashboard.PivotTables("PivotTable4").PivotFields("WeekDate").LabelRange.Group _ Start:=True, End:=True, Periods:=Array(False, False, False, False, False, True, True) 'group by quarter & year ElseIf ThisWorkbook.SlicerCaches("NativeTimeline_WeekDate").Slicers("WeekDate").TimelineViewState.Level = xlTimelineLevelMonths Then 'change times series chart to months ptDashboard.PivotTables("PivotTable4").PivotFields("WeekDate").LabelRange.Group _ Start:=True, End:=True, Periods:=Array(False, False, False, False, True, False, True) 'group by months & year End If On Error GoTo 0 End If Application.EnableEvents = True End Sub ``` Upvotes: 0
2018/03/15
436
1,674
<issue_start>username_0: when app loads i have to select on option but i want to show default radio button selected when app loads.. I have used this code for showing radio button ``` public func createRadioButton(frame : CGRect, title : String, color : UIColor) -> DLRadioButton { radioButton = DLRadioButton(frame: frame); radioButton.titleLabel!.font = UIFont.systemFont(ofSize: 14); radioButton.setTitle(title, for: []); radioButton.setTitleColor(color, for: []); radioButton.iconColor = color; radioButton.indicatorColor = color; radioButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left; radioButton.addTarget(self, action: #selector(ViewController.logSelectedButton), for: UIControlEvents.touchUpInside); self.view.addSubview(radioButton); return radioButton; } @objc @IBAction public func logSelectedBtn(radioButton : DLRadioButton) { if (radioButton.isMultipleSelectionEnabled) { for button in radioButton.selectedButtons() { print(String(format: "%@ is selected.\n", button.titleLabel!.text!)); } } else { hello2 = radioButton.selected()!.titleLabel!.text! print(String(format: "%@ is selected.\n", hello2)); } } ```<issue_comment>username_1: Use this code: ``` radioButton.isSelected = true ``` Upvotes: 1 <issue_comment>username_2: Changing in the attribute inspector did't work for me, so I added it programatically as follows: In the ViewDidLoad method: self.yourRadioButton.isSelected = true There you go! [![enter image description here](https://i.stack.imgur.com/IDpEL.png)](https://i.stack.imgur.com/IDpEL.png) Upvotes: 0
2018/03/15
386
1,328
<issue_start>username_0: I have two sheets in a workbook with data pulls from different days to add a new column to the data needed. However, I need to work only with the original data pull (as new items have been added since original pull and those can be ignored). So sheet 1 has 53,875 line items and sheet 2 has 54134 items. The first column is a user ID, so I have sorted both sheets on that column. What I would like to do, is take the data from column L on sheet 2, and insert it into a blank column on sheet 1 for `Sheet1!Ax = Sheet2!Ax`. The formula that I came up with is: `=VLOOKUP(Sheet1!A1,Sheet2!A1:L1,12,0)` I then filled it in for the rest of the blank cells in the first sheet. It worked fine, until the first new data item in Sheet 2 failed to match Sheet 1. After that, every cell has the #N/A error. Is `Vlookup` the correct tool to use for this task, or would it be something else?<issue_comment>username_1: Use this code: ``` radioButton.isSelected = true ``` Upvotes: 1 <issue_comment>username_2: Changing in the attribute inspector did't work for me, so I added it programatically as follows: In the ViewDidLoad method: self.yourRadioButton.isSelected = true There you go! [![enter image description here](https://i.stack.imgur.com/IDpEL.png)](https://i.stack.imgur.com/IDpEL.png) Upvotes: 0
2018/03/15
711
2,690
<issue_start>username_0: We currently have a SaaS application that lives at `app.ourcompany.com`. I am trying to understand what it would take to let our clients access our application via a custom subdomain like `clients.theirbrand.com`. I have done some research and there seems to be a few things in common with other companies that provide this. 1. They have their clients create a `CNAME` record that points `clients.theirbrand.com` to something like `clientaccess.ourcompany.com`. 2. Or the application has client subdomains (`clientname.ourcompany.com`) in which case they have the client create a `CNAME` that points `clients.theirbrand.com` to `clientname.ourcompany.com` I tried taking one of our extra domains and pointing `app.extra.com` to `app.ourcompany.com` via `CNAME` but it just redirects to `app.ourcompany.com`. My question revolves around what we need to do to facilitate this, specifically: 1. What needs to be done on our clients end via DNS? (just CNAME?) 2. What needs to be done our end via DNS? 3. How would we incorporate SSL? (We currently use lets encrypt on `app.ourcompany.com`) We can secure our side but do clients have steps to take as well? Update: We are using nginx to serve the application.<issue_comment>username_1: So I finally figured this out. Step 1. Have your client setup a `CNAME` record that points `their.domain.com` to your `app.saas.com` Step 2. Add `their.domain.com` to your nginx server block: `server\_name app.saas.com their.domain.com; and reload nginx I am now working on setting up SSL for the extra domains and will comment when I figure it out exactly. Edit: SSL is working with a SAN Let's Encrypt certificate installed on the server. Upvotes: 2 <issue_comment>username_2: I know its a little late but I was stuck in a similar situation and thought it might be helpful for newbies like me :) Have a look at: [OpenResty](https://openresty.org/) We have two requirements: * allocate a subdomain to all new customers (e.g: [trumptower.mibuilding.eu](https://mibuilding.eu)) * allow customers to bring their own domain (my.trumptower.com) The first one was pretty easy with [Lets encrypt's](https://www.letsencrypt.org) wildcard subdomain ssl. The second one was tricky. Since we needed to not only issue an SSL on the fly but also configure our gateway (haproxy at that time) and reload the configuration terminating all active sessions briefly. Mind you, HAproxy and nginx wasn't able to coup with dynamic configurations. Openresty with lua plugin allows us to do everything above automatically and on-the-fly. The module we used was: [lua-resty-auto-ssl](https://github.com/GUI/lua-resty-auto-ssl) Upvotes: 2
2018/03/15
1,111
4,391
<issue_start>username_0: I'm trying to understand decorators, so thought I'd start with the simplest cases, checking/modifying the output of a function: Example 1: ``` def checkIsFriend(func): def wrapper(arg): friends = ['alan', 'brian', 'carol'] ret = arg # function not called if ret in friends: return 'hello {}, good to see you!'.format(ret) else: return 'Sorry {}, don\'t know you...'.format(ret) return wrapper @checkIsFriend def greet(name): return 'hi {}, good to see you!'.format(name) print greet('alan') print greet('simon') # output: # hello alan, good to see you! # Sorry simon, don't know you... ``` Example 2: ``` def reject_vowels(func): def wrapper(): reject = 'aieou' new_str = [] ret = func() # need to call the function for char in ret: if char in reject: continue new_str.append(char) return ''.join(new_str) return wrapper @reject_vowels def make_string(): return 'hello world, how are you?' print make_string() # output: # hll wrld, hw r y? ``` What is confusing me is that in example 1, the argument to the decorated function (arg) is not called. In example 2, I need to call the function. Can anyone explain the flow for these examples, please?<issue_comment>username_1: The idea is that `wrapper` will *replace* the decorated function; decorator syntax is short for function application. ``` @checkIsFriend def greet(name): ... ``` is just short for ``` def greet(name): ... greet = checkIsFriend(greet) ``` Knowing that, `checkIsFriend` should be defined as ``` def checkIsFriend(func): def wrapper(arg): friends = ['alan', 'brian', 'carol'] if arg in friends: return func(arg) else: return 'Sorry {}, don\'t know you...'.format(arg) return wrapper ``` Here, `func` may be your `greet` function, or any other function. Inside the wrapper, we don't know anything about `func` except that it takes a single argument and will return a value. The wrapper is a new function that takes the same argument as `func`, and indeed just examines the value of that argument to decide whether to simply call `func` or to return a different string instead. It might make a little more sense if we define a helper replacement for `func`: ``` def checkIsFriend(func): friends = ['alan', 'brian', 'carol'] def donotgreet(arg): return "Sorry {}, don't know you...".format(arg) def wrapper(arg): if arg in friends: f = func else: f = donotgreet return f(arg) return wrapper ``` All the wrapper does is decide whether to pass its argument to and call either the original function or the decorator-defined default function, depending on what argument it receives. Upvotes: 1 <issue_comment>username_2: The decorators that you posted do different things. * In example 1, the decorated function `greet` is replaced by a new function with one argument `arg` that does not use `greet` for anything. In fact, if you change the body of `greet` for anything else, the result will be exactly the same. This new function does some operation with the argument it receives and returns the result; the operation it does is similar to the decorated function `greet`, but it is not related to it anyhow, and would the same no matter what function you are decorating. * In example 2, the decorated function `make_string` is replaced by a new function with no parameters that calls `make_string`, does something with its output and returns the result. In this case, if you had decorated a different function the result would be different, because the new function is actually using the function received by the decorator. Decorators do not require you to actually use the decorated function (like having a parameter in a function does not require you to actually use it). They will just replace the decorated thing with their returned value, which can be *anything*. Usually it is something that you can call and that does something *related* to the decorated function, because otherwise it generally isn't very useful (for example, in example 1 you could just have a regular function that does what `wrapper` does), but it is not necessary. Upvotes: 1 [selected_answer]
2018/03/15
301
944
<issue_start>username_0: I want to write an oracle query to find the substring after nth occurrence of a specific substring couldn't find solution for it Example string - ab##cd##gh How to get gh from above string i.e. string after second occurrence of ##<issue_comment>username_1: This will return everything after second occurance of ##: ``` substr(string, instr(string, '##', 1, 2)+1) ``` If you need to find a substring with specific length, then just add third parameter to substr function ``` substr(string, instr(string, '##', 1, 2)+1, 2) ``` You can also use it in query: ``` select substr(some_value, instr(some_value, '##', 1, 2)+1, 2) from some_table where... ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: ```sql SELECT 'ab##cd##gh' String, Substr('ab##cd##gh',Instr('ab##cd##gh','gh',-1,1),2) Substr FROM Dual; ``` --- ``` STRING SU ---------- -- ab##cd##gh gh ``` Upvotes: -1
2018/03/15
1,263
3,828
<issue_start>username_0: I'm trying to make a recursive method that will give me the following result when printing (example with n = 5): 1 2 3 4 5 4 3 2 1. I can easily achieve it the opposite way using this code: ``` public static void DownUp(int n) { if (n == 1) { System.out.print(n +" "); } else { System.out.print(n +" "); DownUp(n - 1); System.out.print(n +" "); } } ``` This will give me the result of: 5 4 3 2 1 2 3 4 5, but I can't seem to do it the way I need because of the way recursion works. I can do it using 2 parameters, but for my needs I want to use only 1 parameter. I've searched and found a few similar posts here/other places using ArrayList etc. That's decent, but not something that gives me the result I need. If someone could guide me how to do that, that would be great, p.s, it's not homework. Thanks.<issue_comment>username_1: You could use a method to set the start value: ``` public static void downUp(int limit) { downUp(1, limit); } private static void downUp(int value, int limit) { if (((2 * limit) - value) ==0 ) { return;} if (value > limit) { System.out.print((2 * limit) - value); } else { System.out.print(value); } downUp(++value, limit); } ``` Test it with `downUp(5);` If you do not like this concept, you can encapsulate the method in a class and use a field as incrementing value: ``` class UpDown { static int value = 1; public static void downUp(int limit) { if (((2 * limit) - value) ==0 ) { return;} if (value > limit) { System.out.print((2 * limit) - value); } else { System.out.print(value); } value++; downUp(limit); } } ``` Test it with `UpDown.downUp(5);` Upvotes: 3 [selected_answer]<issue_comment>username_2: Have a placeholder (here, "x") that marks the place in the string you want to insert the result of a recursive call. Then have a wrapper method that eliminates the placeholder for the final return. ``` /** * Removes the " x " + i from the helper's string. * E.g. "1 2 3 4 5 x 5 4 3 2 1" -> "1 2 3 4 5 4 3 2 1". */ public static String upDown(int i) { return upDownHelper(i).replace(" x " + i, ""); } /** * Returns a string e.g. "1 2 3 4 5 x 5 4 3 2 1" if i = 5. * The "x" marks the spot where, after a recursive call, * the method replaces its current "i" value. */ private static String upDownHelper(int i) { if (i == 1) { return "1 x 1"; } else { return upDownHelper(i - 1).replace("x", i + " x " + i); } } ``` This only requires 1 argument. Testing: ``` for (int i = 1; i <= 5; i++) { System.out.println(upDown(i)); } ``` Output: ``` 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 ``` Upvotes: 1 <issue_comment>username_3: Got it without extra args, without global static vars, and with same `print`-structure as in original question: ``` public class UpDown { public static void upDown(int i) { class Helper { void rec(int j) { if (i == j) { System.out.print(i); } else { System.out.print(j + " "); rec(j + 1); System.out.print(" " + j); } } }; new Helper().rec(1); } public static void main(String[] args) { upDown(5); } } ``` output: ``` 1 2 3 4 5 4 3 2 1 ``` It's not exactly `recursive` though, because the `upDown` never calls itself. The nested `rec` is recursive. Upvotes: 0 <issue_comment>username_4: ``` private static void increasingDecreasing(int i, int n){ if(i == n + 1) return; System.out.print(i + ", "); increasingDecreasing(i + 1, n); System.out.print(i + ", "); } ``` To execute for 5: increasingDecreasing(1, 5); Easy, simple and recursive. This will work. Upvotes: 0
2018/03/15
832
3,671
<issue_start>username_0: I'm working on an AndroidTV app. So I have a recyclerview that contains a horizontal linear layout with 5 items. During OnBindViewHolder I call viewholder.bind() and in there I change the width of the individual items dynamically. I then call getLocalVisibleRect() to see which of those views are actually on screen. Here is the issue though. It works for the initial screen, but when I scroll down the recyclerview, it is inconsistent with the results of if they are on screen or not. Here is where I set the length of the item and try to set it focusable if it is on screen or not. ``` private void setProgramDataToView(Programme programme, TextView textView) { textView.setText(getEPGText(programme)); textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); boolean v = textView.getLocalVisibleRect(r); textView.setFocusable(v); textView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); ViewGroup.LayoutParams layoutParams = textView.getLayoutParams(); layoutParams.width = timeLineHelper.getDurationProgram(programme); textView.setLayoutParams(layoutParams); } ``` I've tried to change the GlobalLayoutListener to before or after changing the length, it doesn't make a difference it seems like. And since it works for the initial recyclerview items, it seems like the logic works. It seems like it could be a race condition, but while scrolling some of the items give the right results while the rest are very inconsistent. For example it will say views that are on screen are not on screen and views that are off screen are on screen. Any help would be appreciated.<issue_comment>username_1: I ended up just checking which views were on screen during OnKeyDown in the fragment the recyclerview was used in. This is a bit excessive in terms of computation but worked for my case. This ensures the view is drawn completely before checking if its on screen. ``` private boolean setOnScreenViewsFocusable(View focus) { View parentView = (View) focus.getParent(); if (parentView.getId() != View.NO_ID && parentView.getId() == R.id.channel_item) { LinearLayout parentLayout = (LinearLayout) parentView; for (int i = 1; i < 6; i++) { parentLayout.getChildAt(i).setFocusable(isViewOnScreen(parentLayout.getChildAt(i))); } } return false; } private boolean isViewOnScreen(View view) { Rect r = new Rect(); return view.getGlobalVisibleRect(r); } ``` Upvotes: 0 <issue_comment>username_2: Here is an alternative to the `isViewOnScreen()` method that you posted. It uses the layout manager of the `RecyclerView` to bracket the views that are visible then checks to make sure the adapter position of the view in question is bracketed by these positions. See [doc for these methods](https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#findFirstVisibleItemPosition()). ``` private boolean isViewOnScreen(RecyclerView rv, View view) { // Assuming a LinearLayoutManager but it could be another type. LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager(); int firstVisiblePosition = lm.findFirstVisibleItemPosition(); int lastVisiblePosition = lm.findLastVisibleItemPosition(); int viewPosition = lm.getPosition(view); return viewPosition >= firstVisiblePosition && viewPosition <= lastVisiblePosition; } ``` Upvotes: 1
2018/03/15
601
2,507
<issue_start>username_0: I am trying to print the largest odd number. So far I have the code below. ``` largest = None for integer in range(1,11): integer = int(input('Enter integer #%d: ' % integer)) if integer % 2 != 0 and (not largest or integer > largest): largest = integer if largest is None: print ("You didn't enter any odd numbers") else: print ("Your largest odd number was: "), max(largest) ``` I am able to enter 10 integers, but all I get is `Your largest odd number was:` instead of the largest number and that is just blank. I am trying to use the (max) to print the largest integer, but not very successfully.<issue_comment>username_1: I ended up just checking which views were on screen during OnKeyDown in the fragment the recyclerview was used in. This is a bit excessive in terms of computation but worked for my case. This ensures the view is drawn completely before checking if its on screen. ``` private boolean setOnScreenViewsFocusable(View focus) { View parentView = (View) focus.getParent(); if (parentView.getId() != View.NO_ID && parentView.getId() == R.id.channel_item) { LinearLayout parentLayout = (LinearLayout) parentView; for (int i = 1; i < 6; i++) { parentLayout.getChildAt(i).setFocusable(isViewOnScreen(parentLayout.getChildAt(i))); } } return false; } private boolean isViewOnScreen(View view) { Rect r = new Rect(); return view.getGlobalVisibleRect(r); } ``` Upvotes: 0 <issue_comment>username_2: Here is an alternative to the `isViewOnScreen()` method that you posted. It uses the layout manager of the `RecyclerView` to bracket the views that are visible then checks to make sure the adapter position of the view in question is bracketed by these positions. See [doc for these methods](https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#findFirstVisibleItemPosition()). ``` private boolean isViewOnScreen(RecyclerView rv, View view) { // Assuming a LinearLayoutManager but it could be another type. LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager(); int firstVisiblePosition = lm.findFirstVisibleItemPosition(); int lastVisiblePosition = lm.findLastVisibleItemPosition(); int viewPosition = lm.getPosition(view); return viewPosition >= firstVisiblePosition && viewPosition <= lastVisiblePosition; } ``` Upvotes: 1
2018/03/15
555
2,201
<issue_start>username_0: How to replace Thread.Sleep ()? While all the elements are loaded ``` public void Test() { home.OpenHomePage(); users.Login(new Logins("test1", "test2")); Thread.Sleep(2000); BtnOk(); Thread.Sleep(2000); ..................} ``` For example: `BtnOk ();` before this, I wait until the element is loaded: (`driver.FindElement (By.XPath ("// button")). Click ()`<issue_comment>username_1: I ended up just checking which views were on screen during OnKeyDown in the fragment the recyclerview was used in. This is a bit excessive in terms of computation but worked for my case. This ensures the view is drawn completely before checking if its on screen. ``` private boolean setOnScreenViewsFocusable(View focus) { View parentView = (View) focus.getParent(); if (parentView.getId() != View.NO_ID && parentView.getId() == R.id.channel_item) { LinearLayout parentLayout = (LinearLayout) parentView; for (int i = 1; i < 6; i++) { parentLayout.getChildAt(i).setFocusable(isViewOnScreen(parentLayout.getChildAt(i))); } } return false; } private boolean isViewOnScreen(View view) { Rect r = new Rect(); return view.getGlobalVisibleRect(r); } ``` Upvotes: 0 <issue_comment>username_2: Here is an alternative to the `isViewOnScreen()` method that you posted. It uses the layout manager of the `RecyclerView` to bracket the views that are visible then checks to make sure the adapter position of the view in question is bracketed by these positions. See [doc for these methods](https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#findFirstVisibleItemPosition()). ``` private boolean isViewOnScreen(RecyclerView rv, View view) { // Assuming a LinearLayoutManager but it could be another type. LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager(); int firstVisiblePosition = lm.findFirstVisibleItemPosition(); int lastVisiblePosition = lm.findLastVisibleItemPosition(); int viewPosition = lm.getPosition(view); return viewPosition >= firstVisiblePosition && viewPosition <= lastVisiblePosition; } ``` Upvotes: 1
2018/03/15
690
2,710
<issue_start>username_0: I have a relation with primary key named idavaliacao and foreign key named trabalho\_idtrabalho, and I want to get the last tuple for each foreign key order by idavaliacao, desc. Eg: ``` idavaliacao | trabalho_idtrabalho ------------+-------------------- 1 | 1 2 | 1 3 | 2 4 | 3 5 | 3 6 | 4 ``` returns: ``` idavaliacao | trabalho_idtrabalho ------------+-------------------- 2 | 1 3 | 2 5 | 3 6 | 4 ``` Eloquent Queries: ``` $ids = Trabalho::where([['trabalho.eventos_ideventos',$evento->ideventos],['eixos_tematicos_ideixos_tematicos',$id_eixo]])->get(['trabalho.idtrabalho'])->toArray(); $avaliacao = Avaliacao::whereIn('trabalho_idtrabalho',$ids)->to be continued ```<issue_comment>username_1: I ended up just checking which views were on screen during OnKeyDown in the fragment the recyclerview was used in. This is a bit excessive in terms of computation but worked for my case. This ensures the view is drawn completely before checking if its on screen. ``` private boolean setOnScreenViewsFocusable(View focus) { View parentView = (View) focus.getParent(); if (parentView.getId() != View.NO_ID && parentView.getId() == R.id.channel_item) { LinearLayout parentLayout = (LinearLayout) parentView; for (int i = 1; i < 6; i++) { parentLayout.getChildAt(i).setFocusable(isViewOnScreen(parentLayout.getChildAt(i))); } } return false; } private boolean isViewOnScreen(View view) { Rect r = new Rect(); return view.getGlobalVisibleRect(r); } ``` Upvotes: 0 <issue_comment>username_2: Here is an alternative to the `isViewOnScreen()` method that you posted. It uses the layout manager of the `RecyclerView` to bracket the views that are visible then checks to make sure the adapter position of the view in question is bracketed by these positions. See [doc for these methods](https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#findFirstVisibleItemPosition()). ``` private boolean isViewOnScreen(RecyclerView rv, View view) { // Assuming a LinearLayoutManager but it could be another type. LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager(); int firstVisiblePosition = lm.findFirstVisibleItemPosition(); int lastVisiblePosition = lm.findLastVisibleItemPosition(); int viewPosition = lm.getPosition(view); return viewPosition >= firstVisiblePosition && viewPosition <= lastVisiblePosition; } ``` Upvotes: 1
2018/03/15
512
1,967
<issue_start>username_0: I have a sample json file as below. ``` { "TestOneConfig": { "SvcUrl": "www.abc.com/", "Port": "3455" }, "LiveTestConfig": { "ConnString": "abcd" } } ``` And I have class model for "TestOneConfig" as below ``` public class TestOneConfig { public string SvcUrl { get; set; } public string Port { get; set; } } ``` How to deserialize the "TestOneConfig" sub items to the class model. I tried as below but did not work. I used NewtonJsoft. ``` using (StreamReader reader = new StreamReader("appsettings.json")) { var settingsJson = reader.ReadToEnd(); dynamic settings1 = JsonConvert.DeserializeObject(settingsJson); dynamic settings2 = JsonConvert.DeserializeObject(settings1.TestOneConfig); } ```<issue_comment>username_1: Assuming you're using [Json.NET](https://www.newtonsoft.com/json), you could do something like this: ``` var jsonObj = JObject.Parse(json); var testOneConfig = JsonConvert.DeserializeObject(jsonObj["TestOneConfig"].ToString()); ``` Alternatively, you can just use the `jsonObj` variable which holds the entire json string, instead of deserializing individual properties, to access the fields you need: ``` var testOneConfigSvcUrl = jsonObj["TestOneConfig"]["SvcUrl"].ToString(); var testOneConfigPort = jsonObj["TestOneConfig"]["Port"].ToString(); var liveTestConfigConnString = jsonObj["LiveTestConfig"]["ConnString"].ToString(); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Thanks @PoweredByOrange. That helped. Since I used NewtonJsoft, only the format is changed. It become as below ``` using (StreamReader reader = new StreamReader("appsettings.json")) { dynamic settingsJson = reader.ReadToEnd(); var settings = JObject.Parse(settingsJson); var testOneConfigObj = JsonConvert.DeserializeObject(settings.TestOneConfig.ToString()); } ``` Upvotes: 0
2018/03/15
1,195
4,756
<issue_start>username_0: I have two entities Accounts: ``` @Entity(tableName = "accounts",foreignKeys = arrayOf( ForeignKey( entity = Currency::class, parentColumns = arrayOf("id"), childColumns = arrayOf("currencyId"), onDelete = ForeignKey.CASCADE ) )) data class Account ( @PrimaryKey(autoGenerate = true) var id:Int=0, @ColumnInfo(name="name") var accountName:String, @ColumnInfo(name = "balance") var initialBalance:Double, var currencyId:Int, var date:Date, var isDefault:Boolean=true ){ constructor():this(0,"",0.0,0,Date(),false) } ``` And Currencies: ``` @Entity(tableName = "currencies") data class Currency( @PrimaryKey(autoGenerate = true) var id:Int=0, @ColumnInfo(name="name") var currencyName:String, @ColumnInfo(name="code") var currencyCode:String ) { constructor():this(0,"","") override fun toString(): String =currencyCode } ``` I want to embed a `currency` object in `account`. As you can see, I have one-to-many relationship between `currencies` and `accounts`. When I query the `accounts` entity I want to view its currency too. I tried adding an `@Embedded` field in `account` entity but it doesn't work **obviously there is something I'm misunderstanding** , the field is returned with null "No exception just null". And if possible to "flatten" the `currency` object inside the `account` object, this would be much better. The point of all of this is, I want to display all accounts in `RecyclerView` with their currencies information. I'm now confused between `@Embedded` and `@Relation` any help would be much appreciated. **Edit** I don't know if this might help: This is my `AccountDao`: ``` @Dao interface AccountDao { @Insert fun insertAll(items:Array) @Update fun update(item:Account) @Delete fun delete(item:Account) @Query("select \* from accounts") fun getAll():LiveData> } ```<issue_comment>username_1: I managed to get it to work. The solution was to create a separate (POJO or POKO whatever) class, I called it `AccountModel`: ``` class AccountModel{ var accountId:Int = 0 var accountName:String = "" var accountInitialBalance:Double = 0.0 var accountCreationDate: Date = Date() var currencyId:Int = 0 var currencyCode:String = "" var isDefaultAccount:Boolean = false constructor() constructor(id:Int,name:String,balance:Double,date:Date,currencyId:Int,currencyCode:String,isDefault:Boolean){ this.accountId = id this.accountName = name this.accountInitialBalance = balance this.accountCreationDate = date this.currencyId = currencyId this.currencyCode = currencyCode this.isDefaultAccount= isDefault } fun toAccount():Account = Account(this.accountId,this.accountName,this.accountInitialBalance,this.currencyId,this.accountCreationDate,this.isDefaultAccount) } ``` And then, constructing the query to do a normal `inner join` as if you are doing `inner join` for ordinary SQL database. Like this: ``` @Query("select accounts.id as accountId," + "accounts.name as accountName," + "accounts.balance as accountInitialBalance," + "accounts.currencyId," + "accounts.date as accountCreationDate," + "accounts.isDefault as isDefaultAccount," + "currencies.code as currencyCode " + "from accounts inner join currencies on accounts.currencyId=currencies.id") fun getAll():LiveData> ``` Apparently, you can use `as x` to project this column to a `x` field in the returned object, as you can tell, in the database the column is `accounts.id` but in my `AccountModel` it is a `accountId`. And the really impressive thing by Google Room is that I was able to get a `LiveData` of `AccountModel` even though I'm adding an `Account` object which is really clever. Upvotes: 3 [selected_answer]<issue_comment>username_2: I won't recommend the above method because you end up writing the same properties (repeating yourself) aka boilerplate code. Use the [@Embedded](https://developer.android.com/reference/android/arch/persistence/room/Embedded.html) and [Relation](https://developer.android.com/reference/android/arch/persistence/room/Relation.html) annotation in the following way and your code will most probably look like this: ``` data class AccountWithCurrency ( @Embedded var account: Account? = null, @Relation(parentColumn = "id", entityColumn = "currencyId") var currency: List? = null, ){ constructor() : this(Account(), emptyList()) } ``` Upvotes: 2
2018/03/15
775
2,402
<issue_start>username_0: Is this: ``` between cast(date as date) and cast(date1 as date) ``` The same as: ``` between '01/01/01 00:00:00' and '01/01/01 11:59:59' ``` I've been told that when comparing date time values in SQL Server that if I wanted to return the PROPER results I should ALWAYS include a time component with my date.<issue_comment>username_1: Don't use `between` with dates. It is just risky. In general, the right syntax to use is: ``` where dtcol >= @date1 and dtcol < dateadd(day, 1, @date2) ``` Note the direction of the inequalities. This works for columns that are both dates and date/times. So, it just works. <NAME> has an excellent blog post on this, [What do BETWEEN and the devil have in common?](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common). Upvotes: 3 <issue_comment>username_2: Gordon is spot on. And I can demonstrate why with your own words. You wrote: ``` between '01/01/01 00:00:00' and '01/01/01 11:59:59' ``` To people who do not use 24 hour time regularly, this can easily appear to be correct logic. Unfortunately it has 2 problems. First and foremost, without an "AM/PM" designation, the default interpretation is **noon**. This is an easy mistake to make and one that might not be found during testing (developers are lazy - trust that). Secondly, you specifically state datetime. What is the maximum possible time component of that datatype? Is it not what you have provided; rather it is 23:59:59.997. And what happens if someone changes the datatype to a more precise datetime2? You might easily discard this concern as unlikely - and it is. But such edge cases have a habit of showing up eventually - and usually in situations where something has gone wrong. It is better to write code that is correct for the datatypes in use and not dependent on assumptions and luck. I'll give a link to [Tibor's](http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes) datetime guide - whose site also contains lots of other excellent content worth reading when possible. Upvotes: 2 <issue_comment>username_3: No, ``` between cast(date as date) and cast(date1 as date) ``` is the same as: ``` between '20180310 00:00:00' and '20180315 00:00:00' ``` Between is inclusive of the values, it's the equivalent of: ``` @Dt >= '20180310 00:00:00' and @Dt <= '20180315 00:00:00' ``` Upvotes: 1
2018/03/15
634
2,734
<issue_start>username_0: Why guidelines says "avoid `async` `void`". I don't know, but I feel guideline should rather say - "`await` `task`". Problem with `async void` is that caller will not know if it need to `await` for completion and control will continue with execution of following statements. I can understand ill effect of this. But even if `async` method returns `task` instead of `void`, caller can still miss to await and get into same issues, right ? Hence the question, why not guideline rather says - *don't avoid awaiting task*<issue_comment>username_1: You don't always *want* to prevent the rest of the method from executing until that operation has finished. Sometimes you have some things you can do before it finishes, so you want to await it later, maybe that one caller happens to just not need the results, so it can ignore it safely, etc. The point is, because the method returns a `Task` it is up to the caller to do with it what they will. If they want to do something when that task finishes, or know if it has succeeded or failed, they can, and if they don't that's fine to. When the method is an `async void` method *that is taken out of your hands*. The caller is put into a position where they *can't* know when the operation has finished, even if they really need to know. And that's just not a decision that should be made when writing the method. That method isn't going to know who all is going to call it, and whether or not they'll need to know when/if it has finished, so when writing the method you need to assume that someone *will* want that information. All of that said firing off an async method and ignoring it entirely should be very rare. There *are* situations where it's appropriate, but it should be a big red flag anytime you see it. When it *does* happen though, it should be the *caller* of the method making the decision that they don't care about when that operation finishes, not the author of the method deciding that no one should ever be able to know when it finishes (again, outside of some really exceptional situations). Upvotes: 2 <issue_comment>username_2: You can do that, i.e., you can do void or do not wait for `task` to complete at all. But there mayt be a scenario where you developed an `API` which is used by multiple `projects`, and some of the project which use your method want to wait to complete call although the method is going to returning nothing just for check or for doing work after method get completed. In that senario its helpful and that is the reason you must return `Task` not `void`. It helps the others who are using your method. That is one of the logic reason apart form what you have given in question. Upvotes: -1 [selected_answer]
2018/03/15
1,224
4,381
<issue_start>username_0: I am working with Orchestration Design, but found that it doesn't have all the functions I need, so we have a lot of hard coded JAVA. I have read several post discussing similar errors as below. > > org.codehaus.jettison.json.JSONException: JSONObject["customer"] not > found > > > I have tried several of the solutions that were previously published, but am still not able to get this fixed. I have only 2 weeks of java training, and next to no real world experience with Java. So if you can break it down or provide more guidance I would be really appreciative. Here is my data: ``` {"statusCode":"200", "statusMessage":"OK", "data": {"customer": [{"name":"<NAME>", "dob":"06-14-2000", "phones": [{"phoneID":"d3dd30b1-cd47-46f5-8e06-1fd5e8631203", "phoneNumberTypeCode":"3", "phoneNumber":"2162100834", "sortOrderCode":"1"}, {"phoneID":"0153632c-ae8f-4b12-a68f-1ab33fa4e7e3", "phoneNumberTypeCode":"3", "phoneNumber":"3306973358", "sortOrderCode":"2"}]}, {"name":"same five", "dob":"06-01-1968", "phones": [{"phoneID":"83c49dd0-d308-4e88-b25e-4ddff53bf124", "phoneNumberTypeCode":"3", "phoneNumber":"3306973358", "sortOrderCode":"1"}]}, {"name":"same five", "dob":"06-01-1968", "phones": [{"phoneID":"ac61e9ce-ea4e-46c3-85d7-cd07bdcbf54e", "phoneNumberTypeCode":"3", "phoneNumber":"3306973358", "sortOrderCode":"1"}]}, {"name":"kjhdv askljdh", "dob":"06-01-1968", "phones": [{"phoneID":"8706e547-c9fe-4844-84a8-f4c78abd7277", "phoneNumberTypeCode":"3", "phoneNumber":"3306973358", "sortOrderCode":"1"}]}]}} ``` At this point I am only interested in getting to the DOB. I need to compare it to data entered by a customer to try pull the correct account. Later on I will need to get to the rest of the data, but I hope once I understand how to get to the DOB I can figure the rest out on my own. Here is the code I have been writing. I have a lot of commented out code which was examples I found on this forum and tried to get to work as well. Each version give me an error > > JSONObject["customer"] not found. > > > I do realize that there are other posts with this same issue, but I have not been able to make any of the solutions work for me (probably due to my lack of experience) ``` public String getAccount(String requestUrl, String token) throws Exception { String statusmessage = ""; try { CloseableHttpClient httpClient = getHttpClient(); HttpGet getRequest = new HttpGet(requestUrl); getRequest.addHeader("accept", "application/json"); getRequest.addHeader("Authorization", token); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { System.out.println("StatCode = " + response.getStatusLine().getStatusCode()); return "500"; //throw new Exception("Failed : HTTP error code : " + //response.getStatusLine().getStatusCode()); } String responseStr = EntityUtils.toString(response.getEntity()); System.out.println("RESPONSE *** " + responseStr); String jsonResp = responseStr; JSONObject jsonObj = new JSONObject(jsonResp); statusmessage = jsonObj.get("statusMessage").toString(); System.out.println("StatusMes : " + statusmessage); String data = jsonObj.get("data").toString(); System.out.println("Data : " + data); //String customer = jsonObj.get("customer").toString(); JSONArray customer = jsonObj.getJSONArray("customer"); for(int i=0;i ``` Thank you,<issue_comment>username_1: JSONObject["customer"] not found because it doesn't exists. On your JSON the "customer" is under "data" not under root. Upvotes: 2 <issue_comment>username_2: Just try this :) ``` JSONObject mainNode = new JSONObject(jsonResp); JSONObject dataNode = mainNode.getJSONObject("data"); JSONArray customerNode = dataNode.getJSONArray("customer"); for(int i=0;i ``` Upvotes: 1 [selected_answer]
2018/03/15
1,425
4,603
<issue_start>username_0: I'm trying to parse a string formatted like so: ``` 1900-001T00:00:00Z ``` into a DateTime object. The middle bit there (right after the "1900-" and before the "T") is supposed to be the day of year. I know the rest of the formatting string I would need to use would be ``` yyyy-XXXTHH:mm:ssZ ``` but what should I put in for that 'XXX'?<issue_comment>username_1: A self written parser could look like this: ``` static DateTime ToDt(string date) { var splitYear = date.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries); var splitDays = splitYear[1].Split(new[] { 'T' }, StringSplitOptions.RemoveEmptyEntries); var hms = splitDays[1].TrimEnd('Z').Split(':'); var dt = new DateTime(int.Parse(splitYear[0]), 1, 1, 0, 0, 0); dt = dt.AddDays(int.Parse(splitDays[0]) - 1); dt = dt.AddHours(int.Parse(hms[0])); dt = dt.AddMinutes(int.Parse(hms[1])); dt = dt.AddSeconds(int.Parse(hms[2])); return dt; } static void Main(string[] args) { Console.WriteLine(ToDt("1900-001T00:10:00Z")); Console.WriteLine(ToDt("1923-180T12:11:10Z")); Console.WriteLine(ToDt("1979-365T23:59:59Z")); Console.WriteLine(ToDt("2017-074T18:47:10Z")); Console.ReadLine(); } ``` Output: ``` 01.01.1900 00:10:00 29.06.1923 12:11:10 31.12.1979 23:59:59 15.03.2017 18:47:10 ``` This will throw if * splits are not returning the expected amount of splits (ill formatting) **`IndexOutOfRangeException`** * numbers are not parsable to int **`FormatException`** and int won't guard against "nonsensical but wellformed" inputs ``` '2000-999T99:99:99Z' --> 29.09.2002 04:40:39 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I'm sure there's a fancier way, but you could write your own method to do it: ``` private static DateTime CustomParseDayOfYear(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); var parts = input.Split('-', 'T'); if (parts.Length != 3) throw new FormatException(nameof(input)); var timeParts = parts[2].Trim('Z').Split(':'); if (timeParts.Length != 3) throw new FormatException(nameof(input)); int hour, minute, second, year, dayOfYear; if (!int.TryParse(parts[0], out year)) throw new FormatException("Year must be an integer"); if (!int.TryParse(parts[1], out dayOfYear)) throw new FormatException("DayOfYear must be an integer"); if (!int.TryParse(timeParts[0], out hour)) throw new FormatException("Hour must be an integer"); if (!int.TryParse(timeParts[1], out minute)) throw new FormatException("Minute must be an integer"); if (!int.TryParse(timeParts[2], out second)) throw new FormatException("Second must be an integer"); var maxDayOfYear = new DateTime(year, 12, 31).DayOfYear; if (year < 1 || year > 9999) throw new ArgumentOutOfRangeException( "Year must be greater than zero and less than 10000"); if (dayOfYear < 1 || dayOfYear > maxDayOfYear) throw new ArgumentOutOfRangeException( $"DayOfYear must be greater than zero and less than {maxDayOfYear + 1}"); if (hour > 23) throw new ArgumentOutOfRangeException($"Hour must be less than 24"); if (minute > 59) throw new ArgumentOutOfRangeException($"Minute must less than 60"); if (second > 59) throw new ArgumentOutOfRangeException($"Second must less than 60"); return new DateTime(year, 1, 1, hour, minute, second).AddDays(dayOfYear - 1); } ``` Upvotes: 2 <issue_comment>username_3: Based on @AlexK's suggestion, here you go, nice and simple... ``` using System.Globalization; using System.Text.RegularExpressions; private DateTime? ParseDayOfYearDate(string value) { DateTime? result = null; Regex dayOfYearDatePattern = new Regex(@"^(\d+\-)(\d+)(.+)$"); Match dayOfYearDateMatch = dayOfYearDatePattern.Match(value); if (dayOfYearDateMatch.Success) { string altered = dayOfYearDateMatch.Groups[1].Value + "01-01" + dayOfYearDateMatch.Groups[3].Value; int dayOfYear = int.Parse(dayOfYearDateMatch.Groups[2].Value); // will succeed due to the definition of the pattern DateTime startOfYear = DateTime.ParseExact(altered, "yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); result = startOfYear.AddDays(dayOfYear - 1); // since we already gave it 1st January } else { // It didn't match the pattern, will return null. } return result; } ``` Upvotes: 1
2018/03/15
1,131
4,375
<issue_start>username_0: Usually I make projects with database first, now I tried (due to the ASP.NET login framework) the code first approach. So far so good, all works. Now I needed to add a new model to the project, did this and added the model in the `DbContext`: ``` public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public System.Data.Entity.DbSet Orders { get; set; } // existing one public System.Data.Entity.DbSet Documents { get; set; } // new one } ``` So I already have data in the orders table in my database and users in the asp.net user tables, I can't allow to drop the db, so I thought, automatic migration: ``` Package Manager > Enable-Migrations -EnableAutomaticMigrations ``` And then ``` PM > update-database (-f) ``` however, this returns: ``` No pending explicit migrations. ``` The table just won't be created. However, a new folder called *Migrations* was created with 2 files: `###########_dbname.cs` and `Configurations.cs` Any hints why my table won't be created? I even tried this in the migration file ``` public partial class project: DbMigration { public override void Up() { CreateTable("dbo.Documents", c => new { DocumentId = c.Int(nullable: false, identity: true), Label = c.Int(nullable: false), Data = c.Binary(), OrderId = c.Int(nullable: false) }).PrimaryKey(t => t.DocumentId) .ForeignKey("dbo.Orders", t => t.OrderId, cascadeDelete: true); ``` in vain **UPDATE** If I perform `add-migration`, the following file is being created, how do I modify it? ``` using System; using System.Data.Entity.Migrations; public partial class documents : DbMigration { public override void Up() { } public override void Down() { } } ``` simply performing `update-database` doesn't change anything<issue_comment>username_1: You need to add the migration for your changes, and then execute the `Update-Database`. The fact that the Migrations folder has only 2 files, and none of them is a migration file(TimeStamp\_MigrationName.cs), tells you that there is no migration to be executed. You need something like (after enabling migrations): ``` PM > Add-Migration -Name NewEntityAdded ``` The entire syntax is: > > Add-Migration [-Name] [-Force] [-ProjectName ] [-StartUpProjectName ] > [-ConfigurationTypeName ] [-ConnectionStringName ] [-IgnoreChanges] > [-AppDomainBaseDirectory ] [] > > > And after that - execute `Update-Database`. More info - [Here](https://coding.abel.nu/2012/03/ef-migrations-command-reference/) **EDIT after the update** The fact that the migration file is empty, means that when executing `add-migration` there was no difference between the current snapshot and the one that you are trying to migrate to. You don't have to modify the migration file. All the changes must be there. According to the file, there is nothing to change. This is why 'update-database' is not changing anything Are you still keeping this: ``` public partial class project: DbMigration { public override void Up() { CreateTable("dbo.Documents", c => new { DocumentId = c.Int(nullable: false, identity: true), Label = c.Int(nullable: false), Data = c.Binary(), OrderId = c.Int(nullable: false) }).PrimaryKey(t => t.DocumentId) .ForeignKey("dbo.Orders", t => t.OrderId, cascadeDelete: true); ``` in your code? If yes - remove it Upvotes: 3 [selected_answer]<issue_comment>username_2: Please try the following steps: 1. Run DbContext.tt file after creating the model class 2. In Package Manager Console, select your migrations project (if you have created one) as a default project 3. Run add-migration -startupProject "your startup projectname" [Migration\_Name] 4. Run DbContext.Views.tt file 5. update-database -startupProject "your startup projectname" -Verbose Upvotes: 0 <issue_comment>username_3: I realized I had the same problems, I run add-migration rewreww, the migration script does not generate tables, then I realized you need to delete whatever is in the snapshot, then rerun it solved my problem. thanks username_1 Upvotes: 0
2018/03/15
825
3,076
<issue_start>username_0: I have a `fildset` in my html. It already comes with a default border, but, I was trying to make it less horrible. It's all going well, except for the `border-color`. The first time that i aply i didn't realize that my border was *"duplicated"*. Then, seeing others components with same color, I saw that my `fildset` border was not with the properly color. ![This is what i mean duplicated](https://i.stack.imgur.com/Fuala.png) This is my css: ``` .tabelaConclusao{ border-radius: 10px; border-color: #a6c9e2; } ``` PS: My css looks exacly the same when i use Chromes developer tools. PPS: In the image, i just change the border width to get bigger, than you can see better what I'm talking about.<issue_comment>username_1: You need to add the migration for your changes, and then execute the `Update-Database`. The fact that the Migrations folder has only 2 files, and none of them is a migration file(TimeStamp\_MigrationName.cs), tells you that there is no migration to be executed. You need something like (after enabling migrations): ``` PM > Add-Migration -Name NewEntityAdded ``` The entire syntax is: > > Add-Migration [-Name] [-Force] [-ProjectName ] [-StartUpProjectName ] > [-ConfigurationTypeName ] [-ConnectionStringName ] [-IgnoreChanges] > [-AppDomainBaseDirectory ] [] > > > And after that - execute `Update-Database`. More info - [Here](https://coding.abel.nu/2012/03/ef-migrations-command-reference/) **EDIT after the update** The fact that the migration file is empty, means that when executing `add-migration` there was no difference between the current snapshot and the one that you are trying to migrate to. You don't have to modify the migration file. All the changes must be there. According to the file, there is nothing to change. This is why 'update-database' is not changing anything Are you still keeping this: ``` public partial class project: DbMigration { public override void Up() { CreateTable("dbo.Documents", c => new { DocumentId = c.Int(nullable: false, identity: true), Label = c.Int(nullable: false), Data = c.Binary(), OrderId = c.Int(nullable: false) }).PrimaryKey(t => t.DocumentId) .ForeignKey("dbo.Orders", t => t.OrderId, cascadeDelete: true); ``` in your code? If yes - remove it Upvotes: 3 [selected_answer]<issue_comment>username_2: Please try the following steps: 1. Run DbContext.tt file after creating the model class 2. In Package Manager Console, select your migrations project (if you have created one) as a default project 3. Run add-migration -startupProject "your startup projectname" [Migration\_Name] 4. Run DbContext.Views.tt file 5. update-database -startupProject "your startup projectname" -Verbose Upvotes: 0 <issue_comment>username_3: I realized I had the same problems, I run add-migration rewreww, the migration script does not generate tables, then I realized you need to delete whatever is in the snapshot, then rerun it solved my problem. thanks username_1 Upvotes: 0
2018/03/15
253
910
<issue_start>username_0: Is there a way to display commands using tab? By commands, I don't mean bash ones, but vim ones, using **:** For instance : I use Nerdtree plugin by typing ':' in NORMAL mode (:NERDTree). If I tab NER, I directly have NERDTree. Then in I tab again > NERDTreeCWD > NERDTreeClose > NERDTreeFind etc... Is it possible to display all the available commands somehow in the status bar? Thank you for your help!<issue_comment>username_1: Perhaps you're looking for ? This will show you all possible completions of the current command. See `:help cmdline-completion`. Upvotes: 4 [selected_answer]<issue_comment>username_2: Thank Rinceldor for your answer, that was helpful. By the way, if you want to use `Tab` key to display available commands, you must add `cnoremap` into your `~/.vimrc` file. It will replace two keystrokes is `Ctrl + L` and `Ctrl + D` with the `Tab` key. Upvotes: 1
2018/03/15
378
1,417
<issue_start>username_0: I have following two props that i need to access in linear-gradient in `MyComponent.scss` ``` startColor: PropTypes.string endColor: PropTypes.string ``` My component looks like below ``` MyComponent.jsx ``` Currently it accepts only one color. linear-gradient property in `MyComponent.scss` looks like below ``` linear-gradient(to left, currentcolor, currentcolor); ``` It'll be updated to use startColor and endColor. How could i achieve that?<issue_comment>username_1: You could do this with inline CSS or using a CSS Object in a JS file. But not directly in a file that is interpreted as CSS specifically. TECHNICALLY, you could achieve this using server side rendering, requiring express to overwrite a file in the file system and return the style. But that's insane, and dumb, and insane. Upvotes: 2 <issue_comment>username_2: You can't pass props to SCSS, but [styled-components](https://github.com/styled-components/styled-components) supports that. See [Adapting based on props](https://www.styled-components.com/docs/basics#adapting-based-on-props) from its documentation. Without styled-components, the only other option is using inline styles by passing a `style` prop to the element. Upvotes: 3 <issue_comment>username_3: yes you can easily get props in scss from jsx is send props as a data-text(item) and in scss i get this : content: attr(data-text); Upvotes: 0
2018/03/15
434
1,473
<issue_start>username_0: I have query as below: ``` SELECT COUNT(*) FROM (SELECT h2.hacker_id, COUNT(c2.challenge_id) AS co FROM hackers h2 INNER JOIN challenges c2 ON h2.hacker_id = c2.hacker_id GROUP BY h2.hacker_id HAVING COUNT(c2.challenge_id) = 1) ``` But, my query can not execute well and I get this error: > > Msg 102, Level 15, State 1, Server WIN-ILO9GLLB9J0, Line 33 > > Incorrect syntax near ')' > > > Please help me resolve this.<issue_comment>username_1: You could do this with inline CSS or using a CSS Object in a JS file. But not directly in a file that is interpreted as CSS specifically. TECHNICALLY, you could achieve this using server side rendering, requiring express to overwrite a file in the file system and return the style. But that's insane, and dumb, and insane. Upvotes: 2 <issue_comment>username_2: You can't pass props to SCSS, but [styled-components](https://github.com/styled-components/styled-components) supports that. See [Adapting based on props](https://www.styled-components.com/docs/basics#adapting-based-on-props) from its documentation. Without styled-components, the only other option is using inline styles by passing a `style` prop to the element. Upvotes: 3 <issue_comment>username_3: yes you can easily get props in scss from jsx is send props as a data-text(item) and in scss i get this : content: attr(data-text); Upvotes: 0
2018/03/15
300
1,138
<issue_start>username_0: this is my code of a dynamic drop down menu and I want to change the text of the first option which has no id and the value is empty! this is the code: ``` All America ```<issue_comment>username_1: You could do this with inline CSS or using a CSS Object in a JS file. But not directly in a file that is interpreted as CSS specifically. TECHNICALLY, you could achieve this using server side rendering, requiring express to overwrite a file in the file system and return the style. But that's insane, and dumb, and insane. Upvotes: 2 <issue_comment>username_2: You can't pass props to SCSS, but [styled-components](https://github.com/styled-components/styled-components) supports that. See [Adapting based on props](https://www.styled-components.com/docs/basics#adapting-based-on-props) from its documentation. Without styled-components, the only other option is using inline styles by passing a `style` prop to the element. Upvotes: 3 <issue_comment>username_3: yes you can easily get props in scss from jsx is send props as a data-text(item) and in scss i get this : content: attr(data-text); Upvotes: 0
2018/03/15
5,334
9,055
<issue_start>username_0: In React, I have an array of objects with an createdAt attribute which I'm trying to sort on. However the sort doesn't seem to work properly because some it comes out in the wrong order. I've written the following code in Node.js for testing... any help would be appreciated. ``` const moment = require('./node_modules/moment/moment.js') const sortObjects = () => { const objects = [ {id: "cje633i3v03wl0130lsse3zev", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cjeqtudhd000u0149skzacpq5", createdAt: "2018-03-14T08:31:57.000Z"}, {id: "cje633goc03vn01309m2iocas", createdAt: "2018-02-27T20:07:48.000Z"}, {id: "cje633k1z03ww0130ce27niez", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k3303x50130n1a7vnft", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k5b03xa0130m07ndgpn", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k2y03x10130q1076pq4", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k0b03wq0130bmg0t6rd", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633gmp03ve0130xu314ti4", createdAt: "2018-02-27T20:07:47.000Z"}, {id: "cje633i2x03wd0130cqk5sdap", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633i1w03w60130rfpngz0b", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633i1u03w301307s44jfyy", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633i3i03wh0130f3t1iyl4", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633gp803vw0130frck18wq", createdAt: "2018-02-27T20:07:48.000Z"}, {id: "cje633gos03vs0130tzv7xfpe", createdAt: "2018-02-27T20:07:48.000Z"}, {id: "cje633gnu03vj0130nnt4abin", createdAt: "2018-02-27T20:07:47.000Z"}, {id: "cje633enx03uo0130qw0r35l6", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633eot03uw0130r42aqbox", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633eou03uy0130hdwg0uvn", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633epl03v30130hsugr6vp", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633eps03v70130xr826vf2", createdAt: "2018-02-27T20:07:45.000Z"}, ] objects.sort( (a, b) => moment.utc(b.createdAt).isAfter(moment.utc(a.createdAt))); console.log('objects',objects) } sortObjects() ``` **Update - here's the output** ``` [ { id: 'cje633i1w03w60130rfpngz0b', createdAt: '2018-02-27T20:07:49.000Z' }, { id: 'cje633i3v03wl0130lsse3zev', createdAt: '2018-02-27T20:07:49.000Z' }, { id: 'cje633i3i03wh0130f3t1iyl4', createdAt: '2018-02-27T20:07:49.000Z' }, { id: 'cje633k1z03ww0130ce27niez', createdAt: '2018-02-27T20:07:52.000Z' }, { id: 'cje633k3303x50130n1a7vnft', createdAt: '2018-02-27T20:07:52.000Z' }, { id: 'cje633k5b03xa0130m07ndgpn', createdAt: '2018-02-27T20:07:52.000Z' }, { id: 'cje633k2y03x10130q1076pq4', createdAt: '2018-02-27T20:07:52.000Z' }, { id: 'cje633k0b03wq0130bmg0t6rd', createdAt: '2018-02-27T20:07:52.000Z' }, { id: 'cje633i1u03w301307s44jfyy', createdAt: '2018-02-27T20:07:49.000Z' }, { id: 'cje633i2x03wd0130cqk5sdap', createdAt: '2018-02-27T20:07:49.000Z' }, { id: 'cjeqtudhd000u0149skzacpq5', createdAt: '2018-03-14T08:31:57.000Z' }, { id: 'cje633goc03vn01309m2iocas', createdAt: '2018-02-27T20:07:48.000Z' }, { id: 'cje633gp803vw0130frck18wq', createdAt: '2018-02-27T20:07:48.000Z' }, { id: 'cje633gos03vs0130tzv7xfpe', createdAt: '2018-02-27T20:07:48.000Z' }, { id: 'cje633gmp03ve0130xu314ti4', createdAt: '2018-02-27T20:07:47.000Z' }, { id: 'cje633gnu03vj0130nnt4abin', createdAt: '2018-02-27T20:07:47.000Z' }, { id: 'cje633enx03uo0130qw0r35l6', createdAt: '2018-02-27T20:07:45.000Z' }, { id: 'cje633eot03uw0130r42aqbox', createdAt: '2018-02-27T20:07:45.000Z' }, { id: 'cje633eou03uy0130hdwg0uvn', createdAt: '2018-02-27T20:07:45.000Z' }, { id: 'cje633epl03v30130hsugr6vp', createdAt: '2018-02-27T20:07:45.000Z' }, { id: 'cje633eps03v70130xr826vf2', createdAt: '2018-02-27T20:07:45.000Z' } ] ```<issue_comment>username_1: ``` var sortedObj = objects.sort(function(a,b){ return new Date(b.createdAt) - new Date(a.createdAt); }); console.log(sortedObj) ``` Upvotes: 0 <issue_comment>username_2: Compare them as strings. `a.createdAt < b.createdAt? 1 : -1` will sort descending. `a.createdAt > b.createdAt? 1 : -1` sill sort ascendant ```js const sortObjects = () => { const objects = [ {id: "cje633i3v03wl0130lsse3zev", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cjeqtudhd000u0149skzacpq5", createdAt: "2018-03-14T08:31:57.000Z"}, {id: "cje633goc03vn01309m2iocas", createdAt: "2018-02-27T20:07:48.000Z"}, {id: "cje633k1z03ww0130ce27niez", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k3303x50130n1a7vnft", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k5b03xa0130m07ndgpn", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k2y03x10130q1076pq4", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633k0b03wq0130bmg0t6rd", createdAt: "2018-02-27T20:07:52.000Z"}, {id: "cje633gmp03ve0130xu314ti4", createdAt: "2018-02-27T20:07:47.000Z"}, {id: "cje633i2x03wd0130cqk5sdap", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633i1w03w60130rfpngz0b", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633i1u03w301307s44jfyy", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633i3i03wh0130f3t1iyl4", createdAt: "2018-02-27T20:07:49.000Z"}, {id: "cje633gp803vw0130frck18wq", createdAt: "2018-02-27T20:07:48.000Z"}, {id: "cje633gos03vs0130tzv7xfpe", createdAt: "2018-02-27T20:07:48.000Z"}, {id: "cje633gnu03vj0130nnt4abin", createdAt: "2018-02-27T20:07:47.000Z"}, {id: "cje633enx03uo0130qw0r35l6", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633eot03uw0130r42aqbox", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633eou03uy0130hdwg0uvn", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633epl03v30130hsugr6vp", createdAt: "2018-02-27T20:07:45.000Z"}, {id: "cje633eps03v70130xr826vf2", createdAt: "2018-02-27T20:07:45.000Z"}, ] objects.sort( (a, b) =>a.createdAt < b.createdAt? 1 : -1); console.log('objects',objects) } sortObjects() ``` Upvotes: 0 <issue_comment>username_3: You are returning `true` or `false` from the sort callback when [you should return a number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description). Aside from that you don't need `moment.js` to sort by those dates. You can just use: ``` objects.sort( (a, b) => new Date(a.createdAt) - new Date(b.createdAt)); ``` to sort in ascending order, or flip `a` and `b` to sort in descending order. Upvotes: 3 [selected_answer]<issue_comment>username_4: You could treat the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date strings as stings. They are sortable without using date methods, as long as they are un thge same time zone (which is actually zulu (UTC)). ```js const objects = [{ id: "cje633i3v03wl0130lsse3zev", createdAt: "2018-02-27T20:07:49.000Z" }, { id: "cjeqtudhd000u0149skzacpq5", createdAt: "2018-03-14T08:31:57.000Z" }, { id: "cje633goc03vn01309m2iocas", createdAt: "2018-02-27T20:07:48.000Z" }, { id: "cje633k1z03ww0130ce27niez", createdAt: "2018-02-27T20:07:52.000Z" }, { id: "cje633k3303x50130n1a7vnft", createdAt: "2018-02-27T20:07:52.000Z" }, { id: "cje633k5b03xa0130m07ndgpn", createdAt: "2018-02-27T20:07:52.000Z" }, { id: "cje633k2y03x10130q1076pq4", createdAt: "2018-02-27T20:07:52.000Z" }, { id: "cje633k0b03wq0130bmg0t6rd", createdAt: "2018-02-27T20:07:52.000Z" }, { id: "cje633gmp03ve0130xu314ti4", createdAt: "2018-02-27T20:07:47.000Z" }, { id: "cje633i2x03wd0130cqk5sdap", createdAt: "2018-02-27T20:07:49.000Z" }, { id: "cje633i1w03w60130rfpngz0b", createdAt: "2018-02-27T20:07:49.000Z" }, { id: "cje633i1u03w301307s44jfyy", createdAt: "2018-02-27T20:07:49.000Z" }, { id: "cje633i3i03wh0130f3t1iyl4", createdAt: "2018-02-27T20:07:49.000Z" }, { id: "cje633gp803vw0130frck18wq", createdAt: "2018-02-27T20:07:48.000Z" }, { id: "cje633gos03vs0130tzv7xfpe", createdAt: "2018-02-27T20:07:48.000Z" }, { id: "cje633gnu03vj0130nnt4abin", createdAt: "2018-02-27T20:07:47.000Z" }, { id: "cje633enx03uo0130qw0r35l6", createdAt: "2018-02-27T20:07:45.000Z" }, { id: "cje633eot03uw0130r42aqbox", createdAt: "2018-02-27T20:07:45.000Z" }, { id: "cje633eou03uy0130hdwg0uvn", createdAt: "2018-02-27T20:07:45.000Z" }, { id: "cje633epl03v30130hsugr6vp", createdAt: "2018-02-27T20:07:45.000Z" }, { id: "cje633eps03v70130xr826vf2", createdAt: "2018-02-27T20:07:45.000Z" }]; objects.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); console.log(objects); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` Upvotes: 1 <issue_comment>username_5: I can confirm to you that, **due the unstable sort algorithm used by Javascript you have to return 3 possible values**: 1,0 and -1. The sort order for elements with the same value is not guarantee. So a correct sort function call could be (in pure JavaScript) ``` var a = [{key:2},{key:1},{key:2},{key:3}] //sort in ascending order a = a.sort((a,b)=>{ return (ab) ? 1 : 0) }); ``` Upvotes: 0
2018/03/15
422
1,430
<issue_start>username_0: I want regular expression to find & replace first and third `rownum` word in the below-given string with the word `NONE`. ``` String str = "select dummy,rownum,rowid as \"rownum\",rownum as order_number from dual"; ``` I have tried below regular expression but it replacing the comma `,` before or after the word `rownum` ``` str = str.replaceAll("(?i)[^\"A-Z0-9]rownum[^$\"A-Z0-9]"," NONE ") ``` Actual Output : `select dummy NONE rowid as "rownum" NONE as order_number from dual` Expected Output : `select dummy,NONE, rowid as "rownum",NONE as order_number from dual`<issue_comment>username_1: You can try this, it's works ``` str = str.replace("rownum", "NONE"); str = str.replace("\"NONE\"", "\"rownum\""); ``` Upvotes: 0 <issue_comment>username_2: If you want to avoid replacing `"rownum"` because it is surrounded by `"` then you can use [look-around](https://www.regular-expressions.info/lookaround.html) mechanisms to forbid `"` before or after it like ``` String str = "select dummy,rownum,rowid as \"rownum\",rownum as order_number from dual"; str = str.replaceAll("(?i)(?!<\")\\brownum\\b(?!\")"," NONE "); System.out.println(str); ``` Output: `select dummy, NONE ,rowid as "rownum", NONE as order_number from dual` But that solution is valid only for this particular scenario. If you have other ones you should search for SQL parsers instead of RegEx. Upvotes: 2 [selected_answer]
2018/03/15
446
1,609
<issue_start>username_0: I'm trying to add a PayPal 'Donate' button to a React app built using Meteor. I've pasted the code generated by the PayPal website into a file DonateButton.jsx in my 'includes' directory: ``` import React from 'react'; function DonateButton() { return ( ![](https://www.paypalobjects.com/en_GB/i/scr/pixel.gif) ); } export default DonateButton; ``` When the project tries to compile I see this error: ``` Unterminated JSX contents ``` I notice that the img and input elements in the PayPal code are unterminated: `![]()` If I add a forward stroke to each element to close it like this `![]()` the error goes away and the button can be added to a page just like any other other React component: ``` import DonateButton from '../../components/DonateButton/DonateButton.jsx'; const Home = ({ history }) => ( ); ``` Everything looks fine, and clicking the button takes me to a PayPal donation form. My question is, does anybody know if this is OK or if there is some reason that the PayPal button needs to have unterminated elements? I've googled but not found anything.<issue_comment>username_1: All input fields need to be self closing tags. and the img tag `![]()` Like this: ``` ![](https://www.paypalobjects.com/en_GB/i/scr/pixel.gif) ``` There are no Gotcha's since this is JSX not actual HTML that will then get transpiled into JS that will render a correct HTML element to the DOM. Upvotes: 3 [selected_answer]<issue_comment>username_2: You need to terminate your tags. for example. You also need to do the same for your `![]()` tags Upvotes: 1
2018/03/15
292
1,016
<issue_start>username_0: So I have a for loop iterating through a large list (so taking long time). So I want it to call `helper.clear()`(session) every 200 second (when I am running the for loop). how should I do it? I see timer and thread.sleep() in other similar post, and not sure which is better, or if there's better answer for my case. It would be something similar to: ``` for(int a : aList) { //this for loop takes ~ 10 min //call session.clear() every 200 second when we are running the for loop } ```<issue_comment>username_1: All input fields need to be self closing tags. and the img tag `![]()` Like this: ``` ![](https://www.paypalobjects.com/en_GB/i/scr/pixel.gif) ``` There are no Gotcha's since this is JSX not actual HTML that will then get transpiled into JS that will render a correct HTML element to the DOM. Upvotes: 3 [selected_answer]<issue_comment>username_2: You need to terminate your tags. for example. You also need to do the same for your `![]()` tags Upvotes: 1
2018/03/15
233
804
<issue_start>username_0: I zipped some files, intrinsically important (old code, tune ideas, a few recording sessions). Put them on Google Drive. All the zips are corrupt. I just wanted to hear a tune from yesteryear now I realize it might all be gone. I've tried zip -F x.zip --out y.zip no dice. Any ideas?<issue_comment>username_1: All input fields need to be self closing tags. and the img tag `![]()` Like this: ``` ![](https://www.paypalobjects.com/en_GB/i/scr/pixel.gif) ``` There are no Gotcha's since this is JSX not actual HTML that will then get transpiled into JS that will render a correct HTML element to the DOM. Upvotes: 3 [selected_answer]<issue_comment>username_2: You need to terminate your tags. for example. You also need to do the same for your `![]()` tags Upvotes: 1
2018/03/15
532
2,002
<issue_start>username_0: My invocation of the `ask deploy` command failed because of the following error: ``` $ ask deploy [Error]: Invalid url info. Cannot find valid lambda function with the given name, nor find sourceDir as codebase path to create lambda function. ``` How can I fix this error?<issue_comment>username_1: For my problem, the solution was to clone my repository into a new directory and deploy from there. For example: ``` $ ask clone --skill-id <> -------------------- Clone Skill Project -------------------- Project directory for mySkill created at ./mySkill Skill schema for movie-go created at ./mySkill/skill.json Skill model for en-US created at ./mySkill/models/en-US.json Downloading Lambda functions... arn:aws:lambda:us-east-1:876716374418:function:ask-custom-mySkill-default download finished. $ cd mySkill/ $ ask deploy This skill project was cloned from a pre-existing skill. Deploying this project will - Update skill metadata (skill.json) - Update interaction model (models/\*.json) - Deploy the Lambda function(s) in ./lambda/\* ? Do you want to proceed with the above deployments? Yes -------------------- Update Skill Project -------------------- Skill Id: <> Skill deployment finished. Model deployment finished. Lambda deployment finished. ``` I found this solution suggested in a comment on [this intro to ASK CLI video](https://ru-clip.com/video/p-zlSdixCZ4/introduction-to-the-alexa-skills-kit-cli-ask-cli.html). Upvotes: 0 <issue_comment>username_2: The `.aws/config` file will look something like below. If you change the endpoint uri to match the lambda function ARN that you have in `skill.json`, the skill should deploy using `ask deploy` ``` { "deploy_settings": { "default": { "skill_id": "", "was_cloned": false, "merge": { "manifest": { "apis": { "custom": { "endpoint": { "uri": "" } } } } }, "in\_skill\_products": [] } } } ``` Upvotes: 1
2018/03/15
814
3,010
<issue_start>username_0: I’m trying to set up a performance timer in some Informix sprocs to see how long an insert is taking. I think I’m close, but I’m getting all zeros back. I'm using the code below in the real sprocs, too, which contain real insert statements (i.e., not just the sleep statement). It still returns all zeroes. It should be at least a few milliseconds, I would think. Anything jump out that I’m doing wrong? EDIT: I also tried using `sysdate` instead of `current` and still got all zeroes. Return value in C#: 0.00000 Test sproc: ``` CREATE PROCEDURE JayTest() returning char(10); define start datetime second to fraction(5); define end datetime second to fraction(5); let start = current; system "sleep 1"; -- stuff happens here that I want to time let end = current; return ((end - start)::interval second to fraction(5))::char(10); END PROCEDURE; ```<issue_comment>username_1: That's normal. Time is frozen for the duration of a stored procedure — CURRENT will be reported the same throughout the execution, even if you run `SYSTEM('sleep 100');` in the middle of the procedure. There isn't an easy workaround for this that I know of. Upvotes: 1 <issue_comment>username_2: It is the expected behavior according to the documentation (Informix 12.10): > > SQL is not a procedural language, and CURRENT might not execute in the lexical order of its position in a statement. You should not use > CURRENT to mark the start, the end, nor a specific point in the > execution of an SQL statement. > > > If you use the CURRENT operator in more than once in a single > statement, identical values might be returned by each instance of > CURRENT. You cannot rely on CURRENT to return distinct values each > time it executes. > > > The returned value is based on the system clock and is fixed when the > SQL statement that specifies CURRENT starts execution. For example, > any call to CURRENT from inside the SPL function that an EXECUTE > FUNCTION (or EXECUTE PROCEDURE) statement invokes returns the value of > the system clock when the SPL function starts. > > > [CURRENT Operator](https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_1455.htm "Informix Online Documentation") If it is acceptable to do the time keeping arithmetic with a 2nd process and ignoring the overheads, a possible solution could be something like this: ``` SELECT SYSDATE AS start FROM systables WHERE tabid = 1; PROCEDURE JayTest(); SELECT SYSDATE AS end FROM systables WHERE tabid = 1; ``` There is also the use of the column `sh_curtime` from the table `sysshmvals`in the `sysmaster` database as described in [How to obtain the actual date and time in a stored procedure](http://www-01.ibm.com/support/docview.wss?uid=swg21252128 "IBM Informix article") The column contains the actual system time but it only has a precision up to the second, so useless if we want intervals up to fractions of a second. Upvotes: 2
2018/03/15
602
2,137
<issue_start>username_0: I wrote this regular expression in JavaScript: ``` node_modules\/(?!react\-hot).*-loader.* ``` The idea is to match every string like `node_modules/babel-loader` or `node_modules/css-loader` but exclude `node_modules/react-hot-loader`. [Here is a regex101 link of this working](https://regex101.com/r/0zHgFc/1). (The context here is that I am writing a [Flowtype config file](https://flow.org/en/docs/config/ignore/)). I am trying to test the same RegEx in OCaml but I am not being successful: ``` # let regexp = Str.regexp "node_modules/(?!react-hot).*-loader.*";; val regexp : Str.regexp = # Str.string\_match regexp "node\_modules/babel-loader" 0 ;; - : bool = false # Str.string\_match regexp "node\_modules/react-hot-loader" 0 ;; - : bool = false ``` I don't understand why the `babel-loader` string is not matching the RegEx because this very same RegEx works in RegEx 101 for JavaScript RegExes. I understand that OCaml Regular Expressions do not follow the same standard as JavaScript Regular Expressions. However, after reading about OCaml Regular Expressions in the official documentation [here](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp), I couldn't find anything that could cause this difference in behavior.<issue_comment>username_1: Apparently, `!` is not a special character in OCaml regular expressions. So it seems you are using an unsupported feature. Upvotes: 2 <issue_comment>username_2: `Str` is a good old OCaml regexp library in the POSIX style syntax. It does not support PCRE and its extensions. There is no advantage to use `Str` today, except that it is included in the OCaml compiler. You may want to try `pcre-ocaml` <https://github.com/mmottl/pcre-ocaml> which fully supports PCRE. There is even another OCaml regexp library called `ocaml-re` <https://github.com/ocaml/ocaml-re> . It is newer and written purely in OCaml, and supports multiple regexp syntax flavors (POSIX, PCRE, glob), but it seems to me that the negation lookahead `(?!..)` is not supported for now (I tried to parse your regexp but it rejected `(?!..)` part). Upvotes: 0
2018/03/15
1,066
3,446
<issue_start>username_0: Having a problem where Mapbox using Leaflet is not displaying correctly in a modal. The map and marker are in the upper left and the rest of the tiles are blank. I have tried the code directly in a page and not a modal and it works... ```html #mapid { height: 300px; } var mymap = L.map('mapid').setView([<?= $return['latitude']; ?>, <?= $return['longitude']; ?>], 13); //var mymap = L.Map('mapid', { center: new L.LatLng(<?= $return['latitude']; ?>, <?= $return['longitude']; ?>]), zoom: 15, layers: [nexrad], zoomControl: true }); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access\_token=<?= $MapBoxToken ?>', { attribution: '&copy; <a href="http://mapbox.com">Mapbox</a>, &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>', maxZoom: 20, id: 'mapbox.streets', accessToken: '<?= $MapBoxToken ?>' }).addTo(mymap); var marker = L.marker([<?= $return['latitude']; ?>, <?= $return['longitude']; ?>]).addTo(mymap); ``` [![screen shot of modal and map](https://i.stack.imgur.com/0nfM6.png)](https://i.stack.imgur.com/0nfM6.png) [![Screen shot of modal and map with display style removed on map to show actual map.](https://i.stack.imgur.com/LT8xD.png)](https://i.stack.imgur.com/LT8xD.png)<issue_comment>username_1: As explained in the [linked post](https://stackoverflow.com/questions/36246815/data-toggle-tab-does-not-download-leaflet-map), having the map work when the browser window is resized is just a *symptom* of the issue. Leaflet listens to browser window resize event, and reads again the map viewport dimensions when it occurs, so that it can properly display tiles and center the view. Under the hood, Leaflet simply calls [`map.invalidateSize()`](http://leafletjs.com/reference-1.3.0.html#map-invalidatesize) on the resize event. So the proper solution for your case is **NOT** to have the browser window be resized, but to call `map.invalidateSize()`. And do that **NOT** after your map loads, but after your **modal** is opened, so that the map viewport now has its final dimensions. Since you added the Bootstrap tag to your question, I guess your modal is built using Bootstrap. In that case, you can listen to the [`"shown.bs.modal"`](https://getbootstrap.com/docs/3.3/javascript/#modals-events) event: ```js var map = L.map('map').setView([48.86, 2.35], 11); L.marker([48.86, 2.35]).addTo(map); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© [OpenStreetMap](http://osm.org/copyright) contributors' }).addTo(map); // Comment out the below code to see the difference. $('#myModal').on('shown.bs.modal', function() { map.invalidateSize(); }); ``` ```html Launch demo modal that contains the map container. × #### Modal title Close ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: The problem seem to with bootstap modal. Needed to add map.invalidateSize(); but within "shown.bs.modal", as per username_1 suggestion. ``` $('#myModal').on('shown.bs.modal', function() { map.invalidateSize(); }); ``` Note that the "map" in map.invalidateSize(); needs to be replace with the varable assigned in "var map = L.map()". In my original code in this post it was: ``` var mymap = L.map('mapid').setView([= $return['latitude']; ?, = $return['longitude']; ?], 13); ``` so I added: ``` $('#modalID').on('shown.bs.modal', function() { mymap.invalidateSize(); }); ``` Upvotes: 1
2018/03/15
887
1,872
<issue_start>username_0: when I try to convert a long number to a string and an array by using google dev tool, I got a problem. ``` let m=123000000000000000000000000000000 //1.23e+32 m=m+'good' //"1.23e+32good" // instead of "123000000000000000000000000000000good" ``` I plan to get the result of ["1","2","3","0",....."0"],but now I'm stuck. anyone know how to solve this? Thanks. --- **Intl.NumberFormat** is a good way, but when I try a long number: ``` Intl.NumberFormat('en-US', {useGrouping: false}).format(73167176531330624919225119674426574742355349194934) //"73167176531330600000000000000000000000000000000000" ``` ops. There is still an issue.<issue_comment>username_1: Use the `Intl.NumberFormat` API: ``` Intl.NumberFormat('en-US', {useGrouping: false}).format(123000000000000000000000000000000) ``` returns a string: ``` "123000000000000000000000000000000" ``` Upvotes: 1 <issue_comment>username_2: ``` function numberToDigitNumber(number) { let arrayOfNumber = number.toString().split('e+'); let digitsOfNumber = arrayOfNumber[0].replace('.' , ''); for(let i = 0; i < Number(arrayOfNumber[1]); i++) { digitsOfNumber += '0'; } return digitsOfNumber; } let num = 123000000000000000000000000000000; console.log(numberToDigitNumber(num) + ', instead of ' + num); // -> 123000000000000000000000000000000 instead of 123e+32 ``` Use this function, i created one for this problem. You can define a variable and assign its number value with this fuckion like this; ``` let myNumber = numberToDigitNumber(123000000000000); ``` Upvotes: 0 <issue_comment>username_3: Use a string instead: ```js //current result var m = 123000000000000000000000000000000; m = m + 'good'; console.log(m); //desired result var n = '123000000000000000000000000000000'; n = n + 'good'; console.log(n); ``` Upvotes: 1 [selected_answer]
2018/03/15
1,338
4,599
<issue_start>username_0: I have this class ``` public class Parent { [Key] public int Id { get; set; } public string Name { get; set; } public virtual Child Child { get; set; } } ``` and a child class ``` public class Child { [Key] [ForeignKey] public int ParentId { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } ``` The relation is such that a parent can have either 0 or 1 child. I've checked SO and found two solutions. ``` modelBuilder.Configurations.Add(new ParentChildMap()); // solution 1 class ParentChildMap : EntityTypeConfiguration { public ParentChildMap() { HasRequired(t => t.Parent). WithRequiredDependent(t => t.Child); } } // solution 2 class ParentChildMap : EntityTypeConfiguration { public ParentChildMap() { HasOptional(c => c.Parent) .WithRequired(c => c.Child); } } ``` *And the thing is, they are both working*! But the problem is, **I am not sure which one is correct.** Which one is providing me the mapping that one parent can have only 0 or 1 child. And then, what is the other one saying?<issue_comment>username_1: > > And the thing is, they are both working! But the problem is, I am not > sure which one is correct? > > > Yes! your both approach is incorrect (Credit goes to username_3). Because: Your solution 1 : ``` HasRequired(t => t.Parent).WithRequiredDependent(t => t.Child); ``` represents Parent 1 <--> 1 Child relationship (parent must have always 1 child). Your solution 2: ``` HasOptional(c => c.Parent).WithRequired(c => c.Child); ``` represents Parent 0..1 <--> 1 Child relationship (child can have 0 or 1 parent, parent must have always 1 child), i.e. the opposite of what you want. Your Fluent API should be as follows: ``` modelBuilder.Entity() .HasOptional(p => p.Child) // Mark Child property optional in Parent entity .WithRequired(c => c.Parent); // mark Parent property as required in Child entity. Cannot save Child without Parent ``` Moreover you can also configure One-to-One or One-to-Zero relationship with Data Annotation as follows: Child class should be as follows: ``` public class Child { [Key,ForeignKey("Parent")] public int ParentId { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } ``` Upvotes: 2 <issue_comment>username_2: you don't need to decorate `ForeignKey` attribute. if you want to have a 1 to 0 relation, a side of relation must be optional (ex: HasOptional), like the following code: ``` public class Parent { [Key] public int Id { get; set; } public string Name { get; set; } public virtual Child Child { get; set; } } public class Child { [Key] public int Id { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } public class ParentMap : EntityTypeConfiguration { public ParentMap () { HasOptional(t => t.Child).WithRequired(t => t.Parent); } } ``` now when you add a new parent to the database does not need to add a child because it is optional but when you want to add a new child to the database the child `Id` must equal with parent `Id`. Upvotes: 1 <issue_comment>username_3: Let add the related entities to the desired relationship along with their cardinality: **Parent 1 <--> 0..1 Child** You can read it this way: (1) **--> 0..1 Child** means that each Parent can have 0 or 1 Child, or in other words, the `Child` property of the `Parent` entity is **optional** (2) **Parent 1 <--** means that each Child always have 1 Parent, or in other words, the `Parent` property of the `Child` entity is **required**. The fluent configuration which corresponds to the above from `Child` side is: ``` HasRequired(c => c.Parent).WithOptional(p => p.Child); ``` or alternatively from `Parent` side: ``` HasOptional(p => p.Child).WithRequired(c => c.Parent); ``` These two are the correct ones and fully equivalent - you can use one or the another depending of whether you start the configuration from `Child` (as in your sample) or from `Parent`. To avoid discrepancies, never do both. *Why both your current solutions are incorrect?* Because: (solution 1) ``` HasRequired(t => t.Parent).WithRequiredDependent(t => t.Child); ``` represents **Parent 1 <--> 1 Child** relationship (parent must have always 1 child). (solution 2) ``` HasOptional(c => c.Parent).WithRequired(c => c.Child); ``` represents **Parent 0..1 <--> 1 Child** relationship (child can have 0 or 1 parent, parent must have always 1 child), i.e. the opposite of what you want. Upvotes: 4 [selected_answer]
2018/03/15
1,312
4,405
<issue_start>username_0: I am looking for a pythonic/elegant way to transform my list of dict (e.g. `LD`) into a aggregated list of dict (e.g. `DD`). The dict in `LD` have `id`, `result`, and `count` as keys, and there can be multiple dict's with the same `id` with different `result`s. The resulting dict `DD` should aggregate the `id`'s together and display all the `result`s together (in `results`). Here is an example: ``` LD = [ {'id':1, 'result': 'passed', 'count': 10}, {'id':1, 'result': 'failed', 'count': 20}, {'id':2, 'result': 'failed', 'count': 100} ] ``` Here is the output I want ``` DD = [ {'id':1, 'results': {'passed': 10, 'failed': 20}}, {'id':2, 'results': {'passed': 10}} ] ``` I could create a for loop and a output dict to process each items in `LD`, but am wondering if this can be achieved in a one-liner using things like `zip`, etc. Thanks in advance!<issue_comment>username_1: > > And the thing is, they are both working! But the problem is, I am not > sure which one is correct? > > > Yes! your both approach is incorrect (Credit goes to username_3). Because: Your solution 1 : ``` HasRequired(t => t.Parent).WithRequiredDependent(t => t.Child); ``` represents Parent 1 <--> 1 Child relationship (parent must have always 1 child). Your solution 2: ``` HasOptional(c => c.Parent).WithRequired(c => c.Child); ``` represents Parent 0..1 <--> 1 Child relationship (child can have 0 or 1 parent, parent must have always 1 child), i.e. the opposite of what you want. Your Fluent API should be as follows: ``` modelBuilder.Entity() .HasOptional(p => p.Child) // Mark Child property optional in Parent entity .WithRequired(c => c.Parent); // mark Parent property as required in Child entity. Cannot save Child without Parent ``` Moreover you can also configure One-to-One or One-to-Zero relationship with Data Annotation as follows: Child class should be as follows: ``` public class Child { [Key,ForeignKey("Parent")] public int ParentId { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } ``` Upvotes: 2 <issue_comment>username_2: you don't need to decorate `ForeignKey` attribute. if you want to have a 1 to 0 relation, a side of relation must be optional (ex: HasOptional), like the following code: ``` public class Parent { [Key] public int Id { get; set; } public string Name { get; set; } public virtual Child Child { get; set; } } public class Child { [Key] public int Id { get; set; } public string Name { get; set; } public virtual Parent Parent { get; set; } } public class ParentMap : EntityTypeConfiguration { public ParentMap () { HasOptional(t => t.Child).WithRequired(t => t.Parent); } } ``` now when you add a new parent to the database does not need to add a child because it is optional but when you want to add a new child to the database the child `Id` must equal with parent `Id`. Upvotes: 1 <issue_comment>username_3: Let add the related entities to the desired relationship along with their cardinality: **Parent 1 <--> 0..1 Child** You can read it this way: (1) **--> 0..1 Child** means that each Parent can have 0 or 1 Child, or in other words, the `Child` property of the `Parent` entity is **optional** (2) **Parent 1 <--** means that each Child always have 1 Parent, or in other words, the `Parent` property of the `Child` entity is **required**. The fluent configuration which corresponds to the above from `Child` side is: ``` HasRequired(c => c.Parent).WithOptional(p => p.Child); ``` or alternatively from `Parent` side: ``` HasOptional(p => p.Child).WithRequired(c => c.Parent); ``` These two are the correct ones and fully equivalent - you can use one or the another depending of whether you start the configuration from `Child` (as in your sample) or from `Parent`. To avoid discrepancies, never do both. *Why both your current solutions are incorrect?* Because: (solution 1) ``` HasRequired(t => t.Parent).WithRequiredDependent(t => t.Child); ``` represents **Parent 1 <--> 1 Child** relationship (parent must have always 1 child). (solution 2) ``` HasOptional(c => c.Parent).WithRequired(c => c.Child); ``` represents **Parent 0..1 <--> 1 Child** relationship (child can have 0 or 1 parent, parent must have always 1 child), i.e. the opposite of what you want. Upvotes: 4 [selected_answer]
2018/03/15
1,460
5,927
<issue_start>username_0: I have a list of files in a target folder: Example/HUVEC.csv Example/HUVEC-1.csv Example/HUVEC-3.3.2n-1.csv (random hash) Example/Endo1.csv What I'd like is to be able to create a folder called "HUVEC" if there are files that start with "HUVECxxx" in the "Example" Folder and then move the files that starts with "HUVECxxx" to the "HUVEC" Folder. Here's what I have so far, having been modified from the simple version (see below) ``` set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?" tell application "Finder" set fileList to files of mgFilesFolder repeat with aFile in fileList set prefix to name of aFile if prefix starts with "HUVEC" and (exists folder (HUVEC_folder)) then move aFile to HUVEC_folder else set HUVEC_folder to make new folder in mgFilesFolder with properties {name:"HUVEC"} end if end repeat repeat with aFile in fileList set prefix to name of aFile if prefix starts with "HUVEC" then move aFile to HUVEC_folder end repeat end tell ``` A more simplistic version works for one file ``` set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?" tell application "Finder" set fileList to files of mgFilesFolder repeat with aFile in fileList set prefix to name of aFile if prefix starts with "HUVEC" and set HUVEC_folder to make new folder in mgFilesFolder with properties {name:"HUVEC"} end if end repeat repeat with aFile in fileList set prefix to name of aFile if prefix starts with "HUVEC" then move aFile to HUVEC_folder end repeat end tell ``` but the issue with multiple files I'm quite certain is that if the folder already exists then the script fails. Basically I *think* the biggest issue is how to check if a folder exists that otherwise should be created! Thanks for any help, still relatively new at Applescript.<issue_comment>username_1: Instead of manually looping through files, you can take advantage of AppleScript's keyword `every`, which: > > specifies every object in a container ([ref.](https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_keywords.html)) > > > Here's what the script looks like when you employ this handy little feature: ``` property prefix : "HUVEC" -- The prefix for file sorting set mgFilesFolder to choose folder with prompt "Where are the files stored?" tell application "Finder" -- Retrieve all files that have names -- beginning with the prefix set fileList to every file of folder mgFilesFolder ¬ whose name starts with prefix if fileList is {} then return "No files to move." -- Nothing to do -- Check to see if a folder with the right -- name exists; if not, create it. if not (exists folder named prefix in folder mgFilesFolder) ¬ then make new folder in folder mgFilesFolder ¬ with properties {name:prefix} set prefix_folder to the ¬ folder named prefix in the ¬ folder mgFilesFolder -- Move the files into the folder and return -- a list of file references for them return move the fileList to the prefix_folder end tell ``` I've put comments throughout the code to explain what each section of the script does. But, not once did I need to use a `repeat` loop. Your other issue was in trying to combine the checks for both file name and the existence of the destination folder into a single command, which got repeated over and over in the `repeat` loop. I kept everything separate so each line of code knows what it's doing and will do it well. If something doesn't work, it's easy to pinpoint where the problem arises: 1. Get the relevant files. 2. If there are none, stop the script—no need to keep going. 3. If the destination folder doesn't exist, create it. 4. Get the reference for the destination folder. 5. Move the files into the destination folder. Done. --- ### Addendum: Bash...? Have you thought about using bash scripting for this sort of task ? It's about ten-thousand times faster for large numbers of files, and here's an example of code that accomplishes what you want: ``` [[ -d HUVEC ]] && mv HUVEC*.csv HUVEC || { mkdir HUVEC && mv HUVEC*.csv HUVEC; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: CJK - I've made some modifications but still there is a minor problem. The code below introduces another variable, `prefix1`, with my other start string `"ENDO"`. The script complies and runs and goes so far as to create the `prefix1` folder, however the `"ENDO"` file itself fails to move with the two `return move...` commands at the end of the script. I've confirmed that the order matters, i.e. if I switch the order of the lines ``` return move the fileList1 to the prefix_folder1 return move the fileList to the prefix_folder ``` then the `ENDO` files are appropriately moved but the `HUVEC` files fail to move. ``` set prefixes to {"HUVEC", "ENDO"} set mgFilesFolder to choose folder with prompt "Where are the files stored?" tell application "Finder" to ¬ repeat with prefix in prefixes set fileList to every file of folder mgFilesFolder ¬ whose name starts with prefix if (count fileList) is not 0 then if not (exists folder named prefix in folder mgFilesFolder) ¬ then make new folder in folder mgFilesFolder ¬ with properties {name:prefix} set prefix_folder to the folder named prefix ¬ in the folder mgFilesFolder move the fileList to the prefix_folder end if end repeat ``` Upvotes: 0
2018/03/15
507
1,662
<issue_start>username_0: Each record in the **movies** table has: **user** - user id **movie** - movie id **rating** - user rating for the movie User **1** wants to receive recommendations (list of movies) from the group of users **2,3,4,5,6,7**. The recommended movies should NOT be found among the movies of user 1 and should have an average rating in the group not less than **3**. At the same time, the movies that were watched by less than 3 people from the group can not be recommended. Here's my option, but it does not reflect the last requirement: ``` SELECT t2.movie FROM movies t1 INNER JOIN movies t2 ON t1.user = 1 AND t2.user IN(2,3,4,5,6,7) AND t2.movie NOT IN ( SELECT movie FROM movies WHERE user = 1 ) GROUP BY(t2.movie) HAVING AVG(t2.rating)>=3 ```<issue_comment>username_1: ``` SELECT t2.movie FROM movies t1 INNER JOIN movies t2 ON t1.user = 1 AND t2.user IN(2,3,4,5,6,7) AND t2.movie NOT IN ( SELECT movie FROM movies WHERE user = 1 ) WHERE (select count(distinct t3.user) from movies t3 where t3.movie = t2.movie) >= 3 GROUP BY(t2.movie) HAVING AVG(t2.rating)>=3 ``` Upvotes: 0 <issue_comment>username_2: Does this not work? ``` SELECT t2.movie FROM movies t1 INNER JOIN movies t2 ON t1.user = 1 AND t2.user IN(2,3,4,5,6,7) AND t2.movie NOT IN ( SELECT movie FROM movies WHERE user = 1 ) GROUP BY(t2.movie) HAVING AVG(t2.rating)>=3 AND COUNT(DISTINCT t2.user) >= 3 ``` Upvotes: 3 [selected_answer]
2018/03/15
918
3,418
<issue_start>username_0: I understand that tuple is immutable. Therefore, I am trying to convert the tuple to a list first then delete the item. My original tuple is `('monkey', 'camel', ('python', 'elephant', 'penguin'))`. It's a tuple including another tuple inside. I want to delete `'python'`. Firstly I defined a flatten() function (I found it from the forum): ``` def flatten(foo): for x in foo: if hasattr(x,'__iter__') and not isinstance(x,str): for y in flatten(x): yield y else: yield x ``` Then define the delete function: ``` def tuple_without(original_tuple,item_remove): lst=flatten(list(original_tuple)) # convert the original tuple to list and flatten it return list(x for x in lst if x !=item_remove) print(tuple_without(new_zoo,'python')) ``` It works and the results shows as: ``` ['monkey', 'camel', 'elephant', 'penguin'] ``` I would like to know if there is any better and more Pythonic solution here.<issue_comment>username_1: You could create a recursive function as below ``` def removeItem(myTuple, item): myList = list(myTuple) for index, value in enumerate(myList): if isinstance(value, tuple): myList[index] = removeItem(value, item) if value==item: del myList[index] return myList ``` This just loops through the tuple, converting it to a list, re-calling itself on finding another nested tuple and deleting the found item. This also keeps the nested structure, no flattening required! Also, I just noticed that your code above does not actually use the new list from `list(original_tuple)` list. Instead, it is just flattened and then a new tuple is made using a tuple comprehension with the contents of the flattened tuple (which is now a generator). So at no point in your example is the contents of a list ever edited (just to clarify things a bit). So in the line `lst=flatten(list(original_tuple))`, you do not need the list function. Upvotes: 1 <issue_comment>username_2: This code can do the job for you: ``` def exclude_words(the_tuple, exclude=[]): new_list = [] for value in the_tuple: if type(value) == tuple: new_list.extend(exclude_words(value, exclude)) elif not value in exclude: new_list.append(value) return new_list ``` Upvotes: 1 <issue_comment>username_3: There is no need to turn the tuple into a list before you flatten it. As this flatten() version is really a generator of all the values, you can just use its result in the generator expression: ``` def tuple_without(original_tuple,item_remove): return list(x for x in flatten(original_tuple) if x !=item_remove) ``` You could remove the `list()` call here as well; if you need a list then you can turn it into one where you call this function, and if you only need to loop over it there you can just use the returned generator expression. Upvotes: 1 <issue_comment>username_4: For loop the tuple and check if an item is a tuple. Append the item to the list if its not a tuple. If the item is a tuple then for loop that tuple for the item you want and append to list what you want from that tuple. ``` a = (1,2,(3,4)) b = [ ] for x in a: if type(x) is tuple: for y in x: if y != 3: b.append(y) else: b.append(x) print(b) >>[1,2,4] ``` Upvotes: 0
2018/03/15
835
2,926
<issue_start>username_0: I ran a matrix multiplication code serially and parallelized.There was no significant improvement with the parallel version. ``` dimension =4000; //#pragma omp parallel for shared(A,B,C) private(i,j,k) { for(int i=0; i ``` Output: time ./a.out ``` real 4m58,760s user 4m58,706s sys 0m0,036s ``` for serial code (I put the #pragma... in a comment,rest of code is same) I got following output ``` real 4m51,240s user 4m51,210s sys 0m0,024s ```<issue_comment>username_1: You could create a recursive function as below ``` def removeItem(myTuple, item): myList = list(myTuple) for index, value in enumerate(myList): if isinstance(value, tuple): myList[index] = removeItem(value, item) if value==item: del myList[index] return myList ``` This just loops through the tuple, converting it to a list, re-calling itself on finding another nested tuple and deleting the found item. This also keeps the nested structure, no flattening required! Also, I just noticed that your code above does not actually use the new list from `list(original_tuple)` list. Instead, it is just flattened and then a new tuple is made using a tuple comprehension with the contents of the flattened tuple (which is now a generator). So at no point in your example is the contents of a list ever edited (just to clarify things a bit). So in the line `lst=flatten(list(original_tuple))`, you do not need the list function. Upvotes: 1 <issue_comment>username_2: This code can do the job for you: ``` def exclude_words(the_tuple, exclude=[]): new_list = [] for value in the_tuple: if type(value) == tuple: new_list.extend(exclude_words(value, exclude)) elif not value in exclude: new_list.append(value) return new_list ``` Upvotes: 1 <issue_comment>username_3: There is no need to turn the tuple into a list before you flatten it. As this flatten() version is really a generator of all the values, you can just use its result in the generator expression: ``` def tuple_without(original_tuple,item_remove): return list(x for x in flatten(original_tuple) if x !=item_remove) ``` You could remove the `list()` call here as well; if you need a list then you can turn it into one where you call this function, and if you only need to loop over it there you can just use the returned generator expression. Upvotes: 1 <issue_comment>username_4: For loop the tuple and check if an item is a tuple. Append the item to the list if its not a tuple. If the item is a tuple then for loop that tuple for the item you want and append to list what you want from that tuple. ``` a = (1,2,(3,4)) b = [ ] for x in a: if type(x) is tuple: for y in x: if y != 3: b.append(y) else: b.append(x) print(b) >>[1,2,4] ``` Upvotes: 0
2018/03/15
891
3,141
<issue_start>username_0: In our project we have base css file which contains classes for most of the common css properties (like `.p10` -> `padding:10px`, `vam` -> `vertical-align:middle`). If I use many of these classes in a single DOM, does it lead to any performance impact?<issue_comment>username_1: You're adding 7 bytes of HTML, this is effectively 0 impact on your site, and the CSS processes that so fast again, effectively 0 impact on your site. There are plenty of CSS frameworks that utilize a modular approach like that, and your code may look something like this: ``` .p10 { padding: 10px; } .p10_20 { padding: 10px 20px; } .vam { vertical-align: middle; } .d_ib { display: inline-block; } .internal { background: #fff; } .blk { color: #000; } .bigshadow { box-shadow: 0 10px 15px -8px rgba(0,0,0,.5); } ``` Without using a framework, (or developing an internal one) you may want something a little less modular, and more element oriented: ``` ``` with the accompanying CSS: ``` /* This or main > div */ main .container { padding: 10px; display: inline-block; color: #000; box-shadow: 0 10px 15px -8px rgba(0,0,0,.5); } .container.accent { padding: 10px 20px; border: 2px solid #0095ee; } ``` To reiterate an answer to the question at hand, there is effectively **zero** impact of stacking classes on elements. Upvotes: 3 [selected_answer]<issue_comment>username_2: It does not lead to any performance impact (it may be even faster than constructing deeply nested selectors). Moreover, the method that you are asking about has even its own name - **atomic css** and apart from what @username_1 said it is not always that bad as it allows for easy customization and is widely used in many CSS libraries. Upvotes: 2 <issue_comment>username_3: Even though this kind of notation doesn't have impact on the speed of processing such monstrosity, there is a **massive** impact in terms of readability. It's not going to be long before you start having lines that span more than 160 characters. Been there, seen it, didn't do it, and you shouldn't do it either because readability of such code suffers too much. Imagine having 10 `div`s one by line with 200+ characters describing how you want the to look. It completely overshadows the structure of your HTML and makes it really hard to maintain such a beast. Atomic CSS used with `@apply` with TailwindCSS nad PostCSS for empty/unused classes elimination is the way to go. If you would like to learn more about it, I have a repository that shows the problem: <https://github.com/padcom/tailwind-example/blob/inline-apply-cmp/src/App.vue> vs <https://github.com/padcom/tailwind-example/blob/master/src/App.vue> There's also been a concern regarding the size of produced output. [README.md](https://github.com/padcom/tailwind-example/blob/inline-apply-cmp/README.md) shows the comparison between different styles and compression methods. As it was to be expected, the compressed size (so the way it will actually be transferred over the wire) with `@apply` instead of inlining all the classes rules in favor of using cleaner code. Upvotes: 0
2018/03/15
453
1,522
<issue_start>username_0: I know it is possible to access the docker api and the following command works just fine: `curl -s --unix-socket /var/run/docker.sock http:/v1.24/containers/$HOSTNAME/json | jq -r '.Image'` However, I would really like avoid exposing the `docker.sock` to the container itself because it is part of a CI build. Is there any other way of retrieving the container image id / hash (i.e. `2acdef41a0c`) from within a container itself without exposing the `docker.sock` and making a `curl` request to it? Maybe something like what's shown here [Docker, how to get container information from within the container](https://stackoverflow.com/a/25729598/393805) ?<issue_comment>username_1: The following command run inside the container should give you the container ID or the docker image hash- `cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3 | cut -c 1-12` Upvotes: -1 <issue_comment>username_2: This sets IMAGE env var inside a container: ``` docker run --rm -it -e IMAGE=$(docker images ubuntu:bionic --format {{.ID}}) ubuntu:bionic ``` Upvotes: 2 <issue_comment>username_3: The same as @Shayk response, but using docker SDK (python) <https://docker-py.readthedocs.io/> ``` import docker .... client = docker.from_env() image_name = "ubuntu:bionic" image_id = str(client.images.get(image_name).id).split(":")[1][:12] container = client.containers.run(image_name, network = "host", environment=[f"IMAGE_ID={image_id}",f"IMAGE_NAME={image_name}"], detach=True) ``` Upvotes: 0
2018/03/15
905
3,394
<issue_start>username_0: I have two `JFrames`. `AddSongFrame` takes in the user input through `jTextFields` and `MusicPlayerandLibraryForm` updates the `jList` with the user input. However, I have run into a problem with adding elements to the `jList`. At the line ``` MusicPlayerAndLibraryForm mplf = new MusicPlayerAndLibraryForm(); ``` it seems that the `JFrame` is not updating the `jList`. It clears the `jList` and then adds the `songName` to the `jList`. How can I access the `JFrame` in a way where it doesn't clear the `jList` when the user accesses another `jFrame`? ``` public class AddSongFrame extends javax.swing.JFrame { ArrayList songs = new ArrayList(); ArrayList songFileLibrary = new ArrayList(); DefaultListModel dlm = new DefaultListModel(); int currentIndex = 0; public AddSongFrame() { initComponents(); } private void jButtonBrowseFilesActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fileBrowser = new JFileChooser(); fileBrowser.showOpenDialog(null); File f = fileBrowser.getSelectedFile(); String fileName = f.getAbsolutePath(); jTextFieldFileName.setText(fileName); } private void jButtonAddSongActionPerformed(java.awt.event.ActionEvent evt) { String fileName = jTextFieldFileName.getText(); String songName = jTextFieldSongName.getText(); String songGenre = jTextFieldSongGenre.getText(); String songArtist = jTextFieldArtist.getText(); Song song = new Song(songName, fileName, songGenre, songArtist); Song songFiles = new Song(fileName,songName, songGenre,songArtist); songs.add(song); songFileLibrary.add(songFiles); updatejListMusicLibrary(); } private void updatejListMusicLibrary() { MusicPlayerAndLibraryForm mplf = new MusicPlayerAndLibraryForm(); MusicPlayerAndLibraryForm.getjListMusicLibrary().setModel(dlm); mplf.setDlmMain(dlm); this.setVisible(false); mplf.setVisible(true); } ```<issue_comment>username_1: You can make the list static and then create a method in your JFrame class which calls the static list and adds to it, when the button or any other thing is pressed in the JFrame... Hope this Helps..... Upvotes: -1 <issue_comment>username_2: Your problem is more than likely here: ``` MusicPlayerAndLibraryForm mplf = new MusicPlayerAndLibraryForm(); ``` This is being called everytime you click your `JButton` and it create a new instance of `MusicPlayerAndLibraryForm` everytime. You need to create an instance of this class only once, then use that instance to update the `JList`, however this line: ``` MusicPlayerAndLibraryForm.getjListMusicLibrary() ``` Tells me that `getjListMusicLibrary()` is a `static` method and shows an problem of design in your program. However as I already said in the comments above, avoid [the use of multiple JFrames](https://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-or-bad-practice) and use [`Dialogs`](https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html) or a [`CardLayout`](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html#card) for asking user for information and then use it to update the single instance of the `JList` in the `JFrame`. As I said, also avoid [extending JFrame](https://stackoverflow.com/questions/22003802/extends-jframe-vs-creating-it-inside-the-program) and create an instance of it inside your class. Upvotes: 2 [selected_answer]
2018/03/15
511
1,519
<issue_start>username_0: I want to delete all the same cells but because of changes in my list the length is changing as well so instead of 9 loops it makes 5. For the input: `apple,banana,coconut,apple,banana,coconut,apple,banana,coconut(str)` I expect the output: `apple, banana, coconut (list)` but I got: `banana, apple, banana, coconut` I tried to make another list so it won't change the original list length but as you can understand it hasn't helped. Can you help, please? P.S I made the string to a list(list\_of\_products) ``` just_a_list = list_of_products for product in just_a_list: if list_of_products.count(product) > 1: list_of_products.remove(product) ```<issue_comment>username_1: Just use a [`set`](https://docs.python.org/3/tutorial/datastructures.html#sets), which by definition, is: > > an unordered collection with no duplicate elements > > > ``` x = ['apple','banana','coconut','apple','banana','coconut','apple','banana','coconut'] print(set(x)) ``` Output: ``` {'apple', 'coconut', 'banana'} ``` If you want it as a list: ``` >>> unique = list(set(x)) ['coconut', 'apple', 'banana'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The easiest way to achieve this is simply converting the list to a set and then to a list again. ``` list_of_products = ["apple", "banana", "coconut", "apple", "banana", "coconut", "apple", "banana", "coconut"] products = list(set(list_of_products)) # products = ['coconut', 'apple', 'banana'] ``` Upvotes: 2
2018/03/15
642
1,550
<issue_start>username_0: I am using Azure table storage which provides very less options to query the table storage. I have my RowKey as a composed key in the following way: ``` "b844be0d-2280-49f7-9ad7-58c36da80d22_2518908336099522182" ,"b844be0d-2280-49f7-9ad7-58c36da80d22_2518908336099522183" ,"b844be0d-2280-49f7-9ad7-58c36da80d22_2518908336099522184" ,"b844be0d-2280-49f7-9ad7-58c36da80d22_2518908336099522185" ``` The first part is a Guid, and the second part after the separator(\_) is the timeticks. I want to search on azure storage using its operators for rowkeys ending with "2518908336099522182" There is no "Contains" operator that can help here, What do i do to get it working for "EndsWith" kind of filtering?<issue_comment>username_1: Just use a [`set`](https://docs.python.org/3/tutorial/datastructures.html#sets), which by definition, is: > > an unordered collection with no duplicate elements > > > ``` x = ['apple','banana','coconut','apple','banana','coconut','apple','banana','coconut'] print(set(x)) ``` Output: ``` {'apple', 'coconut', 'banana'} ``` If you want it as a list: ``` >>> unique = list(set(x)) ['coconut', 'apple', 'banana'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The easiest way to achieve this is simply converting the list to a set and then to a list again. ``` list_of_products = ["apple", "banana", "coconut", "apple", "banana", "coconut", "apple", "banana", "coconut"] products = list(set(list_of_products)) # products = ['coconut', 'apple', 'banana'] ``` Upvotes: 2
2018/03/15
420
1,262
<issue_start>username_0: Apologies; I'm new to Regex; is it possible to develop an expression that will match strings that has a list of adjacent numbers (that don't have to be ordered) where the count of the numbers equals the expression 2n+2? So " asdasd 02" would match because when n is 0, 2\*0+2=2; similarly "asdasd 098675asas" would match because when n is 2, the 2\*2+2 = 6 and the string has 6 numbers. Sorry for any clumsy language!<issue_comment>username_1: Just use a [`set`](https://docs.python.org/3/tutorial/datastructures.html#sets), which by definition, is: > > an unordered collection with no duplicate elements > > > ``` x = ['apple','banana','coconut','apple','banana','coconut','apple','banana','coconut'] print(set(x)) ``` Output: ``` {'apple', 'coconut', 'banana'} ``` If you want it as a list: ``` >>> unique = list(set(x)) ['coconut', 'apple', 'banana'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The easiest way to achieve this is simply converting the list to a set and then to a list again. ``` list_of_products = ["apple", "banana", "coconut", "apple", "banana", "coconut", "apple", "banana", "coconut"] products = list(set(list_of_products)) # products = ['coconut', 'apple', 'banana'] ``` Upvotes: 2
2018/03/15
392
1,230
<issue_start>username_0: I got a file on the form ``` org.apache.spark.rdd.RDD[(String, Array[String])] = MapPartitionsRDD[364] ``` Which is a file where i got a couple of keys (`string`), and many values per key (`Array[String]`). I want to be able to count the number of each occurrence in the Value for each separate string. I have tried different approaches but I haven't found anything that works yet.<issue_comment>username_1: Just use a [`set`](https://docs.python.org/3/tutorial/datastructures.html#sets), which by definition, is: > > an unordered collection with no duplicate elements > > > ``` x = ['apple','banana','coconut','apple','banana','coconut','apple','banana','coconut'] print(set(x)) ``` Output: ``` {'apple', 'coconut', 'banana'} ``` If you want it as a list: ``` >>> unique = list(set(x)) ['coconut', 'apple', 'banana'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The easiest way to achieve this is simply converting the list to a set and then to a list again. ``` list_of_products = ["apple", "banana", "coconut", "apple", "banana", "coconut", "apple", "banana", "coconut"] products = list(set(list_of_products)) # products = ['coconut', 'apple', 'banana'] ``` Upvotes: 2
2018/03/15
1,845
6,333
<issue_start>username_0: Apologies upfront if I fail to use the correct SQL terminology/approach in this issue. What I'm looking to do is write a SQL query (using SQL Server 2008R2) for an e-commerce system which will collate order data from one table and customer data from a second table. My SQL skills go so far as `JOIN`s, and I'm fairly certain this will involve something more comprehensive like sub-queries as the customer data storage isn't (what I'd call) straight forward. I'm not sure what approach to take. *Note, this is a third party system so I have no control over the database schema.* I have 2 tables: **Orders**: ``` OrderId | OrderValue -------------------- 1 | 123 2 | 338 3 | 500 ``` **CustomerData**: ``` OrderId | Alias | Value ------------------------------- 1 | firstName | John 1 | lastName | Smith 1 | city | Boston 1 | zip | 12345 1 | address1 | Someplace 2 | firstName | Jane 2 | lastName | Doe 2 | city | New Orleans 2 | zip | 23456 2 | address1 | 1 Brookland Avenue 3 | firstName | Eric 3 | lastName | Black 3 | city | Chicago 3 | zip | 34567 3 | address1 | Apartment 356 ``` What I need to do is generate a query to output the following: ``` OrderId | OrderValue | FirstName | LastName | Address ------------------------------------------------------------------------------------ 1 | 123 | John | Smith | Someplace, Boston, 12345 2 | 338 | Jane | Doe | 1 Brookland Avenue, New Orleans, 23456 3 | 500 | Eric | Black | Apartment 356, Chicago, 34567 ``` The 'Address' field needs to be made up of the values from the CustomerData table where the Alias values are 'address1', 'city' and 'zip', concatenated as a comma-separated string. These fields will always be present in the CustomerData table but won't necessarily be in the same order, and won't be in the order in which they're needed in the output data-set - so I'll need to explicitly concatenate them as 'address1, city, zip'. I'm struggling with the fact that the CustomerData values need to be selected based on the alias field, they're not table columns, which would have made life much simpler. Could anyone advise how to go about this? The fact I've not created a starting query isn't due to laziness or lack of willing, I'm just really unsure how to get those CustomerData values through correctly, even as a sub-query. Many thanks.<issue_comment>username_1: This is how you summarize `customers`: ``` select orderid, max(case when alias = 'firstName' then value end) as firstname, max(case when alias = 'lastName' then value end) as lastname, (max(case when alias = 'address1' then value end) + ',' + max(case when alias = 'city' then value end) + ',' + max(case when alias = 'zip' then value end) ) as address from customers c group by orderid; ``` The rest of the query is just a `join` to `orders`. You specify in the question that you know how to do that. Actually, the `orders` could be a little tricky: ``` select c.orderid, o.ordervalue, max(case when c.alias = 'firstName' then c.value end) as firstname, max(case when c.alias = 'lastName' then c.value end) as lastname, (max(case when c.alias = 'address1' then c.value end) + ',' + max(case when c.alias = 'city' then c.value end) + ',' + max(case when c.alias = 'zip' then c.value end) ) as address from customers c join orders o on o.orderid = c.orderid group by o.orderid, o.ordervalue; ``` > > **EDIT:** One comma added to the end of the first line in the second query > > > Upvotes: 3 [selected_answer]<issue_comment>username_2: looks like you just need to pivot the customer data then join to that from orders ``` select o.OrderId, o.OrderValue, cd.[firstName], cd.[lastName], coalesce([address1] + ', ','') + coalesce([city] + ', ','') + coalesce([zip],'') as Address from orders o left join ( select * from CustomerData pivot ( max(Value) for Alias in ([firstName],[lastName],[address1],[city],[zip]) ) p ) cd on o.OrderId = cd.OrderId ``` Upvotes: 1 <issue_comment>username_3: This is `join` based. It may be a more efficient. ``` declare @O table(id int primary key, val int); insert into @O values (1, 123) , (2, 338) , (3, 500); declare @C table(oid int, alias varchar(20), val varchar(20)); insert into @C values (1, 'firstName', 'John') , (1, 'lastName', 'Smith') , (1, 'city', 'Boston') , (1, 'zip', '12345') , (1, 'address1', 'Someplace') , (2, 'firstName', 'Jane') , (2, 'lastName', 'Doe') , (2, 'city', 'New Orleans') , (2, 'zip', '23456') , (2, 'address1', '1 Brookland Avenue') , (3, 'firstName', 'Eric') , (3, 'lastName', 'Black') , (3, 'city', 'Chicago') , (3, 'zip', '34567') , (3, 'address1', 'Apartment 356'); select o.id as orderId, o.val as orderValue , cF.val as firstName, cl.val as lastName --, cC.val as city, cZ.val as zip, cA.val as address1 , cC.val + ', ' + cZ.val + ', ' + cA.val as address from @O o join @C cF on cF.oid = o.id and cF.alias = 'firstName' join @C cL on cL.oid = o.id and cL.alias = 'lastName' join @C cC on cC.oid = o.id and cC.alias = 'city' join @C cZ on cZ.oid = o.id and cZ.alias = 'zip' join @C cA on cA.oid = o.id and cA.alias = 'address1' order by o.id; orderId orderValue firstName lastName address ----------- ----------- -------------------- -------------------- ---------------------------------------------------------------- 1 123 John Smith Boston, 12345, Someplace 2 338 Jane Doe New Orleans, 23456, 1 Brookland Avenue 3 500 Eric Black Chicago, 34567, Apartment 356 ``` Upvotes: 0