Id
int64
34.6M
60.5M
Title
stringlengths
15
150
Body
stringlengths
33
36.7k
Tags
stringlengths
3
112
CreationDate
stringdate
2016-01-01 00:21:59
2020-02-29 17:55:56
Y
stringclasses
3 values
56,771,019
how can use the fields in the class in python
` class TPCANTimestamp (Structure): """ Represents a timestamp of a received PCAN message Total Microseconds = micros + 1000 * millis + 0x100000000 * 1000 * millis_overflow """ _fields_ = [ ("millis", c_uint), # Base-value: milliseconds: 0.. 2^32-1 ("millis_overflow", c_ushort), # Roll-arounds of millis ("micros", c_ushort) ]` How can i use the fileds in the TPCANTimestamp class ??
<python><python-3.x><class>
2019-06-26 10:46:33
LQ_EDIT
56,771,856
Angular - how to find if an element in an array that matches a certain condition exists?
Typescript newb question, but I need the fastest way to find if an element with certain condition exists. Is there something like `exists(e=>{e.....bla bla bla})` in typescript?
<javascript>
2019-06-26 11:33:48
LQ_EDIT
56,771,881
Concat two dataframes wit common columns
<p>I have two dataframes with same columns. Only one column has different values. I want to concatenate the two without duplication.</p> <pre class="lang-py prettyprint-override"><code>df2 = pd.DataFrame({'key': ['K0', 'K1', 'K2'],'cat': ['C0', 'C1', 'C2'],'B': ['B0', 'B1', 'B2']}) df1 = pd.DataFrame({'key': ['K0', 'K1', 'K2'],'cat': ['C0', 'C1', 'C2'],'B': ['A0', 'A1', 'A2']}) df1 Out[630]: key cat B 0 K0 C0 A0 1 K1 C1 A1 2 K2 C2 A2 df2 Out[631]: key cat B 0 K0 C0 B0 1 K1 C1 B1 2 K2 C2 B2 </code></pre> <p>I tried:</p> <pre class="lang-py prettyprint-override"><code>result = pd.concat([df1, df2], axis=1) result Out[633]: key cat B key cat B 0 K0 C0 A0 K0 C0 B0 1 K1 C1 A1 K1 C1 B1 2 K2 C2 A2 K2 C2 B2 </code></pre> <p>The desired output:</p> <pre><code> key cat B_df1 B_df2 0 K0 C0 A0 B0 1 K1 C1 A1 B1 2 K2 C2 A2 B2 </code></pre> <p>NOTE: I could drop duplicates afterwards and rename columns but that doesn't seem efficient</p>
<python><pandas>
2019-06-26 11:34:46
LQ_CLOSE
56,772,170
Convert string array into integer python
<p>I need to convert following string array into integers. How to do it in python. Those string are hex values.</p> <pre><code>['02', '01', '03', '01', '04', '01', '05', '01', '06', '01', '07', '01', '08', '01', '09', '01', '0a', '01', '0b', '01', '0c', '01', '0d', '01', '0e', '01', '0f', '01', '10', '01', '11', '01', '12', '01', '13', '01', '14', '01', '03', '02', '04', '02', '05', '02', '06', '02', '07', '02', '08', '02', '09', '02', '0a', '02', '0b', '02', '0c', '02', '0d', '02', '0e', '02', '0f', '02', '10', '02', '11', '02', '12', '02', '13', '02', '14', '02', '04', '03', '05', '03', '06', '03', '07', '03', '08', '03', '09', '03', '0a', '03', '0b', '03', '0c', '03', '0d', '03', '0e', '03', '0f', '03', '10', '03', '11', '03', '12', '03', '13', '03', '14', '03', '05', '04', '06', '04', '07', '04', '08', '04', '09', '04', '0a', '04', '0b', '04', '0c', '04', '0d', '04', '0e', '04', '0f', '04', '10', '04', '11', '04', '12', '04', '13', '04', '14', '04', '06', '05', '07', '05', '08', '05', '09', '05', '0a', '05', '0b', '05', '0c', '05', '0d', '05', '0e', '05', '0f', '05', '10', '05', '11', '05', '12', '05', '13', '05', '14', '05', '07', '06', '08', '06', '09', '06', '0a', '06', '0b', '06', '0c', '06', '0d', '06', '0e', '06', '0f', '06', '10', '06', '11', '06', '12', '06', '13', '06', '14', '06', '08', '07', '09', '07', '0a', '07', '0b', '07', '0c', '07', '0d', '07', '0e', '07', '0f', '07', '10', '07', '11', '07', '12', '07', '13', '07', '14', '07', '09', '08', '0a', '08', '0b', '08', '0c', '08', '0d', '08', '0e', '08', '0f', '08', '10', '08', '11', '08', '12', '08', '13', '08', '14', '08', '0a', '09', '0b', '09', '0c', '09', '0d', '09', '0e', '09', '0f', '09', '10', '09', '11', '09', '12', '09', '13', '09', '14', '09', '0b', '0a', '0c', '0a', '0d', '0a', '0e', '0a', '0f', '0a', '10', '0a', '11', '0a', '12', '0a', '13', '0a', '14', '0a', '0c', '0b', '0d', '0b', '0e', '0b', '0f', '0b', '10', '0b', '11', '0b', '12', '0b', '13', '0b', '14', '0b', '0d', '0c', '0e', '0c', '0f', '0c', '10', '0c', '11', '0c', '12', '0c', '13', '0c', '14', '0c', '0e', '0d', '0f', '0d', '10', '0d', '11', '0d', '12', '0d', '13', '0d', '14', '0d', '0f', '0e', '10', '0e', '11', '0e', '12', '0e', '13', '0e', '14', '0e', '10', '0f', '11', '0f', '12', '0f', '13', '0f', '14', '0f', '11', '10', '12', '10', '13', '10', '14', '10', '12', '11', '13', '11', '14', '11', '13', '12', '14', '12', '14', '13'] </code></pre>
<python><string><hex><converters>
2019-06-26 11:52:28
LQ_CLOSE
56,772,484
SEND EMAIL FROM GOOGLE SHEET AS A TABLE WITHOUT USING SHEET CONVERTER
Please check the spreadsheet below: spreadsheethttps://docs.google.com/spreadsheets/d/1QFPO4bQfYPM4rRJ_6PYxUrYsFgVeUFx89_nZ1mNaLew/edit#gid=0 The script that I'm currently using is working fine thanks to the posts I've seen here. I just wanted to send it in a better way. I've already checked other posts and I even saw the SheetConverter but is too complicated for me. Current Result: https://drive.google.com/file/d/1-OQqnsRwIJaoXOnYZEtPxHy6r3buB8H7/view?usp=sharing Please check image for the desired result. Thanks! https://drive.google.com/file/d/1p7cJBTyaZ1ZqI5Jv5WWOGg6_Q-JegfHj/view?usp=sharing
<email><google-apps-script><google-sheets><html-email>
2019-06-26 12:09:40
LQ_EDIT
56,772,628
how to use unlink function in php
I Want to use this code update image working fine but. I have need add unlink function this code so please help me ... where add code **unlink function**. I am using PHP 7.2 and database > Note: the Previous File Delete in a file after update new file **php update script here...** <?php if(isset($_POST['submit'])) { $sql1 = "SELECT * FROM banner WHERE banner_id='$banner_id'"; $result1 = mysqli_query($conn, $sql1); mysqli_num_rows($result1) > 0; $row1 = mysqli_fetch_assoc($result1); $fileinfo = @getimagesize($_FILES["image"]["tmp_name"]); $width = $fileinfo[0]; $height = $fileinfo[1]; if(!empty($_FILES['image'] ['name'])) { $extension = pathinfo($_FILES['image'] ['name'], PATHINFO_EXTENSION); $image = "Banner".'-'. rand(10000,99999) . '.' . $extension; } if (($_FILES["image"]["size"] > 2000000)) { $response = array( "type" => "error", $_SESSION['msg1'] = "Image size exceeds 2MB" ); } else if ($width < "900" || $height < "250") { $response = array( "type" => "error", $_SESSION['msg2'] = "the image should be used greater than 900 X 250 " ); } else { $location = "../image/banner/".$image; if(in_array(strtolower($extension), [ 'png', 'jpeg', 'jpg', ])){ compressImage($_FILES['image']['tmp_name'],$location,60);} else{$image=$row1['image'];} $sql=mysqli_query($conn,"update banner set Image='$image' where banner_id='$banner_id' "); $_SESSION['msg']="Successfully Banner Image Updated Successfully !!"; } } ?>
<php>
2019-06-26 12:17:17
LQ_EDIT
56,772,967
Converting ImageProxy to Bitmap
<p>So, I wanted to explore new Google's Camera API - <code>CameraX</code>. What I want to do, is take an image from camera feed every second and then pass it into a function that accepts bitmap for machine learning purposes. </p> <p>I read the documentation on <code>Camera X</code> Image Analyzer:</p> <blockquote> <p>The image analysis use case provides your app with a CPU-accessible image to perform image processing, computer vision, or machine learning inference on. The application implements an Analyzer method that is run on each frame.</p> </blockquote> <p>..which basically is what I need. So, I implemented this image analyzer like this:</p> <pre><code>imageAnalysis.setAnalyzer { image: ImageProxy, _: Int -&gt; viewModel.onAnalyzeImage(image) } </code></pre> <p>What I get is <code>image: ImageProxy</code>. How can I transfer this <code>ImageProxy</code> to <code>Bitmap</code>?</p> <p>I tried to solve it like this:</p> <pre><code>fun decodeBitmap(image: ImageProxy): Bitmap? { val buffer = image.planes[0].buffer val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) } return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } </code></pre> <p>But it returns <code>null</code> - because <code>decodeByteArray</code> does not receive valid (?) bitmap bytes. Any ideas?</p>
<android><android-camerax>
2019-06-26 12:34:35
HQ
56,773,357
dynamically How to convert rows to columns in sql server
I want to convert rows to columns dynamically, for sample data I have given below query. create table testtable( tableid int primary key identity(1,1), tableDatetime datetime, names varchar(50), tablevalue decimal(18,9) ) go insert into testtable select '2019-06-13 13:56:39.117', 'test1',23.45 union all select '2019-06-13 13:56:39.117', 'test2',33.45 union all select '2019-06-13 13:56:39.117', 'test3',10.45 union all select '2019-06-13 13:56:39.117', 'test4',90.45 union all select '2019-06-13 14:01:41.280', 'test1',33.45 union all select '2019-06-13 14:01:41.280', 'test2',53.45 union all select '2019-06-13 14:01:41.280', 'test3',41.45 union all select '2019-06-13 14:01:41.280', 'test4',93.45 union all select '2019-06-13 14:06:42.363', 'test1',30.45 union all select '2019-06-13 14:06:42.363', 'test2',13.45 union all select '2019-06-13 14:06:42.363', 'test3',23.45 union all select '2019-06-13 14:06:42.363', 'test4',73.45 go select * from testtable I want to convert data into below format Datetime test1 test2 test3 test4 2019-06-13 13:56:39 23.45 33.45 10.45 90.45 2019-06-13 14:01:41 33.45 53.45 41.45 93.45 2019-06-13 14:06:42 30.45 13.45 23.45 73.45
<sql><sql-server><pivot>
2019-06-26 12:55:31
LQ_EDIT
56,773,551
How to make a python loop that would run a c program many times?
I have a c program that I can use from the terminal but i would like to run it many times in a loop in python. Someone told me to use the subprocess.call function but I have some trouble understanding how that works. From the terminal I usually run exactly this ```./grezza_foresta -w /Users/stordd/Desktop/StageI2M/Leiden/text_file/USA.g" -m 5 -e 0 > file_name.g ``` (the -w -m -e are option and the > is to create a file with the output) So I tried something like that from what I've been told to do . ``` import subprocess subprocess.call(["g++", "/Users/stordd/Desktop/StageI2M/C/forestenostre/grezza_foresta"]) ntrial = input("How many trials? ") for i in range(int(ntrial)): tmp=subprocess.call("/Users/stordd/Desktop/StageI2M/C/forestenostre/grezza_foresta") print(i,tmp) ``` I'm getting these error : ```ld: warning: ignoring file /Users/stordd/Desktop/StageI2M/Leiden/text_file/USA.g, file was built for unsupported file format ( 0x6E 0x75 0x6D 0x65 0x72 0x6F 0x5F 0x64 0x69 0x5F 0x76 0x65 0x72 0x74 0x69 0x63 ) which is not the architecture being linked (x86_64): /Users/stordd/Desktop/StageI2M/Leiden/text_file/USA.g How many trials? ld: can't link with a main executable file '/Users/stordd/Desktop/StageI2M/C/forestenostre/grezza_foresta' for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)``` It actually seems to be working in some way but I don't know how to add the options.
<python><python-3.7>
2019-06-26 13:06:24
LQ_EDIT
56,773,951
Crash on Canvas SwiftUI
<p>i'm implementing a little app with new iOS framework SwiftUI. I'm using <code>@EnvironmentObject</code> to bind my data to view. All works, but the Canvas crash and not show nothing. Why?</p> <pre><code>struct CompetitionsListSwiftUIView : View { @EnvironmentObject var competitionsViewModel: CompetitionsViewModel var body: some View { List(self.competitionsViewModel.competitions.identified(by: \.id)) { competition in CompetitionCellSwiftUIView(competition: competition) } } } #if DEBUG struct CompetitionsListSwiftUIView_Previews : PreviewProvider { static var previews: some View { CompetitionsListSwiftUIView() } } #endif </code></pre> <p>The error message of the Canvas is this:</p> <pre><code>Error Domain=render service Code=12 "Rendering service was interrupted" UserInfo={NSLocalizedDescription=Rendering service was interrupted} </code></pre>
<ios><swift><swiftui><combine>
2019-06-26 13:26:01
HQ
56,774,485
Any tool to create graphs from data of a tree?
<p>is there any simply and easy to use tool for Django (or for python) which is going to create a nice graphicon from the datas of a tree? Of course i can format the datas in any way, i just need a program which can process it and create a graphicon for it, like:</p> <p><a href="https://en.wikipedia.org/wiki/Tree_(data_structure)#/media/File:Binary_tree.svg" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Tree_(data_structure)#/media/File:Binary_tree.svg</a></p> <p>. It' s only a tree, no circle inside. Actually i' m using django-treenode .</p> <p>Thanks for any tip, idea.</p>
<django><python-3.x>
2019-06-26 13:52:22
LQ_CLOSE
56,774,570
Optimice multiple window.location.href = "index.html"
I have multiples IDs in my HTML. When I click that element (.onclick) I want to redirect them all (window.location.href) to the same site. So far I have tried this code but doesn't works: document.getElementById("boxed", "inmerse", "flow", "scape", "fierce", "name6", "name7", "name8", "name9").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" This is the code that works ```javascript document.getElementById("boxed").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("immerse").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("flow").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("scape").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("fierce").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("name6").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("name7").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("name8").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" document.getElementById("name9").onclick = () => window.location.href = "../3infoCardPremium/3infoCardPremium.html" ``` I'm expecting to create some function or another way to optimize the code.
<javascript>
2019-06-26 13:56:38
LQ_EDIT
56,774,676
How to split up a large string into an array of individual sentences
<p>I have a string, with a bunch of sentences separated by periods. For example:</p> <pre><code>const test = 'Dolore nostrud enim ea fugiat amet cupidatat enim. Fugiat qui tempor adipisicing velit et officia aliqua aliqua culpa ad veniam fugiat. Velit voluptate pariatur minim labore occaecat qui velit nostrud non deserunt non est voluptate. Quis est veniam sint nisi do.' </code></pre> <p>My desired outcome is to be able to turn each sentence of this paragraph into bullet points. I'm not concerned about creating the bullet points, I just need to break up this paragraph into an array of strings.</p> <p>I'm assuming I need to write an algorithm that splits each sentence by a delimiter (doesn't have to a period but I used one in this example) and push them to a new array. I'm not that good working with regular expressions so I would appreciate any help.</p>
<javascript><algorithm>
2019-06-26 14:01:59
LQ_CLOSE
56,775,305
How to get top 50 countries and leave the rest of the countries grouped to others in MS sql server
I would like to see TOP 50 countries, remaining countries need to be grouped as other countries using CASE statement. IS that possible to do. Please suggest.
<sql><sql-server>
2019-06-26 14:35:27
LQ_EDIT
56,776,586
I want to concatinate two values into a single string
i have two different values systolic and diastolic blood pressure readings in string, i just want when those two values come from front-end i'll just store them into a single string E.g if systolic ='120' and diastolic='80' i want it to be bp='120/80' # frozen_string_literal: true module Api module V1 module CheckinMachine class BpsController < ApplicationController include MachineError before_action :authenticate_user! def create raise BatteryNotFunctionalError if battery_functional? # user = User.find_by!(bp_machine_imei: params[:imei]) health_reading = current.health_readings.create!(key: :blood_pressure, value: bp_value) Solera::PostActivityApi.call(user, bp, health_reading.solera_activities.new) head :ok rescue ActiveRecord::RecordNotFound => _e render_machine_error and return end def show puts params end private def bp { systolic_blood_pressure: params[:systolic], diastolic_blood_pressure: params[:diastolic] } end end end end end That's what i have tried, what do i do to make it exactly like i want it to be like bp = '120/80'
<ruby-on-rails>
2019-06-26 15:43:44
LQ_EDIT
56,777,143
solve recurrence relation in which there is a separate relation for even and odd values
[enter image description here][1] [1]: https://i.stack.imgur.com/wjjWw.png Can someone help me how to solve these type of questions? What kind of approach should I follow?
<algorithm><math><recurrence>
2019-06-26 16:14:40
LQ_EDIT
56,777,176
Is there any way to increase visibility with a using declaration?
<p>The following code doesn't compile:</p> <pre><code>class C { private: int m_x; protected: C(int t_x) : m_x(t_x) { } }; class D : public C { public: using C::C; }; int main(int argc, char **argv) { D o(0); } </code></pre> <p>The compiler's objection is that the constructor for C is declared <code>protected</code>, meaning that I can't access it from <code>main</code>. In other words, it seems like the <code>using</code> declaration drags the original visibility of the identifier with it, despite the fact that it lives in the <code>public</code> block.</p> <p>Two questions:</p> <ol> <li>Why does this happen? (Both in terms of the rules for how this works, and the rationale for making those rules).</li> <li>Is there any way I can get around this without explicitly writing a constructor for <code>D</code>?</li> </ol>
<c++>
2019-06-26 16:16:49
HQ
56,777,337
In Python, how do I create and array from words from multiple lists, with word occurrences
<p>I have a JSON file that has multiple objects with a text field:</p> <pre><code>{ "messages": [ {"timestamp": "123456789", "timestampIso": "2019-06-26 09:51:00", "agentId": "2001-100001", "skillId": "2001-20000", "agentText": "That customer was great"}, {"timestamp": "123456789", "timestampIso": "2019-06-26 09:55:00", "agentId": "2001-100001", "skillId": "2001-20001", "agentText": "That customer was stupid\nI hope they don't phone back"}, {"timestamp": "123456789", "timestampIso": "2019-06-26 09:57:00", "agentId": "2001-100001", "skillId": "2001-20002", "agentText": "Line number 3"}, {"timestamp": "123456789", "timestampIso": "2019-06-26 09:59:00", "agentId": "2001-100001", "skillId": "2001-20003", "agentText": ""} ] } </code></pre> <p>I'm only interested in the 'agentText' field.</p> <p>I basically need to strip out every word in the agentText field and do a count of the occurrences of the word.</p> <p>So my python code:</p> <pre><code>import json with open('20190626-101200-text-messages.json') as f: data = json.load(f) for message in data['messages']: splittext= message['agentText'].strip().replace('\n',' ').replace('\r',' ') if len(splittext)&gt;0: splittext2 = splittext.split(' ') print(splittext2) </code></pre> <p>gives me this:</p> <pre><code>['That', 'customer', 'was', 'great'] ['That', 'customer', 'was', 'stupid', 'I', 'hope', 'they', "don't", 'phone', 'back'] ['Line', 'number', '3'] </code></pre> <p>how can I add each word to an array with counts? so like;</p> <pre><code>That 2 customer 2 was 2 great 1 .. </code></pre> <p>and so on?</p>
<python><json>
2019-06-26 16:29:16
LQ_CLOSE
56,778,048
what does console.readline do when i code string username = console.readline(); What is specific purpose of console.readline in this code?
String username = Console.Readline(); String password = Console.Readline(); String Valid = (username = "Kmp" && password = "Kmp")? "Valid user": "Invalid User"; Console.Writeline(Valid); /*I am noob player ;), i need your help as much as you can give.*/
<c#>
2019-06-26 17:16:56
LQ_EDIT
56,779,000
How is the following expression will be executed?
What is output of following program? #include<iostream> using namespace std; int main() { int a=2,b=4; a++=b; cout<<a<<b; return 0; }
<c++><post-increment>
2019-06-26 18:25:58
LQ_EDIT
56,779,352
Null Pointer Exc: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
<p>I have MainActivity: public class MainActivity extends Activity {</p> <pre><code>private ArrayList&lt;Antrenament&gt; listaAntr = new ArrayList&lt;&gt;(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Antrenament a1 = new Antrenament("forta","12/06/2019",50,"Andrei"); listaAntr.add(a1); Button bAdd = (Button) findViewById(R.id.buttonAdd); Button bLista = (Button) findViewById(R.id.buttonList); bAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), AdaugareAntrenament.class); intent.putParcelableArrayListExtra("listaant",listaAntr); startActivityForResult(intent,1); } }); bLista.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), ListaAntr.class); intent.putParcelableArrayListExtra("listaant",listaAntr); startActivityForResult(intent,1); } }); Intent intent2 = getIntent(); listaAntr = intent2.getParcelableArrayListExtra("listaantr"); } </code></pre> <p>}</p> <p>I want to send the list of objects Antrenament name listaAntr to AdaugareAntrenament activity, where I want to create a new Antrenament object, add it to the list and then send back the list to mainactivity. This updated list I want to send afterward to ListaAntr Activity, from mainactivity.</p> <p>AdaugareAntrenament activity:</p> <p>public class AdaugareAntrenament extends Activity {</p> <pre><code> ArrayList&lt;Antrenament&gt; listaAntr1=new ArrayList&lt;&gt;(); //private Button add; EditText etcateg, etdurata, etinstr,etdata; List&lt;String&gt; listacateg=new ArrayList&lt;&gt;(); Spinner spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_adaugare_antrenament); Intent intent = getIntent(); listaAntr1 = intent.getParcelableArrayListExtra("listaant"); Button add = findViewById(R.id.buttonSave); etdurata=findViewById(R.id.editTextDurata); etinstr=findViewById(R.id.editTextInstructor); etdata=findViewById(R.id.editTextData); spinner=findViewById(R.id.spinner); listacateg=new ArrayList&lt;&gt;(Arrays.asList(getResources().getStringArray(R.array.categ))); ArrayAdapter&lt;String&gt; adapter=new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item,listacateg); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String categorie,instructor,data; int durata; durata = Integer.parseInt(etdurata.getText().toString()); instructor = etinstr.getText().toString().trim(); data = etdata.getText().toString().trim(); categorie = spinner.getSelectedItem().toString().trim(); if(TextUtils.isEmpty(instructor)) { etinstr.setError("Introduceti numele instructorului"); return; } if(TextUtils.isEmpty(data)) { etdata.setError("Introduceti data programarii"); return; } Antrenament antr = new Antrenament(categorie, data, durata, instructor); listaAntr1.add(antr); Intent intent=new Intent(getApplicationContext(), MainActivity.class); intent.putParcelableArrayListExtra("listaantr",listaAntr1); } }); } </code></pre> <p>For the moment I get that error when I try to create the Antrenament object.. but this after some changes, because my code doesn't even send the updated list back to main activity.</p> <p>Current error: </p> <pre><code> java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference at com.example.ancaa.rezolvarerestanta20181.AdaugareAntrenament$1.onClick(AdaugareAntrenament.java:78) </code></pre> <p>The error points to the line : </p> <pre><code> listaAntr1.add(antr); </code></pre> <p>and ListaAntr Activity: </p> <p>public class ListaAntr extends Activity {</p> <pre><code>public ArrayList&lt;Antrenament&gt; listaAntr = new ArrayList&lt;&gt;(); public ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_antr); lv = (ListView)findViewById(R.id.lista); Intent intent = getIntent(); listaAntr = intent.getParcelableArrayListExtra("listaantr"); ArrayAdapter&lt;Antrenament&gt; adapter=new ArrayAdapter&lt;Antrenament&gt;(this,android.R.layout.simple_list_item_1,listaAntr); lv.setAdapter(adapter); } </code></pre> <p>}</p> <p>Here the content of the arraylist should be shown as a listview.</p>
<java><android><nullpointerexception>
2019-06-26 18:51:19
LQ_CLOSE
56,780,197
Javascript: Sort Object by value
<p>I have the following object: </p> <pre><code>{1234: "3.05", 1235: "2.03", 1236: "3.05"} </code></pre> <p>I would like to sort them by <strong>value</strong> to get something like this:</p> <pre><code>{1235: "2.03", 1234: "3.05", 1236: "3.05"} </code></pre> <p>I tried:</p> <pre><code>const sortedList = _.orderBy(myList, (value, key) =&gt; { return value; }, ['asc']); </code></pre> <p>The values get sorted but it is only a list of values:</p> <pre><code>{0: "2.03", 1: "3.05", 2: "3.05"} </code></pre> <p>How can I retain the keys?</p>
<javascript>
2019-06-26 20:12:12
LQ_CLOSE
56,782,456
Is it possible to have an executable file not run after a certain date?
<p>I am learning to code with c++. I recently made a magic 8 ball script. I was wondering, when people share .exe files with others. Is it possible to write a command so that the .exe file won't work after a week? </p> <p>I have not tried it, because I do not know where to start.</p>
<c++><c>
2019-06-27 00:25:42
LQ_CLOSE
56,783,231
Is it correct to use do while loop inside a for loop? Why and why not
//program to count words #include<stdio.h> int main() { int i; int word=0; char sent[]="How are you doing mister"; //character pointer for(i=0;sent[i]!='\0';i++) { do { word++; } while(sent[i]==' '); } printf("There are %d words in the sentence\n", word+1); //words are always 1 more than the no. of spaces. return 0; } //or word=1; This is a code for counting the number of words. Please tell me why cannot we use do while inside a for loop. Or if we can, how to do it.
<c><for-loop><do-while>
2019-06-27 02:48:15
LQ_EDIT
56,784,309
CSS Color overlay with background image
<p>I am able to set a background image that covers a page but the green overlay does not work. What am I doing wrong? Thank you.</p> <pre><code>body { margin: 0 auto; padding: 0; background: url("../images/worldmap.jpg") no-repeat rgba(0,255,0,.5); /*background-image: url("../images/worldmap.jpg");*/ /*background-repeat: no-repeat;*/ } </code></pre>
<css>
2019-06-27 05:12:31
LQ_CLOSE
56,785,186
Why setText causes my program to fail while Toast doesn't
The setText method when un-commented crashes the Activity/program. However, when it's just the TOAST with the same variable it works perfectly. int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int min = Calendar.getInstance().get((Calendar.MINUTE)); int ft = hour + min; int second = Calendar.getInstance().get(Calendar.SECOND); if(second<10){ second = second + 10; } String sft = Integer.toString(ft); String ssecond = Integer.toString(second); fid = sft + ssecond; Toast.makeText(addRoll.this, fid, Toast.LENGTH_LONG).show(); id.setText(fid); So this should change the TextView into the 4 digit number created. currently, it is at 0000. I know the variable works because the toast shows the correct variable. Thanks in advance.
<java><android>
2019-06-27 06:32:25
LQ_EDIT
56,785,259
How to format minutes to hours - using moment.js
<p>I am using moment.js.</p> <p>I get minutes (max 1440) and i wanted to format that in hours in specific format. </p> <p>Something like this:</p> <p>420 minutes is: <strong>07:00</strong></p> <p>1140 minutes is: <strong>24:00</strong></p> <p>451 minutes is: <strong>07:31</strong></p>
<javascript><momentjs>
2019-06-27 06:37:10
LQ_CLOSE
56,785,649
How I can make a window and an input box in Python?
<p>Make a window 400*400 And there is an input box there I can't do anything right now Can you help me with my programming?</p>
<python>
2019-06-27 07:02:17
LQ_CLOSE
56,787,147
Extract Largest Number from list of strings in python
<p>so I am trying to extract the largest number from a list of strings in python. The string I'm trying to work with looks like this</p> <pre><code>a = ['a', '3', '5', 'c10', 'foo', 'bar', '999'] </code></pre> <p>And I'm trying to get back the largest number. So in this case, it would be 999 and I wan't it back as an int.</p> <p>I can't seem to find a pretty way of doing this, hope you guys can help.</p>
<python><python-3.x>
2019-06-27 08:38:25
LQ_CLOSE
56,791,003
Execute .sql file in python
Hello everyone I have this sql file Student.sql Select * from student where age > 18; Delet student_ name , studen_id if age > 18 ; Commit; Using cx_oracle pip Any help
<python><python-3.x><oracle><cx-oracle>
2019-06-27 12:27:19
LQ_EDIT
56,791,399
How to split string in JavaScript with regular expression
<p>I have following html. I want to split it by <code>&lt;span&gt;</code> tag.</p> <pre><code>let storyHtml = "&lt;span&gt;People&lt;/span&gt; born in different ages are different from each other in various aspects. The world is changing at &lt;span&gt;a&lt;/span&gt; rapid pace and thus the difference between &lt;span&gt;people&lt;/span&gt; born in different times is inevitable."; let allSplitPart = storyHtml.split(/&lt;span&gt;.*?&lt;\/span&gt;/gim); let allMatchPart = storyHtml.match(/&lt;span&gt;.*?&lt;\/span&gt;/gim); // Output 1: ["", " born in different ages are different from each other in various aspects. The world is changing at ", " rapid pace and thus the difference between ", " born in different times is inevitable."] //Output 2: ["&lt;span&gt;People&lt;/span&gt;", "&lt;span&gt;a&lt;/span&gt;", "&lt;span&gt;people&lt;/span&gt;"] </code></pre> <p><strong>What output I want:</strong></p> <pre><code>["&lt;span&gt;People&lt;/span&gt;", " born in different ages are different from each other in various aspects. The world is changing at ","&lt;span&gt;a&lt;/span&gt;"," rapid pace and thus the difference between ","&lt;span&gt;people&lt;/span&gt;", " born in different times is inevitable."] </code></pre>
<javascript><regex>
2019-06-27 12:49:15
LQ_CLOSE
56,791,721
Couldnt execute long sql statement in python?
<p>I have defined my sql statement as follows ( note the line breaks)</p> <pre><code> def getTankSystemIds(): sql='select tt.TankSystemId,ts.sitecode,tt.productid ' \ 'from [dbo].[TankSystems] tt' \ 'left join [dbo].sites ts on tt.siteid=ts.siteid where ts.companyid=8' \ 'and ProductId in (10,4,2,3,11,4)' cursor = connectDB() cursor.execute(sql) records = cursor.fetchall() </code></pre> <p>When calling this method, I get following error. I changed single quote to " and ''',""" but all gave same error What Im doing wrong here? I tried providing the sql statement in a single long line too. But same error</p> <pre><code>SyntaxError: Non-ASCII character '\xef' in file /Users/ratha/PycharmProjects/Processor/Utilities/DbConnector.py on line 86, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details </code></pre>
<python><python-2.7>
2019-06-27 13:06:05
LQ_CLOSE
56,791,913
Unknow css change border's color
<p>Select checkbox auto changes border's color after open select checkbox.</p> <p>I can't find any class change select checkbox color on Developer tool,how to solve the problem?</p> <p><a href="https://i.stack.imgur.com/sBqUM.jpg" rel="nofollow noreferrer">demo</a></p>
<css>
2019-06-27 13:16:51
LQ_CLOSE
56,792,793
How to sort a JSON file with more than one argument numerical
Well,I need to create a function to my web application. This function receive as parameter a jSON and return the organized list from lowest to highest. The object of my json file have two parameters to analyse. var medicines = [ {type:"Glibenclamida 5 mg", hour1:2, hour2: 4}, {type:"Noretisterona 0,35 mg", hour1:4, hour2: 8}, {type:"Glibenclamida 99 mg", hour1:8, hour2: 16} ]; So,this is only a example and I need these list return... 1: hour 2- Glibenclamida 5 mg 2: hour 4- Glibenclamida 5 mg, Noretisterona 0,35 mg 3: hour 8- Noretisterona 0,35 mg, Glibenclamida 99 mg 4: hour 16 - Glibenclamida 99 mg This is just a example I need a organized list like these.
<javascript><html>
2019-06-27 14:03:00
LQ_EDIT
56,793,024
Bash evaluation of expression .[].[]
<p>Consider the following expression evaluations:</p> <pre><code>$ echo . . $ echo .[] .[] $ echo .[]. .[]. $ echo .[].[] .. # &lt;- WAT?? $ echo .[].[]. .[].[]. $ echo .[].[].[] .[].[].[] </code></pre> <p>Can someone explain why <code>.[].[]</code> has this special behavior?</p> <p>(Tested in bash <code>3.2.57(1)-release (x86_64-apple-darwin18)</code> and <code>4.4.23(1)-release (arm-unknown-linux-androideabi)</code>.</p> <p>I suspect it has something to do with <code>..</code> being a valid "file" (the parent directory). But then why doesn't e.g. <code>.[].</code> produce the same result?</p>
<bash>
2019-06-27 14:14:36
HQ
56,793,455
How to update Google Play Developer API to version 3 on Xamarin Forms App?
<p><a href="https://i.stack.imgur.com/ejivj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ejivj.png" alt="enter image description here"></a></p> <p>While uploading new APK to GooglePlay of a very simple APP which using only webview using Visual Studio 2019 Xamarin.Forms i am getting the following error on Google Play console:</p> <blockquote> <p>"We’ve detected that your app is using an old version of the Google Play Developer API. From December 1 2019, versions 1 and 2 of this API will no longer be available. Update to version 3 before this date. Learn more"</p> </blockquote> <p><a href="https://i.stack.imgur.com/VnwZ2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VnwZ2.png" alt=""></a> </p> <p><a href="https://i.stack.imgur.com/qKd9I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qKd9I.png" alt="enter image description here"></a></p> <p>Nuget Packages:</p> <blockquote> <p>Id Versions ProjectName<br> -- -------- -----------<br> Microsoft.AppCenter.Analytics {2.1.1} xamarin<br> Xamarin.Essentials {1.1.0} xamarin<br> Microsoft.AppCenter.Push {2.1.1} xamarin<br> NETStandard.Library {2.0.3} xamarin<br> Microsoft.AppCenter.Crashes {2.1.1} xamarin<br> Xamarin.Forms {4.0.0.540366} xamarin<br> Microsoft.AppCenter {2.1.1} xamarin<br> Microsoft.AppCenter {2.1.1} fms_xamarin.Android<br> Microsoft.AppCenter.Analytics {2.1.1} fms_xamarin.Android<br> Microsoft.AppCenter.Crashes {2.1.1} fms_xamarin.Android<br> Microsoft.AppCenter.Push {2.1.1} fms_xamarin.Android<br> Xamarin.Forms {4.0.0.540366} fms_xamarin.Android<br> Xamarin.Android.Support.Design {28.0.0.1} fms_xamarin.Android<br> Xamarin.Android.Support.v7.AppCo... {28.0.0.1} fms_xamarin.Android<br> Xamarin.Android.Support.v4 {28.0.0.1} fms_xamarin.Android<br> Xamarin.Android.Support.v7.CardView {28.0.0.1} fms_xamarin.Android<br> Xamarin.Android.Support.v7.Media... {28.0.0.1} fms_xamarin.Android<br> Xamarin.Android.Support.Core.Utils {28.0.0.1} fms_xamarin.Android<br> Xamarin.Android.Support.CustomTabs {28.0.0.1} fms_xamarin.Android<br> Xamarin.Essentials {1.1.0} fms_xamarin.Android<br> Xamarin.GooglePlayServices.Base {60.1142.1} fms_xamarin.Android<br> Xamarin.GooglePlayServices.Basement {60.1142.1} fms_xamarin.Android </p> </blockquote> <p>How can i update the SDK as google asking for?</p>
<xamarin><xamarin.forms><xamarin.android>
2019-06-27 14:38:16
HQ
56,797,665
Error response from daemon: Drive has not been shared
<p>In Windows 10, trying to mount an external volume in docker</p> <p><code>docker run --rm -v d:/data:/data alpine ls /data</code></p> <p>gives this error</p> <p><code>Error response from daemon: Drive has not been shared.</code></p>
<docker>
2019-06-27 19:42:54
HQ
56,797,703
Compare 2 dataframe columns and add a new column in one dataframe as "Yes" or "No" if the cell data matches
<p>I have 2 data frames as below:</p> <pre><code>df1(main data) UID SG 1 A 2 B 3 C 4 D 5 E df2 UID AN SG 1 x A 3 y C 2 z B 1 xy A 3 v C </code></pre> <p>Now, I want to add a new column to df1, say "isPresent". This column will have "Yes" if the UID from df1 is present in df2 and "No" if UID in not in df2. So my df1 will finally looks like this,</p> <pre><code>df1 UID SG isPresent 1 A Yes 2 B Yes 3 C Yes 4 D No 5 E No </code></pre> <p>My approach is taking an intersection of the UIDs from both the dataframes and then a for loop in df1 to add data cell by cell.</p> <p>But I want to apply an approach without using for loop and using pandas as much as possible, if possible.</p>
<python><pandas><dataframe>
2019-06-27 19:47:16
LQ_CLOSE
56,798,459
Using random numbers vs hardcoded values in unit tests
<p>When I write tests, I like to use random numbers to calculate things.</p> <p>e.g.</p> <pre><code> func init() { rand.Seed(time.Now().UnixNano()) } func TestXYZ(t *testing.T) { amount := rand.Intn(100) cnt := 1 + rand.Intn(10) for i := 0; i &lt; cnt; i++ { doSmth(amount) } //more stuff } </code></pre> <p>which of course has the disadvantage that </p> <pre><code>expected := calcExpected(amount, cnt) </code></pre> <p>in that the expected value for the test needs to be calculated from the random values.</p> <p>If have received criticism for this approach:</p> <ul> <li>It makes the test unnecessarily complex</li> <li>Less reproduceable due to randomness</li> </ul> <p>I think though that without randomness, I could actually:</p> <ul> <li>Make up my results, e.g. the test only works for a specific value. Randomness proves my test is "robust"</li> <li>Catch more edge cases (debatable as edge cases are usually specific, e.g. 0,1,-1)</li> </ul> <p>Is it really that bad to use random numbers?</p> <p>(I realize this is a bit of an opinion question, but I am very much interested in people's point of views, don't mind downvotes).</p>
<unit-testing><go><testing><random>
2019-06-27 21:05:25
LQ_CLOSE
56,799,476
Member function invocation through object
<p>I just to understand the logic behind this code. When member function is not part of the object then how does the compiler invokes the function. Somehow the compiler needs to know the address of the function to invoke. Where it gets the address of the right function.I know this is silly question but curious to understand the underlying truth behind this</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Base { public: Base() { cout &lt;&lt; "Base class constructor\n"; } void Fun() { cout &lt;&lt; sizeof(this) &lt;&lt; endl; cout &lt;&lt; "This is member function" ; } void Fun1() { cout &lt;&lt; "This is second member fun" &lt;&lt; endl; } int Val; }; int main(int argc, char* argv[]) { Base Obj; cout &lt;&lt; sizeof(Obj) &lt;&lt; endl; Obj.Fun(); return 0; } </code></pre>
<c++><function><member>
2019-06-27 23:32:30
LQ_CLOSE
56,799,790
resize program works for some and not others
> so the problem, is suppose to take 3 arguments (factor, infile and outfile) the factor is a positive integer from 1 - 100. the program then is suppose to resize the infile image depending on the factor, 1 produce the same image and 2 twice as big and so on to the outfile. currently my program does this succesfully for some images and only on certain scale factors. when i run it through my courses ide check program for this question the errors i recieve are; **:) resize.c and bmp.h exist. :) resize.c compiles. :) doesn't resize small.bmp when n is 1 :( resizes small.bmp correctly when n is 2 Byte 34 of pixel data doesn't match. Expected 0xff, not 0x00 :( resizes small.bmp correctly when n is 3 Byte 48 of pixel data doesn't match. Expected 0xff, not 0x00 :( resizes small.bmp correctly when n is 4 Byte 62 of pixel data doesn't match. Expected 0xff, not 0x00 :( resizes small.bmp correctly when n is 5 Byte 80 of pixel data doesn't match. Expected 0xff, not 0x00 :) resizes large.bmp correctly when n is 2 :) resizes smiley.bmp correctly when n is 2** ```C // Copies a BMP file and resizes it #include <stdio.h> #include <stdlib.h> #include "bmp.h" int main(int argc, char *argv[]) { // ensure proper usage if (argc != 4) { fprintf(stderr, "Usage: ./resize factor infile outfile\n"); return 1; } // Check argument 1 to see if integer within aceptable range int factor = atoi(argv[1]); if (factor <= 0 || factor > 100) { fprintf(stderr, "Must be a positive integer greater than 0 and eqaul or less than 100\n"); return 1; } // remember filenames char *infile = argv[2]; char *outfile = argv[3]; // open input file FILE *inptr = fopen(infile, "r"); if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 2; } // open output file FILE *outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // read infile's BITMAPFILEHEADER BITMAPFILEHEADER bf; BITMAPFILEHEADER bf_New; fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); bf_New = bf; // read infile's BITMAPINFOHEADER BITMAPINFOHEADER bi; BITMAPINFOHEADER bi_New; fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); bi_New = bi; // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || bi.biBitCount != 24 || bi.biCompression != 0) { fclose(outptr); fclose(inptr); fprintf(stderr, "Unsupported file format.\n"); return 4; } // set new height and width of BMP bi_New.biHeight = bi.biHeight * factor; bi_New.biWidth = bi.biWidth * factor; // calculate padding for old file and new file int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; int padding_New = (4 - (bi_New.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; // set the file size for the new file bi_New.biSizeImage = (bi_New.biWidth * sizeof(RGBTRIPLE) + padding_New) * abs(bi_New.biHeight); bf_New.bfSize = bi_New.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); // write outfile's BITMAPFILEHEADER fwrite(&bf_New, sizeof(BITMAPFILEHEADER), 1, outptr); // write outfile's BITMAPINFOHEADER fwrite(&bi_New, sizeof(BITMAPINFOHEADER), 1, outptr); // iterate over infile's scanlines for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++) { // itterate factor times for (int k = 0; k < factor; k++) { // iterate over pixels in scanline for (int j = 0; j < bi.biWidth; j++) { // temporary storage RGBTRIPLE triple; // read RGB triple from infile fread(&triple, sizeof(RGBTRIPLE), 1, inptr); // iterate over horizontal pixels for (int l = 0; l < factor; l++) { // write RGB triple to outfile itterate the same pixel by factor times fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr); } } // skip over padding, if any fseek(inptr, padding, SEEK_CUR); // add new padding for (int m = 0; m < padding_New; m++) { fputc(0x00, outptr); } // seek back to the beginning of row in input file, but not after iteration of printing if (k + 1 < factor ) { fseek(inptr, -(bi.biWidth * sizeof(RGBTRIPLE)), SEEK_CUR); } } } // close infile fclose(inptr); // close outfile fclose(outptr); // success return 0; } ```
<c><computer-science><cs50>
2019-06-28 00:42:50
LQ_EDIT
56,803,128
Error in is.data.frame(x) : object file name' not found
pls, i dont know why always fail when i save my work #menentukan tempat penyimpanan setwd("C:/Users/Child-PC/Documents/Doc/Kerja/Jakarta Smart City/Data/CRM/CRM (Files) Mei 2019/R Function") #menyimpan data ke csv write.csv(nilai_data, file="nilai_data.csv")
<r><dataframe><export-to-csv>
2019-06-28 08:04:27
LQ_EDIT
56,803,499
Need Regular Expression Logic to find string in C#
I want to find a particular string (word) from a sentence. Given String: "In a given health plan your Plan Name: Medical and Plan Type: PPO whose effective date: 2019-01-01 and coverage value $100 and $200". 1) if I pass "Plan Name:" then my output would be "Medical". 2) if I pass "Plan Type:" then my output would be "PPO". 3) if I pass "effective date:" then my output would be "2019-01-01". 4) if I pass "coverage value" then in this case I need two value. Min value "$100" and MAX value "$200". Similarly I need email address from a given sentence. There could be scenario where I just need to pic a date, email or a numeric value from a given sentence. In this case I do not have any previous value to match. I need a regular expression logic that covers all above requirements. Thanks Udai Mathur I tried but I need all the scenario.
<c#>
2019-06-28 08:30:57
LQ_EDIT
56,803,689
flutter dart try catch, catch does not fire
<p>given the short code example below:</p> <pre><code> ... print("1 parsing stuff"); List&lt;dynamic&gt; subjectjson; try { subjectjson = json.decode(response.body); } on Exception catch (_) { print("throwing new error"); throw Exception("Error on server"); } print("2 parsing stuff"); ... </code></pre> <p>I would Expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch not the continuation code fires.. </p> <pre><code>flutter: 1 parsing stuff [VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap&lt;String, dynamic&gt;' is not a subtype of type 'List&lt;dynamic&gt;' </code></pre> <p>What am I missing here?</p> <p>John.</p>
<flutter><dart>
2019-06-28 08:43:55
HQ
56,805,007
npm WARN: npm does not support Node.js v12.4.0
<p>I've been getting the following warnings lately whenever I run any npm script:</p> <pre><code>npm WARN npm npm does not support Node.js v12.4.0 npm WARN npm You should probably upgrade to a newer version of node as we npm WARN npm can't make any promises that npm will work with this version. npm WARN npm Supported releases of Node.js are the latest release of 6, 8, 9, 10, 11. npm WARN npm You can find the latest version at https://nodejs.org/ </code></pre> <p>It says that I should upgrade to a newer version, but v12.4 <em>is</em> the newest version. Even though the scripts run fine, I think there's no guarantee and something might break at any moment.</p> <p>I've also tried updating <code>npm</code> in case there's a newer version using <code>npm install npm -g</code> but got the error:</p> <pre><code>npm ERR! path /usr/local/Cellar/node/12.4.0/lib/node_modules/npm npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall access npm ERR! Error: EACCES: permission denied, access '/usr/local/Cellar/node/12.4.0/lib/node_modules/npm' npm ERR! [Error: EACCES: permission denied, access '/usr/local/Cellar/node/12.4.0/lib/node_modules/npm'] { npm ERR! stack: 'Error: EACCES: permission denied, access ' + npm ERR! "'/usr/local/Cellar/node/12.4.0/lib/node_modules/npm'", npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'access', npm ERR! path: '/usr/local/Cellar/node/12.4.0/lib/node_modules/npm' npm ERR! } npm ERR! npm ERR! The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator (though this is not recommended). </code></pre> <p>Then I've seen that Homebrew version of <code>npm</code> can't be updated using npm itself, so I tried updating through <code>Homebrew</code> using <code>brew upgrade npm</code> but got this error:</p> <p><code>Error: npm 12.4.0 already installed</code></p> <p>For some reason Brew mixes up <code>node</code>s and <code>npm</code>s versions.</p> <p>What am I doing wrong and how can I get rid of this warning?</p>
<node.js><npm><homebrew><npm-install><homebrew-cask>
2019-06-28 10:10:43
HQ
56,805,421
Reqular expression for formula which contains number, alphabets,expressions and brackets
I am trying to write a regular expression for the formula for the following examples. `1. C=A+B => Output {A, +, B} 2. D= C+50 => Output{C, +, 50} 3. E = (A+B)*C -100 => Output{(, A, +, B, ), *, C, -, 100}` Please help me to create a regular expression. Thanks in advance.
<c#><regex><parsing>
2019-06-28 10:38:54
LQ_EDIT
56,806,376
Compare two Columns using index position in R
[![The dataframe][1]][1] I have a scenario where I have to compare two columns in a dataframe. The condition is that the Field1 column has a set of values. Field2 column has few values and the remaining are NA. There is another column called Field3. So, the work here is to compare the Field1 values with Field2. The conditions to compare are as follows. 1. If Field1 has a corresponding row in Field2. Copy the row value of Field2. Ex. Location and Place. So, I have to copy Place. 2. If Field1 does not have a corresponding Field2 value. Then compare Field1 with Field3. Copy the Field3 value to Field2. Kindly suggest a way to go about this.`dft = data.frame(Field1 = c("Location","Time","Date","Problem"), Field2 = c("Place","Balance","NA","NA"), Field3 = c("NA","NA","Pay","NA"))` [1]: https://i.stack.imgur.com/nPTpt.png
<r><dataframe><data-analysis><data-cleaning>
2019-06-28 11:46:48
LQ_EDIT
56,806,391
open form on html button click in asp.net using C#
<p>will any body help me in opening a form on button click?? Thanks in advance.</p> <p><strong>aspx.cs Code:</strong></p> <pre><code> public string wogrid() { string htmlStr = ""; con.COpen(); string qry = "SELECT id,casetype,Case when status_c=1 then 'Active' else 'Inactive' End as status_c FROM t_claimtype"; SqlDataReader rd = gd.DataReader(qry); while (rd.Read()) { int ID = Convert.ToInt16(rd["id"].ToString()); string caseType = rd["casetype"].ToString(); string status = rd["status_c"].ToString(); htmlStr += "&lt;tr&gt;&lt;td&gt;" + ID + "&lt;/td&gt;" + "&lt;td&gt;" + caseType + "&lt;/td&gt;" + "&lt;td&gt;" + status + "&lt;/td&gt;" + "&lt;td&gt;" + "&lt;input type='submit' id='" + (rd)["ID"].ToString() + "' name='edit' value='EDIT' **onclick='windows.open(viewClaims.aspx)'** runat='server' /&gt;" + "&lt;/td&gt;&lt;/tr&gt;"; } con.cClose(); return htmlStr; } private void AddPlanToCart() { Response.Redirect("viewClaims.aspx"); } </code></pre>
<c#><asp.net>
2019-06-28 11:48:21
LQ_CLOSE
56,806,479
Postgre sql query ? whats wrong with the having clause in my query?
Select facid, sum(slots) as total from cd.bookings group by facid having total > 1000 oerder by facid;
<postgresql><group-by><having>
2019-06-28 11:54:09
LQ_EDIT
56,807,876
ODCIAggregateMerge without parallel_enabled
<p>These are quotes from <a href="https://docs.oracle.com/cd/B28359_01/appdev.111/b28425/aggr_functions.htm" rel="noreferrer">Oracle docs</a>:</p> <blockquote> <p>[Optional] Merge by combining the two aggregation contexts and return a single context. This operation combines the results of aggregation over subsets in order to obtain the aggregate over the entire set. This extra step can be required during <strong>either serial or parallel</strong> evaluation of an aggregate. If needed, it is performed before step 4: </p> </blockquote> <p>,</p> <blockquote> <p>The ODCIAggregateMerge() interface is invoked to compute super aggregate values in such rollup operations.</p> </blockquote> <p>We have an aggregate function, that we do NOT want to ever run in parallel.<br> The reason is that the merging of contexts would be resource consuming and would force us to use different data structures than we are using now, effectively offseting any performance benefits from parallel execution.</p> <p>Thus, we did <strong>not</strong> declare our function as <em>parallel_enabled</em>, and instead return ODCIconst.Error in ODCIAggregateMerge 'just in case'.</p> <p>However, the first quote docs claim, that merge may occur even in serial evaluation.<br> Super-aggregates (rollup, cube) are obvious examples, but are there any others?</p> <p>I've been totally unable to reproduce it with simple group by, merge is never called without parallel_enabled and it seems that always only one context is created within the group. </p> <p>Is it safe to assume that without the parallel_enabled set, merge will never be run?<br> Have you ever seen a counterexample to that rule?</p>
<sql><oracle><plsql><aggregate>
2019-06-28 13:30:16
HQ
56,809,864
How can I convert an array of elements to the individual elements for variable element method in Scala?
<p>I'm wondering if it's possible to convert an array of elements to the elements themselves. For my example, I'm trying to pass individual strings into a function whose arguments are a variable number of strings. I currently have an array of strings and am trying to pass them into .toDF (which takes a variable number of strings). This is what I have:</p> <p>.toDF((df.columns)</p> <p>How can I convert this array into the individual elements?</p>
<arrays><scala>
2019-06-28 15:51:53
LQ_CLOSE
56,813,923
App is getting crashed while retrieving data from SQLite and displaying on Custom list view
I'm trying to retrieve data stored in the database and show it onto custom ListView. Whenever I call FenceActivity.class to view data app gets crashed. *FenceActivity* ``` public class FenceActivity extends AppCompatActivity { List<Fence> fenceList; SQLiteDatabase sqLiteDatabase; ListView listViewFences; FenceAdapter fenceAdapter; DataBaseHelper dataBaseHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.savedfences); listViewFences = findViewById(R.id.fencesListView); fenceList = new ArrayList<>(); showFencesFromDatabase(); } public void showFencesFromDatabase(){ dataBaseHelper = new DataBaseHelper(this); Cursor cursor = dataBaseHelper.getAllData(); if(cursor.moveToFirst()){ do{ fenceList.add(new Fence(cursor.getInt(0),cursor.getDouble(1),cursor.getDouble(2),cursor.getInt(3))); }while (cursor.moveToNext()); } cursor.close(); fenceAdapter = new FenceAdapter(FenceActivity.this,R.layout.list_layout_fences,fenceList); listViewFences.setAdapter(fenceAdapter); } } ``` I use Fence Activity to retrieve Data using DatabaseHelper class from the database. *Fence Adapter* ``` public class FenceAdapter extends ArrayAdapter<Fence> { Context context; int listLayoutRes; List<Fence> fenceList; public FenceAdapter(Context context, int listLayoutRes, List<Fence> fenceList){ super(context,listLayoutRes,fenceList); this.context = context; this.listLayoutRes=listLayoutRes; this.fenceList = fenceList; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = LayoutInflater.from(context); View view = layoutInflater.inflate(listLayoutRes,null); Fence fence = fenceList.get(position); TextView textViewSno = view.findViewById(R.id.textViewSnoLabel); TextView textViewLat = view.findViewById(R.id.textViewLatitudeValue); TextView textViewLon = view.findViewById(R.id.textViewLongitudeValue); TextView textViewRadi = view.findViewById(R.id.textViewRadiusValue); textViewSno.setText(fence.getSno()); textViewLat.setText(String.valueOf(fence.getLat())); textViewLon.setText(String.valueOf(fence.getLon())); textViewRadi.setText(fence.getRadius()); Button buttonDel = view.findViewById(R.id.buttonDeleteFence); return view; } } ``` This my adapter class to inflate listview. *Fence* ``` public class Fence { int radius,sno; double lat,lon; public Fence( int sno,double lat, double lon,int radius) { this.radius = radius; this.sno = sno; this.lat = lat; this.lon = lon; } public int getRadius() { return radius; } public int getSno() { return sno; } public double getLat() { return lat; } public double getLon() { return lon; } } ``` This my simple Fence class with getters and a constructor. What changes can I make to prevent my app from getting crashed?
<java><android><listview><android-sqlite>
2019-06-28 23:00:36
LQ_EDIT
56,814,358
How to add random numbers together. Python
number_checker = 0 for random_variables in range(1,11): import random random = random.randint(1,25) print(random) if random % 2 == 0: print("This number is even") even_numbers = number_checker + random else: print("This number is odd") odd_numbers = number_checker + random print("") print("This is the sum of even numbers.") print(even_numbers) print("") print("This is the sum of odd numbers.") print(odd_numbers)
<python><random>
2019-06-29 00:49:37
LQ_EDIT
56,815,114
Regex for nested pattern
<p>I have a pattern like this:</p> <pre><code>#alphanumericX(anythingY){ anythingZ }# </code></pre> <p>It can be nested like this:</p> <pre><code>#alphanumeric1(anything1){ #alphanumericX(anythingY){ anythingZ }# }# </code></pre> <p>Or like this:</p> <pre><code>#alphanumeric1(anything1){ anything2 #alphanumericX(anythingY){ anythingZ }# }# </code></pre> <p>The patterns can be written not just once, but multiple like this:</p> <pre><code>#alphanumericX(anythingY){ anythingZ }# #alphanumeric1(anything1){ anything1 }# </code></pre> <p>I want a regex to match the the patterns above, so it will return like this:</p> <pre><code>#alphanumericX(anythingY){ anythingZ }# </code></pre> <p>How to achieve that?</p> <p>Here is my current regex: <code>/#(.*?)\((.*?)\)\{(.*?)\}#/sm</code></p>
<php><regex>
2019-06-29 04:42:47
LQ_CLOSE
56,816,241
Difference between "detach()" and "with torch.nograd()" in PyTorch?
<p>I know about two ways to exclude elements of a computation from the gradient calculation <code>backward</code></p> <p><strong>Method 1:</strong> using <code>with torch.no_grad()</code></p> <pre><code>with torch.no_grad(): y = reward + gamma * torch.max(net.forward(x)) loss = criterion(net.forward(torch.from_numpy(o)), y) loss.backward(); </code></pre> <p><strong>Method 2:</strong> using <code>.detach()</code></p> <pre><code>y = reward + gamma * torch.max(net.forward(x)) loss = criterion(net.forward(torch.from_numpy(o)), y.detach()) loss.backward(); </code></pre> <p>Is there a difference between these two? Are there benefits/downsides to either?</p>
<python><pytorch>
2019-06-29 08:47:44
HQ
56,816,374
Context.Consumer vs useContext() to access values passed by Context.Provider
<pre><code>&lt;MyContext.Consumer&gt; {value =&gt; { }} &lt;/MyContext.Consumer&gt; VS let value = useContext(MyContext); </code></pre> <p>What is the difference between this two snippets, using Context.Consumer and using useContext hook to access values passed by the context Provider? I think useContext will subscribe to the context Provider, since we passed the Context as an argument, so that it will trigger a re-render, when the provider value changes.</p>
<reactjs><react-hooks>
2019-06-29 09:12:35
HQ
56,817,728
Ruby on rails toggling favourite button using jquery and ajax comes with "rendering head :no_content Completed 204 No Content'
I am trying to create a favourite button where users will be able to use toggle button to 'favourite' a post and 'unfavourite' same depending on what they like. So far if I 'unfavourite' the post it seems to work but whenever i do otherwise the link does not change. I used jquery and ajax. class FavouritesController < ApplicationController before_action :authenticate_user! def create @favourite = current_user.favourites.build(favourite_params) if @favourite.save @post = @favourite.post respond_to :js else flash[:alert] = "something went wrong..." end end def destroy @favourite = Favourite.find(params[:id]) @school = @favourite.post if @favourite.destroy respond_to :js else flash[:alert] = "Something Went Wrong..." end end private def favourite_params params.permit :user_id, :post_id end end HERE ARE THE MODELS class Post < ApplicationRecord belongs_to :user has_many :favourites def is_favourited user Favourite.find_by(user_id: user.id, school_id: id) end end FAVOURITE MODEL class Favourite < ApplicationRecord belongs_to :user belongs_to :post end CREATED J.S IN THE FAVOURITE VIEW FOLDER IE VIEWS/FAVOURITES/created.js.erb $('#favourite').html('<%= j render "posts/favourite", {is_favourited: @is_favourited, post: @post} %>'); console.log("Added to your favourite List"); CREATED J.S IN THE FAVOURITE VIEW FOLDER IE VIEWS/FAVOURITES/destroy.js.erb /destroy.js.erb $('#favourite').html('<%= j render "posts/favourite", {is_favourited: @is_favourited, post: @post} %>'); console.log("Added to your favourite List"); FAVOURITE PARTIAL FILE IN THE POSTS FOLDER IE VIEWS/POSTS/_favourite.html.erb <% if @is_favourited.present? %> <%= link_to "favourited", favourite_path(@is_favourited), method: :delete, remote: true, id: 'favourited' %> <% else %> <%= link_to "favourite", post_favourites_path(@post), method: :post, remote: true, id: 'favourite' %> <% end %> ON THE SHOW PAGE OF THE POST I RENDERED THE PARTIAL LIKE THIS <%= render 'favourite' %>
<ruby-on-rails><ruby>
2019-06-29 12:58:36
LQ_EDIT
56,818,409
Is there any way to select some rows in data set whose for some columns they reapet more than once?
<p>I have a data set with 10000 rows and 32 columns. I am wondering is it possible we choose some rows whose have the same value for some features? </p> <p>Here is an example which make my question more clear. </p> <pre><code>col1 col2 col3 col4 col5 1 2 3 4 5 3 4 3 6 8 2 2 5 4 5 4 2 7 4 5 5 4 `8 6 8` 2 3 1 0 9 3 4 1 5 2 </code></pre> <p>In this data set there are 5 columns. Suppose I want to select some rows whose have same value in column 2,4 and 5. </p> <p>As it can be seen, the first, third and forth row have same value in col2 , col4 and col5 also second and 5-th rows have same value in those columns. So I will pick these rows and new data set will be</p> <pre><code> col1 col2 col3 col4 col5 1 2 3 4 5 3 4 3 6 8 2 2 5 4 5 4 2 7 4 5 5 4 `8 6 8` </code></pre>
<r><database>
2019-06-29 14:41:42
LQ_CLOSE
56,819,208
SQL Multiple Joins Query-Error while executing
I am trying to execute the below query having multiple joins between tables. However, I am getting an error "%s: Invalid Identifier" in SQL Developer. The below column throws an error: "GCCCOND.ID_COND", invalid identifier I validated the query online and I couldn't understand what am I missing in this one. Any insights regarding this would be really helpful. Here is the query-- SELECT gcibjdnf.danfe, gcibjdnf.bjd_situacao, gcibjdnf.obs_rejeicao, gcibjdnf.bjd_tipo_cobranca, gcibjdnf.bjd_data_vencto_cbs, gcibjdnf.bjd_liberacao_valor, gcibjdnf.bjd_liberacao_data, gcibjdnf.cd_rejeicao, gcibjdnf.id_cond, gcibjdnf.bjd_sit_interna, gcibjdnf.dh_carga_nf, gcibjdnf.dt_expira, gcibjdnf.cd_emp, gcibjdnf.cd_und, gcibjdnf.sg_mod, gcibjdnf.cd_cli, gcibjdnf.nr_ctr, gcibjdnf.nr_adl, gcibjdnf.planta, gcibjdnf.nf_data, gcibjdnf.nf_numero, gcibjdnf.dealer_sap, gcibjdnf.baan_fatura, gcibjdnf.sap_titulo, gcibjdnf.nf_valor_total, gcibjdnf.nf_fdd, gcibjdnf.nf_data_gravacao, gcibjdnf.nf_tipo_produto, gcibjdnf.pedido_cotacao, gcibjdnf.jdb_situacao_normal, gcibjdnf.jdb_situacao_proc, gcibjdnf.cd_liberada, SUM(gcinfitens.item_valor_contratar) AS nf_vl_contratar, Max(gcrcontitens.id_contgrupo) AS id_contgrupo, MIN(gmin.nu_interv) AS nu_min_prz, MAX(gmax.nu_interv) AS nu_max_prz, priper.vl_taxa AS nu_taxa, priper.cd_tp_taxa, priper.cd_indicador, gcccond.nm_cond, gcccond.cd_tp_ctr, priper.sg_mod AS sg_mod_cond, gcccond.dt_validade, gcccond.cd_sit AS cd_sit_cond, gcccond.nu_car_prz, gcccond.cd_base_carencia, gcccond.nu_car_desc, apcconc.cd_loja, apcconc.cd_concess, apcconc.cd_conc_mat, apcconc.nm_conc, apcconc.nm_apelido, apcconc.cd_tp_mercado, dnccontrfundo.dt_emis_ctr FROM gcibjdnf LEFT JOIN gcinfitens ON gcinfitens.danfe = gcibjdnf.danfe LEFT JOIN gcrcontitens ON gcrcontitens.danfe = gcibjdnf.danfe LEFT JOIN gcrcondper gmin ON gmin.id_cond = gcccond.id_cond LEFT JOIN gcrcondper gmax ON gmax.id_cond = gcccond.id_cond LEFT JOIN apcconc ON TO_CHAR(apcconc.cd_sap_dealer) = gcibjdnf.dealer_sap LEFT JOIN gcccond ON gcccond.id_cond = gcibjdnf.id_cond LEFT JOIN dnccontrfundo ON dnccontrfundo.danfe = gcibjdnf.danfe AND dnccontrfundo.cd_sit NOT IN ('CA', 'RE') LEFT JOIN gcrcondper priper ON priper.id_cond = gcccond.id_cond AND priper.sq_per = 1 WHERE ( ( apcconc.cd_concess = '1586297' OR apcconc.cd_conc_mat = '1586297' ) AND gcibjdnf.bjd_situacao = 'I' AND bjd_sit_interna IN ('NO', 'SD') ) ORDER BY apcconc.nm_apelido, danfe
<sql><oracle><performance><query-optimization><sql-tuning>
2019-06-29 16:44:56
LQ_EDIT
56,819,218
How to delete string with no specific character pattern?
<p>I think what I want to do is a fairly common task but I've found no reference on the web.</p> <p>I have a list of names, with the following pattern</p> <p>'first name middle name last name last seen 10 months ago"</p> <p>I want to keep only the names, to delete all the string starting from the word last, is there a way I can do it?</p> <p>Example:</p> <p>output = ' David Smith last seen 8 months ago'</p> <p>desired_output = 'David Smith'</p> <p>I thought using regular expression, but I didn't succeed. </p> <p>Thanks</p>
<python><string>
2019-06-29 16:45:54
LQ_CLOSE
56,820,327
The name tf.Session is deprecated. Please use tf.compat.v1.Session instead
<p>I got the following deprecation warning in my tensorflow code: </p> <blockquote> <p>The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.</p> </blockquote> <ul> <li>Why I got this warning</li> <li>What will happen in tensorflow 2.0. instead of <code>tf.session</code></li> <li>Is it okay to use <code>tf.compat.v1.Session</code></li> </ul>
<tensorflow><tensorflow2.0>
2019-06-29 19:29:51
HQ
56,820,782
I need to Parse whole java code and save statements in a tree structure for making Control flow graph
<p>I need to identify java source code all type of statements and store them in a tree structure to make a control flow graph! what i cannot understand is how should i read a java source code so that my program may distinguish all different types of statements in java( if,for, classes, methods etc.) Do i need to add the whole grammar of java language?</p> <p>what i cannot understand is how should i read a java source code so that my program may distinguish all different types of statements in java( if,for, classes, methods etc.)</p>
<java><parsing>
2019-06-29 20:47:36
LQ_CLOSE
56,821,342
Why do we need to use bind() in ReactJS to access this.props or this.state?
<p>look at this code for example</p> <pre><code> import React, { Component } from ‘react’; class App extends Component { constructor(props) { super(props); this.clickFunction = this.clickFunction.bind(this); } clickFunction() { console.log(this.props.value); } render() { return( &lt;div onClick={this.clickFunction}&gt;Click Me!&lt;/div&gt; ); } } </code></pre> <p>what's the purpose of bind(this) ? it binds the function clickFunction to the context of the object which clickFunction is already bound to , let me illustrate what i am trying to say with a normal javascript code : </p> <pre><code>class my_class { constructor() { this.run = this.run.bind(this) } run() { console.log(this.data) } } my_class.data = 'this is data' new my_class().run() //outputs 'undefined' </code></pre> <p>and if you remove bind(this) it will give you the same results </p> <pre><code> constructor() { this.run = this.run } </code></pre> <p>results : </p> <pre><code>new my_class().run() //still outputs 'undefined' </code></pre> <p>i am sure i am understanding something wrong and this might the worst question on earth however i am new to es6 and i am not used to classes yet so i apologize for that</p>
<javascript><reactjs>
2019-06-29 22:48:19
LQ_CLOSE
56,822,573
How to create a color with an alpha value using SwiftUI?
<p>In <code>UIKit</code> to create a color with an alpha value there are different ways, for example:</p> <pre><code>UIColor(red: 0, green: 0, blue: 0, alpha: 0.8) </code></pre> <p>but this method is not available on the corresponding class <code>Color</code> of <code>SwiftUI</code>.</p> <p>What can I use?</p>
<ios><swiftui>
2019-06-30 05:15:55
HQ
56,822,791
Hug subviews in SwiftUI
<p>Dave Abrahams explained some of the mechanics of SwiftUI layouts in his WWDC19 talk about Custom Views, but he left out some bits and I have trouble getting my views properly sized. </p> <p><strong>Is there a way for a View to tell its container that it is not making any space demands, but it will use all the space it is given? Another way to say it is that the container should hug its subviews.</strong></p> <p>Concrete example, I want something like c:</p> <p><a href="https://i.stack.imgur.com/nuA4r.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nuA4r.png" alt="Some Texts inside a VStack"></a></p> <p>If you have some <code>Text</code>s inside a <code>VStack</code> like in a), the <code>VStack</code> will adopt it's width to the widest subview.</p> <p>If you add a <code>Rectangle</code> though as in b), it will expand as much as it can, until the <code>VStack</code> fills <em>its</em> container.</p> <p>This indicates that <code>Text</code>s and <code>Rectangle</code>s are in different categories when it comes to layout, <code>Text</code> has a fixed size and a <code>Rectangle</code> is greedy. <strong>But how can I communicate this to my container if I'm making my own <code>View</code>?</strong></p> <p>The result I actually want to achieve is c). VStack should ignore Rectangle (or my custom view) when it determines its size, and then once it has done that, <em>then</em> it should tell Rectangle, or my custom view, how much space it can have.</p> <p>Given that SwiftUI seems to layout bottom-up, maybe this is impossible, but it seems that there should be <code>some</code> way to achieve this.</p>
<swift><swiftui>
2019-06-30 06:08:56
HQ
56,822,823
WinAPI ReadFile returns corrupted data
<p>I'm writing a function in my Visual C++ project that reads contents of a file via WinAPI in 2000 byte increments and returns it as a std::string.</p> <p>A problem occurs when the file is much larger than the buffer (for example 100 KB), I get garbage added at several locations in the file in the middle of valid data. This is a long <code>0xcccccccc...</code> sequence terminated by 3-4 other bytes, usually appearing in the middle of a word. The function doesn't fail otherwise and none of the valid data is missing.</p> <p>I haven't checked the exact positions but it seems that this happens at buffer size increments (or a multiplier of buffer size increments). If I increase the size of the buffer to more than the size of the test files, the problem goes away. What causes this to happen? What am I doing wrong?</p> <pre><code>std::string read_file(std::string filename) { HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if (hFile == INVALID_HANDLE_VALUE) { std::string errortext("Error opening " + filename + ", bad handle value: " + to_string((int)hFile)); MessageBox(hwnd, errortext.c_str(), "Error", 0); return ""; } char buffer[2000] = ""; std::string entire_file = ""; DWORD dwBytesRead = 0; while (ReadFile(hFile, buffer, sizeof(buffer), &amp;dwBytesRead, NULL)) { if (!dwBytesRead) break; entire_file += buffer; } CloseHandle(hFile); return entire_file; } </code></pre>
<c++><winapi><visual-c++><readfile><createfile>
2019-06-30 06:15:43
LQ_CLOSE
56,822,896
How do I make it if a certain json string will run a command
I'm making a level system for my discord bot, I want it so if I reach level 5, it will give me a role. How do I make it so it reads the json file to see if my level is level 5?
<discord.js>
2019-06-30 06:34:52
LQ_EDIT
56,823,458
How to initialize an Int from a map Value, C++
<p>I have a large global map in a header of weapon names and ID numbers from a video game . I am trying to find a way that I can take user input for the name and return the item number. For this I created a new int and would like to initialize it with the map value after searching for the name. What is the best way to do this?</p> <pre><code>//header #include &lt;map&gt; #include &lt;string&gt; using namespace std; typedef std:: map &lt;std :: string, int&gt; weaponMap; inline weaponMap &amp; globalMap() { static weaponMap theMap; static bool firstTime = true; if (firstTime) { firstTime = false; theMap["weaponOne"] = 854000; } } //Source.cpp #includes "globalMap" int swapWeapon = weaponMap::["weaponOne"]; cout &lt;&lt; swapWeapon; </code></pre>
<c++><initialization><unordered-map>
2019-06-30 08:25:56
LQ_CLOSE
56,824,636
iam beginner in android testing with Mockito
i want to test this method using mockito and unit testing `public class CurrentIP { public static String getIPAddress() { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress(); boolean isIPv4 = sAddr.indexOf(':') < 0; if (isIPv4) return sAddr; } } } } catch (Exception ignored) { } // for now eat exceptions return ""; } }`
<android><testing><mockito>
2019-06-30 11:52:51
LQ_EDIT
56,824,735
I am having error while running nativescrpt
Am having this error when ever I try tns run android Unable to apply changes on device: 037440992E015901. Error is: zlib: unexpected end of file. ENOTEMPTY: directory not empty, rmdir 'C:\Users\Hazin\AppData\Local\Temp\runtimeDir119530-8496-2dkhiq.wv07n\framework\build-tools'
<nativescript-angular>
2019-06-30 12:09:09
LQ_EDIT
56,825,114
Why does printf function ignore the latter \0?
<p>I am stuck with some features that \0 has.</p> <p>I know that \0 is a null character and it is a term to indicate that the formal is a string. </p> <pre><code>int j; j = printf("abcdef\0abcdefg\0"); printf("%d", j); return 0; </code></pre> <p>When I tried to print "abcdef\0abcdefg\0" out, C would only print string 'abcdef' and '6' instead of both 'abcdef' and 'abcdefg' which would sum up to 13. Why does this happen?</p>
<c>
2019-06-30 13:13:40
LQ_CLOSE
56,825,122
Can get the data response
I am trying to get some data to my state, from a fake online rest api, the problem is the data is not getting to the state properly, so it's not showing up. I have tried to change the state to array or just like this ``` firstName: '', ...``` and it still wont work ``` import React, { Component } from 'react'; import axios from 'axios'; class Success extends Component { state = { firstName: [], username: [], email: [], id: [], show: false }; componentDidMount() { axios .get('https://jsonplaceholder.typicode.com/users') .then(res => this.setState({ firstName: res.data.name })); } onClick = () => { this.setState(prevState => ({ show: !prevState.show })); }; render() { return ( <div> <h1 className="font-weight-light" style={{ color: 'black', marginTop: '50px' }} > UserList: </h1> <div className="mt-5"> <ul className="list-group"> <li className="list-group-item"> {this.state.firstName} <div className="fas fa-angle-down" style={{ marginLeft: '98%' }} onClick={this.onClick} /> </li> {this.state.show === true ? ( <li className="list-group-item"> Username: {this.state.username} </li> ) : null} {this.state.show === true ? ( <li className="list-group-item">Email: {this.state.email}</li> ) : null} {this.state.show === true ? ( <li className="list-group-item">ID: {this.state.id}</li> ) : null} </ul> </div> </div> ); } } export default Success; ``` I want the data to get in the state and show up.
<reactjs><axios>
2019-06-30 13:15:24
LQ_EDIT
56,828,663
How to explicitly set samesite=None on a flask response
<p>Due to changes arriving in Chrome during July, I need to modify my app to explicitly provide the SameSite=None key value. This is due to the RFC treating the absence of this setting in a more impacting way than if it is present but set to None. </p> <p>However on the set_cookie method, the samesite parameter is defaulted to None which results in it not being written into the set-cookie. How can I force this into the set-cookie part of the response?</p> <p>When I try to set the samesite=None with the following code</p> <pre><code>resp.set_cookie('abcid', 'Hello', domain=request_data.domain, path='/', samesite=None, max_age=63072000) </code></pre> <p>This does not show any SameSite detail in the returned set-cookie</p> <blockquote> <p>abcid=Hello; Domain=.localhost; Expires=Tue, 29-Jun-2021 22:34:02 GMT; Max-Age=63072000; Path=/</p> </blockquote> <p>And if I try and explicitly set the value of Lax (which is one of the accepted values per rfc) as so</p> <pre><code>resp.set_cookie('abcid', "Hello", domain=request_data.domain, path='/', samesite="Lax", max_age=63072000) </code></pre> <p>I get back the set-cookie which explicitly has the SameSite=Lax setting</p> <blockquote> <p>abcid=Hello; Domain=.localhost; Expires=Tue, 29-Jun-2021 23:03:10 GMT; Max-Age=63072000; Path=/; SameSite=Lax</p> </blockquote> <p>I have tried None, "None", and "" but these either crash the application or omit the SameSite in the resultant response.</p> <p>Any help would be gratefully received</p>
<python><flask><cookies><samesite>
2019-06-30 23:13:41
HQ
56,828,685
Can't git push to Bitbucket: Unauthorized - fatal: Could not read from remote repository
<p>I can't push to Bitbucket and this is the error message:</p> <blockquote> <p>> git push origin master:master<br> Unauthorized<br> fatal: Could not read from remote repository.</p> <p>Please make sure you have the correct access rights and the repository exists.</p> </blockquote> <p>Debugging, I receive this message when I ssh to bitbucket:</p> <blockquote> <p>> ssh -T bitbucket.org<br> authenticated via a deploy key.</p> <p>You can use git or hg to connect to Bitbucket. Shell access is disabled.</p> <p>This deploy key has read access to the following repositories:<br> my-username/my-repository</p> </blockquote> <p>The <strong>read access</strong> part of this message is suspicious.</p> <p>PS: I know there are dozens of similar questions, but I couldn't find the exact error message here and only got <a href="https://community.atlassian.com/t5/Bitbucket-questions/Unable-to-push-code-to-my-private-repo/qaq-p/708507" rel="noreferrer">the solution outside</a>. That's why I'm self answering this to help others.</p>
<git><bitbucket>
2019-06-30 23:18:53
HQ
56,829,581
(Python) Returning specific values in a string of different format
How do I make python automatically searches a certain specific type of data (e.g date) in a string of different format ? For example, For unix values such as -rwxr-xr-x 1 user usergrp 1632 Feb 26 11:03 Desktop/Application, it should return 26 Feb 19 For values such as Desktop/Application,1632,26/02, it should search out for “26/02” and return 26 Feb 19 For values such as 26/02/19 - Desktop/Application - 1632, it should search out for “26/02/19” and return 26 Feb 19 Appreciate all help provided, thank you everyone!
<python><python-3.x><date>
2019-07-01 03:02:38
LQ_EDIT
56,830,158
why does datetime.today.minute doesn't give the actual minutes
I'm learning Python. Recently, I have encountered, that while using "datetime.today().minute" gives me o/p by adding 30. When I'm commenting the -30 part that time the output is +30 of what the recent minute is, if I keep the -30 part then it gives the correct reselt. Why is that? Code : from datetime import datetime odds = [1, 3, 5, 7, 9, 11 ,13, 15, 17, 19, 21, 23, 25, 27, 29 ,31, 33, 35, 37, 39 ,41, 43, 45, 47 ,49 ,51 ,53 ,55 ,57, 59] odd_min = datetime.today().minute #- 30 print(odd_min) #print("\n") if odd_min in odds: print("Odd min") else: print("Not odd min") O/P : 48 Not odd min When I'm subtracting 30 it gives the correct result. But I wanna know why it doesn't gives the correct output.
<python><python-3.x>
2019-07-01 04:57:59
LQ_EDIT
56,831,319
JavaScript Regex - check for enum value
<p>Currently I have a text field that allow user to enter an <code>Enum</code> value. Once they enter a value I need to validate those value first and throw an error message if not match.</p> <p>The <code>Enum</code> format will be - </p> <pre><code>yes|no|maybe#yes yes | no | maybe #yes 1|2|3|4|5#0 </code></pre> <ol> <li>string must have <code>|</code> symbol, so in the future I able to split the characters.</li> <li><code>#</code> symbol and the end. This will be a "default value" for enum. </li> </ol> <p>How to create this regex? Thanks in advance.</p>
<javascript><jquery><regex>
2019-07-01 07:09:04
LQ_CLOSE
56,831,632
my dates changed to a several digits combination - Sql Server
I have a column in my DB named `BirthDate`. SomeHow (Unfortunately I can't say how and why) the dates became just to several digits and the column type is now `char`. Sorry I can't tell more since it's a new project for me, and I just got some assignments to do. For instance, a date now represented as : 081101 (and it's not 08/11/2001 , that's for sure) Any chance I can get back to original? what are these digits at all? any clue?
<sql><sql-server><date>
2019-07-01 07:33:10
LQ_EDIT
56,831,787
how to solve prime number program?
I'm trying to print all the prime numbers between 2 and 100, but i'm getting only 2 & 3. I've tried every possible alternates, and it comes up with different error or different output. ```class vision{ ```public static void main(String args[]){ ```boolean flag=true; ```for( int i=2;i<=100;i++){ ```for(int j=2;j<i;j++){ ```if(i%j==0){ ```flag=false; ```break; ```} ```} ```if(flag){ ```System.out.println(i); ```} ```} ```} ```} i don't need any alternate way , i just wanna know what's happening in my code and why it gives only 2 & 3.
<java><primes>
2019-07-01 07:46:31
LQ_EDIT
56,831,997
Repeat the content in jquery slick
I have to display dynamically added content using jquery slick carousel. Min and Max I have to display 6 content in the slide. If content is less than 6 it should repeat the same content. for example if the slideToShow:6 but if there is only 4 contents are there. It should repeat the 1st and 2nd content in the last. I cant find out the method in slick for repetition.
<jquery><carousel><slick.js>
2019-07-01 08:02:02
LQ_EDIT
56,832,056
how to put getting rows from excel in an arrayllist in java?
The following code for reading the existing excel file in java. I want to get likely [[a, b], [b, c, d], [a, c, d, e], [a, d, e], [a, b, c], [a, b, c, d], [a], [a, b, c], [a, b, d], [b, c, e]]... where [a,b] referred to one row in excel file.Please help me.. public class Excel { public static void main(String[] args) throws FileNotFoundException { List<Set<String>> itemsetList = new ArrayList<>(); Scanner scanner = new Scanner(new File("bc_dataset.csv")); scanner.next(); while(scanner.hasNext()){ String str=scanner.next(); itemsetList.add(new HashSet<>(Arrays.asList(str.split(",")))); System.out.println(itemsetList); } scanner.close(); } }
<java><arraylist>
2019-07-01 08:06:34
LQ_EDIT
56,832,253
If statement to check if User has a product
One User has many products, one product only belongs to one user. In User profile, I want to implement this concept: 1/ If user does not have a product, "Create new product" button is available 2/ If user already has a store, both "Create new product" and list of products that can be clicked on to direct to the product itself <% if @product.include? current_user.id %> ```ruby <% if @product.include? current_user.id %> <%= link_to 'My product', product_path %> <% end %> <%= link_to 'Create New Product', new_product_path %> <%= link_to 'Edit', edit_user_registration_path %> ``` Expect: 1/ If user does not have a product, "Create new product" button is available 2/ If user already has a store, both "Create new product" and list of products that can be clicked on to direct to the product itself
<ruby-on-rails>
2019-07-01 08:23:29
LQ_EDIT
56,832,897
Change the format of the returned data when selecting records. Flask
<p>In my flask application, in routes.py I get entries with specific fields of the <code>Location</code> model:</p> <pre><code>... location = db.session.query(Location.id, Location.name,Location.code, Location.id_parent).all() newLocat = list( location) print(str(newLocat)) ... </code></pre> <p>The format of the returned data is as follows:</p> <pre><code>[(1, 'Test1', 101, 0), (2, 'Test2', 202, 1)] </code></pre> <p>How to make the returned data format look like this?</p> <pre><code>[{'id': '1', 'name': 'Test1','code':101, 'id_parent': '0'}, {'id': '2', 'name': 'Test2','code':202, 'id_parent': '1'}] </code></pre>
<python><flask>
2019-07-01 09:09:55
LQ_CLOSE
56,833,469
Typescript error: TS7053 Element implicitly has an 'any' type
<p>this is part of my code:</p> <pre class="lang-js prettyprint-override"><code>const myObj: object = {} const propname = 'propname' myObj[propname] = 'string' </code></pre> <p>but I got error:</p> <pre class="lang-sh prettyprint-override"><code>ERROR in path/to/file.ts(4,1) TS7053: Element implicitly has an 'any' type because expression of type '"propname"' can't be used to index type '{}'. Property 'propname' does not exist on type '{}'. </code></pre> <p>What is wrong here, and how can I fix it?</p>
<typescript>
2019-07-01 09:49:53
HQ
56,834,679
Is there any way we can restrict the android application at the time of installation
Its like we specify in android manifest file about minimum amd maximun sdk version so can we restrict the installation of an android application depending on the processor it has like qualcom,mediatek etc.
<android>
2019-07-01 11:13:02
LQ_EDIT
56,836,013
How to use servlet 3.1 in spring mvc?
<p>There are 2 different features available:</p> <ol> <li><p><strong>servlet 3.0</strong> allows to process request in a thread different from the container thread.</p></li> <li><p><strong>servlet 3.1</strong> allows to read/write into socket without blocking reading/writing thread</p></li> </ol> <p>There are a lot of examples in the internet about servlet 3.0 feature. We can use it in Spring very easily. We just have to return <code>DefferedResult</code> or <code>CompletableFuture</code></p> <p>But I can't find example of usage servlet 3.1 in spring. As far as I know we have to register <code>WriteListener</code> and <code>ReadListener</code> and do dome dirty work inside. But I can't find the example of that Listeners. I believe it is not very easy.</p> <p>Could you please provide example of servlet 3.1 feature in spring with explanation of Listener implementaion ?</p>
<java><spring-boot><spring-mvc><nio><servlet-3.1>
2019-07-01 12:48:00
HQ
56,839,374
UITabBarItem icon not colored correctly for iOS 13 when a bar tint color is specified in Interface Builder in Xcode 11, beta 2
<p>I have a problem with the color of my UITabBarItems when I run on iOS 13 simulators, using Xcode 11, beta 2. I have made a sample project from scratch, and everything works correctly when I do not specify a bar tint color. However, when I do specify a custom bar tint color via Interface Builder, I get this:</p> <p><a href="https://i.stack.imgur.com/W2YfC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W2YfC.png" alt="Both selected an unselected item icons have highlight color"></a></p> <p>All items icons in the tab bar have the selected color if I set the "Bar Tint" property in Interface Builder to anything but clear. When it is set to clear, the icons are colored properly. The icons are also colored properly if I compile and run in an iOS 12 simulator.</p> <p>This seems like a bug in Xcode 11, but maybe I'm missing something?</p>
<ios><uitabbarcontroller><interface-builder><uitabbaritem><xcode11>
2019-07-01 16:44:27
HQ
56,839,430
Controling user input as per expected in Python 3
If you ask someone a yes/no question then the answer is one of these two options. In programming what if the response was "Y" or "y" or "yes" or whatever? I had to create a compound condition repeating my statement while its actually the same one. I'm not an expert but i can see that it can be improved. below is s snippet from my code: -------------------------------- def note_maker(note): case_note = open("case_note.txt", "a+") update = case_note.write("\n" + note) multiple_inputs = input("Do you want to enter more details? Y/N") while multiple_inputs == "yes" or multiple_inputs == "YES" or multiple_inputs == "Yes" or multiple_inputs == "Y" or multiple_inputs == "y": update_again = case_note.write("\n" + input("Enter your additional information")) multiple_inputs = input("Do you want to enter more details?") case_note.close() Is there a way to control the user input into what I expect ? thanks alot,
<python><python-3.x><input>
2019-07-01 16:48:33
LQ_EDIT
56,840,403
How do I make a sideways L look in html/css?
<p><a href="https://i.stack.imgur.com/PXZnP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PXZnP.png" alt="enter image description here"></a></p> <p>I know the title wasn't the best way to describe it. But I am trying to recreate the symbols shown in the image on both sides of the word interval. I have no idea how to do this. Is it a symbol? Or some kind of graphic using svg?</p>
<html><css>
2019-07-01 18:05:18
LQ_CLOSE
56,840,495
setLevel okhttp LoggingInterceptor deprecated
<p>setLevel(okhttp3.logging.HttpLoggingInterceptor.Level)' is deprecated</p> <p>what should replace with setLevel? to remove the deprecated issue</p>
<android><retrofit2><okhttp3>
2019-07-01 18:12:20
HQ
56,840,549
What is the proper way to put divider lines between navigation links?
<p>I have a CSS/HTML homework assignment to make a page look like the page my instructor gave me. I need to add "pipes" in between the links. I added pipe characters to my HTML, but I don't feel like that is the proper way to do it. Thanks! Here is a screenshot of what it needs to look like: </p> <p><a href="https://i.imgur.com/sC7OLut.png" rel="nofollow noreferrer">https://i.imgur.com/sC7OLut.png</a></p>
<html><css>
2019-07-01 18:16:52
LQ_CLOSE
56,840,994
How to show Icon in Text widget in flutter?
<p>I want to show an icon in text widget. How do I do this ? </p> <p>The following code only shows the <code>IconData</code></p> <pre><code>Text("Click ${Icons.add} to add"); </code></pre>
<flutter>
2019-07-01 18:53:36
HQ
56,841,585
Delphi - How to use Alt Codes?
Delphi RIO - I need to build a string which contains Alt Codes, specifically Alt-16 (Arrow symbol). I have a line of text (aka a string). I append a Carriage return, then want an ARROW symbol and the new line of text. This line will then be passed to PPT. If I manually go into PPT, into a text box, I can hit Alt+16, and get the arrow symbol. This is what I programatically want to do. Alt symbols found [here][1]. Here is what I am trying, but it gives me a totally different symbol. line := line + #13 + Chr(VK_MENU) + #16 + NewLine; How do I build a string with ALT Codes as part of the string? [1]: https://www.alt-codes.net/
<delphi><delphi-10.3-rio>
2019-07-01 19:44:12
LQ_EDIT
56,841,995
How to convert my fat arrow function to a "normal" function in javascript
<p>I'm just trying to convert this to a normal js function without the "fat arrow".</p> <p>I want body => to be a normal function.</p> <p>How do I write that?</p> <p>snippet from code</p> <pre><code>fetch(this.JobExecEndpoint) .then(response =&gt; response.json()) .then(body =&gt; { this.cleanStartTime = moment(body[0].time_start); this.cleanEndTime = moment(body[0].time_end); this.cleanDuration = this.calculateDuration( this.cleanStartTime, this.cleanEndTime ); </code></pre>
<javascript>
2019-07-01 20:23:56
LQ_CLOSE
56,842,217
Scrape YouTube video views
<p>I have a list of youtube video links like this <a href="https://www.youtube.com/watch?v=ywZevdHW5bQ" rel="nofollow noreferrer">https://www.youtube.com/watch?v=ywZevdHW5bQ</a> and I need to scrape the views count using BeautifulSoup and requests library</p>
<python><beautifulsoup><youtube><screen-scraping>
2019-07-01 20:42:46
LQ_CLOSE
56,842,353
download file 1Gb
I am having difficulty downloading files with a size of 1 GB. Smaller files works fine. I've tried some options. My file is a zip folder that contais some pdf files. I've tried some options like use WebClient namespace This is my code that works just smaller files. byte[] fileBytes = System.IO.File.ReadAllBytes(sPath); string fileName = System.IO.Path.GetFileName(sPath); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); my fileBytes variable stay like this = byte[1099288209] and I get a "Overflow or underflow in the arithmetic operation." But when my file has 1Gb size or greater it isn't works. If a use the WebClient namespace I have the follow error: wClient.DownloadFile("https://site/folder/", sPath); "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.127.1.180:8080" my fileBytes variable stay like this = byte[1099288209] and I get a "Overflow or underflow in the arithmetic operation." Using webClient I get an error like this "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.127.1.180:8080"
<c#><webclient-download>
2019-07-01 20:54:08
LQ_EDIT
56,843,745
Automatic cell execution timing in jupyter lab
<p>In jupyter <strong>notebook</strong>, I can configure an automatic cell timing with <a href="https://github.com/ipython-contrib/jupyter_contrib_nbextensions" rel="noreferrer">nbextensions</a>, the result is like so:</p> <p><img src="https://i.ibb.co/n78VmMs/Screenshot-1.png" alt="jupyter_notebook"></p> <p>How can i do this in jupyter <strong>lab</strong>? I didn't found any extensions that did a similar thing.</p> <p>Obs.: I know that a similar result can be achieved with <code>%%time</code> magic, but i want it to be automatic, so I don't have to place the magic function at the begining of each cell</p>
<jupyter-notebook><ipython><jupyter><jupyter-lab>
2019-07-01 23:54:05
HQ
56,843,993
I need such type of matrix output in MS SQL server ...please help me with the query
I need count of customers who got subscribed to channels. Where channel =telugu and channel = hindi Where channel =telugu and channel = English Where channel = hindi and channel = English
<sql-server>
2019-07-02 00:42:40
LQ_EDIT
56,845,422
how come small dataset in dataset has high variance?
Why small dataset has a high variance? Out professor once said it. I just did not understand it. Any help would be greatly appreciated. Thanks in advance.
<machine-learning><data-science>
2019-07-02 04:40:49
LQ_EDIT
56,847,212
App is running but doe not fetch data from json
I am learning json and not getting solution. I have tried updating my json file and xml file but no working. here is the code the errors I have faced in the code is written in the comment section below please help me through it. The app is running perfectly but does not fetch data from this link below https://api.myjson.com/bins/1hkm17 package com.taxsmart.jsonsimpleexample; import android.os.AsyncTask; import com.taxsmart.jsonsimpleexample.MainActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class fetchData extends AsyncTask<Void,Void,Void> { String data =""; String dataParsed = ""; String singleParsed =""; @Override protected Void doInBackground(Void... voids) { try { URL url = new URL("https://api.myjson.com/bins/1hkm17"); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while(line != null){ line = bufferedReader.readLine(); data = data + line; } JSONArray JA = new JSONArray(data); for(int i =0 ;i <JA.length(); i++){ JSONObject JO = (JSONObject) JA.get(i); singleParsed = "Name" + JO.get("name") + "\n"+ "Password" + JO.get("Password") + "\n"+ "Contact" + JO.get("Contact") + "\n"+ "Country" + JO.get("Country") + "\n"; dataParsed = dataParsed + singleParsed +"\n" ; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); MainActivity.data.setText(this.dataParsed); } }
<java><android><json>
2019-07-02 07:17:29
LQ_EDIT