content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: What type of file this is and purpose of files name - (.jscsrc) { "requireCurlyBraces": [ "if", "else", "for", "while", "do" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "return" ], "disallowKeywords": [ "with" ], "disallowKeywordsOnNewLine": [ "else" ], "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireMultipleVarDecl": "onevar", "disallowMixedSpacesAndTabs": "smart", "disallowTrailingWhitespace": true, "requireSpacesInsideObjectBrackets": "all", "requireSpacesInsideArrayBrackets": "all", "requireSpacesInConditionalExpression": true, "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceAfterBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "disallowSpaceAfterPrefixUnaryOperators": [ "++", "--" ], "disallowSpaceBeforePostfixUnaryOperators": [ "++", "--" ], "disallowSpaceBeforeBinaryOperators": [ ",", ":" ], "disallowMultipleLineBreaks": true, "requireLineFeedAtFileEnd": true, "validateLineBreaks": "LF" } found this file in owl carousel want to understand importance of this file A: This file is a JSON file with a .jscsrc file extension. It is a configuration file used by JSCS (JavaScript Code Style), a code linting tool that checks JavaScript code for style errors and enforces a specific coding style. This file specifies the rules and settings that JSCS should use when linting the code. For example, it specifies that the keywords "if", "else", "for", "while", and "do" must be followed by curly braces, and that binary operators such as "+" and "=" must be surrounded by spaces. A: .jscsrc is the file extension for a configuration file used by the JSCS (JavaScript Code Style) linter. The purpose of this file is to specify the coding conventions and rules that JSCS should enforce when linting JavaScript code. The file consists of a JSON object that contains various properties and their corresponding values, which define the linting rules. For example, the "requireCurlyBraces" property in the provided code snippet specifies that JSCS should require curly braces for certain types of control structures (such as "if" and "for").
What type of file this is and purpose of files name - (.jscsrc)
{ "requireCurlyBraces": [ "if", "else", "for", "while", "do" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "return" ], "disallowKeywords": [ "with" ], "disallowKeywordsOnNewLine": [ "else" ], "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireMultipleVarDecl": "onevar", "disallowMixedSpacesAndTabs": "smart", "disallowTrailingWhitespace": true, "requireSpacesInsideObjectBrackets": "all", "requireSpacesInsideArrayBrackets": "all", "requireSpacesInConditionalExpression": true, "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceAfterBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "disallowSpaceAfterPrefixUnaryOperators": [ "++", "--" ], "disallowSpaceBeforePostfixUnaryOperators": [ "++", "--" ], "disallowSpaceBeforeBinaryOperators": [ ",", ":" ], "disallowMultipleLineBreaks": true, "requireLineFeedAtFileEnd": true, "validateLineBreaks": "LF" } found this file in owl carousel want to understand importance of this file
[ "This file is a JSON file with a .jscsrc file extension. It is a configuration file used by JSCS (JavaScript Code Style), a code linting tool that checks JavaScript code for style errors and enforces a specific coding style. This file specifies the rules and settings that JSCS should use when linting the code. For example, it specifies that the keywords \"if\", \"else\", \"for\", \"while\", and \"do\" must be followed by curly braces, and that binary operators such as \"+\" and \"=\" must be surrounded by spaces.\n", ".jscsrc is the file extension for a configuration file used by the JSCS (JavaScript Code Style) linter. The purpose of this file is to specify the coding conventions and rules that JSCS should enforce when linting JavaScript code. The file consists of a JSON object that contains various properties and their corresponding values, which define the linting rules. For example, the \"requireCurlyBraces\" property in the provided code snippet specifies that JSCS should require curly braces for certain types of control structures (such as \"if\" and \"for\").\n" ]
[ 0, 0 ]
[]
[]
[ "owl_carousel", "owl_carousel_2" ]
stackoverflow_0074672964_owl_carousel_owl_carousel_2.txt
Q: big-O-calculator: AttributeError: 'list' object has no attribute 'lower' I'm trying to calculate the speed of two functions that I have, this one uses quick sort method. I am using this page to download and use the big O calculator, and test the speed using this. But when I try to execute it, it throws me this error: AttributeError: 'list' object has no attribute 'lower'. I'm not sure why, otherwise the program works fine. from bigO import BigO data = "studentMockData_AS2.txt" students = [] with open(data, "r") as datafile: for line in datafile: datum = line.split() students.append(datum) size = len(students) def quicksort(array, lowest, highest): if lowest < highest: pi = partition(array, lowest, highest) quicksort(array, lowest, pi - 1) quicksort(array, pi + 1, highest) def partition(array, lowest, highest): pivot = array[highest] ptr = lowest - 1 for student in range(lowest, highest): if array[student] <= pivot: ptr += 1 (array[ptr], array[student]) = (array[student], array[ptr]) (array[ptr + 1], array[highest]) = (array[highest], array[ptr + 1]) return ptr + 1 lib=BigO() comp = lib.test(quicksort, students, 0, size-1) print(comp) A: Big0 test func parameters: def test(**args): functionName [Callable]: a function to call. array [str]: "random", "big", "sorted", "reversed", "partial", "Ksorted", "string", "almost_equal", "equal", "hole". limit [bool] = True: To break before it takes "forever" to sort an array. (ex. selectionSort) prtResult [bool] = True: Whether to print result by itself You are passing a list students to Big0.test() method where it is expecting a str. Use 'random' instead.
big-O-calculator: AttributeError: 'list' object has no attribute 'lower'
I'm trying to calculate the speed of two functions that I have, this one uses quick sort method. I am using this page to download and use the big O calculator, and test the speed using this. But when I try to execute it, it throws me this error: AttributeError: 'list' object has no attribute 'lower'. I'm not sure why, otherwise the program works fine. from bigO import BigO data = "studentMockData_AS2.txt" students = [] with open(data, "r") as datafile: for line in datafile: datum = line.split() students.append(datum) size = len(students) def quicksort(array, lowest, highest): if lowest < highest: pi = partition(array, lowest, highest) quicksort(array, lowest, pi - 1) quicksort(array, pi + 1, highest) def partition(array, lowest, highest): pivot = array[highest] ptr = lowest - 1 for student in range(lowest, highest): if array[student] <= pivot: ptr += 1 (array[ptr], array[student]) = (array[student], array[ptr]) (array[ptr + 1], array[highest]) = (array[highest], array[ptr + 1]) return ptr + 1 lib=BigO() comp = lib.test(quicksort, students, 0, size-1) print(comp)
[ "Big0 test func parameters:\ndef test(**args):\n functionName [Callable]: a function to call.\n array [str]: \"random\", \"big\", \"sorted\", \"reversed\", \"partial\", \"Ksorted\", \"string\", \"almost_equal\", \"equal\", \"hole\".\n limit [bool] = True: To break before it takes \"forever\" to sort an array. (ex. selectionSort)\n prtResult [bool] = True: Whether to print result by itself\n\nYou are passing a list students to Big0.test() method where it is expecting a str. Use 'random' instead.\n" ]
[ 0 ]
[]
[]
[ "big_o", "python", "quicksort" ]
stackoverflow_0074672974_big_o_python_quicksort.txt
Q: 320 Error after IBApi.EClient.placeOrder() in Python & Interactive Brokers I am trying to place an order through Interactive Brokers' Python API but receive the error: ERROR 1 320 Error reading request: Unable to parse data. java.lang.NumberFormatException: For input string: "1.7976931348623157e+308" Connecting and retrieving data works fine but when submitting an order, one of my parameters seems to be wrong and I simply can't figure out what it is. I was closely following IB's documentation, so it really comes as a bit of a surprise to me. The error code (320) is not really telling, unfortunately, as IB merely describes it as a "Server error". The only related question I found online, links the error to an invalid ID but I checked mine and it should be fine. The code: from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract from ibapi.order import Order import threading class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def run_loop(): app.run() app = IBapi() app.connect('127.0.0.1', 7496, 1) api_thread = threading.Thread(target = run_loop, daemon = True) api_thread.start() ctr = Contract() ctr.symbol = 'AAPL' ctr.secType = 'STK' ctr.exchange = 'SMART' ctr.currency = 'USD' ord = Order() ord.action = 'BUY' ord.orderType = 'LMT' ord.totalQuantity = 1 ord.lmtPrice = 150 app.reqIds(-1) id = app.nextValidOrderId print(id) print(isinstance(id, int)) app.placeOrder(id, ctr, ord) returns: 1 True ERROR 1 320 Error reading request: Unable to parse data. java.lang.NumberFormatException: For input string: "1.7976931348623157e+308" My TWS version is 10.20.1d, which is the latest as of now (since this fixed a somewhat related question). Can someone help me with what I am doing wrong, please? A: Using TWS 10.20.1d and API_Version=10.20.01 I find your code works with only a minor change with nextValidOrderId. Suggest checking API version, and upgrading if not latest version.
320 Error after IBApi.EClient.placeOrder() in Python & Interactive Brokers
I am trying to place an order through Interactive Brokers' Python API but receive the error: ERROR 1 320 Error reading request: Unable to parse data. java.lang.NumberFormatException: For input string: "1.7976931348623157e+308" Connecting and retrieving data works fine but when submitting an order, one of my parameters seems to be wrong and I simply can't figure out what it is. I was closely following IB's documentation, so it really comes as a bit of a surprise to me. The error code (320) is not really telling, unfortunately, as IB merely describes it as a "Server error". The only related question I found online, links the error to an invalid ID but I checked mine and it should be fine. The code: from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract from ibapi.order import Order import threading class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def run_loop(): app.run() app = IBapi() app.connect('127.0.0.1', 7496, 1) api_thread = threading.Thread(target = run_loop, daemon = True) api_thread.start() ctr = Contract() ctr.symbol = 'AAPL' ctr.secType = 'STK' ctr.exchange = 'SMART' ctr.currency = 'USD' ord = Order() ord.action = 'BUY' ord.orderType = 'LMT' ord.totalQuantity = 1 ord.lmtPrice = 150 app.reqIds(-1) id = app.nextValidOrderId print(id) print(isinstance(id, int)) app.placeOrder(id, ctr, ord) returns: 1 True ERROR 1 320 Error reading request: Unable to parse data. java.lang.NumberFormatException: For input string: "1.7976931348623157e+308" My TWS version is 10.20.1d, which is the latest as of now (since this fixed a somewhat related question). Can someone help me with what I am doing wrong, please?
[ "Using TWS 10.20.1d and API_Version=10.20.01 I find your code works with only a minor change with nextValidOrderId.\nSuggest checking API version, and upgrading if not latest version.\n" ]
[ 0 ]
[]
[]
[ "interactive_brokers", "java", "python" ]
stackoverflow_0074632771_interactive_brokers_java_python.txt
Q: Returning only non-null key/value in bigQuery I have an object in bigQuery that stores all possible parameters in the system. Therefore somewhere under the hood the 'parameter' object, has a lot of keys, and when I build a query to SELECT param it returns a lot of columns with null, and maybe only 1 with a value, which makes it impossible to analyze as the output table is incredibly wide. How can I write the query so that it returns 1 column, with only the non null key/value pair? i.e. instead of returning: param.phone, param.lob, param.destination, param.id, param.1, param.2 etc with null values i want to see one column with value {"e_line_of_business":"internet"} or any other non-null key/values. It's ok to be stringified. A: You might consider below approach. WITH sample_data AS ( SELECT STRUCT(STRING(null) AS phone, STRING(null) AS lob, STRING(null) AS destination, 'internet' AS e_line_of_business, STRING(null) AS param1) params UNION ALL SELECT STRUCT(STRING(null) AS phone, STRING(null) AS lob, STRING(null) AS destination, 'internet' AS e_line_of_business, 'value_1' AS param1) UNION ALL SELECT STRUCT('01012345678' AS phone, 'web' AS lob, STRING(null) AS destination, null AS e_line_of_business, null AS param1) ) SELECT params, REPLACE(REGEXP_REPLACE(TO_JSON_STRING(params), r'"[^,{]+"\:null,?', ''), ',}', '}') non_nulls FROM sample_data; Query results
Returning only non-null key/value in bigQuery
I have an object in bigQuery that stores all possible parameters in the system. Therefore somewhere under the hood the 'parameter' object, has a lot of keys, and when I build a query to SELECT param it returns a lot of columns with null, and maybe only 1 with a value, which makes it impossible to analyze as the output table is incredibly wide. How can I write the query so that it returns 1 column, with only the non null key/value pair? i.e. instead of returning: param.phone, param.lob, param.destination, param.id, param.1, param.2 etc with null values i want to see one column with value {"e_line_of_business":"internet"} or any other non-null key/values. It's ok to be stringified.
[ "You might consider below approach.\nWITH sample_data AS (\n SELECT STRUCT(STRING(null) AS phone, STRING(null) AS lob, STRING(null) AS destination, 'internet' AS e_line_of_business, STRING(null) AS param1) params\n UNION ALL\n SELECT STRUCT(STRING(null) AS phone, STRING(null) AS lob, STRING(null) AS destination, 'internet' AS e_line_of_business, 'value_1' AS param1)\n UNION ALL\n SELECT STRUCT('01012345678' AS phone, 'web' AS lob, STRING(null) AS destination, null AS e_line_of_business, null AS param1)\n)\nSELECT params, REPLACE(REGEXP_REPLACE(TO_JSON_STRING(params), r'\"[^,{]+\"\\:null,?', ''), ',}', '}') non_nulls \n FROM sample_data;\n\nQuery results\n\n" ]
[ 1 ]
[]
[]
[ "google_bigquery", "sql" ]
stackoverflow_0074670469_google_bigquery_sql.txt
Q: Why is one ternary statement cancelling out another? I'm trying to build a set of traffic lights and am currently working on the automated functionality. When I comment out the (sec >= 54) statement, the rest of the program functions as expected - a smooth transition from green to orange to red and back again. However, with the 'orange flash' (sec >= 54) statement active, the (sec >= 26) statement doesn't work. let time = new Date(); let sec = time.getSeconds(); const defaultSystem = setInterval(dispSecs, 1000); function dispSecs() { console.log(sec++); sec === 60 ? sec = 0 : sec; sec < 26 ? greenLight.style.backgroundColor = 'green' : greenLight.style.backgroundColor = 'black'; sec >= 26 && sec < 29 ? orangeLight.style.backgroundColor = 'orange' : orangeLight.style.backgroundColor = 'black'; sec >= 29 && sec < 54 ? redLight.style.backgroundColor = 'red' : redLight.style.backgroundColor = 'black'; sec >= 54 && sec % 2 === 0 ? orangeLight.style.backgroundColor = 'orange' : orangeLight.style.backgroundColor = 'black'; } I have tried to contain the 'orange flash' statement in a while loop. I've looked for spelling errors and I have tried commenting out different parts of the code. I have also tried rearranging parts of the code but this just causes different issues. Even with the 'orange flash' statement operational, the other lights function as intended. I'm just not getting the still orange between seconds 26 and 29. Any advice is much appreciated. Thanks! A: As it happens, I have managed to figure out the solution. let time = new Date(); let sec = time.getSeconds(); const defaultSystem = setInterval(dispSecs, 1000); function dispSecs() { console.log(sec++); sec === 60 ? sec = 0 : sec; sec < 26 ? greenLight.style.backgroundColor = 'green' : greenLight.style.backgroundColor = 'black'; sec >= 26 && sec < 29 ? orangeLight.style.backgroundColor = 'orange' : orangeLight.style.backgroundColor = 'black'; sec >= 29 && sec < 54 ? redLight.style.backgroundColor = 'red' : redLight.style.backgroundColor = 'black'; sec >= 54 && sec % 2 === 0 ? orangeLight.style.backgroundColor = 'orange' : sec; } It is my understanding that by creating the 'orange flash' rule, I have caused the orange light to remain black at any time outside of (sec >= 54). I think this is due to the last part of that ternary statement. For some reason, this third argument overrode everything else in the program related to the orange light.
Why is one ternary statement cancelling out another?
I'm trying to build a set of traffic lights and am currently working on the automated functionality. When I comment out the (sec >= 54) statement, the rest of the program functions as expected - a smooth transition from green to orange to red and back again. However, with the 'orange flash' (sec >= 54) statement active, the (sec >= 26) statement doesn't work. let time = new Date(); let sec = time.getSeconds(); const defaultSystem = setInterval(dispSecs, 1000); function dispSecs() { console.log(sec++); sec === 60 ? sec = 0 : sec; sec < 26 ? greenLight.style.backgroundColor = 'green' : greenLight.style.backgroundColor = 'black'; sec >= 26 && sec < 29 ? orangeLight.style.backgroundColor = 'orange' : orangeLight.style.backgroundColor = 'black'; sec >= 29 && sec < 54 ? redLight.style.backgroundColor = 'red' : redLight.style.backgroundColor = 'black'; sec >= 54 && sec % 2 === 0 ? orangeLight.style.backgroundColor = 'orange' : orangeLight.style.backgroundColor = 'black'; } I have tried to contain the 'orange flash' statement in a while loop. I've looked for spelling errors and I have tried commenting out different parts of the code. I have also tried rearranging parts of the code but this just causes different issues. Even with the 'orange flash' statement operational, the other lights function as intended. I'm just not getting the still orange between seconds 26 and 29. Any advice is much appreciated. Thanks!
[ "As it happens, I have managed to figure out the solution.\nlet time = new Date();\nlet sec = time.getSeconds();\nconst defaultSystem = setInterval(dispSecs, 1000);\nfunction dispSecs() {\nconsole.log(sec++);\nsec === 60 ? sec = 0 : sec;\nsec < 26 ? greenLight.style.backgroundColor = 'green' : \n greenLight.style.backgroundColor = 'black';\nsec >= 26 && sec < 29 ? orangeLight.style.backgroundColor = 'orange' :\n orangeLight.style.backgroundColor = 'black';\nsec >= 29 && sec < 54 ? redLight.style.backgroundColor = 'red' :\n redLight.style.backgroundColor = 'black';\nsec >= 54 && sec % 2 === 0 ? orangeLight.style.backgroundColor = 'orange' :\n sec;\n}\n\nIt is my understanding that by creating the 'orange flash' rule, I have caused the orange light to remain black at any time outside of (sec >= 54). I think this is due to the last part of that ternary statement. For some reason, this third argument overrode everything else in the program related to the orange light.\n" ]
[ 0 ]
[]
[]
[ "conditional_operator", "function", "javascript" ]
stackoverflow_0074672852_conditional_operator_function_javascript.txt
Q: worst latency for single message I have a requirement to build a real-time-low-latency messaging system. I read up ZeroMQ guide, for my requirement ROUTER-DEALER pattern matches perfectly. I built the system around it and it is working fine. But when I am doing performance testing I found ZeroMQ latency is staggeringly high. libzmq version : 4.2.5 ./local_lat tcp://127.0.0.1:5555 1 1000 ./remote_lat tcp://127.0.0.1:5555 1 1000 message size: 1 [B] roundtrip count: 1000 average latency: 26.123 [us] When the message count is high, ZeroMQ performance is awesome, but when the same message count is 1 the latency is quite high. ./local_lat tcp://127.0.0.1:5555 1 1 ./remote_lat tcp://127.0.0.1:5555 1 1 message size: 1 [B] roundtrip count: 1 average latency: 506.500 [us] Still not convienced I took the PUB-SUB example from ZeroMQ guide modified to ROUTER-DEALER and added a timestamp and tested again. There is also the latency really very high. This makes ZeroMQ unusable. I agree when the message volumes are high there is nothing which will beat ZeroMQ, but for the systems where the latency is critical even for single message ZeroMQ fails. Note : I ran the PUB-SUB example also, it is showing me same latency figures sender.cpp #include <zmq.hpp> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <sys/time.h> int main () { // Prepare our context and publisher zmq::context_t context (1); zmq::socket_t publisher (context, ZMQ_ROUTER); publisher.bind("tcp://*:5556"); //wait for peer to connect //once connected store the identity to send message later zmq::message_t identity,m; publisher.recv(&identity);//identity publisher.recv(&m);//message sleep(1);//sleep to set up connections struct timeval timeofday; int i=1;//no of messages to send while (i) { zmq::message_t id,message("10101",5); id.copy(&identity); gettimeofday(&timeofday,NULL); publisher.send(id,ZMQ_SNDMORE); publisher.send(message); std::cout << timeofday.tv_sec << ", " << timeofday.tv_usec << std::endl; usleep(1); --i; } return 0; } reciever.cpp #include <zmq.hpp> #include <iostream> #include <sys/time.h> int main (int argc, char *argv[]) { zmq::context_t context (1); zmq::socket_t subscriber (context, ZMQ_DEALER); subscriber.setsockopt(ZMQ_IDENTITY,"1",1); subscriber.connect("tcp://localhost:5556"); struct timeval timeofday; subscriber.send(" ",1); int update_nbr; int i=1; for (update_nbr = 0; update_nbr < i; update_nbr++) { zmq::message_t update; subscriber.recv(&update); gettimeofday(&timeofday,NULL); std::cout << timeofday.tv_sec << ", " << timeofday.tv_usec << std::endl; } return 0; } sender output 1562908600, 842072 reciever output 1562908600, 842533 As you can see it takes about 400 ms. Is there any way to reduce the latency? A: The overhead of setting up a TCP connection is not trivial - and the overhead increases for ZMQ, because the action of creating a connection is accomplished, behind the scenes, with some TCP back-and-forth. So, the latency of your first message is not just the latency of the message itself. It's the latency of the message combined with the latency of the messages involved in setting up the connection. The other thing to note is that 1 byte is a staggeringly inefficient payload, even with vanilla TCP. If ZMQ is doing any sort of batching when it sends, that'll dramatically improve latency of a large number of messages. I don't know if it does any of that under the hood or not, but the fact remains that 1 byte is saddled with the same unavoidable overhead involved with both TCP and ZMQ to establish the connection as 1000 bytes is, it just overwhelms the latency involved with sending the 1 byte and is negligible for 1000 bytes. I recommend you send 2 messages and watch the individual latency for each message - if I'm right, the 2nd one should be back down into the ~25ยตs range. If that's the case, then it's up to you whether that overhead represents a problem or not. I suspect it won't in practice. A: ZMQ does not send messages serially, ie there is not a 1:1 relationship between zmq_send() and the send() function on the underlying TCP socket. As a message queue it gives the buffer the chance to fill at least some between actual sends over TCP. This delay is very minimal, but effective enough to allow many msgs to be sent at once, potentially utilizing the whole bandwidth available between two points. If I'm not mistaken ZMQ's IO will automatically tune itself to maximize throughput while maintaining as little latency as possible if the buffer isn't filling between sends. So true latency may be as high as 100 ms or even more if over TCP, but is actually sending thousands of messages at once if the queue is being fed fast enough.
worst latency for single message
I have a requirement to build a real-time-low-latency messaging system. I read up ZeroMQ guide, for my requirement ROUTER-DEALER pattern matches perfectly. I built the system around it and it is working fine. But when I am doing performance testing I found ZeroMQ latency is staggeringly high. libzmq version : 4.2.5 ./local_lat tcp://127.0.0.1:5555 1 1000 ./remote_lat tcp://127.0.0.1:5555 1 1000 message size: 1 [B] roundtrip count: 1000 average latency: 26.123 [us] When the message count is high, ZeroMQ performance is awesome, but when the same message count is 1 the latency is quite high. ./local_lat tcp://127.0.0.1:5555 1 1 ./remote_lat tcp://127.0.0.1:5555 1 1 message size: 1 [B] roundtrip count: 1 average latency: 506.500 [us] Still not convienced I took the PUB-SUB example from ZeroMQ guide modified to ROUTER-DEALER and added a timestamp and tested again. There is also the latency really very high. This makes ZeroMQ unusable. I agree when the message volumes are high there is nothing which will beat ZeroMQ, but for the systems where the latency is critical even for single message ZeroMQ fails. Note : I ran the PUB-SUB example also, it is showing me same latency figures sender.cpp #include <zmq.hpp> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <sys/time.h> int main () { // Prepare our context and publisher zmq::context_t context (1); zmq::socket_t publisher (context, ZMQ_ROUTER); publisher.bind("tcp://*:5556"); //wait for peer to connect //once connected store the identity to send message later zmq::message_t identity,m; publisher.recv(&identity);//identity publisher.recv(&m);//message sleep(1);//sleep to set up connections struct timeval timeofday; int i=1;//no of messages to send while (i) { zmq::message_t id,message("10101",5); id.copy(&identity); gettimeofday(&timeofday,NULL); publisher.send(id,ZMQ_SNDMORE); publisher.send(message); std::cout << timeofday.tv_sec << ", " << timeofday.tv_usec << std::endl; usleep(1); --i; } return 0; } reciever.cpp #include <zmq.hpp> #include <iostream> #include <sys/time.h> int main (int argc, char *argv[]) { zmq::context_t context (1); zmq::socket_t subscriber (context, ZMQ_DEALER); subscriber.setsockopt(ZMQ_IDENTITY,"1",1); subscriber.connect("tcp://localhost:5556"); struct timeval timeofday; subscriber.send(" ",1); int update_nbr; int i=1; for (update_nbr = 0; update_nbr < i; update_nbr++) { zmq::message_t update; subscriber.recv(&update); gettimeofday(&timeofday,NULL); std::cout << timeofday.tv_sec << ", " << timeofday.tv_usec << std::endl; } return 0; } sender output 1562908600, 842072 reciever output 1562908600, 842533 As you can see it takes about 400 ms. Is there any way to reduce the latency?
[ "The overhead of setting up a TCP connection is not trivial - and the overhead increases for ZMQ, because the action of creating a connection is accomplished, behind the scenes, with some TCP back-and-forth.\nSo, the latency of your first message is not just the latency of the message itself. It's the latency of the message combined with the latency of the messages involved in setting up the connection.\nThe other thing to note is that 1 byte is a staggeringly inefficient payload, even with vanilla TCP. If ZMQ is doing any sort of batching when it sends, that'll dramatically improve latency of a large number of messages. I don't know if it does any of that under the hood or not, but the fact remains that 1 byte is saddled with the same unavoidable overhead involved with both TCP and ZMQ to establish the connection as 1000 bytes is, it just overwhelms the latency involved with sending the 1 byte and is negligible for 1000 bytes.\nI recommend you send 2 messages and watch the individual latency for each message - if I'm right, the 2nd one should be back down into the ~25ยตs range. If that's the case, then it's up to you whether that overhead represents a problem or not. I suspect it won't in practice.\n", "ZMQ does not send messages serially, ie there is not a 1:1 relationship between zmq_send() and the send() function on the underlying TCP socket. As a message queue it gives the buffer the chance to fill at least some between actual sends over TCP. This delay is very minimal, but effective enough to allow many msgs to be sent at once, potentially utilizing the whole bandwidth available between two points. If I'm not mistaken ZMQ's IO will automatically tune itself to maximize throughput while maintaining as little latency as possible if the buffer isn't filling between sends. So true latency may be as high as 100 ms or even more if over TCP, but is actually sending thousands of messages at once if the queue is being fed fast enough.\n" ]
[ 0, 0 ]
[]
[]
[ "centos", "ubuntu_16.04", "zeromq" ]
stackoverflow_0057000649_centos_ubuntu_16.04_zeromq.txt
Q: What is the difference between an interface and abstract class? What exactly is the difference between an interface and an abstract class? A: Interfaces An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way". An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. For example (pseudo code): // I say all motor vehicles should look like this: interface MotorVehicle { void run(); int getFuel(); } // My team mate complies and writes vehicle looking that way class Car implements MotorVehicle { int fuel; void run() { print("Wrroooooooom"); } int getFuel() { return this.fuel; } } Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices. Abstract classes Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!". For example: // I say all motor vehicles should look like this: abstract class MotorVehicle { int fuel; // They ALL have fuel, so lets implement this for everybody. int getFuel() { return this.fuel; } // That can be very different, force them to provide their // own implementation. abstract void run(); } // My teammate complies and writes vehicle looking that way class Car extends MotorVehicle { void run() { print("Wrroooooooom"); } } Implementation While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are. In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared. In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods). As usual with programming, there is theory, practice, and practice in another language :-) A: The key technical differences between an abstract class and an interface are: Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default). When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined. Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public). A: An Interface contains only the definition / signature of functionality, and if we have some common functionality as well as common signatures, then we need to use an abstract class. By using an abstract class, we can provide behavior as well as functionality both in the same time. Another developer inheriting abstract class can use this functionality easily, as they would only need to fill in the blanks. Taken from: http://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html http://www.dotnetbull.com/2011/11/what-is-abstract-class-in-c-net.html http://www.dotnetbull.com/2011/11/what-is-interface-in-c-net.html A: An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class. An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface. Anyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code. A: I don't want to highlight the differences, which have been already said in many answers ( regarding public static final modifiers for variables in interface & support for protected, private methods in abstract classes) In simple terms, I would like to say: interface: To implement a contract by multiple unrelated objects abstract class: To implement the same or different behaviour among multiple related objects From the Oracle documentation Consider using abstract classes if : You want to share code among several closely related classes. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). You want to declare non-static or non-final fields. Consider using interfaces if : You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface. You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour. You want to take advantage of multiple inheritance of type. abstract class establishes "is a" relation with concrete classes. interface provides "has a" capability for classes. If you are looking for Java as programming language, here are a few more updates: Java 8 has reduced the gap between interface and abstract classes to some extent by providing a default method feature. An interface does not have an implementation for a method is no longer valid now. Refer to this documentation page for more details. Have a look at this SE question for code examples to understand better. How should I have explained the difference between an Interface and an Abstract class? A: Some important differences: In the form of a table: As stated by Joe from javapapers: 1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. 2.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. 3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. 4.Java interface should be implemented using keyword โ€œimplementsโ€; A Java abstract class should be extended using keyword โ€œextendsโ€. 5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. 6.A Java class can implement multiple interfaces but it can extend only one abstract class. 7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. 8.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection. A: The main point is that: Abstract is object oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization). Interface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces. A: When you want to provide polymorphic behaviour in an inheritance hierarchy, use abstract classes. When you want polymorphic behaviour for classes which are completely unrelated, use an interface. A: I am constructing a building of 300 floors The building's blueprint interface For example, Servlet(I) Building constructed up to 200 floors - partially completed---abstract Partial implementation, for example, generic and HTTP servlet Building construction completed-concrete Full implementation, for example, own servlet Interface We don't know anything about implementation, just requirements. We can go for an interface. Every method is public and abstract by default It is a 100% pure abstract class If we declare public we cannot declare private and protected If we declare abstract we cannot declare final, static, synchronized, strictfp and native Every interface has public, static and final Serialization and transient is not applicable, because we can't create an instance for in interface Non-volatile because it is final Every variable is static When we declare a variable inside an interface we need to initialize variables while declaring Instance and static block not allowed Abstract Partial implementation It has an abstract method. An addition, it uses concrete No restriction for abstract class method modifiers No restriction for abstract class variable modifiers We cannot declare other modifiers except abstract No restriction to initialize variables Taken from DurgaJobs Website A: Let's work on this question again: The first thing to let you know is that 1/1 and 1*1 results in the same, but it does not mean that multiplication and division are same. Obviously, they hold some good relationship, but mind you both are different. I will point out main differences, and the rest have already been explained: Abstract classes are useful for modeling a class hierarchy. At first glance of any requirement, we are partially clear on what exactly is to be built, but we know what to build. And so your abstract classes are your base classes. Interfaces are useful for letting other hierarchy or classes to know that what I am capable of doing. And when you say I am capable of something, you must have that capacity. Interfaces will mark it as compulsory for a class to implement the same functionalities. A: If you have some common methods that can be used by multiple classes go for abstract classes. Else if you want the classes to follow some definite blueprint go for interfaces. Following examples demonstrate this. Abstract class in Java: abstract class Animals { // They all love to eat. So let's implement them for everybody void eat() { System.out.println("Eating..."); } // The make different sounds. They will provide their own implementation. abstract void sound(); } class Dog extends Animals { void sound() { System.out.println("Woof Woof"); } } class Cat extends Animals { void sound() { System.out.println("Meoww"); } } Following is an implementation of interface in Java: interface Shape { void display(); double area(); } class Rectangle implements Shape { int length, width; Rectangle(int length, int width) { this.length = length; this.width = width; } @Override public void display() { System.out.println("****\n* *\n* *\n****"); } @Override public double area() { return (double)(length*width); } } class Circle implements Shape { double pi = 3.14; int radius; Circle(int radius) { this.radius = radius; } @Override public void display() { System.out.println("O"); // :P } @Override public double area() { return (double)((pi*radius*radius)/2); } } Some Important Key points in a nutshell: The variables declared in Java interface are by default final. Abstract classes can have non-final variables. The variables declared in Java interface are by default static. Abstract classes can have non-static variables. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. A: It's pretty simple actually. You can think of an interface as a class which is only allowed to have abstract methods and nothing else. So an interface can only "declare" and not define the behavior you want the class to have. An abstract class allows you to do both declare (using abstract methods) as well as define (using full method implementations) the behavior you want the class to have. And a regular class only allows you to define, not declare, the behavior/actions you want the class to have. One last thing, In Java, you can implement multiple interfaces, but you can only extend one (Abstract Class or Class)... This means inheritance of defined behavior is restricted to only allow one per class... ie if you wanted a class that encapsulated behavior from Classes A,B&C you would need to do the following: Class A extends B, Class C extends A .. its a bit of a round about way to have multiple inheritance... Interfaces on the other hand, you could simply do: interface C implements A, B So in effect Java supports multiple inheritance only in "declared behavior" ie interfaces, and only single inheritance with defined behavior.. unless you do the round about way I described... Hopefully that makes sense. A: The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class. Interface vs Class Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address: interface Package { String address(); } Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts: class Box implements Package, Property { @Override String address() { return "5th Street, New York, NY"; } @Override Human owner() { // this method is part of another contract } } Abstract vs Final Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map: abstract class GpsBox implements Package { @Override public abstract String address(); protected Coordinates whereAmI() { // connect to GPS and return my current position } } This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes. Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction: final class DirectBox implements Package { private final String to; public DirectBox(String addr) { this.to = addr; } @Override public String address() { return this.to; } } In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though. Again, comparing interfaces with abstract classes is not correct. A: The only difference is that one can participate in multiple inheritance and other cannot. The definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8? Interfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do. Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables. See Why does Java allow static final variables in interfaces when they are only intended to be contracts?. A: Interface: Turn ( Turn Left, Turn Right.) Abstract Class: Wheel. Class: Steering Wheel, derives from Wheel, exposes Interface Turn One is for categorizing behavior that can be offered across a diverse range of things, the other is for modelling an ontology of things. A: In short the differences are the following: Syntactical Differences Between Interface and Abstract Class: Methods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface. A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces. A child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public. Abstract Classes can have constructors but not interfaces. Interfaces from Java 9 have private static methods. In Interfaces now: public static - supported public abstract - supported public default - supported private static - supported private abstract - compile error private default - compile error private - supported A: Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code. Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes. Summary An interface defines a contract that some implementation will fulfill for you. An abstract class provides a default behavior that your implementation can reuse. Alternative summary An interface is for defining public APIs An abstract class is for internal use, and for defining SPIs On the importance of hiding implementation details A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating. On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update. An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data. APIs versus SPIs Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces. Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces. The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it. Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run. A note on Java 8 and default methods Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes). Which one to use? Is the thing supposed to be publicly used by other parts of the code, or by other external code? Add an interface to it to hide the implementation details from the public abstract contract, which is the general behavior of the thing. Is the thing something that's supposed to have multiple implementations with a lot of code in common? Make both an interface and an abstract, incomplete implementation. Is there ever going to be only one implementation, and nobody else will use it? Just make it a concrete class. "ever" is long time, you could play it safe and still add an interface on top of it. A corollary: the other way around is often wrongly done: when using a thing, always try to use the most generic class/interface that you actually need. In other words, don't declare your variables as ArrayList theList = new ArrayList(), unless you actually have a very strong dependency on it being an array list, and no other type of list would cut it for you. Use List theList = new ArrayList instead, or even Collection theCollection = new ArrayList if the fact that it's a list, and not any other type of collection doesn't actually matter. A: Not really the answer to the original question, but once you have the answer to the difference between them, you will enter the when-to-use-each dilemma: When to use interfaces or abstract classes? When to use both? I've limited knowledge of OOP, but seeing interfaces as an equivalent of an adjective in grammar has worked for me until now (correct me if this method is bogus!). For example, interface names are like attributes or capabilities you can give to a class, and a class can have many of them: ISerializable, ICountable, IList, ICacheable, IHappy, ... A: You can find clear difference between interface and abstract class. Interface Interface only contains abstract methods. Force users to implement all methods when implements the interface. Contains only final and static variables. Declare using interface keyword. All methods of an interface must be defined as public. An interface can extend or a class can implement multiple other interfaces. Abstract class Abstract class contains abstract and non-abstract methods. Does not force users to implement all methods when inherited the abstract class. Contains all kinds of variables including primitive and non-primitive Declare using abstract keyword. Methods and members of an abstract class can be defined with any visibility. A child class can only extend a single class (abstract or concrete). A: I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here. tl;dr; When you see โ€œIs Aโ€ relationship use inheritance/abstract class. when you see โ€œhas aโ€ relationship create member variables. When you see โ€œrelies on external providerโ€ implement (not inherit) an interface. Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces. ZK (Thatโ€™s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why canโ€™t you create an object of abstract class or interface? Answer 2: Abstract classes can have a function body as partial/default implementation. ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that? Answer 3: Interfaces allow multi-inheritance and abstract classes donโ€™t. ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? Whatโ€™s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better. Common Noun: A common noun is a name given โ€œin commonโ€ to things of the same class or kind. For e.g. fruits, animals, city, car etc. Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc. Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns. Coming to the UML Part. You should be familiar with below relationships: Is A Has A Uses Letโ€™s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car? Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an โ€œIs Aโ€ relationship. Honda accord doesnโ€™t have a car in it. It โ€œis aโ€ car. Honda Accord โ€œhas aโ€ music player in it. When two entities share the โ€œIs Aโ€ relationship itโ€™s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this: abstract class Car { string color; int speed; } class HondaAccord : Car { MusicPlayer musicPlayer; } Now Honda doesn't manufacture music players. Or at least itโ€™s not their main business. So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires itโ€™ll play just fine on these speakers. This makes Music Player a perfect candidate for an interface. You donโ€™t care who provides support for it as long as the connections work just fine. You can replace the MusicPlayer of LG with Sony or the other way. And it wonโ€™t change a thing in Honda Accord. Why canโ€™t you create an object of abstract classes? Because you canโ€™t walk into a showroom and say give me a car. Youโ€™ll have to provide a proper noun. What car? Probably a honda accord. And thatโ€™s when a sales agent could get you something. Why canโ€™t you create an object of an interface? Because you canโ€™t walk into a showroom and say give me a contract of music player. It wonโ€™t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It wonโ€™t play music. Why do interfaces allow multiple inheritance? Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below: abstract class Car { string color; int speed; } class HondaAccord : Car, IInflateAir, IRefueling { MusicPlayer musicPlayer; } And the English will read like this โ€œHonda Accord is a Car that supports inflating tire and refuelingโ€. A: Key Points: Abstract class can have property, Data fields ,Methods (complete / incomplete) both. If method or Properties define in abstract keyword that must override in derived class.(its work as a tightly coupled functionality) If define abstract keyword for method or properties in abstract class you can not define body of method and get/set value for properties and that must override in derived class. Abstract class does not support multiple inheritance. Abstract class contains Constructors. An abstract class can contain access modifiers for the subs, functions, properties. Only Complete Member of abstract class can be Static. An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface. Advantage: It is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards. If various implementations are of the same kind and use common behavior or status then abstract class is better to use. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. Its allow fast execution than interface.(interface Requires more time to find the actual method in the corresponding classes.) It can use for tight and loosely coupling. find details here... http://pradeepatkari.wordpress.com/2014/11/20/interface-and-abstract-class-in-c-oops/ A: The shortest way to sum it up is that an interface is: Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods. Subject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not. Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface. Meanwhile, an abstract class is: Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract. A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified). Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply. Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is. A: Inheritance is used for two purposes: To allow an object to regard parent-type data members and method implementations as its own. To allow a reference to an objects of one type to be used by code which expects a reference to supertype object. In languages/frameworks which support generalized multiple inheritance, there is often little need to classify a type as either being an "interface" or an "abstract class". Popular languages and frameworks, however, will allow a type to regard one other type's data members or method implementations as its own even though they allow a type to be substitutable for an arbitrary number of other types. Abstract classes may have data members and method implementations, but can only be inherited by classes which don't inherit from any other classes. Interfaces put almost no restrictions on the types which implement them, but cannot include any data members or method implementations. There are times when it's useful for types to be substitutable for many different things; there are other times when it's useful for objects to regard parent-type data members and method implementations as their own. Making a distinction between interfaces and abstract classes allows each of those abilities to be used in cases where it is most relevant. A: Differences between abstract class and interface on behalf of real implementation. Interface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement. Some of other use cases where we should use interface. Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract. Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality. Example of Abstract Class: public abstract class DesireCar { //It is an abstract method that defines the prototype. public abstract void Color(); // It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels. // and hence no need to define this in all the sub classes in this way it saves the code duplicasy public void Wheel() { Console.WriteLine("Car has four wheel"); } } **Here is the sub classes:** public class DesireCar1 : DesireCar { public override void Color() { Console.WriteLine("This is a red color Desire car"); } } public class DesireCar2 : DesireCar { public override void Color() { Console.WriteLine("This is a red white Desire car"); } } Example Of Interface: public interface IShape { // Defines the prototype(template) void Draw(); } // All the sub classes follow the same template but implementation can be different. public class Circle : IShape { public void Draw() { Console.WriteLine("This is a Circle"); } } public class Rectangle : IShape { public void Draw() { Console.WriteLine("This is a Rectangle"); } } A: I'd like to add one more difference which makes sense. For example, you have a framework with thousands of lines of code. Now if you want to add a new feature throughout the code using a method enhanceUI(), then it's better to add that method in abstract class rather in interface. Because, if you add this method in an interface then you should implement it in all the implemented class but it's not the case if you add the method in abstract class. A: To give a simple but clear answer, it helps to set the context : you use both when you do not want to provide full implementations. The main difference then is an interface has no implementation at all (only methods without a body) while abstract classes can have members and methods with a body as well, i.e. can be partially implemented. A: usually Abstract class used for core of something but interface used for appending peripheral. when you want to create base type for vehicle you should use abstract class but if you want to add some functionality or property that is not part of base concept of vehicle you should use interface,for example you want to add "ToJSON()" function. interface has wide range of abstraction rather than abstract class. you can see this in passing arguments.look this example: if you use vehicle as argument you just can use one of its derived type (bus or car-same category-just vehicle category). but when you use IMoveable interface as argument you have more choices. A: The topic of abstract classes vs interfaces is mostly about semantics. Abstract classes act in different programming languages often as a superset of interfaces, except one thing and that is, that you can implement multiple interfaces, but inherit only one class. An interface defines what something must be able to do; like a contract, but does not provide an implementation of it. An abstract class defines what something is and it commonly hosts shared code between the subclasses. For example a Formatter should be able to format() something. The common semantics to describe something like that would be to create an interface IFormatter with a declaration of format() that acts like a contract. But IFormatter does not describe what something is, but just what it should be able to to. The common semantics to describe what something actually is, is to create a class. In this case we create an abstract class... So we create an abstract class Formatter which implements the interface. That is a very descriptive code, because we now know we have a Formatter and we now know what every Formatter must be able to do. Also one very important topic is documentation (at least for some people...). In your documentation you probably want to explain within your subclasses what a Formatter actually is. It is very convenient to have an abstract class Formatter to which documentation you can link to within your subclasses. That is very convenient and generic. On the other hand if you do not have an abstract class Formatter and only an interface IFormatter you would have to explain in each of your subclasses what a Formatter actucally is, because an interface is a contract and you would not describe what a Formatter actually is within the documentation of an interface โ€” at least it would be not something common to do and you would break the semantics that most developers consider to be correct. Note: It is a very common pattern to make an abstract class implement an interface. A: In an interface all methods must be only definitions, not single one should be implemented. But in an abstract class there must an abstract method with only definition, but other methods can be also in the abstract class with implementation... A: An abstract class is a class whose object cannot be created or a class which cannot be instantiated. An abstract method makes a class abstract. An abstract class needs to be inherited in order to override the methods that are declared in the abstract class. No restriction on access specifiers. An abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have. An interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) . It is a collection of abstract methods , default methods , static methods , final variables and nested classes. All members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed. A class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding) An interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class. For Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions). Why interface when we already have abstract class? Java supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance. A: In practicality terms(JAVA), the major difference between abstract class and interface is Abstract class can hold state. Other than holding state we can achieve rest operations with Interface also. A: Similarities Both forces classes extending or implementing them to override base methods. Differences A class can implement multiple interfaces. A class can only extend from one abstract class. Fields declared in interfaces must be static and final because all objects that created from such implementation share same values. In Abstract classes, fields can be named and not assigned. subclasses can override them. Usecases Abstract classes are used in subclasses that are closely related, or have almost same functionalities and behaviours. Interfaces are used for unrelated classes that you want to force a certain thing or behaviour, because its Just a contract without implementation. A: A simple yet effective explanation of abstract class and interface on php.net: An Interface is like a protocol. It doesn't designate the behavior of the object; it designates how your code tells that object to act. An interface would be like the English Language: defining an interface defines how your code communicates with any object implementing that interface. An interface is always an agreement or a promise. When a class says "I implement interface Y", it is saying "I promise to have the same public methods that any object with interface Y has". On the other hand, an Abstract Class is like a partially built class. It is much like a document with blanks to fill in. It might be using English, but that isn't as important as the fact that some of the document is already written. An abstract class is the foundation for another object. When a class says "I extend abstract class Y", it is saying "I use some methods or properties already defined in this other class named Y". So, consider the following PHP: <?php class X implements Y { } // this is saying that "X" agrees to speak language "Y" with your code. class X extends Y { } // this is saying that "X" is going to complete the partial class "Y". ?> You would have your class implement a particular interface if you were distributing a class to be used by other people. The interface is an agreement to have a specific set of public methods for your class. You would have your class extend an abstract class if you (or someone else) wrote a class that already had some methods written that you want to use in your new class. These concepts, while easy to confuse, are specifically different and distinct. For all intents and purposes, if you're the only user of any of your classes, you don't need to implement interfaces. A: We have various structural/syntactical difference between interface and abstract class. Some more differences are [1] Scenario based difference: Abstract classes are used in scenarios when we want to restrict the user to create object of parent class AND we believe there will be more abstract methods will be added in future. Interface has to be used when we are sure there can be no more abstract method left to be provided. Then only an interface is published. [2] Conceptual difference: "Do we need to provide more abstract methods in future" if YES make it abstract class and if NO make it Interface. (Most appropriate and valid till java 1.7) A: Interfaces are generally the classes without logic just a signature. Whereas abstract classes are those having logic. Both support contract as interface all method should be implemented in the child class but in abstract only the abstract method should be implemented. When to use interface and when to abstract? Why use Interface? class Circle { protected $radius; public function __construct($radius) { $this->radius = $radius } public function area() { return 3.14159 * pow(2,$this->radius); // simply pie.r2 (square); } } //Our area calculator class would look like class Areacalculator { $protected $circle; public function __construct(Circle $circle) { $this->circle = $circle; } public function areaCalculate() { return $circle->area(); //returns the circle area now } } We would simply do $areacalculator = new Areacalculator(new Circle(7)); Few days later we would need the area of rectangle, Square, Quadrilateral and so on. If so do we have to change the code every time and check if the instance is of square or circle or rectangle? Now what OCP says is CODE TO AN INTERFACE NOT AN IMPLEMENTATION. Solution would be: Interface Shape { public function area(); //Defining contract for the classes } Class Square implements Shape { $protected length; public function __construct($length) { //settter for length like we did on circle class } public function area() { //return l square for area of square } Class Rectangle implements Shape { $protected length; $protected breath; public function __construct($length,$breath) { //settter for length, breath like we did on circle,square class } public function area() { //return l*b for area of rectangle } } Now for area calculator class Areacalculator { $protected $shape; public function __construct(Shape $shape) { $this->shape = $shape; } public function areaCalculate() { return $shape->area(); //returns the circle area now } } $areacalculator = new Areacalculator(new Square(1)); $areacalculator->areaCalculate(); $areacalculator = new Areacalculator(new Rectangle(1,2)); $areacalculator->;areaCalculate(); Isn't that more flexible? If we would code without interface we would check the instance for each shape redundant code. Now when to use abstract? Abstract Animal { public function breathe(){ //all animals breathe inhaling o2 and exhaling co2 } public function hungry() { //every animals do feel hungry } abstract function communicate(); // different communication style some bark, some meow, human talks etc } Now abstract should be used when one doesn't need instance of that class, having similar logic, having need for the contract. A: The general idea of abstract classes and interfaces is to be extended/implemented by other classes (cannot be constructed alone) that use these general "settings" (some kind of a template), making it simple to set a specific-general behaviour for all the objects that later extend it. An abstract class has regular methods set AND abstract methods. Extended classes can include unset methods after being extended by an abstract class. When setting abstract methods - they are defined by the classes that are extending it later. Interfaces have the same properties as an abstract class, but includes only abstract methods, which could be implemented in an other class/es (and can be more than one interface to implement), this creates a more permanent-solid definishion of methods/static variables. Unlike the abstract class, you cannot add custom "regular" methods. A: An interface is so called because it provides an interface of methods to a caller (or a COM client for instance) that are implemented by some class. By polymorphically casting an object pointer to the type of an interface that the object's class implements, it restricts the access of the object to functions and members of the interface that it implements, separated from other COM interfaces the coclass might implement. The client does not need to know what class implements the interface or what other methods are present in the class; the object presents as an instance of the interface it knows (where the instance of the class has been polymorphically cast to the interface instance, which is a subinstance of the class) and it just uses the interface by calling the methods of the interface on the interface instance. All details of the actual implementation and extraneous functionality / details implemented by different interfaces are separated from the interface the caller expects -- the caller just uses the interface it has with the object (the interface instance and its virtual table pointer that's part of the object), and the underlying object implementation is called without the caller having to know the location or the details of the implementation. Accessing the object through the interface (a pointer of the type of the interface) is a form of encapsulation that syntactically prevents unauthorised access to the object as well as hiding implementation details and other functionality that does not pertain to the interface and its defined personality. An interface is where all methods are virtual and abstract (abstract is known as pure virtual in C++; all abstract methods contain the virtual specifier and therefore are virtual). An abstract class is where at least one of the methods is virtual and specified as abstract (or pure virtual in C++). Other details differ across languages. All interface attributes are implicitly public static final in java but they aren't in C++. Java allows non-static attributes in abstract classes but C++ allows them in both. Attributes cannot be virtual / abstract in either language. A: Abstract class provides both declaration and implementation but Interfaces have only declaration. When you want to achieve multiple inheritance then you should use Interface not Abstract class because in C#, a class can inherit from one class only but from more than one interface. Abstract class contains constructors while Interface does not. Interfaces have only public members whereas abstract classes can contain public, private protected modifiers. Abstract class can provide complete, partial or no implementation whereas Interface provides only declaration. Performance wise, Abstract class is fast as Interface needs to identify the actual method implementation which takes some time. Interface provides you the ability of a class whereas An abstract class gives you the identity of class. Abstract class allows you to define and implement some common functionality which can be used by many child classes but Interface gives you common method signatures that can be implemented differently as per requirement. Abstract class can provide default implementation for any newly added method and all code will work properly but in case of Interface you need to implement that new method in all the classes using that interface. Members of Interface can not be static but complete members of Abstract class can be static. Interfaces allow you to create Mocks easily in unit testing while Abstract class needs extra coding.
What is the difference between an interface and abstract class?
What exactly is the difference between an interface and an abstract class?
[ "Interfaces\nAn interface is a contract: The person writing the interface says, \"hey, I accept things looking that way\", and the person using the interface says \"OK, the class I write looks that way\".\nAn interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.\nFor example (pseudo code):\n// I say all motor vehicles should look like this:\ninterface MotorVehicle\n{\n void run();\n\n int getFuel();\n}\n\n// My team mate complies and writes vehicle looking that way\nclass Car implements MotorVehicle\n{\n\n int fuel;\n\n void run()\n {\n print(\"Wrroooooooom\");\n }\n\n\n int getFuel()\n {\n return this.fuel;\n }\n}\n\nImplementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.\n\nAbstract classes\nAbstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.\nAbstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, \"these classes should look like that, and they have that in common, so fill in the blanks!\".\nFor example:\n// I say all motor vehicles should look like this:\nabstract class MotorVehicle\n{\n\n int fuel;\n\n // They ALL have fuel, so lets implement this for everybody.\n int getFuel()\n {\n return this.fuel;\n }\n\n // That can be very different, force them to provide their\n // own implementation.\n abstract void run();\n}\n\n// My teammate complies and writes vehicle looking that way\nclass Car extends MotorVehicle\n{\n void run()\n {\n print(\"Wrroooooooom\");\n }\n}\n\n\nImplementation\nWhile abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.\nIn Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.\nIn Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).\nAs usual with programming, there is theory, practice, and practice in another language :-)\n", "The key technical differences between an abstract class and an interface are:\n\nAbstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.\nMethods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).\nWhen inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined.\nSimilarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.\nA child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.\nA child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).\n\n", "An Interface contains only the definition / signature of functionality, and if we have some common functionality as well as common signatures, then we need to use an abstract class. By using an abstract class, we can provide behavior as well as functionality both in the same time. Another developer inheriting abstract class can use this functionality easily, as they would only need to fill in the blanks.\n\nTaken from:\nhttp://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html\nhttp://www.dotnetbull.com/2011/11/what-is-abstract-class-in-c-net.html\nhttp://www.dotnetbull.com/2011/11/what-is-interface-in-c-net.html\n", "An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm\n\nAn abstract class is a class that is\n only partially implemented by the\n programmer. It may contain one or more\n abstract methods. An abstract method\n is simply a function definition that\n serves to tell the programmer that the\n method must be implemented in a child\n class.\nAn interface is similar to an abstract\n class; indeed interfaces occupy the\n same namespace as classes and abstract\n classes. For that reason, you cannot\n define an interface with the same name\n as a class. An interface is a fully\n abstract class; none of its methods\n are implemented and instead of a class\n sub-classing from it, it is said to\n implement that interface.\n\nAnyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code.\n", "I don't want to highlight the differences, which have been already said in many answers ( regarding public static final modifiers for variables in interface & support for protected, private methods in abstract classes)\nIn simple terms, I would like to say:\ninterface: To implement a contract by multiple unrelated objects\nabstract class: To implement the same or different behaviour among multiple related objects\nFrom the Oracle documentation\nConsider using abstract classes if :\n\nYou want to share code among several closely related classes.\nYou expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).\nYou want to declare non-static or non-final fields. \n\nConsider using interfaces if :\n\nYou expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.\nYou want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.\nYou want to take advantage of multiple inheritance of type.\n\nabstract class establishes \"is a\" relation with concrete classes. interface provides \"has a\" capability for classes.\nIf you are looking for Java as programming language, here are a few more updates:\nJava 8 has reduced the gap between interface and abstract classes to some extent by providing a default method feature. An interface does not have an implementation for a method is no longer valid now. \nRefer to this documentation page for more details. \nHave a look at this SE question for code examples to understand better.\nHow should I have explained the difference between an Interface and an Abstract class?\n", "Some important differences:\nIn the form of a table:\n\nAs stated by Joe from javapapers: \n\n1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can\n have instance methods that implements a default behavior.\n2.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.\n3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private,\n protected, etc..\n4.Java interface should be implemented using keyword โ€œimplementsโ€; A Java abstract class should be extended using keyword โ€œextendsโ€.\n5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java\n interfaces.\n6.A Java class can implement multiple interfaces but it can extend only one abstract class.\n7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a\n main() exists.\n8.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.\n\n", "The main point is that:\n\nAbstract is object oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization).\nInterface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.\n\n", "When you want to provide polymorphic behaviour in an inheritance hierarchy, use abstract classes. \nWhen you want polymorphic behaviour for classes which are completely unrelated, use an interface.\n", "I am constructing a building of 300 floors\nThe building's blueprint interface\n\nFor example, Servlet(I)\n\nBuilding constructed up to 200 floors - partially completed---abstract\n\nPartial implementation, for example, generic and HTTP servlet\n\nBuilding construction completed-concrete\n\nFull implementation, for example, own servlet \n\nInterface\n\nWe don't know anything about implementation, just requirements. We can\ngo for an interface.\nEvery method is public and abstract by default \nIt is a 100% pure abstract class\nIf we declare public we cannot declare private and protected\nIf we declare abstract we cannot declare final, static, synchronized, strictfp and native\nEvery interface has public, static and final\nSerialization and transient is not applicable, because we can't create an instance for in interface\nNon-volatile because it is final\nEvery variable is static\nWhen we declare a variable inside an interface we need to initialize variables while declaring\nInstance and static block not allowed\n\nAbstract\n\nPartial implementation\nIt has an abstract method. An addition, it uses concrete\nNo restriction for abstract class method modifiers\nNo restriction for abstract class variable modifiers\nWe cannot declare other modifiers except abstract\nNo restriction to initialize variables\n\nTaken from DurgaJobs Website\n", "Let's work on this question again: \nThe first thing to let you know is that 1/1 and 1*1 results in the same, but it does not mean that multiplication and division are same. Obviously, they hold some good relationship, but mind you both are different. \nI will point out main differences, and the rest have already been explained:\nAbstract classes are useful for modeling a class hierarchy. At first glance of any requirement, we are partially clear on what exactly is to be built, but we know what to build. And so your abstract classes are your base classes.\nInterfaces are useful for letting other hierarchy or classes to know that what I am capable of doing. And when you say I am capable of something, you must have that capacity. Interfaces will mark it as compulsory for a class to implement the same functionalities.\n", "If you have some common methods that can be used by multiple classes go for abstract classes.\nElse if you want the classes to follow some definite blueprint go for interfaces.\nFollowing examples demonstrate this.\nAbstract class in Java:\nabstract class Animals\n{\n // They all love to eat. So let's implement them for everybody\n void eat()\n {\n System.out.println(\"Eating...\");\n }\n // The make different sounds. They will provide their own implementation.\n abstract void sound();\n}\n \nclass Dog extends Animals\n{\n void sound()\n {\n System.out.println(\"Woof Woof\");\n }\n}\n \nclass Cat extends Animals\n{\n void sound()\n {\n System.out.println(\"Meoww\");\n }\n}\n\nFollowing is an implementation of interface in Java:\ninterface Shape\n{\n void display();\n double area();\n}\n \nclass Rectangle implements Shape \n{\n int length, width;\n Rectangle(int length, int width)\n {\n this.length = length;\n this.width = width;\n }\n @Override\n public void display() \n {\n System.out.println(\"****\\n* *\\n* *\\n****\"); \n }\n @Override\n public double area() \n {\n return (double)(length*width);\n }\n} \n \nclass Circle implements Shape \n{\n double pi = 3.14;\n int radius;\n Circle(int radius)\n {\n this.radius = radius;\n }\n @Override\n public void display() \n {\n System.out.println(\"O\"); // :P\n }\n @Override\n public double area() \n { \n return (double)((pi*radius*radius)/2);\n }\n}\n\nSome Important Key points in a nutshell:\n\nThe variables declared in Java interface are by default final. Abstract classes can have non-final variables.\n\nThe variables declared in Java interface are by default static. Abstract classes can have non-static variables.\n\nMembers of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..\n\n\n", "It's pretty simple actually.\nYou can think of an interface as a class which is only allowed to have abstract methods and nothing else. \nSo an interface can only \"declare\" and not define the behavior you want the class to have.\nAn abstract class allows you to do both declare (using abstract methods) as well as define (using full method implementations) the behavior you want the class to have.\nAnd a regular class only allows you to define, not declare, the behavior/actions you want the class to have.\nOne last thing,\nIn Java, you can implement multiple interfaces, but you can only extend one (Abstract Class or Class)...\nThis means inheritance of defined behavior is restricted to only allow one per class... ie if you wanted a class that encapsulated behavior from Classes A,B&C you would need to do the following: Class A extends B, Class C extends A .. its a bit of a round about way to have multiple inheritance...\nInterfaces on the other hand, you could simply do: interface C implements A, B\nSo in effect Java supports multiple inheritance only in \"declared behavior\" ie interfaces, and only single inheritance with defined behavior.. unless you do the round about way I described...\nHopefully that makes sense.\n", "The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class.\nInterface vs Class\nInterface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address:\ninterface Package {\n String address();\n}\n\nClass is a group of objects that obey the contract. E.g., I'm a box from \"Box\" group and I obey the contract required by the Postman. At the same time I obey other contracts:\nclass Box implements Package, Property {\n @Override\n String address() {\n return \"5th Street, New York, NY\";\n }\n @Override\n Human owner() {\n // this method is part of another contract\n }\n}\n\nAbstract vs Final\nAbstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map:\nabstract class GpsBox implements Package {\n @Override\n public abstract String address();\n protected Coordinates whereAmI() {\n // connect to GPS and return my current position\n }\n}\n\nThis class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes.\nFinal class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction:\nfinal class DirectBox implements Package {\n private final String to;\n public DirectBox(String addr) {\n this.to = addr;\n }\n @Override\n public String address() {\n return this.to;\n }\n}\n\nIn most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though.\nAgain, comparing interfaces with abstract classes is not correct.\n", "The only difference is that one can participate in multiple inheritance and other cannot.\nThe definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8?\nInterfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do.\nInterfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables.\nSee Why does Java allow static final variables in interfaces when they are only intended to be contracts?.\n", "Interface: Turn ( Turn Left, Turn Right.)\nAbstract Class: Wheel.\nClass: Steering Wheel, derives from Wheel, exposes Interface Turn\nOne is for categorizing behavior that can be offered across a diverse range of things, the other is for modelling an ontology of things.\n", "In short the differences are the following:\nSyntactical Differences Between Interface and Abstract Class:\n\nMethods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore\nA concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface. \nA child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces. \nA child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public.\nAbstract Classes can have constructors but not interfaces.\nInterfaces from Java 9 have private static methods.\n\nIn Interfaces now:\npublic static - supported\npublic abstract - supported\npublic default - supported\nprivate static - supported\nprivate abstract - compile error\nprivate default - compile error\nprivate - supported \n", "Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: \"I\". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code.\nInterfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes.\nSummary\n\nAn interface defines a contract that some implementation will fulfill for you.\nAn abstract class provides a default behavior that your implementation can reuse.\n\nAlternative summary\n\nAn interface is for defining public APIs\nAn abstract class is for internal use, and for defining SPIs\n\nOn the importance of hiding implementation details\nA concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating.\nOn the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update.\nAn abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data.\nAPIs versus SPIs\nInterfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces.\nAbstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces.\nThe difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it.\nAdding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run.\nA note on Java 8 and default methods\nAlthough Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes).\nWhich one to use?\n\nIs the thing supposed to be publicly used by other parts of the code, or by other external code? Add an interface to it to hide the implementation details from the public abstract contract, which is the general behavior of the thing.\nIs the thing something that's supposed to have multiple implementations with a lot of code in common? Make both an interface and an abstract, incomplete implementation.\nIs there ever going to be only one implementation, and nobody else will use it? Just make it a concrete class.\n\n\n\"ever\" is long time, you could play it safe and still add an interface on top of it.\n\n\nA corollary: the other way around is often wrongly done: when using a thing, always try to use the most generic class/interface that you actually need. In other words, don't declare your variables as ArrayList theList = new ArrayList(), unless you actually have a very strong dependency on it being an array list, and no other type of list would cut it for you. Use List theList = new ArrayList instead, or even Collection theCollection = new ArrayList if the fact that it's a list, and not any other type of collection doesn't actually matter.\n", "Not really the answer to the original question, but once you have the answer to the difference between them, you will enter the when-to-use-each dilemma:\nWhen to use interfaces or abstract classes? When to use both?\nI've limited knowledge of OOP, but seeing interfaces as an equivalent of an adjective in grammar has worked for me until now (correct me if this method is bogus!). For example, interface names are like attributes or capabilities you can give to a class, and a class can have many of them: ISerializable, ICountable, IList, ICacheable, IHappy, ...\n", "You can find clear difference between interface and abstract class.\nInterface\n\nInterface only contains abstract methods.\nForce users to implement all methods when implements the interface.\nContains only final and static variables.\nDeclare using interface keyword.\nAll methods of an interface must be defined as public.\nAn interface can extend or a class can implement multiple other\ninterfaces.\n\nAbstract class\n\nAbstract class contains abstract and non-abstract methods.\nDoes not force users to implement all methods when inherited the\nabstract class.\nContains all kinds of variables including primitive and non-primitive\nDeclare using abstract keyword.\nMethods and members of an abstract class can be defined with any\nvisibility.\nA child class can only extend a single class (abstract or concrete).\n\n", "I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here.\ntl;dr; When you see โ€œIs Aโ€ relationship use inheritance/abstract class. when you see โ€œhas aโ€ relationship create member variables. When you see โ€œrelies on external providerโ€ implement (not inherit) an interface.\nInterview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what?\nI mostly get one or all of the below answers:\nAnswer 1: You cannot create an object of abstract class and interfaces.\nZK (Thatโ€™s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter \nQuestion: Why canโ€™t you create an object of abstract class or interface?\nAnswer 2: Abstract classes can have a function body as partial/default implementation.\nZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?\nAnswer 3: Interfaces allow multi-inheritance and abstract classes donโ€™t.\nZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? Whatโ€™s the difference between implementing and inheriting?\nThese counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming.\nThe answer to the original question and all the counter questions is found in the English language and the UML.\nYou must know at least below to understand these two constructs better.\nCommon Noun: A common noun is a name given โ€œin commonโ€ to things of the same class or kind. For e.g. fruits, animals, city, car etc.\nProper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.\nCar is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.\nComing to the UML Part. You should be familiar with below relationships:\n\nIs A\nHas A\nUses\n\nLetโ€™s consider the below two sentences.\n- HondaAccord Is A Car?\n- HondaAccord Has A Car?\nWhich one sounds correct? Plain English and comprehension. HondaAccord and Cars share an โ€œIs Aโ€ relationship. Honda accord doesnโ€™t have a car in it. It โ€œis aโ€ car. Honda Accord โ€œhas aโ€ music player in it.\nWhen two entities share the โ€œIs Aโ€ relationship itโ€™s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables.\nWith this established our code looks like this:\nabstract class Car\n{\n string color;\n int speed;\n}\nclass HondaAccord : Car\n{\n MusicPlayer musicPlayer;\n}\n\nNow Honda doesn't manufacture music players. Or at least itโ€™s not their main business.\nSo they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires itโ€™ll play just fine on these speakers.\nThis makes Music Player a perfect candidate for an interface. You donโ€™t care who provides support for it as long as the connections work just fine.\nYou can replace the MusicPlayer of LG with Sony or the other way. And it wonโ€™t change a thing in Honda Accord.\nWhy canโ€™t you create an object of abstract classes?\nBecause you canโ€™t walk into a showroom and say give me a car. Youโ€™ll have to provide a proper noun. What car? Probably a honda accord. And thatโ€™s when a sales agent could get you something.\nWhy canโ€™t you create an object of an interface?\nBecause you canโ€™t walk into a showroom and say give me a contract of music player. It wonโ€™t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It wonโ€™t play music.\nWhy do interfaces allow multiple inheritance?\nInterfaces are not inherited. Interfaces are implemented.\nThe interface is a candidate for interaction with the external world.\nHonda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:\nabstract class Car\n{\n string color;\n int speed;\n}\nclass HondaAccord : Car, IInflateAir, IRefueling\n{\n MusicPlayer musicPlayer;\n}\n\nAnd the English will read like this โ€œHonda Accord is a Car that supports inflating tire and refuelingโ€.\n", "Key Points:\n\nAbstract class can have property, Data fields ,Methods (complete /\nincomplete) both.\nIf method or Properties define in abstract keyword that must override in derived class.(its work as a tightly coupled\nfunctionality)\nIf define abstract keyword for method or properties in abstract class you can not define body of method and get/set value for\nproperties and that must override in derived class.\nAbstract class does not support multiple inheritance.\nAbstract class contains Constructors.\nAn abstract class can contain access modifiers for the subs, functions, properties.\nOnly Complete Member of abstract class can be Static.\nAn interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.\n\nAdvantage:\n\nIt is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.\nIf various implementations are of the same kind and use common behavior or status then abstract class is better to use.\nIf we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.\nIts allow fast execution than interface.(interface Requires more time to find the actual method in the corresponding classes.)\nIt can use for tight and loosely coupling.\n\nfind details here...\nhttp://pradeepatkari.wordpress.com/2014/11/20/interface-and-abstract-class-in-c-oops/\n", "The shortest way to sum it up is that an interface is:\n\nFully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods.\nSubject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not.\nGenerally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface.\n\nMeanwhile, an abstract class is:\n\nAnywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract.\nA full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified).\nGenerally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply.\n\nOr, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is.\n", "Inheritance is used for two purposes:\n\nTo allow an object to regard parent-type data members and method implementations as its own.\nTo allow a reference to an objects of one type to be used by code which expects a reference to supertype object.\n\nIn languages/frameworks which support generalized multiple inheritance, there is often little need to classify a type as either being an \"interface\" or an \"abstract class\". Popular languages and frameworks, however, will allow a type to regard one other type's data members or method implementations as its own even though they allow a type to be substitutable for an arbitrary number of other types.\nAbstract classes may have data members and method implementations, but can only be inherited by classes which don't inherit from any other classes. Interfaces put almost no restrictions on the types which implement them, but cannot include any data members or method implementations.\nThere are times when it's useful for types to be substitutable for many different things; there are other times when it's useful for objects to regard parent-type data members and method implementations as their own. Making a distinction between interfaces and abstract classes allows each of those abilities to be used in cases where it is most relevant.\n", "Differences between abstract class and interface on behalf of real implementation.\nInterface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement.\nSome of other use cases where we should use interface.\nCommunication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract.\nAbstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality.\nExample of Abstract Class:\n public abstract class DesireCar\n {\n\n //It is an abstract method that defines the prototype.\n public abstract void Color();\n\n // It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels. \n // and hence no need to define this in all the sub classes in this way it saves the code duplicasy \n\n public void Wheel() { \n\n Console.WriteLine(\"Car has four wheel\");\n }\n }\n\n\n **Here is the sub classes:**\n\n public class DesireCar1 : DesireCar\n {\n public override void Color()\n {\n Console.WriteLine(\"This is a red color Desire car\");\n }\n }\n\n public class DesireCar2 : DesireCar\n {\n public override void Color()\n {\n Console.WriteLine(\"This is a red white Desire car\");\n }\n }\n\nExample Of Interface:\n public interface IShape\n {\n // Defines the prototype(template) \n void Draw();\n }\n\n\n // All the sub classes follow the same template but implementation can be different.\n\n public class Circle : IShape\n {\n public void Draw()\n {\n Console.WriteLine(\"This is a Circle\");\n }\n }\n\n public class Rectangle : IShape\n {\n public void Draw()\n {\n Console.WriteLine(\"This is a Rectangle\");\n }\n }\n\n", "I'd like to add one more difference which makes sense.\nFor example, you have a framework with thousands of lines of code. Now if you want to add a new feature throughout the code using a method enhanceUI(), then it's better to add that method in abstract class rather in interface. Because, if you add this method in an interface then you should implement it in all the implemented class but it's not the case if you add the method in abstract class.\n", "To give a simple but clear answer, it helps to set the context : you use both when you do not want to provide full implementations.\nThe main difference then is an interface has no implementation at all (only methods without a body) while abstract classes can have members and methods with a body as well, i.e. can be partially implemented. \n", "usually Abstract class used for core of something but interface used for appending peripheral.\nwhen you want to create base type for vehicle you should use abstract class but if you want to add some functionality or property that is not part of base concept of vehicle you should use interface,for example you want to add \"ToJSON()\" function.\ninterface has wide range of abstraction rather than abstract class.\nyou can see this in passing arguments.look this example:\n\nif you use vehicle as argument you just can use one of its derived type (bus or car-same category-just vehicle category).\nbut when you use IMoveable interface as argument you have more choices.\n", "The topic of abstract classes vs interfaces is mostly about semantics.\nAbstract classes act in different programming languages often as a superset of interfaces, except one thing and that is, that you can implement multiple interfaces, but inherit only one class.\nAn interface defines what something must be able to do; like a contract, but does not provide an implementation of it.\nAn abstract class defines what something is and it commonly hosts shared code between the subclasses.\nFor example a Formatter should be able to format() something. The common semantics to describe something like that would be to create an interface IFormatter with a declaration of format() that acts like a contract. But IFormatter does not describe what something is, but just what it should be able to to. The common semantics to describe what something actually is, is to create a class. In this case we create an abstract class... So we create an abstract class Formatter which implements the interface. That is a very descriptive code, because we now know we have a Formatter and we now know what every Formatter must be able to do.\nAlso one very important topic is documentation (at least for some people...). In your documentation you probably want to explain within your subclasses what a Formatter actually is. It is very convenient to have an abstract class Formatter to which documentation you can link to within your subclasses. That is very convenient and generic. On the other hand if you do not have an abstract class Formatter and only an interface IFormatter you would have to explain in each of your subclasses what a Formatter actucally is, because an interface is a contract and you would not describe what a Formatter actually is within the documentation of an interface โ€” at least it would be not something common to do and you would break the semantics that most developers consider to be correct.\nNote: It is a very common pattern to make an abstract class implement an interface.\n", "In an interface all methods must be only definitions, not single one should be implemented. \nBut in an abstract class there must an abstract method with only definition, but other methods can be also in the abstract class with implementation...\n", "An abstract class is a class whose object cannot be created or a class which cannot be instantiated.\nAn abstract method makes a class abstract. \nAn abstract class needs to be inherited in order to override the methods that are declared in the abstract class. \nNo restriction on access specifiers. \nAn abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have.\nAn interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) . \nIt is a collection of abstract methods , default methods , static methods , final variables and nested classes.\nAll members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed. \nA class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding)\nAn interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class. \nFor Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions).\nWhy interface when we already have abstract class?\nJava supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance. \n", "In practicality terms(JAVA), the major difference between abstract class and interface is\nAbstract class can hold state.\nOther than holding state we can achieve rest operations with Interface also.\n", "Similarities\nBoth forces classes extending or implementing them to override base methods.\nDifferences\n\nA class can implement multiple interfaces.\nA class can only extend from one abstract class.\nFields declared in interfaces must be static and final because all objects that created from such implementation share same values.\nIn Abstract classes, fields can be named and not assigned. subclasses can override them.\n\nUsecases\n\nAbstract classes are used in subclasses that are closely related, or have almost same functionalities and behaviours.\nInterfaces are used for unrelated classes that you want to force a certain thing or behaviour, because its Just a contract without implementation.\n\n", "A simple yet effective explanation of abstract class and interface on php.net:\n\nAn Interface is like a protocol. It doesn't designate the behavior of the object; it designates how your code tells that object to act. An interface would be like the English Language: defining an interface defines how your code communicates with any object implementing that interface.\nAn interface is always an agreement or a promise. When a class says \"I implement interface Y\", it is saying \"I promise to have the same public methods that any object with interface Y has\".\nOn the other hand, an Abstract Class is like a partially built class. It is much like a document with blanks to fill in. It might be using English, but that isn't as important as the fact that some of the document is already written.\nAn abstract class is the foundation for another object. When a class says \"I extend abstract class Y\", it is saying \"I use some methods or properties already defined in this other class named Y\".\nSo, consider the following PHP:\n<?php\nclass X implements Y { } // this is saying that \"X\" agrees to speak language \"Y\" with your code.\n\nclass X extends Y { } // this is saying that \"X\" is going to complete the partial class \"Y\".\n?>\n\nYou would have your class implement a particular interface if you were distributing a class to be used by other people. The interface is an agreement to have a specific set of public methods for your class.\nYou would have your class extend an abstract class if you (or someone else) wrote a class that already had some methods written that you want to use in your new class.\nThese concepts, while easy to confuse, are specifically different and distinct. For all intents and purposes, if you're the only user of any of your classes, you don't need to implement interfaces.\n\n", "We have various structural/syntactical difference between interface and abstract class. Some more differences are\n[1] Scenario based difference:\nAbstract classes are used in scenarios when we want to restrict the user to create object of parent class AND we believe there will be more abstract methods will be added in future.\nInterface has to be used when we are sure there can be no more abstract method left to be provided. Then only an interface is published.\n[2] Conceptual difference:\n\"Do we need to provide more abstract methods in future\" if YES make it abstract class and if NO make it Interface.\n(Most appropriate and valid till java 1.7)\n", "Interfaces are generally the classes without logic just a signature. Whereas abstract classes are those having logic. Both support contract as interface all method should be implemented in the child class but in abstract only the abstract method should be implemented. When to use interface and when to abstract? Why use Interface?\nclass Circle {\n\nprotected $radius;\n\npublic function __construct($radius)\n\n{\n $this->radius = $radius\n}\n\npublic function area()\n{\n return 3.14159 * pow(2,$this->radius); // simply pie.r2 (square);\n}\n\n}\n\n//Our area calculator class would look like\n\nclass Areacalculator {\n\n$protected $circle;\n\npublic function __construct(Circle $circle)\n{\n $this->circle = $circle;\n}\n\npublic function areaCalculate()\n{\n return $circle->area(); //returns the circle area now\n}\n\n}\n\nWe would simply do\n$areacalculator = new Areacalculator(new Circle(7)); \n\nFew days later we would need the area of rectangle, Square, Quadrilateral and so on. If so do we have to change the code every time and check if the instance is of square or circle or rectangle? Now what OCP says is CODE TO AN INTERFACE NOT AN IMPLEMENTATION. \nSolution would be:\nInterface Shape {\n\npublic function area(); //Defining contract for the classes\n\n}\n\nClass Square implements Shape {\n\n$protected length;\n\npublic function __construct($length) {\n //settter for length like we did on circle class\n}\n\npublic function area()\n{\n //return l square for area of square\n}\n\nClass Rectangle implements Shape {\n\n$protected length;\n$protected breath;\n\npublic function __construct($length,$breath) {\n //settter for length, breath like we did on circle,square class\n}\n\npublic function area()\n{\n //return l*b for area of rectangle\n}\n\n}\n\nNow for area calculator\nclass Areacalculator {\n\n$protected $shape;\n\npublic function __construct(Shape $shape)\n{\n $this->shape = $shape;\n}\n\npublic function areaCalculate()\n{\n return $shape->area(); //returns the circle area now\n}\n\n}\n\n$areacalculator = new Areacalculator(new Square(1));\n$areacalculator->areaCalculate();\n\n$areacalculator = new Areacalculator(new Rectangle(1,2));\n$areacalculator->;areaCalculate();\n\nIsn't that more flexible? If we would code without interface we would check the instance for each shape redundant code.\nNow when to use abstract?\nAbstract Animal {\n\npublic function breathe(){\n\n//all animals breathe inhaling o2 and exhaling co2\n\n}\n\npublic function hungry() {\n\n//every animals do feel hungry \n\n}\n\nabstract function communicate(); \n// different communication style some bark, some meow, human talks etc\n\n}\n\nNow abstract should be used when one doesn't need instance of that class, having similar logic, having need for the contract.\n", "The general idea of abstract classes and interfaces is to be extended/implemented by other classes (cannot be constructed alone) that use these general \"settings\" (some kind of a template), making it simple to set a specific-general behaviour for all the objects that later extend it.\nAn abstract class has regular methods set AND abstract methods. Extended classes can include unset methods after being extended by an abstract class. When setting abstract methods - they are defined by the classes that are extending it later.\nInterfaces have the same properties as an abstract class, but includes only abstract methods, which could be implemented in an other class/es (and can be more than one interface to implement), this creates a more permanent-solid definishion of methods/static variables. Unlike the abstract class, you cannot add custom \"regular\" methods. \n", "An interface is so called because it provides an interface of methods to a caller (or a COM client for instance) that are implemented by some class. By polymorphically casting an object pointer to the type of an interface that the object's class implements, it restricts the access of the object to functions and members of the interface that it implements, separated from other COM interfaces the coclass might implement. The client does not need to know what class implements the interface or what other methods are present in the class; the object presents as an instance of the interface it knows (where the instance of the class has been polymorphically cast to the interface instance, which is a subinstance of the class) and it just uses the interface by calling the methods of the interface on the interface instance. All details of the actual implementation and extraneous functionality / details implemented by different interfaces are separated from the interface the caller expects -- the caller just uses the interface it has with the object (the interface instance and its virtual table pointer that's part of the object), and the underlying object implementation is called without the caller having to know the location or the details of the implementation. Accessing the object through the interface (a pointer of the type of the interface) is a form of encapsulation that syntactically prevents unauthorised access to the object as well as hiding implementation details and other functionality that does not pertain to the interface and its defined personality.\nAn interface is where all methods are virtual and abstract (abstract is known as pure virtual in C++; all abstract methods contain the virtual specifier and therefore are virtual). An abstract class is where at least one of the methods is virtual and specified as abstract (or pure virtual in C++). Other details differ across languages. All interface attributes are implicitly public static final in java but they aren't in C++. Java allows non-static attributes in abstract classes but C++ allows them in both. Attributes cannot be virtual / abstract in either language.\n", "\nAbstract class provides both declaration and implementation but Interfaces have only declaration.\nWhen you want to achieve multiple inheritance then you should use Interface not Abstract class because in C#, a class can inherit from one class only but from more than one interface.\nAbstract class contains constructors while Interface does not.\nInterfaces have only public members whereas abstract classes can contain public, private protected modifiers.\nAbstract class can provide complete, partial or no implementation whereas Interface provides only declaration.\nPerformance wise, Abstract class is fast as Interface needs to identify the actual method implementation which takes some time.\nInterface provides you the ability of a class whereas An abstract class gives you the identity of class.\nAbstract class allows you to define and implement some common functionality which can be used by many child classes but Interface gives you common method signatures that can be implemented differently as per requirement.\nAbstract class can provide default implementation for any newly added method and all code will work properly but in case of Interface you need to implement that new method in all the classes using that interface.\nMembers of Interface can not be static but complete members of Abstract class can be static.\nInterfaces allow you to create Mocks easily in unit testing while Abstract class needs extra coding.\n\n" ]
[ 2435, 953, 158, 84, 57, 42, 41, 29, 27, 22, 17, 16, 15, 10, 10, 10, 8, 7, 7, 7, 5, 5, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0 ]
[ "\nHere is a very basic understanding over interface vs abstract class.\n" ]
[ -1 ]
[ "abstract_class", "interface", "oop" ]
stackoverflow_0001913098_abstract_class_interface_oop.txt
Q: How to filter between dates but keep duplicates that aren't included in the time period? I have a have a dataset that looks something like this: data <- data.frame(group = c("09081997", "13122006", "09081997", "22031969", "09081997"), date1 = c("2021-08-09", "2021-08-10", "2021-08-21", "2021-07-19", "2021-07-15")) There are duplicated numbers in "group" variable. For example, I need to filter between the dates "2021-08-01" to "2021-08-31". By doing that, I would "delete" the last two numbers from "group", but I need to keep all duplicates, even if they're not between the time period I want to filter. I'd need to keep all "09081997" registers. At least one of the duplicates would have to be in the time period. Is it possible to do that? A: If I understood correctly, this will work. I created an auxiliary variable counting by group, and only applied the filter for dates of groups that appear only one time. library(dplyr) library(lubridate) data %>% mutate(across(.cols = starts_with("date"),.fns = ymd)) %>% add_count(group) %>% filter(!(n == 1 & (date1 >= ymd("2021-08-01") & date2 <= ymd("2021-08-31")))) group date1 date2 n 1 09081997 2021-08-09 2021-08-31 3 2 09081997 2021-08-21 2021-08-29 3 3 22031969 2021-07-19 2021-07-20 1 4 09081997 2021-07-15 2021-07-19 3 I am just unsure how date1 and date2 are supposed to be filtered. A: Using ave, you could groupwise grepl for '2021-08' pattern and check if it occurs anywhere. Since date* columns are character we get "false" booleans, but we can easily turn the mode to "logical". Finally we check if the rowSums of the boolean are greater than zero, i.e. if any of the two dates in that row falls in '2021-08', which yields the desired boolean vector to subset the data frame. data[with(data, ave(cbind(date1, date2), group, FUN=\(x) any(grepl(x, pat='2021-08')))) |> `mode<-`('logical') |> rowSums() |> base::`>`(0), ] # group date1 date2 # 1 09081997 2021-08-09 2021-08-31 # 2 13122006 2021-08-10 2021-08-22 # 3 09081997 2021-08-21 2021-08-29 # 5 09081997 2021-07-15 2021-07-19 If you just have one date column, this simplifies to data1[with(data1, as.logical(ave(date1, group, FUN=\(x) any(grepl(x, pat='2021-08'))))), ] # group date1 # 1 09081997 2021-08-09 # 2 13122006 2021-08-10 # 3 09081997 2021-08-21 # 5 09081997 2021-07-15 Update: If you have a time period that is more complicated e.g. overlaps a month, we can use a comparison instead of the grepl: data1[with(data1, as.logical(ave(date1, group, FUN=\(x) any( x >= "2021-03-08" | x <= "2021-06-04" )))), ] Data: data <- structure(list(group = c("09081997", "13122006", "09081997", "22031969", "09081997"), date1 = c("2021-08-09", "2021-08-10", "2021-08-21", "2021-07-19", "2021-07-15"), date2 = c("2021-08-31", "2021-08-22", "2021-08-29", "2021-07-20", "2021-07-19")), class = "data.frame", row.names = c(NA, -5L)) data1 <- data[1:2]
How to filter between dates but keep duplicates that aren't included in the time period?
I have a have a dataset that looks something like this: data <- data.frame(group = c("09081997", "13122006", "09081997", "22031969", "09081997"), date1 = c("2021-08-09", "2021-08-10", "2021-08-21", "2021-07-19", "2021-07-15")) There are duplicated numbers in "group" variable. For example, I need to filter between the dates "2021-08-01" to "2021-08-31". By doing that, I would "delete" the last two numbers from "group", but I need to keep all duplicates, even if they're not between the time period I want to filter. I'd need to keep all "09081997" registers. At least one of the duplicates would have to be in the time period. Is it possible to do that?
[ "If I understood correctly, this will work. I created an auxiliary variable counting by group, and only applied the filter for dates of groups that appear only one time.\nlibrary(dplyr)\nlibrary(lubridate)\n\ndata %>% \n mutate(across(.cols = starts_with(\"date\"),.fns = ymd)) %>% \n add_count(group) %>% \n filter(!(n == 1 & (date1 >= ymd(\"2021-08-01\") & date2 <= ymd(\"2021-08-31\"))))\n\n group date1 date2 n\n1 09081997 2021-08-09 2021-08-31 3\n2 09081997 2021-08-21 2021-08-29 3\n3 22031969 2021-07-19 2021-07-20 1\n4 09081997 2021-07-15 2021-07-19 3\n\nI am just unsure how date1 and date2 are supposed to be filtered.\n", "Using ave, you could groupwise grepl for '2021-08' pattern and check if it occurs anywhere. Since date* columns are character we get \"false\" booleans, but we can easily turn the mode to \"logical\". Finally we check if the rowSums of the boolean are greater than zero, i.e. if any of the two dates in that row falls in '2021-08', which yields the desired boolean vector to subset the data frame.\ndata[with(data, ave(cbind(date1, date2), group, FUN=\\(x) any(grepl(x, pat='2021-08')))) |> \n `mode<-`('logical') |> rowSums() |> base::`>`(0), ]\n# group date1 date2\n# 1 09081997 2021-08-09 2021-08-31\n# 2 13122006 2021-08-10 2021-08-22\n# 3 09081997 2021-08-21 2021-08-29\n# 5 09081997 2021-07-15 2021-07-19\n\nIf you just have one date column, this simplifies to\ndata1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(grepl(x, pat='2021-08'))))), ]\n# group date1\n# 1 09081997 2021-08-09\n# 2 13122006 2021-08-10\n# 3 09081997 2021-08-21\n# 5 09081997 2021-07-15\n\nUpdate: If you have a time period that is more complicated e.g. overlaps a month, we can use a comparison instead of the grepl:\ndata1[with(data1, as.logical(ave(date1, group, FUN=\\(x) any(\n x >= \"2021-03-08\" | x <= \"2021-06-04\"\n)))), ]\n \n\n\nData:\ndata <- structure(list(group = c(\"09081997\", \"13122006\", \"09081997\", \n\"22031969\", \"09081997\"), date1 = c(\"2021-08-09\", \"2021-08-10\", \n\"2021-08-21\", \"2021-07-19\", \"2021-07-15\"), date2 = c(\"2021-08-31\", \n\"2021-08-22\", \"2021-08-29\", \"2021-07-20\", \"2021-07-19\")), class = \"data.frame\", row.names = c(NA, \n-5L))\n\ndata1 <- data[1:2]\n\n" ]
[ 1, 0 ]
[]
[]
[ "date", "r" ]
stackoverflow_0074671893_date_r.txt
Q: SSRS Report showing blank values but on export it is showing actual values I have an report, which was working fine on my old laptope but when i use the same in my new laptop is showing blank in place of data values like image below:- enter image description here But when i use same report after publishing on report server or i export it to excel. It shows actual values image given below. enter image description here What may be the reason. Please help, I checked everything like server connection, font colour, data in sql is coming fine with same query, even data is correct when we execute the query in query designer of SSRS. Pls help, thanks in advance. I tried checking connection. Query execution in SSRS. Font & Background color properties. A: This issue is due to some screen setting issue I changed the scale from 150% to 100% and took control of my laptop from my old laptop through any desk now it is working fine for the last two days. I don't know what it did but seems like my issue is resolved.
SSRS Report showing blank values but on export it is showing actual values
I have an report, which was working fine on my old laptope but when i use the same in my new laptop is showing blank in place of data values like image below:- enter image description here But when i use same report after publishing on report server or i export it to excel. It shows actual values image given below. enter image description here What may be the reason. Please help, I checked everything like server connection, font colour, data in sql is coming fine with same query, even data is correct when we execute the query in query designer of SSRS. Pls help, thanks in advance. I tried checking connection. Query execution in SSRS. Font & Background color properties.
[ "This issue is due to some screen setting issue I changed the scale from 150% to 100% and took control of my laptop from my old laptop through any desk now it is working fine for the last two days. I don't know what it did but seems like my issue is resolved.\n" ]
[ 0 ]
[]
[]
[ "reporting_services", "reporting_services_2016", "sql_server", "sqlreportingservice" ]
stackoverflow_0074642778_reporting_services_reporting_services_2016_sql_server_sqlreportingservice.txt
Q: Solve the problem with a specific limitation Assume that there are a set of roads that connect the cities between A and B. We model this as a graph of $n$ nodes (cities) connected by $m$ edges (roads). Each edge weight corresponds to the time it takes to travel along that road, so the edge weight for the road between city $u$ and the city $v$ is $w(u, v)$. There are two types of roads: free roads and roads with cost. All cost roads cost the same amount and are generally (although not always) faster than free roads. Bob would like to reach city B from A as fast as possible, however, he only has enough money to take at most one cost road. How to find such a route? A: First let's specify the problem in terms of directed graphs. If the original graph is undirected, simply double each edge and give them opposite directions. One simple method is to have a graph that contains two copies v' and v'' of each of the original vertex v. If there is a free road between u and v, there are edges between u' and v', and between u'' and v''. If there is a toll road between u and v, there is an edge between u' and v''. You can visualise this as a graph with two floors. Each floor is a free part of the original grap, and there are one-way connections between the floors that correspond to toll roads (you can only go down but never up). Also add edges between A' and A'', and B' and B''. Now every path between A' and B'' has no more than one toll road. You use any algorithm to find the shortest one. This generalises to any number of toll road permissible on the route (have N+1 copies of the original graph).
Solve the problem with a specific limitation
Assume that there are a set of roads that connect the cities between A and B. We model this as a graph of $n$ nodes (cities) connected by $m$ edges (roads). Each edge weight corresponds to the time it takes to travel along that road, so the edge weight for the road between city $u$ and the city $v$ is $w(u, v)$. There are two types of roads: free roads and roads with cost. All cost roads cost the same amount and are generally (although not always) faster than free roads. Bob would like to reach city B from A as fast as possible, however, he only has enough money to take at most one cost road. How to find such a route?
[ "First let's specify the problem in terms of directed graphs. If the original graph is undirected, simply double each edge and give them opposite directions.\nOne simple method is to have a graph that contains two copies v' and v'' of each of the original vertex v.\nIf there is a free road between u and v, there are edges between u' and v', and between u'' and v''.\nIf there is a toll road between u and v, there is an edge between u' and v''.\nYou can visualise this as a graph with two floors. Each floor is a free part of the original grap, and there are one-way connections between the floors that correspond to toll roads (you can only go down but never up).\nAlso add edges between A' and A'', and B' and B''.\nNow every path between A' and B'' has no more than one toll road. You use any algorithm to find the shortest one.\nThis generalises to any number of toll road permissible on the route (have N+1 copies of the original graph).\n" ]
[ 1 ]
[]
[]
[ "algorithm", "dijkstra", "graph", "graph_theory", "math" ]
stackoverflow_0074672473_algorithm_dijkstra_graph_graph_theory_math.txt
Q: How to avoid dependee library symbols conflict? I have a Fortran executable that statically links against a specific version of hdf5. The executable makes use of a C++ library foo that is statically linked against a different version of hdf5. The executable refuses to link because of conflict in symbols. Is there a way to avoid this issue without making the C++ library foo dynamic? A: I have a Fortran executable that statically links against a specific version of hdf5. The executable makes use of a C++ library foo that is statically linked against a different version of hdf5. This can work, but you must hide the fact that foo contains a version of the hdf5 library by hiding all of hdf5 symbols. Doing so will avoid symbol conflicts. See this answer.
How to avoid dependee library symbols conflict?
I have a Fortran executable that statically links against a specific version of hdf5. The executable makes use of a C++ library foo that is statically linked against a different version of hdf5. The executable refuses to link because of conflict in symbols. Is there a way to avoid this issue without making the C++ library foo dynamic?
[ "\nI have a Fortran executable that statically links against a specific version of hdf5. The executable makes use of a C++ library foo that is statically linked against a different version of hdf5.\n\nThis can work, but you must hide the fact that foo contains a version of the hdf5 library by hiding all of hdf5 symbols. Doing so will avoid symbol conflicts.\nSee this answer.\n" ]
[ 0 ]
[]
[]
[ "c++", "dynamic_linking", "fortran", "static", "static_linking" ]
stackoverflow_0074654857_c++_dynamic_linking_fortran_static_static_linking.txt
Q: Solidity: What does the caret ^ operator do? I searched solidity documentation and there's nothing on this: What does the caret ^ operator do? What is it doing here? sha3(sha3(valueA) ^ sha3(valueB)) A: It's a bitwise operation, XOR (exclusive or): https://docs.soliditylang.org/en/v0.8.6/types.html "A bitwise XOR is a binary operation that takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only one of the bits is 1, but will be 0 if both are 0 or both are 1." https://en.wikipedia.org/wiki/Bitwise_operation#:~:text=A%20bitwise%20XOR%20is%20a,0%20or%20both%20are%201. A: Per https://www.tutorialspoint.com/solidity/solidity_operators.htm (via Google, BTW), as in many languages, it means XOR (exclusive or): x y x^y 0 0 0 0 1 1 1 0 1 1 1 0 (1=True; 0=False) A: The keyword I left out is "bitwise" (as Nathan mentioned). So, if, for example, sha3(valueA)=0x44=0b01000100, and sha3(valueB)=0x34=0b00110100, then: (sha3(valueA)=0x44=0b01000100 and sha3(valueB))=0x70=0b01110000 PS fun fact: XOR with all 1s is a "bit flip" A: It is xor or exclusive or operator. output is true if the inputs are not alike otherwise the output is false. 1 xor 1 == 0 xor 0 = 0 1 xor 0 == 0 xor 1 = 1 from here The XOR Encryption algorithm is a very effective yet easy to implement method of symmetric encryption. Due to its effectiveness and simplicity, the XOR Encryption is an extremely common component used in more complex encryption algorithms used nowadays. The XOR encryption algorithm is an example of symmetric encryption where the same key is used to both encrypt and decrypt a message. Also Why is XOR used in cryptography?
Solidity: What does the caret ^ operator do?
I searched solidity documentation and there's nothing on this: What does the caret ^ operator do? What is it doing here? sha3(sha3(valueA) ^ sha3(valueB))
[ "It's a bitwise operation, XOR (exclusive or): https://docs.soliditylang.org/en/v0.8.6/types.html\n\"A bitwise XOR is a binary operation that takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only one of the bits is 1, but will be 0 if both are 0 or both are 1.\" https://en.wikipedia.org/wiki/Bitwise_operation#:~:text=A%20bitwise%20XOR%20is%20a,0%20or%20both%20are%201.\n", "Per https://www.tutorialspoint.com/solidity/solidity_operators.htm (via Google, BTW), as in many languages, it means XOR (exclusive or):\nx y x^y\n0 0 0\n0 1 1\n1 0 1\n1 1 0\n(1=True; 0=False)\n\n", "The keyword I left out is \"bitwise\" (as Nathan mentioned).\nSo, if, for example, sha3(valueA)=0x44=0b01000100, and\n sha3(valueB)=0x34=0b00110100, then:\n(sha3(valueA)=0x44=0b01000100 and sha3(valueB))=0x70=0b01110000\n\nPS\nfun fact: XOR with all 1s is a \"bit flip\"\n", "It is xor or exclusive or operator. output is true if the inputs are not alike otherwise the output is false.\n 1 xor 1 == 0 xor 0 = 0\n 1 xor 0 == 0 xor 1 = 1\n\nfrom here\n\nThe XOR Encryption algorithm is a very effective yet easy to implement\nmethod of symmetric encryption. Due to its effectiveness and\nsimplicity, the XOR Encryption is an extremely common component used\nin more complex encryption algorithms used nowadays.\nThe XOR encryption algorithm is an example of symmetric encryption\nwhere the same key is used to both encrypt and decrypt a message.\n\nAlso Why is XOR used in cryptography?\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "blockchain", "cryptography", "ethereum", "solidity", "xor" ]
stackoverflow_0068583591_blockchain_cryptography_ethereum_solidity_xor.txt
Q: How to use a custom font style in flutter? I have already set on my pubspec.yaml the following code: fonts: - family: Roboto fonts: - asset: fonts/Roboto-Light.ttf - asset: fonts/Roboto-Thin.ttf - asset: fonts/Roboto-Italic.ttf But I don't know to use, for example, the style "Roboto-Light.ttf" from Roboto in my widget. I tried this: new ListTile( title: new Text( "Home", style: new TextStyle( fontFamily: "Roboto", fontSize: 60.0, ), ), ), I don't know how to access the style "Roboto-Light.ttf". How to do this? Thanks! A: Roboto is the default font of the Material style, there is no need to add it in pubspec.yaml. To use the different variations, set a TextStyle Text( 'Home', style: TextStyle( fontWeight: FontWeight.w300, // light fontStyle: FontStyle.italic, // italic ), ); I think thin is FontWeight.w200. The FontWeights for the corresponding styles are mentioned in the styles section of the particular font in GoogleFonts website. A: In general, you can specify the font styles directly. pubspec.yaml fonts: - family: Roboto fonts: - asset: fonts/Roboto-Light.ttf weight: 300 - asset: fonts/Roboto-Thin.ttf weight: 100 - asset: fonts/Roboto-Italic.ttf style: italic Widget ListTile( title: Text( 'Home', style: TextStyle( fontFamily: 'Roboto', fontWeight: FontWeight.w300, // -> Roboto-Light.ttf // fontWeight: FontWeight.w100 // -> Roboto-Thin.ttf fontSize: 60.0, ), ), ), A: Declare and Access the font correctly. Declare the font path in the pubspec.yaml file. Follow the correct indentation. For example, I have added IndieFlower-Regular.ttf file inside fonts folder. This is how my pubspec.yaml file looks like. flutter: uses-material-design: true fonts: - family: Indies fonts: - asset: fonts/IndieFlower-Regular.ttf Accessing the font in TextStyle style: TextStyle( color: Colors.green, fontSize: 30.0, fontFamily: 'Indies' ), For better understanding here is the picture which shows the font, pubspec.yaml and the output. A: Note: this is only if you prefer using fonts from fonts.google.com One of the coolest and easiest way to use google fonts is to use the google_fonts_package. The google_fonts package for Flutter allows you to easily use any of the 960 fonts (and their variants) from fonts.google.com in your Flutter app.With the google_fonts package, .ttf files do not need to be stored in your assets folder and mapped in the pubspec. Instead, they are fetched once via http at runtime, and cached in the app's file system. Installation add to pubspec.yaml google_fonts: ^0.1.0 import import 'package:google_fonts/google_fonts.dart'; use your font e.g Text("TestText", style:GoogleFonts.dancingScriptTextStyle( fontSize: 25, fontStyle: FontStyle.normal, ) Although it mentions that it should not be used in production but I see an app deployed on both playstore and appstore by Tim Sneath and works perfectly heres the open source code hope this helps A: If anyone want to change the default Flutter material font or use a custom font all over the app not in a specific widget, first add downloaded font to pubspec.yaml fonts: - family: Outfit fonts: - asset: fonts/Outfit-Light.ttf weight: 300 - asset: fonts/Outfit-Thin.ttf weight: 100 style: italic And then in the root of your project add this return MaterialApp( title: 'Custom Fonts', // Set Outfit as the default app font. theme: ThemeData(fontFamily: 'Outfit'), home: const MyHomePage(), );
How to use a custom font style in flutter?
I have already set on my pubspec.yaml the following code: fonts: - family: Roboto fonts: - asset: fonts/Roboto-Light.ttf - asset: fonts/Roboto-Thin.ttf - asset: fonts/Roboto-Italic.ttf But I don't know to use, for example, the style "Roboto-Light.ttf" from Roboto in my widget. I tried this: new ListTile( title: new Text( "Home", style: new TextStyle( fontFamily: "Roboto", fontSize: 60.0, ), ), ), I don't know how to access the style "Roboto-Light.ttf". How to do this? Thanks!
[ "Roboto is the default font of the Material style, there is no need to add it in pubspec.yaml.\nTo use the different variations, set a TextStyle\nText(\n 'Home',\n style: TextStyle(\n fontWeight: FontWeight.w300, // light\n fontStyle: FontStyle.italic, // italic\n ),\n);\n\nI think thin is FontWeight.w200.\nThe FontWeights for the corresponding styles are mentioned in the styles section of the particular font in GoogleFonts website.\n", "In general, you can specify the font styles directly.\npubspec.yaml\n fonts:\n - family: Roboto\n fonts:\n - asset: fonts/Roboto-Light.ttf\n weight: 300\n - asset: fonts/Roboto-Thin.ttf\n weight: 100\n - asset: fonts/Roboto-Italic.ttf\n style: italic\n\n\nWidget\nListTile(\n title: Text(\n 'Home',\n style: TextStyle(\n fontFamily: 'Roboto',\n fontWeight: FontWeight.w300, // -> Roboto-Light.ttf\n // fontWeight: FontWeight.w100 // -> Roboto-Thin.ttf\n fontSize: 60.0,\n ),\n ),\n),\n\n", "Declare and Access the font correctly.\n\nDeclare the font path in the pubspec.yaml file.\n\nFollow the correct indentation.\nFor example, I have added IndieFlower-Regular.ttf file inside fonts folder. This is how my pubspec.yaml file looks like.\nflutter:\n\n uses-material-design: true\n\n fonts:\n - family: Indies\n fonts:\n - asset: fonts/IndieFlower-Regular.ttf\n \n\n\nAccessing the font in TextStyle\n\nstyle: TextStyle(\n color: Colors.green,\n fontSize: 30.0,\n fontFamily: 'Indies'\n),\n\n\nFor better understanding here is the picture which shows the font,\npubspec.yaml and the output.\n\n\n", "Note: this is only if you prefer using fonts from fonts.google.com\nOne of the coolest and easiest way to use google fonts is to use the google_fonts_package.\n\nThe google_fonts package for Flutter allows you to easily use any of\n the 960 fonts (and their variants) from fonts.google.com in your\n Flutter app.With the google_fonts package, .ttf files do not need to\n be stored in your assets folder and mapped in the pubspec. Instead,\n they are fetched once via http at runtime, and cached in the app's\n file system.\n\nInstallation\n\nadd to pubspec.yaml\n\ngoogle_fonts: ^0.1.0\n\n\nimport \n\nimport 'package:google_fonts/google_fonts.dart';\n\n\nuse your font e.g\n\nText(\"TestText\", style:GoogleFonts.dancingScriptTextStyle(\n fontSize: 25,\n fontStyle: FontStyle.normal,\n )\n\nAlthough it mentions that it should not be used in production but I see an app deployed on both playstore and appstore by Tim Sneath and works perfectly heres the open source code hope this helps\n", "If anyone want to change the default Flutter material font or use a custom font all over the app not in a specific widget,\nfirst add downloaded font to pubspec.yaml\n fonts:\n - family: Outfit\n fonts:\n - asset: fonts/Outfit-Light.ttf\n weight: 300\n - asset: fonts/Outfit-Thin.ttf\n weight: 100\n style: italic\n\nAnd then in the root of your project add this\nreturn MaterialApp(\n title: 'Custom Fonts',\n // Set Outfit as the default app font.\n theme: ThemeData(fontFamily: 'Outfit'),\n home: const MyHomePage(),\n);\n\n\n" ]
[ 43, 4, 1, 1, 0 ]
[]
[]
[ "android", "dart", "flutter", "fonts" ]
stackoverflow_0052132135_android_dart_flutter_fonts.txt
Q: Jetpack Compose: How to change theme from light to dark mode programmatically onClick TL;DR change the theme and recompose the app between light and dark themes onClick. Hello! I have an interesting issue I have been struggling to figure out and would love some help. I am trying to implement a settings screen which lets the user change the theme of the app (selecting Dark, Light, or Auto which matches system setting). I am successfully setting the theme dynamically via invoking the isSystemInDarkTheme() function when choosing the color palette, but am struggling to recompose the app between light and dark themes on the click of a button. My strategy now is to create a theme model which hoists the state from the settings component which the user actually chooses the theme in. This theme model then exposes a theme state variable to the custom theme (wrapped around material theme) to decide whether to pick the light or dark color palette. Here is the relevant code --> Theme @Composable fun CustomTheme( themeViewModel: ThemeViewModel = viewModel(), content: @Composable() () -> Unit, ) { val colors = when (themeViewModel.theme.value.toString()) { "Dark" -> DarkColorPalette "Light" -> LightColorPalette else -> if (isSystemInDarkTheme()) DarkColorPalette else LightColorPalette } MaterialTheme( colors = colors, typography = typography, shapes = shapes, content = content ) } Theme model and state variable class ThemeViewModel : ViewModel() { private val _theme = MutableLiveData("Auto") val theme: LiveData<String> = _theme fun onThemeChanged(newTheme: String) { when (newTheme) { "Auto" -> _theme.value = "Light" "Light" -> _theme.value = "Dark" "Dark" -> _theme.value = "Auto" } } } Component (UI) code @Composable fun Settings( themeViewModel: ThemeViewModel = viewModel(), ) { ... val theme: String by themeViewModel.theme.observeAsState("") ... ScrollableColumn(Modifier.fillMaxSize()) { Column { ... Card() { Row() { Text(text = theme, modifier = Modifier.clickable( onClick = { themeViewModel.onThemeChanged(theme) } ) ) } } } Thanks so much for your time and help! ***I have elided some code here in the UI component, it is possible I have left out some closure syntax in the process. A: One possibility, shown in the Jetpack theming codelab, is to set the darkmode via input parameter, which ensures the theme will be recomposed when the parameter changes: @Composable fun CustomTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { MaterialTheme( colors = if (darkTheme) DarkColors else LightColors, content = content ) } In your mainActivity you can observe changes to your viewModel and pass them down to your customTheme: val darkTheme = themeViewModel.darkTheme.observeAsState(initial = true) CustomTheme(darkTheme.value){ //yourContent } This way your compose previews can simply be styled in dark theme: @Composable private fun DarkPreview() { CustomTheme(darkTheme = true) { content } } A: In case you want a button/switch to change the theme and make it persistent as setting, you can also achieve this by using Jetpack DataStore (recommended) or SharedPreferences, get your theme state in MainActivity and pass it to your Theme composable, and wherever you want to modify it. You can find a complete working example with SharedPreferences in this GitHub repo. This example is using a Singleton and Hilt for dependencies and is valid for all the preferences you want store. A: Based on the docs, the official way to handle theme changes triggered by a user's action (ie. choice of a theme other than the system one through a custom built setting) is to use AppCompatDelegate.setDefaultNightMode() This call alone will take care of most things, including restarting any activity (thus, recomposing). For this to work, we need: The Activity which calls setContent to extend AppCompatActvity The user's choice to be persisted and applied at each start of the app (through AppCompatDelegate) To define whether dark mode is enabled, your CustomTheme should also consider the value of the user's defaultNightMode preference: @Composable fun CustomTheme( isDark: Boolean = isNightMode(), content: @Composable () -> Unit ) { MaterialTheme( colors = if (darkTheme) DarkColors else LightColors, content = content ) } @Composable private fun isNightMode() = when (AppCompatDelegate.getDefaultNightMode()) { AppCompatDelegate.MODE_NIGHT_NO -> false AppCompatDelegate.MODE_NIGHT_YES -> true else -> isSystemInDarkTheme() } this is nice to have as it avoids the need to get this value in an Activity just to pass it to the theme with CustomTheme(isDark = isDark). This article goes through all of the above providing more details. A: It might not be the recommended way, but one option is to use the recreate method (available since API level 11). In order to use it outside of the activity and within your composable, you could pass the function call. Taking your code as a basis class SomeActivity { override fun onCreate(savedInstanceState: Bundle?) { ... setContent { ... themeViewModel.onRecreate = { recreate() } CustomTheme(themeViewModel) { ... } } } } In your viewModel class ThemeViewModel: ViewModel() { lateinit var onRecreate: () -> Unit private val _theme = MutableLiveData("Auto") val theme: LiveData<String> = _theme fun onThemeChanged(newTheme: String) { when (newTheme) { "Auto" -> _theme.value = "Light" "Light" -> _theme.value = "Dark" "Dark" -> _theme.value = "Auto" } onRecreate } } A: I just made it working with a simple model. Here is how you do it. Declare a public variable isUiModeDark lateinit var isUiModeDark : MutableState<Boolean?> Then, inside your theme's Lambda: isUiModeIsDark = remember { mutableStateOf(userSelectedThemeIsNight(context)) } val colorScheme = when (isUiModeIsDark.value) { true -> DarkColorScheme false -> LightColorScheme else -> if (systemTheme) DarkColorScheme else LightColorScheme } . . . MaterialTheme( colorScheme = colorScheme, content = content ) Now how to call recomposition? Simple, just change the value of isUiModeDark in your settings. true means dark theme app override is selected false means light theme app override is selected null means No theme app override is selected and system theme is followed. As to why this works just read the docs on MutableState and remember. Basically any change in MutableStates value causes recomposition. Neither Live data nor any other alternatives work until or unless they are derivates of the type State. The composable is basically just subscribed to the changes made to MutableState or any derivates of the State class.
Jetpack Compose: How to change theme from light to dark mode programmatically onClick
TL;DR change the theme and recompose the app between light and dark themes onClick. Hello! I have an interesting issue I have been struggling to figure out and would love some help. I am trying to implement a settings screen which lets the user change the theme of the app (selecting Dark, Light, or Auto which matches system setting). I am successfully setting the theme dynamically via invoking the isSystemInDarkTheme() function when choosing the color palette, but am struggling to recompose the app between light and dark themes on the click of a button. My strategy now is to create a theme model which hoists the state from the settings component which the user actually chooses the theme in. This theme model then exposes a theme state variable to the custom theme (wrapped around material theme) to decide whether to pick the light or dark color palette. Here is the relevant code --> Theme @Composable fun CustomTheme( themeViewModel: ThemeViewModel = viewModel(), content: @Composable() () -> Unit, ) { val colors = when (themeViewModel.theme.value.toString()) { "Dark" -> DarkColorPalette "Light" -> LightColorPalette else -> if (isSystemInDarkTheme()) DarkColorPalette else LightColorPalette } MaterialTheme( colors = colors, typography = typography, shapes = shapes, content = content ) } Theme model and state variable class ThemeViewModel : ViewModel() { private val _theme = MutableLiveData("Auto") val theme: LiveData<String> = _theme fun onThemeChanged(newTheme: String) { when (newTheme) { "Auto" -> _theme.value = "Light" "Light" -> _theme.value = "Dark" "Dark" -> _theme.value = "Auto" } } } Component (UI) code @Composable fun Settings( themeViewModel: ThemeViewModel = viewModel(), ) { ... val theme: String by themeViewModel.theme.observeAsState("") ... ScrollableColumn(Modifier.fillMaxSize()) { Column { ... Card() { Row() { Text(text = theme, modifier = Modifier.clickable( onClick = { themeViewModel.onThemeChanged(theme) } ) ) } } } Thanks so much for your time and help! ***I have elided some code here in the UI component, it is possible I have left out some closure syntax in the process.
[ "One possibility, shown in the Jetpack theming codelab, is to set the darkmode via input parameter, which ensures the theme will be recomposed when the parameter changes:\n@Composable\nfun CustomTheme(\n darkTheme: Boolean = isSystemInDarkTheme(),\n content: @Composable () -> Unit\n) {\n MaterialTheme(\n colors = if (darkTheme) DarkColors else LightColors,\n content = content\n )\n}\n\nIn your mainActivity you can observe changes to your viewModel and pass them down to your customTheme:\nval darkTheme = themeViewModel.darkTheme.observeAsState(initial = true)\n\nCustomTheme(darkTheme.value){\n//yourContent\n}\n\nThis way your compose previews can simply be styled in dark theme:\n@Composable\nprivate fun DarkPreview() {\n CustomTheme(darkTheme = true) {\n content\n }\n}\n\n", "In case you want a button/switch to change the theme and make it persistent as setting, you can also achieve this by using Jetpack DataStore (recommended) or SharedPreferences, get your theme state in MainActivity and pass it to your Theme composable, and wherever you want to modify it.\nYou can find a complete working example with SharedPreferences in this GitHub repo.\nThis example is using a Singleton and Hilt for dependencies and is valid for all the preferences you want store.\n", "Based on the docs, the official way to handle theme changes triggered by a user's action (ie. choice of a theme other than the system one through a custom built setting) is to use\nAppCompatDelegate.setDefaultNightMode()\n\nThis call alone will take care of most things, including restarting any activity (thus, recomposing). For this to work, we need:\n\nThe Activity which calls setContent to extend AppCompatActvity\nThe user's choice to be persisted and applied at each start of the app (through AppCompatDelegate)\nTo define whether dark mode is enabled, your CustomTheme should also consider the value of the user's defaultNightMode preference:\n\n@Composable\nfun CustomTheme(\n isDark: Boolean = isNightMode(),\n content: @Composable () -> Unit\n) {\n MaterialTheme(\n colors = if (darkTheme) DarkColors else LightColors,\n content = content\n )\n}\n\n@Composable\nprivate fun isNightMode() = when (AppCompatDelegate.getDefaultNightMode()) {\n AppCompatDelegate.MODE_NIGHT_NO -> false\n AppCompatDelegate.MODE_NIGHT_YES -> true\n else -> isSystemInDarkTheme()\n}\n\nthis is nice to have as it avoids the need to get this value in an Activity just to pass it to the theme with CustomTheme(isDark = isDark).\nThis article goes through all of the above providing more details.\n", "It might not be the recommended way, but one option is to use the recreate method (available since API level 11).\nIn order to use it outside of the activity and within your composable, you could pass the function call. Taking your code as a basis\nclass SomeActivity {\n override fun onCreate(savedInstanceState: Bundle?) {\n ...\n setContent {\n ...\n themeViewModel.onRecreate = { recreate() }\n\n CustomTheme(themeViewModel) {\n ...\n }\n }\n }\n}\n\nIn your viewModel\nclass ThemeViewModel: ViewModel() {\n\n lateinit var onRecreate: () -> Unit\n\n private val _theme = MutableLiveData(\"Auto\")\n val theme: LiveData<String> = _theme\n \n fun onThemeChanged(newTheme: String) {\n when (newTheme) {\n \"Auto\" -> _theme.value = \"Light\"\n \"Light\" -> _theme.value = \"Dark\"\n \"Dark\" -> _theme.value = \"Auto\"\n }\n onRecreate\n }\n}\n\n", "I just made it working with a simple model.\nHere is how you do it.\nDeclare a public variable isUiModeDark\nlateinit var isUiModeDark : MutableState<Boolean?>\n\nThen, inside your theme's Lambda:\nisUiModeIsDark = remember { mutableStateOf(userSelectedThemeIsNight(context)) }\nval colorScheme = when (isUiModeIsDark.value) {\n true -> DarkColorScheme\n false -> LightColorScheme\n else -> if (systemTheme) DarkColorScheme else LightColorScheme\n}\n.\n.\n.\nMaterialTheme(\n colorScheme = colorScheme,\n content = content\n)\n\nNow how to call recomposition? Simple, just change the value of isUiModeDark in your settings.\n\ntrue means dark theme app override is selected\nfalse means light theme app override is selected\nnull means No theme app override is selected and system theme is followed.\n\nAs to why this works just read the docs on MutableState and remember. Basically\nany change in MutableStates value causes recomposition. Neither Live data nor any other alternatives work until or unless they are derivates of the type State. The composable is basically just subscribed to the changes made to MutableState or any derivates of the State class.\n" ]
[ 14, 4, 2, 0, 0 ]
[]
[]
[ "android", "android_jetpack", "android_jetpack_compose", "android_theme", "kotlin" ]
stackoverflow_0065192409_android_android_jetpack_android_jetpack_compose_android_theme_kotlin.txt
Q: Video Calling in Expo React Native Application I am building a React Native Application using Expo and I want to integrate a 1:1 video calling functionality in the app. From what I have researched so far on the topic is that I can use SDKs of various libraries like Twilio, Videosdk, VoxImplant etc to implement that feature or I have to use WebRtc in native project alongwith some mechanism to create rooms using socket.io and node and then join users in that room (not completely sure about it but something like this) But both of these solutions require me to make changes in native files which are not present in expo app by default for which I think I have to run expo run:android and then make require changes in files (correct me if I am wrong) Although on web I think its relatively easy to implement video calling using vanilla js or react js. My question is if I implement a webpage that has video calling function and try to open it in webview in my expo react native app will the functionality work on app or not? has someone tried this before. As I was exploring options I came BigBlueButton APIs and another question on Stackoverflow that is using Webview to connect to BigBlueButton APIs. Can I use this logic to implement something in expo app without ejecting or using any sdks? Will it work What would be the best way to implement video calling in my expo app Thanks A: Utilizing Expo, you are essentially using 'React Native for Web', and with the new functionality of Expo config-plugins, almost all packages for React Native with auto-linking can be made to work with your Expo app, or more-or-less can have Config Plugins created for them. For your case, good news for you, you can make it all work on Expo managed workflow, just utilize expo-dev-client and the following library: react-native-webrtc There's an Expo config plugin for this package. So now all you have to do is just utilize the Web-based functionality of WebRTC, such as calling: navigator.mediaDevices.getUserMedia().. navigator.mediaDevices.enumerateDevices().. navigator.* And ensure it works properly on Web. Then, just make a platform hook at your App.js / First loaded module / before having these WebRTC based functionalities calling the aforementioned library's initializer. e.g: import React, { useEffect } from "react"; import { Platform } from "react-native"; import { registerGlobals } from "react-native-webrtc"; ... Platform.OS !== "web" && useEffect(() => { registerGlobals(); }, []); ... One more thing you'd have to do is that for Web, have the <video> element and for native apps, resolve it to <RTCView>, so essentially you could also make a platform specific component/module that resolves to either the web-only <video> tag or the native <RTCView> based on platform, like the example above. Perhaps even have the imports be resolved based on dependencies if you face any errors importing 'registerGlobals' at Web, for example.
Video Calling in Expo React Native Application
I am building a React Native Application using Expo and I want to integrate a 1:1 video calling functionality in the app. From what I have researched so far on the topic is that I can use SDKs of various libraries like Twilio, Videosdk, VoxImplant etc to implement that feature or I have to use WebRtc in native project alongwith some mechanism to create rooms using socket.io and node and then join users in that room (not completely sure about it but something like this) But both of these solutions require me to make changes in native files which are not present in expo app by default for which I think I have to run expo run:android and then make require changes in files (correct me if I am wrong) Although on web I think its relatively easy to implement video calling using vanilla js or react js. My question is if I implement a webpage that has video calling function and try to open it in webview in my expo react native app will the functionality work on app or not? has someone tried this before. As I was exploring options I came BigBlueButton APIs and another question on Stackoverflow that is using Webview to connect to BigBlueButton APIs. Can I use this logic to implement something in expo app without ejecting or using any sdks? Will it work What would be the best way to implement video calling in my expo app Thanks
[ "Utilizing Expo, you are essentially using 'React Native for Web', and with the new functionality of Expo config-plugins, almost all packages for React Native with auto-linking can be made to work with your Expo app, or more-or-less can have Config Plugins created for them.\nFor your case, good news for you, you can make it all work on Expo managed workflow, just utilize expo-dev-client and the following library:\nreact-native-webrtc\nThere's an Expo config plugin for this package. So now all you have to do is just utilize the Web-based functionality of WebRTC, such as calling:\nnavigator.mediaDevices.getUserMedia()..\nnavigator.mediaDevices.enumerateDevices()..\nnavigator.*\n\nAnd ensure it works properly on Web. Then, just make a platform hook at your App.js / First loaded module / before having these WebRTC based functionalities calling the aforementioned library's initializer. e.g:\nimport React, { useEffect } from \"react\";\nimport { Platform } from \"react-native\";\nimport { registerGlobals } from \"react-native-webrtc\";\n\n...\n\nPlatform.OS !== \"web\" && useEffect(() => {\n registerGlobals();\n}, []);\n...\n\nOne more thing you'd have to do is that for Web, have the <video> element and for native apps, resolve it to <RTCView>, so essentially you could also make a platform specific component/module that resolves to either the web-only <video> tag or the native <RTCView> based on platform, like the example above. Perhaps even have the imports be resolved based on dependencies if you face any errors importing 'registerGlobals' at Web, for example.\n" ]
[ 0 ]
[]
[]
[ "expo", "react_native", "react_native_webrtc", "react_native_webview", "videocall" ]
stackoverflow_0074618500_expo_react_native_react_native_webrtc_react_native_webview_videocall.txt
Q: GCC not warning of uninitialized local variable I have some code performing a summation (below). It is called from another file. However, sum was not initialized, caused a bug but GCC (v11.1) did not give a compiler error. I have these flags set: -Wall -Wextra -pedantic -march=native -Werror=return-type -Wswitch-enum -Wconversion -Werror=attributes -Werror=unused-variable -Werror=unused-parameter -Werror=unused-result -Werror=address -Werror=unused-function -Werror=unused-but-set-parameter -Werror=uninitialized -g -O0 Why did I not get an error for this uninitialized local variable/what flag do I need to set? Are there any other useful flags I should set? (I'm aware of switch-enum) Code: #include <unordered_set> #include <concepts> template<typename T> concept arithmetic = std::integral<T> or std::floating_point<T>; template<typename T> requires arithmetic<T> struct Stat { T calculate() { T sum; // Not initialized, caused a bug. Compiler gave no error for(const T& t : m_set) { sum += t; } // Do other calcs return sum; } // Other methods std::unordered_set<T> m_set; }; A: Three things: GCC's uninitialized variable warnings don't work well unless you enable optimizations (-O, -Og, -O2, -O3, -Os, etc). This is documented (see -Wmaybe-uninitialized): "These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables." In general, 100% reliable detection of uninitialized variables is impossible (halting problem). So in some sense, be glad when a compiler does warn you, but you really oughtn't to complain too hard if it doesn't, or if it warns about code that is actually fine. Runtime tools such as valgrind are a good supplement (though still won't always catch everything). The function has to actually be referenced (either used in this source file or visible externally), otherwise the compiler won't actually compile it and in particular won't check for uninitialized variables, not even with optimization enabled. So compiling this source file all by itself will not cause any warnings.
GCC not warning of uninitialized local variable
I have some code performing a summation (below). It is called from another file. However, sum was not initialized, caused a bug but GCC (v11.1) did not give a compiler error. I have these flags set: -Wall -Wextra -pedantic -march=native -Werror=return-type -Wswitch-enum -Wconversion -Werror=attributes -Werror=unused-variable -Werror=unused-parameter -Werror=unused-result -Werror=address -Werror=unused-function -Werror=unused-but-set-parameter -Werror=uninitialized -g -O0 Why did I not get an error for this uninitialized local variable/what flag do I need to set? Are there any other useful flags I should set? (I'm aware of switch-enum) Code: #include <unordered_set> #include <concepts> template<typename T> concept arithmetic = std::integral<T> or std::floating_point<T>; template<typename T> requires arithmetic<T> struct Stat { T calculate() { T sum; // Not initialized, caused a bug. Compiler gave no error for(const T& t : m_set) { sum += t; } // Do other calcs return sum; } // Other methods std::unordered_set<T> m_set; };
[ "Three things:\n\nGCC's uninitialized variable warnings don't work well unless you enable optimizations (-O, -Og, -O2, -O3, -Os, etc). This is documented (see -Wmaybe-uninitialized): \"These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables.\"\n\nIn general, 100% reliable detection of uninitialized variables is impossible (halting problem). So in some sense, be glad when a compiler does warn you, but you really oughtn't to complain too hard if it doesn't, or if it warns about code that is actually fine. Runtime tools such as valgrind are a good supplement (though still won't always catch everything).\n\nThe function has to actually be referenced (either used in this source file or visible externally), otherwise the compiler won't actually compile it and in particular won't check for uninitialized variables, not even with optimization enabled. So compiling this source file all by itself will not cause any warnings.\n\n\n" ]
[ 2 ]
[]
[]
[ "c++", "c++20", "gcc", "gcc_warning" ]
stackoverflow_0074672374_c++_c++20_gcc_gcc_warning.txt
Q: How do I shuffle the characters in a string in JavaScript? In particular, I want to make sure to avoid the mistake made in Microsoft's Browser Choice shuffle code. That is, I want to make sure that each letter has an equal probability of ending up in each possible position. e.g. Given "ABCDEFG", return something like "GEFBDCA". A: I modified an example from the Fisher-Yates Shuffle entry on Wikipedia to shuffle strings: String.prototype.shuffle = function () { var a = this.split(""), n = a.length; for(var i = n - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var tmp = a[i]; a[i] = a[j]; a[j] = tmp; } return a.join(""); } console.log("the quick brown fox jumps over the lazy dog".shuffle()); //-> "veolrm hth ke opynug tusbxq ocrad ofeizwj" console.log("the quick brown fox jumps over the lazy dog".shuffle()); //-> "o dt hutpe u iqrxj yaenbwoolhsvmkcger ozf " More information can be found in Jon Skeet's answer to Is it correct to use JavaScript Array.sort() method for shuffling?. A: If "truly" randomness is important, I recommend against this. See my below edit. I just wanted to add my favorite method for a little variety ;) Given a string: var str = "My bologna has a first name, it's O S C A R."; Shuffle in one line: var shuffled = str.split('').sort(function(){return 0.5-Math.random()}).join(''); Outputs: oa, a si'rSRn f gbomi. aylt AtCnhO ass eM as'oh ngS li Ays.rC nRamsb Oo ait a ,eMtf y alCOSf e gAointsorasmn bR Ms .' ta ih,a EDIT: As @PleaseStand has pointed out, this doesn't meet OP's question at all since it does suffer from "Microsoft's Browser Choice shuffle" code. This isn't a very good randomizer if your string needs to be close to random. It is however, awesome at quickly "jumbling" your strings, where "true" randomness is irrelevant. The article he links below is a great read, but explains a completely different use case, which affects statistical data. I personally can't imagine a practical issue with using this "random" function on a string but as a coder, you're responsible for knowing when not to use this. I've left this here for all the casual randomizers out there. A: Shortest One Liner: const shuffle = str => [...str].sort(()=>Math.random()-.5).join(''); Does not guarantee statistically equal distribution but usable in most cases for me. const shuffle = str => [...str].sort(()=>Math.random()-.5).join(''); document.write(shuffle("The quick brown fox jumps over the lazy dog")); A: Even though this has been answered, I wanted to share the solution I came up with: function shuffleWord (word){ var shuffledWord = ''; word = word.split(''); while (word.length > 0) { shuffledWord += word.splice(word.length * Math.random() << 0, 1); } return shuffledWord; } // 'Batman' => 'aBmnta' You can also try it out (jsfiddle). Snippet is 100k shuffles of 3 character string: var arr={}, cnt=0, loops=100000, ret; do{ ret=shuffle('abc'); arr[ret]=(ret in arr?arr[ret]+1:1); }while(++cnt<loops); for(ret in arr){ document.body.innerHTML+=ret+' '+arr[ret]+' '+(100*arr[ret]/loops).toFixed(1)+'%<br>'; } function shuffle(wd){var t="";for(wd=wd.split("");wd.length>0;)t+=wd.splice(wd.length*Math.random()<<0,1);return t} A: Using Fisher-Yates shuffle algorithm and ES6: // Original string let string = 'ABCDEFG'; // Create a copy of the original string to be randomized ['A', 'B', ... , 'G'] let shuffle = [...string]; // Defining function returning random value from i to N const getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i); // Shuffle a pair of two elements at random position j (Fisher-Yates) shuffle.forEach( (elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]] ); // Transforming array to string shuffle = shuffle.join(''); console.log(shuffle); // 'GBEADFC' A: Single line solution and limited output length... var rnd = "ABCDEF23456789".split('').sort(function(){return 0.5-Math.random()}).join('').substring(0,6); A: String.prototype.shuffle=function(){ var that=this.split(""); var len = that.length,t,i while(len){ i=Math.random()*len-- |0; t=that[len],that[len]=that[i],that[i]=t; } return that.join(""); } A: shuffleString = function(strInput){ var inpArr = strInput.split("");//this will give array of input string var arrRand = []; //this will give shuffled array var arrTempInd = []; // to store shuffled indexes var max = inpArr.length; var min = 0; var tempInd; var i =0 ; do{ tempInd = Math.floor(Math.random() * (max - min));//to generate random index between range if(arrTempInd.indexOf(tempInd)<0){ //to check if index is already available in array to avoid repeatation arrRand[i] = inpArr[tempInd]; // to push character at random index arrTempInd.push(tempInd); //to push random indexes i++; } } while(arrTempInd.length < max){ // to check if random array lenght is equal to input string lenght return arrRand.join("").toString(); // this will return shuffled string } }; Just pass the string to function and in return get the shuffled string A: A different take on scrambling a word. All other answers with enough iterations will return the word unscrambled, mine does not. var scramble = word => { var unique = {}; var newWord = ""; var wordLength = word.length; word = word.toLowerCase(); //Because why would we want to make it easy for them? while(wordLength != newWord.length) { var random = ~~(Math.random() * wordLength); if( unique[random] || random == newWord.length && random != (wordLength - 1) //Don't put the character at the same index it was, nore get stuck in a infinite loop. ) continue; //This is like return but for while loops to start over. unique[random] = true; newWord += word[random]; }; return newWord; }; scramble("God"); //dgo, gdo, ogd A: Yet another Fisher-Yates implementation: const str = 'ABCDEFG', shuffle = str => [...str] .reduceRight((res,_,__,arr) => ( res.push(...arr.splice(0|Math.random()*arr.length,1)), res) ,[]) .join('') console.log(shuffle(str)) .as-console-wrapper{min-height:100%;} A: Just for the sake of completeness even though this may not be exactly what the OP was after as that particular question has already been answered. Here's one that shuffles words. Here's the regex explanation for that: https://regex101.com/r/aFcEtk/1 And it also has some funny outcomes. // Shuffles words // var str = "1 2 3 4 5 6 7 8 9 10"; var str = "the quick brown fox jumps over the lazy dog A.S.A.P. That's right, this happened."; var every_word_im_shuffling = str.split(/\s\b(?!\s)/).sort(function(){return 0.5-Math.random()}).join(' '); console.log(every_word_im_shuffling); A: Rando.js uses a cryptographically secure version of the Fisher-Yates shuffle and is pretty short and readable. console.log(randoSequence("This string will be shuffled.").join("")); <script src="https://randojs.com/2.0.0.js"></script> A: You can't shuffe a string in place but you can use this: String.prototype.shuffle = function() { var len = this.length; var d = len; var s = this.split(""); var array = []; var k, i; for (i = 0; i < d; i++) { k = Math.floor(Math.random() * len); array.push(s[k]); s.splice(k, 1); len = s.length; } for (i = 0; i < d; i++) { this[i] = array[i]; } return array.join(""); } var s = "ABCDE"; s = s.shuffle(); console.log(s); A: If I had a bunch of letters on a table (as in scrabble for example), this is how I would shuffle them. This function mimics that process. I would simply select a letter randomly, one letter at a time, remove it from its current location, and put it in a new location. I didn't see the need to use anything other than a while loop and basic string operations. function stringScrambler(theString) { let scrambledString = ""; while (theString.length > 0) { //pick a random character from the string let characterIndex = Math.floor(Math.random() * (theString.length)); let theCharacter = theString[characterIndex]; //add that character to the new string scrambledString += theCharacter; //remove that character from the original string theString = theString.slice(0, characterIndex) + theString.slice(characterIndex + 1, theString.length); } return scrambledString; } A: You can attach random values to each char and sort by them: console.log("ABCDE".split("") .map(v => [v, Math.random()]).sort((a, b) => a[1] - b[1]).map(v => v[0]) .join("")); /* A - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% B - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% C - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% D - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% E - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% */ Or, like Durstenfeld and Knuth, do the Fisherโ€“Yates: console.log("ABCDE".split("").map((v, i, a) => (r => ([v, a[r]] = [a[r], v], v))(Math.floor(Math.random() * (a.length - i)) + i) ).join("")); // which is equivalent to var array = "ABCDE".split(""); for (var i = 0; i < array.length; i++) { var start = i; var end = array.length - 1; var random = start + Math.floor(Math.random() * (end - start + 1)); var temp = array[random]; array[random] = array[i]; array[i] = temp; } console.log(array.join("")); /* A - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% B - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% C - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% D - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% E - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% */ But never ever go for this, only villains do that: // That's what Microsoft's Browser Choice did console.log("ABCDE".split("").sort(() => Math.random() - 0.5).join("")); /* A - 1st:30.8%, 2nd:30.8%, 3rd:20.5%, 4th:11.7%, 5th: 6.2% B - 1st:30.8%, 2nd:30.8%, 3rd:20.5%, 4th:11.7%, 5th: 6.2% C - 1st:20.5%, 2nd:20.5%, 3rd:26.2%, 4th:20.3%, 5th:12.5% D - 1st:11.7%, 2nd:11.7%, 3rd:20.3%, 4th:31.3%, 5th:25.0% E - 1st: 6.2%, 2nd: 6.2%, 3rd:12.5%, 4th:25.0%, 5th:50.1% */ If someone uses that thing just because it's short then they might use this as well: console.log("EBADC"); // chosen by fair dice roll. // guaranteed to be random. /* A - 1st: 0%, 2nd: 0%, 3rd:100%, 4th: 0%, 5th: 0% B - 1st: 0%, 2nd:100%, 3rd: 0%, 4th: 0%, 5th: 0% C - 1st: 0%, 2nd: 0%, 3rd: 0%, 4th: 0%, 5th:100% D - 1st: 0%, 2nd: 0%, 3rd: 0%, 4th:100%, 5th: 0% E - 1st:100%, 2nd: 0%, 3rd: 0%, 4th: 0%, 5th: 0% */
How do I shuffle the characters in a string in JavaScript?
In particular, I want to make sure to avoid the mistake made in Microsoft's Browser Choice shuffle code. That is, I want to make sure that each letter has an equal probability of ending up in each possible position. e.g. Given "ABCDEFG", return something like "GEFBDCA".
[ "I modified an example from the Fisher-Yates Shuffle entry on Wikipedia to shuffle strings:\nString.prototype.shuffle = function () {\n var a = this.split(\"\"),\n n = a.length;\n\n for(var i = n - 1; i > 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n var tmp = a[i];\n a[i] = a[j];\n a[j] = tmp;\n }\n return a.join(\"\");\n}\nconsole.log(\"the quick brown fox jumps over the lazy dog\".shuffle());\n//-> \"veolrm hth ke opynug tusbxq ocrad ofeizwj\"\n\nconsole.log(\"the quick brown fox jumps over the lazy dog\".shuffle());\n//-> \"o dt hutpe u iqrxj yaenbwoolhsvmkcger ozf \"\n\nMore information can be found in Jon Skeet's answer to Is it correct to use JavaScript Array.sort() method for shuffling?. \n", "If \"truly\" randomness is important, I recommend against this. See my below edit.\nI just wanted to add my favorite method for a little variety ;)\nGiven a string:\nvar str = \"My bologna has a first name, it's O S C A R.\";\n\nShuffle in one line:\nvar shuffled = str.split('').sort(function(){return 0.5-Math.random()}).join('');\n\nOutputs:\noa, a si'rSRn f gbomi. aylt AtCnhO ass eM\nas'oh ngS li Ays.rC nRamsb Oo ait a ,eMtf\ny alCOSf e gAointsorasmn bR Ms .' ta ih,a\n\nEDIT: As @PleaseStand has pointed out, this doesn't meet OP's question at all since it does suffer from \"Microsoft's Browser Choice shuffle\" code. This isn't a very good randomizer if your string needs to be close to random. It is however, awesome at quickly \"jumbling\" your strings, where \"true\" randomness is irrelevant.\nThe article he links below is a great read, but explains a completely different use case, which affects statistical data. I personally can't imagine a practical issue with using this \"random\" function on a string but as a coder, you're responsible for knowing when not to use this.\nI've left this here for all the casual randomizers out there.\n", "Shortest One Liner:\nconst shuffle = str => [...str].sort(()=>Math.random()-.5).join('');\n\nDoes not guarantee statistically equal distribution but usable in most cases for me.\n\n\nconst shuffle = str => [...str].sort(()=>Math.random()-.5).join('');\ndocument.write(shuffle(\"The quick brown fox jumps over the lazy dog\"));\n\n\n\n", "Even though this has been answered, I wanted to share the solution I came up with:\nfunction shuffleWord (word){\n var shuffledWord = '';\n word = word.split('');\n while (word.length > 0) {\n shuffledWord += word.splice(word.length * Math.random() << 0, 1);\n }\n return shuffledWord;\n}\n\n// 'Batman' => 'aBmnta'\n\nYou can also try it out (jsfiddle).\nSnippet is 100k shuffles of 3 character string:\n\n\nvar arr={}, cnt=0, loops=100000, ret;\ndo{\n ret=shuffle('abc');\n arr[ret]=(ret in arr?arr[ret]+1:1);\n}while(++cnt<loops); \n\nfor(ret in arr){\n document.body.innerHTML+=ret+' '+arr[ret]+' '+(100*arr[ret]/loops).toFixed(1)+'%<br>';\n}\n\nfunction shuffle(wd){var t=\"\";for(wd=wd.split(\"\");wd.length>0;)t+=wd.splice(wd.length*Math.random()<<0,1);return t}\n\n\n\n", "Using Fisher-Yates shuffle algorithm and ES6:\n// Original string\nlet string = 'ABCDEFG';\n\n// Create a copy of the original string to be randomized ['A', 'B', ... , 'G']\nlet shuffle = [...string];\n\n// Defining function returning random value from i to N\nconst getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i);\n\n// Shuffle a pair of two elements at random position j (Fisher-Yates)\nshuffle.forEach( (elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]] );\n\n// Transforming array to string\nshuffle = shuffle.join('');\n\nconsole.log(shuffle);\n// 'GBEADFC'\n\n", "Single line solution and limited output length...\nvar rnd = \"ABCDEF23456789\".split('').sort(function(){return 0.5-Math.random()}).join('').substring(0,6);\n\n", "String.prototype.shuffle=function(){\n\n var that=this.split(\"\");\n var len = that.length,t,i\n while(len){\n i=Math.random()*len-- |0;\n t=that[len],that[len]=that[i],that[i]=t;\n }\n return that.join(\"\");\n}\n\n", " shuffleString = function(strInput){\n var inpArr = strInput.split(\"\");//this will give array of input string\n var arrRand = []; //this will give shuffled array\n var arrTempInd = []; // to store shuffled indexes\n var max = inpArr.length;\n var min = 0;\n var tempInd;\n var i =0 ;\n\n do{\n tempInd = Math.floor(Math.random() * (max - min));//to generate random index between range\n if(arrTempInd.indexOf(tempInd)<0){ //to check if index is already available in array to avoid repeatation\n arrRand[i] = inpArr[tempInd]; // to push character at random index\n arrTempInd.push(tempInd); //to push random indexes \n i++;\n }\n }\n while(arrTempInd.length < max){ // to check if random array lenght is equal to input string lenght\n return arrRand.join(\"\").toString(); // this will return shuffled string\n }\n };\n\nJust pass the string to function and in return get the shuffled string\n", "A different take on scrambling a word. All other answers with enough iterations will return the word unscrambled, mine does not.\nvar scramble = word => {\n\n var unique = {};\n var newWord = \"\";\n var wordLength = word.length;\n\n word = word.toLowerCase(); //Because why would we want to make it easy for them?\n\n while(wordLength != newWord.length) {\n\n var random = ~~(Math.random() * wordLength);\n\n if(\n\n unique[random]\n ||\n random == newWord.length && random != (wordLength - 1) //Don't put the character at the same index it was, nore get stuck in a infinite loop.\n\n ) continue; //This is like return but for while loops to start over.\n\n unique[random] = true;\n newWord += word[random];\n\n };\n\n return newWord;\n\n};\n\nscramble(\"God\"); //dgo, gdo, ogd\n\n", "Yet another Fisher-Yates implementation:\n\n\nconst str = 'ABCDEFG',\r\n\r\n shuffle = str => \r\n [...str]\r\n .reduceRight((res,_,__,arr) => (\r\n res.push(...arr.splice(0|Math.random()*arr.length,1)),\r\n res) ,[])\r\n .join('')\r\n\r\nconsole.log(shuffle(str))\n.as-console-wrapper{min-height:100%;}\n\n\n\n", "Just for the sake of completeness even though this may not be exactly what the OP was after as that particular question has already been answered.\nHere's one that shuffles words.\nHere's the regex explanation for that: https://regex101.com/r/aFcEtk/1\nAnd it also has some funny outcomes.\n\n\n// Shuffles words\r\n// var str = \"1 2 3 4 5 6 7 8 9 10\";\r\nvar str = \"the quick brown fox jumps over the lazy dog A.S.A.P. That's right, this happened.\";\r\nvar every_word_im_shuffling = str.split(/\\s\\b(?!\\s)/).sort(function(){return 0.5-Math.random()}).join(' ');\r\nconsole.log(every_word_im_shuffling);\n\n\n\n", "Rando.js uses a cryptographically secure version of the Fisher-Yates shuffle and is pretty short and readable.\n\n\nconsole.log(randoSequence(\"This string will be shuffled.\").join(\"\"));\n<script src=\"https://randojs.com/2.0.0.js\"></script>\n\n\n\n", "You can't shuffe a string in place but you can use this:\n\n\nString.prototype.shuffle = function() {\n var len = this.length;\n var d = len;\n var s = this.split(\"\");\n var array = [];\n var k, i;\n for (i = 0; i < d; i++) {\n k = Math.floor(Math.random() * len);\n array.push(s[k]);\n s.splice(k, 1);\n len = s.length;\n }\n for (i = 0; i < d; i++) {\n this[i] = array[i];\n }\n return array.join(\"\");\n}\n\nvar s = \"ABCDE\";\ns = s.shuffle();\nconsole.log(s);\n\n\n\n", "If I had a bunch of letters on a table (as in scrabble for example), this is how I would shuffle them. This function mimics that process. I would simply select a letter randomly, one letter at a time, remove it from its current location, and put it in a new location.\nI didn't see the need to use anything other than a while loop and basic string operations.\nfunction stringScrambler(theString) {\n let scrambledString = \"\";\n while (theString.length > 0) {\n\n //pick a random character from the string \n let characterIndex = Math.floor(Math.random() * (theString.length));\n let theCharacter = theString[characterIndex];\n\n //add that character to the new string\n scrambledString += theCharacter;\n\n //remove that character from the original string\n theString = theString.slice(0, characterIndex) + theString.slice(characterIndex + 1, theString.length);\n }\n\n return scrambledString;\n}\n\n", "You can attach random values to each char and sort by them:\nconsole.log(\"ABCDE\".split(\"\")\n .map(v => [v, Math.random()]).sort((a, b) => a[1] - b[1]).map(v => v[0])\n.join(\"\"));\n\n/* A - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n B - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n C - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n D - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n E - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% */\n\nOr, like Durstenfeld and Knuth, do the Fisherโ€“Yates:\nconsole.log(\"ABCDE\".split(\"\").map((v, i, a) =>\n (r => ([v, a[r]] = [a[r], v], v))(Math.floor(Math.random() * (a.length - i)) + i)\n).join(\"\"));\n\n// which is equivalent to\n\nvar array = \"ABCDE\".split(\"\");\nfor (var i = 0; i < array.length; i++) {\n var start = i;\n var end = array.length - 1;\n var random = start + Math.floor(Math.random() * (end - start + 1));\n var temp = array[random];\n array[random] = array[i];\n array[i] = temp;\n}\nconsole.log(array.join(\"\"));\n\n/* A - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n B - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n C - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n D - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20%\n E - 1st:20%, 2nd:20%, 3rd:20%, 4th:20%, 5th:20% */\n\nBut never ever go for this, only villains do that:\n// That's what Microsoft's Browser Choice did\nconsole.log(\"ABCDE\".split(\"\").sort(() => Math.random() - 0.5).join(\"\"));\n\n/* A - 1st:30.8%, 2nd:30.8%, 3rd:20.5%, 4th:11.7%, 5th: 6.2%\n B - 1st:30.8%, 2nd:30.8%, 3rd:20.5%, 4th:11.7%, 5th: 6.2%\n C - 1st:20.5%, 2nd:20.5%, 3rd:26.2%, 4th:20.3%, 5th:12.5%\n D - 1st:11.7%, 2nd:11.7%, 3rd:20.3%, 4th:31.3%, 5th:25.0%\n E - 1st: 6.2%, 2nd: 6.2%, 3rd:12.5%, 4th:25.0%, 5th:50.1% */\n\nIf someone uses that thing just because it's short then they might use this as well:\nconsole.log(\"EBADC\"); // chosen by fair dice roll.\n // guaranteed to be random.\n/* A - 1st: 0%, 2nd: 0%, 3rd:100%, 4th: 0%, 5th: 0%\n B - 1st: 0%, 2nd:100%, 3rd: 0%, 4th: 0%, 5th: 0%\n C - 1st: 0%, 2nd: 0%, 3rd: 0%, 4th: 0%, 5th:100%\n D - 1st: 0%, 2nd: 0%, 3rd: 0%, 4th:100%, 5th: 0%\n E - 1st:100%, 2nd: 0%, 3rd: 0%, 4th: 0%, 5th: 0% */\n\n" ]
[ 97, 60, 12, 8, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "String.prototype.shuffle = function(){\n return this.split('').sort(function(a,b){\n return (7 - (Math.random()+'')[5]);\n }).join('');\n};\n\n" ]
[ -1 ]
[ "javascript", "string" ]
stackoverflow_0003943772_javascript_string.txt
Q: Kibana reports a field is conflicting, how can I resolve it? In Kibana I've noticed after I did an Index Pattern refresh that my one field shows up as conflicted. Example: So I understand that this is because Elastic Search found values in that field that are of different types, how can I determine that? It is causing my Visuals to break as they can't work with conflicting fields. How can I get around this problem for the existing data? A: After many hours of playing around and going through the Elastic documentation I have finally found an answer to my problem. In Elastic Search 5.1 (the version I used) you can re-index those specific Indexes that are "problematic". You can find this in Kibana by clicking on Management > Index Patterns and looking for the field that shows up as conflicted. Then click on the corresponding pencil icon to look at the field's details. In there is will show the Indexes under the different field types. I wrote a script in Power-Shell that automated this for me by specifying the "problematic indexes" and then it does the following (let's assume your problematic index is called: log-20170101): Create a mapping for log-20170101-1 Re-index log-20170101 to log-20170101-1 Delete log-20170101 Create a mapping for log-20170101 Re-index log-20170101-1 to log-20170101 Delete log-20170101-1 Now when you Refresh your Index Patter in Kibana you will notice that the field is no longer conflicted. You can read up on: Mappings and Re-Indexing Make sure that when you specify your new mapping below, that you use the appropriate mapping data-types that you are looking for. You can get an existing mapping by querying the Elastic API with: GET /_mapping/<your mapping name> Here is a skeleton (sample) script I did in Power-Shell, it is very basic but I think it can help. $index_list = @( "log-20170101" ) $index_list | % { $index_name = $_ $mapping_body = " { ""mappings"": { ""logevent"": { ""properties"": { ""@timestamp"": { ""type"": ""date"" }, ""correlationId"": { ""type"": ""text"", ""fields"": { ""keyword"": { ""type"": ""keyword"", ""ignore_above"": 256 } } }, ""duration"": { ""properties"": { ""TotalMilliseconds"": { ""type"": ""float"" } } } } } } }" $reindex_body = "{ ""source"": { ""index"": ""$index_name"" }, ""dest"": { ""index"": ""$index_name-1"" } }" $reindex_body_reverse = "{ ""source"": { ""index"": ""$index_name-1"" }, ""dest"": { ""index"": ""$index_name"" } }" Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Put -Body $mapping_body Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Delete Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Put -Body $mapping_body Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body_reverse Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Delete } EDIT See this post for how to setup default mappings going forward to try and prevent this problem from happening again. A: Go to Menu, stack management -> Index patterns, select the index, filter search the field name which is conflicted as shown below(Refer image), click on the warning to view which index is giving error. Go to index management and find the index If you don't worry about the data, delete the index as shown below, else you have to use elastic search API to remap and reindex the wrong data type
Kibana reports a field is conflicting, how can I resolve it?
In Kibana I've noticed after I did an Index Pattern refresh that my one field shows up as conflicted. Example: So I understand that this is because Elastic Search found values in that field that are of different types, how can I determine that? It is causing my Visuals to break as they can't work with conflicting fields. How can I get around this problem for the existing data?
[ "After many hours of playing around and going through the Elastic documentation I have finally found an answer to my problem.\nIn Elastic Search 5.1 (the version I used) you can re-index those specific Indexes that are \"problematic\".\nYou can find this in Kibana by clicking on Management > Index Patterns and looking for the field that shows up as conflicted. Then click on the corresponding pencil icon to look at the field's details. In there is will show the Indexes under the different field types.\nI wrote a script in Power-Shell that automated this for me by specifying the \"problematic indexes\" and then it does the following (let's assume your problematic index is called: log-20170101):\n\nCreate a mapping for log-20170101-1\nRe-index log-20170101 to log-20170101-1\nDelete log-20170101\nCreate a mapping for log-20170101\nRe-index log-20170101-1 to log-20170101\nDelete log-20170101-1\n\nNow when you Refresh your Index Patter in Kibana you will notice that the field is no longer conflicted.\nYou can read up on: Mappings and Re-Indexing\nMake sure that when you specify your new mapping below, that you use the appropriate mapping data-types that you are looking for.\nYou can get an existing mapping by querying the Elastic API with:\nGET /_mapping/<your mapping name>\n\nHere is a skeleton (sample) script I did in Power-Shell, it is very basic but I think it can help.\n$index_list = @( \n \"log-20170101\"\n)\n\n$index_list | % {\n $index_name = $_\n\n $mapping_body = \"\n {\n \"\"mappings\"\": {\n \"\"logevent\"\": {\n \"\"properties\"\": {\n \"\"@timestamp\"\": {\n \"\"type\"\": \"\"date\"\"\n },\n \"\"correlationId\"\": {\n \"\"type\"\": \"\"text\"\",\n \"\"fields\"\": {\n \"\"keyword\"\": {\n \"\"type\"\": \"\"keyword\"\",\n \"\"ignore_above\"\": 256\n }\n }\n },\n \"\"duration\"\": {\n \"\"properties\"\": {\n \"\"TotalMilliseconds\"\": {\n \"\"type\"\": \"\"float\"\"\n }\n }\n }\n }\n }\n }\n }\"\n\n $reindex_body = \"{\n \"\"source\"\": {\n \"\"index\"\": \"\"$index_name\"\"\n },\n \"\"dest\"\": {\n \"\"index\"\": \"\"$index_name-1\"\"\n }\n }\"\n\n $reindex_body_reverse = \"{\n \"\"source\"\": {\n \"\"index\"\": \"\"$index_name-1\"\"\n },\n \"\"dest\"\": {\n \"\"index\"\": \"\"$index_name\"\"\n }\n }\"\n\n Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Put -Body $mapping_body\n Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body\n Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Delete\n Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Put -Body $mapping_body\n Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body_reverse\n Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Delete\n}\n\nEDIT\nSee this post for how to setup default mappings going forward to try and prevent this problem from happening again.\n", "Go to Menu, stack management -> Index patterns, select the index, filter search the field name which is conflicted as shown below(Refer image), click on the warning to view which index is giving error. Go to index management and find the index\nIf you don't worry about the data, delete the index as shown below, else you have to use elastic search API to remap and reindex the wrong data type\n\n\n" ]
[ 7, 0 ]
[]
[]
[ "elasticsearch", "kibana" ]
stackoverflow_0047345816_elasticsearch_kibana.txt
Q: Google Pay Button for Android CSS for hybrid apps I have a CapacitorJS hybrid application which integrates Google Pay. We were using the web Google Pay button seen here: https://developers.google.com/pay/api/web/guides/brand-guidelines#style but the one that says "Pay with Google Pay" However, during our approval process for our Android app, the approver rejected the application because it doesn't use the correct button variant found here: https://developers.google.com/pay/api/android/guides/brand-guidelines#style Note the more rounded corners on the Android version. Unfortunately, there doesn't seem to be any easy way to convert this into CSS since the Android assets only give the SVG Google Pay mark and other Android specific xml assets. Are there any existing resources out there to create the Android google pay button in CSS or does it have to be "eyeballed"? A: A simple solution i would provide is, the brand says for such asssets use google pay mark, the mark is provided by the brand which should only be used. Link to full details: https://developers.google.com/pay/api/web/guides/brand-guidelines Link to download the assets: https://developers.google.com/static/pay/api/download-assets/Google-Pay-Acceptance.zip Info by brand: Display "Google Pay" in text next to the mark if you do so for other brands. Don't change the color or weight of the mark's outline, or alter the mark in any way. Use only the mark provided by Google. Do Use only the Google Pay mark provided by Google. Use the Google Pay mark to indicate Google Pay as a payment option in payment flows. Don't Don't create your own mark or alter it in any way. Don't translate the word โ€œPay.โ€ Don't display the Google Pay mark in a different or smaller size than the other payment options.
Google Pay Button for Android CSS for hybrid apps
I have a CapacitorJS hybrid application which integrates Google Pay. We were using the web Google Pay button seen here: https://developers.google.com/pay/api/web/guides/brand-guidelines#style but the one that says "Pay with Google Pay" However, during our approval process for our Android app, the approver rejected the application because it doesn't use the correct button variant found here: https://developers.google.com/pay/api/android/guides/brand-guidelines#style Note the more rounded corners on the Android version. Unfortunately, there doesn't seem to be any easy way to convert this into CSS since the Android assets only give the SVG Google Pay mark and other Android specific xml assets. Are there any existing resources out there to create the Android google pay button in CSS or does it have to be "eyeballed"?
[ "A simple solution i would provide is, the brand says for such asssets use google pay mark, the mark is provided by the brand which should only be used.\nLink to full details:\nhttps://developers.google.com/pay/api/web/guides/brand-guidelines\nLink to download the assets:\nhttps://developers.google.com/static/pay/api/download-assets/Google-Pay-Acceptance.zip\nInfo by brand:\nDisplay \"Google Pay\" in text next to the mark if you do so for other brands. Don't change the color or weight of the mark's outline, or alter the mark in any way. Use only the mark provided by Google.\nDo\nUse only the Google Pay mark provided by Google.\nUse the Google Pay mark to indicate Google Pay as a payment option in payment flows.\nDon't\nDon't create your own mark or alter it in any way.\nDon't translate the word โ€œPay.โ€\nDon't display the Google Pay mark in a different or smaller size than the other payment options.\n" ]
[ 0 ]
[]
[]
[ "android", "capacitor", "css", "google_pay" ]
stackoverflow_0073226677_android_capacitor_css_google_pay.txt
Q: Cant install a library from pod in IOS which internally uses rust I am trying to install libsignal-client through the pod. It uses a rust encryption library internally. Error is given compiling libsignal-ffi: Compiling libsignal-ffi v0.9.4 (/Users/tanmoy/Library/Caches/CocoaPods/Pods/External/SignalClient/94c18a0d31671033b99c08bafb98f6e4/rust/bridge/ffi) Finished release [optimized + debuginfo] target(s) in 2m 38s warning: Building using xargo to support tier 3 target aarch64-apple-ios-sim. error: `rust-src` component not found. Run `rustup component add rust-src`. note: run with `RUST_BACKTRACE=1` for a backtrace Based on the source repository, https://github.com/signalapp/libsignal-client/blob/master/rust-toolchain I used the exact same rust-src export XARGO_RUST_SRC=/Users/tanmoy/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library This time another error building std. Compiling std v0.0.0 (/Users/tanmoy/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/std) error[E0557]: feature has been removed --> /Users/tanmoy/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/lib.rs:102:37 ..... error: aborting due to 325 previous errors; 7 warnings emitted Some errors have detailed explanations: E0277, E0307, E0522, E0557, E0658. For more information about an error, try `rustc --explain E0277`. error: could not compile `core` Been trying different solutions but none seems to work. Any insight? A: Based on this issue, the two alternative solution was Running rustup +nightly-2021-06-08 component add rust-src All five architectures supported aarch64-apple-io x86_64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios-macabi aarch64-apple-ios-macabi Proceed with default installation guide Comment out tier3 architecture here SignalClient.podspec Two architectures supported aarch64-apple-io x86_64-apple-ios A: Add Rush in iOS Mobile App project for Xcode Follow simple Steps Run these Command one by one curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustup update rustup toolchain install nightly rustup default nightly rustup target add aarch64-apple-ios Upwote and like :)
Cant install a library from pod in IOS which internally uses rust
I am trying to install libsignal-client through the pod. It uses a rust encryption library internally. Error is given compiling libsignal-ffi: Compiling libsignal-ffi v0.9.4 (/Users/tanmoy/Library/Caches/CocoaPods/Pods/External/SignalClient/94c18a0d31671033b99c08bafb98f6e4/rust/bridge/ffi) Finished release [optimized + debuginfo] target(s) in 2m 38s warning: Building using xargo to support tier 3 target aarch64-apple-ios-sim. error: `rust-src` component not found. Run `rustup component add rust-src`. note: run with `RUST_BACKTRACE=1` for a backtrace Based on the source repository, https://github.com/signalapp/libsignal-client/blob/master/rust-toolchain I used the exact same rust-src export XARGO_RUST_SRC=/Users/tanmoy/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library This time another error building std. Compiling std v0.0.0 (/Users/tanmoy/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/std) error[E0557]: feature has been removed --> /Users/tanmoy/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/lib.rs:102:37 ..... error: aborting due to 325 previous errors; 7 warnings emitted Some errors have detailed explanations: E0277, E0307, E0522, E0557, E0658. For more information about an error, try `rustc --explain E0277`. error: could not compile `core` Been trying different solutions but none seems to work. Any insight?
[ "Based on this issue, the two alternative solution was\n\nRunning rustup +nightly-2021-06-08 component add rust-src\n\nAll five architectures supported\n\naarch64-apple-io\nx86_64-apple-ios\naarch64-apple-ios-sim\nx86_64-apple-ios-macabi\naarch64-apple-ios-macabi\n\n\n\n\nProceed with default installation guide\n\nComment out tier3 architecture here SignalClient.podspec\nTwo architectures supported\n\naarch64-apple-io\nx86_64-apple-ios\n\n\n\n\n\n", "Add Rush in iOS Mobile App project for Xcode\nFollow simple Steps\nRun these Command one by one\n curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\n\n rustup update\n rustup toolchain install nightly\n rustup default nightly\n\n rustup target add aarch64-apple-ios\n\nUpwote and like :)\n" ]
[ 0, 0 ]
[]
[]
[ "cocoapods", "swift" ]
stackoverflow_0069224267_cocoapods_swift.txt
Q: Python Pandas - KeyError: 'username' : when username exist its showing key error when I am Trying to slice users data from csv who logged in I am a beginner in python and working with python pandas. I have created a program a demo of payment gateway system . It contains a login page and signup page . I want to display the main page when valid user logs in after that I want to extract the data of the only valid user in the form of Data Frame for a Function To display their profile Containing ( Name ,Email, Phone no.) but facing this error. This Function Executes after the login of valid user def Home(): print(1," : Profile") print(2," : Top-up") print(3," : Account Balance") print(4," : About us") print(5," : Back") print("") pref=int(input("Enter your Choice : ")) print("") if pref==1: p_csv=pd.read_csv('Data.csv') a=p_csv.loc["username"]==["user"] print(a) Output : KeyError: 'username' The Csv File Contains Certain Data and I want to extract the user logged in the system (Only a Single row of csv containing the user data) CSV File : username,password,Name,email,Phone Ramesh,Ramesh123,Ramesh Chaurasiya,[email protected],1234567890 pooja0,Pja125,Pooja Sharma,[email protected],7894561230 I was expecting it to display the Data frame containing users (name , email, phone) I also Faced multiple errors While changing this code like length not match (2,1) (1,) ... df empty[] only showing column names: username, password , name , email , phone index[] keyError: 'username' Below here is the whole code of the program ...... import pandas as pd #functions(): All Functions are here represented ...... #==================================================================================================== def Return(): return Main_Menu() #================================================================================================================= def Main_Menu(): print("") print("-------------------------------------------------------------") print(" ........... Main Menu ........... ") print("-------------------------------------------------------------") print("") print(1,": New user") print(2,": Log-In") print(3,": Exit") print("") inp=int(input("===> Enter your Choice: ")) if inp==1: Sign_Up() if inp==2: login() if inp==3: print("Thanks for visiting...") #======================================================================================== def Main_page(): while True: print("") print("--------------------------------------------------------------------") print(" .........Welcome To /\/[(O)......... ") print("--------------------------------------------------------------------") print("") print(1,": Home") print(2,": Transaction") print(3,": Account Statement") print(4,": Exit") print("") choice=int(input("Enter your preference from above options: ")) print("") if choice==1: print("") print("-------------------------------------------------------------------") print(" ............. Home ............ ") print("-------------------------------------------------------------------") print("") Home() if choice==2: Transaction() if choice==3: Statement() if choice==4: print("Returning Back...") break #==================================================================================================== #profile #top-up #acc_balance #about us def Home(): print(1," : Profile") print(2," : Top-up") print(3," : Account Balance") print(4," : About us") print(5," : Back") print("") pref=int(input("Enter your Choice : ")) print("") if pref==1: p_csv=pd.read_csv('Data.csv') user_= "match_uname" a=p_csv.query("username == @user_") print(a) # ======> This is the place where i am facing Errors if pref==2: print("Top up") if pref==3: print("Balance") if pref==4: print("About us") if pref==5: Main_page() #=================================================================================== def Transaction(): while True: print("") else: Main_page() #==================================================================================== def Statement(): print("stateee") #==================================================================================== def Sign_Up(): _name=input("Enter your Full-Name: " ) E_mail=input("Enter your E-mail: " ) print("") print("Warning: Enter the username and password of 8 alphanumeric Digits (**) ---->") print("") n_user=input("Create Username: ") n_passwd=input("Create Password: ") mobile=int(input("Enter your mobile no.: ")) user_data={"username":[n_user],"password":[n_passwd],"Name":[_name],"email":[E_mail],"Phone":[mobile]} user_cred=pd.DataFrame(user_data) user_cred.to_csv('Data.csv',mode='a',index=True,header=0) print("") print("======Account Successfully Created======") Return() #=================================================================================================== def login(): log_cred=pd.read_csv('Data.csv') # Reading csv File.. print("") print("======= LOGIN ============") print("") user=input('username: ') passwd=input('password: ') # input data taken from user... match_uname=log_cred.loc[log_cred["username"]==user] # comparing the data given by user == True or False/... #================================================================================================ # ......All Function Execution Window........ #========================================================================================================== #login Execution.... if match_uname.empty: print("") print("Oops! Invalid Username `\(*_*)") print("") return False else: match_pass=log_cred.loc[log_cred["password"]==passwd] if match_pass.empty: print("") print("Invalid Password \(@_@)..Oops!") print("") return False else: print("") print("Valid username and password...<(~_~)>...Welcome") print("") Main_page() return True #================================================================================================== #Main menu execution .... print("") print("") a=input("Press Enter ...") if a=="": Main_Menu() else: print("Get lost") A: user = "Ramesh" a = p_csv.query("username == @user") print(a) username password Name email Phone 0 Ramesh Ramesh123 Ramesh Chaurasiya [email protected] 1234567890
Python Pandas - KeyError: 'username' : when username exist its showing key error when I am Trying to slice users data from csv who logged in
I am a beginner in python and working with python pandas. I have created a program a demo of payment gateway system . It contains a login page and signup page . I want to display the main page when valid user logs in after that I want to extract the data of the only valid user in the form of Data Frame for a Function To display their profile Containing ( Name ,Email, Phone no.) but facing this error. This Function Executes after the login of valid user def Home(): print(1," : Profile") print(2," : Top-up") print(3," : Account Balance") print(4," : About us") print(5," : Back") print("") pref=int(input("Enter your Choice : ")) print("") if pref==1: p_csv=pd.read_csv('Data.csv') a=p_csv.loc["username"]==["user"] print(a) Output : KeyError: 'username' The Csv File Contains Certain Data and I want to extract the user logged in the system (Only a Single row of csv containing the user data) CSV File : username,password,Name,email,Phone Ramesh,Ramesh123,Ramesh Chaurasiya,[email protected],1234567890 pooja0,Pja125,Pooja Sharma,[email protected],7894561230 I was expecting it to display the Data frame containing users (name , email, phone) I also Faced multiple errors While changing this code like length not match (2,1) (1,) ... df empty[] only showing column names: username, password , name , email , phone index[] keyError: 'username' Below here is the whole code of the program ...... import pandas as pd #functions(): All Functions are here represented ...... #==================================================================================================== def Return(): return Main_Menu() #================================================================================================================= def Main_Menu(): print("") print("-------------------------------------------------------------") print(" ........... Main Menu ........... ") print("-------------------------------------------------------------") print("") print(1,": New user") print(2,": Log-In") print(3,": Exit") print("") inp=int(input("===> Enter your Choice: ")) if inp==1: Sign_Up() if inp==2: login() if inp==3: print("Thanks for visiting...") #======================================================================================== def Main_page(): while True: print("") print("--------------------------------------------------------------------") print(" .........Welcome To /\/[(O)......... ") print("--------------------------------------------------------------------") print("") print(1,": Home") print(2,": Transaction") print(3,": Account Statement") print(4,": Exit") print("") choice=int(input("Enter your preference from above options: ")) print("") if choice==1: print("") print("-------------------------------------------------------------------") print(" ............. Home ............ ") print("-------------------------------------------------------------------") print("") Home() if choice==2: Transaction() if choice==3: Statement() if choice==4: print("Returning Back...") break #==================================================================================================== #profile #top-up #acc_balance #about us def Home(): print(1," : Profile") print(2," : Top-up") print(3," : Account Balance") print(4," : About us") print(5," : Back") print("") pref=int(input("Enter your Choice : ")) print("") if pref==1: p_csv=pd.read_csv('Data.csv') user_= "match_uname" a=p_csv.query("username == @user_") print(a) # ======> This is the place where i am facing Errors if pref==2: print("Top up") if pref==3: print("Balance") if pref==4: print("About us") if pref==5: Main_page() #=================================================================================== def Transaction(): while True: print("") else: Main_page() #==================================================================================== def Statement(): print("stateee") #==================================================================================== def Sign_Up(): _name=input("Enter your Full-Name: " ) E_mail=input("Enter your E-mail: " ) print("") print("Warning: Enter the username and password of 8 alphanumeric Digits (**) ---->") print("") n_user=input("Create Username: ") n_passwd=input("Create Password: ") mobile=int(input("Enter your mobile no.: ")) user_data={"username":[n_user],"password":[n_passwd],"Name":[_name],"email":[E_mail],"Phone":[mobile]} user_cred=pd.DataFrame(user_data) user_cred.to_csv('Data.csv',mode='a',index=True,header=0) print("") print("======Account Successfully Created======") Return() #=================================================================================================== def login(): log_cred=pd.read_csv('Data.csv') # Reading csv File.. print("") print("======= LOGIN ============") print("") user=input('username: ') passwd=input('password: ') # input data taken from user... match_uname=log_cred.loc[log_cred["username"]==user] # comparing the data given by user == True or False/... #================================================================================================ # ......All Function Execution Window........ #========================================================================================================== #login Execution.... if match_uname.empty: print("") print("Oops! Invalid Username `\(*_*)") print("") return False else: match_pass=log_cred.loc[log_cred["password"]==passwd] if match_pass.empty: print("") print("Invalid Password \(@_@)..Oops!") print("") return False else: print("") print("Valid username and password...<(~_~)>...Welcome") print("") Main_page() return True #================================================================================================== #Main menu execution .... print("") print("") a=input("Press Enter ...") if a=="": Main_Menu() else: print("Get lost")
[ "user = \"Ramesh\"\na = p_csv.query(\"username == @user\")\nprint(a)\n\n username password Name email Phone\n0 Ramesh Ramesh123 Ramesh Chaurasiya [email protected] 1234567890\n\n" ]
[ 0 ]
[]
[]
[ "csv", "keyerror", "pandas", "python", "slice" ]
stackoverflow_0074672980_csv_keyerror_pandas_python_slice.txt
Q: Python Trouble Parsing a .max translated to OLE File => output unreadable in text format The following script outputs files unreadable in .txt format. Please advise. I inspired myself with: https://area.autodesk.com/m/drew.avis/tutorials/writing-and-reading-3ds-max-scene-sidecar-data-in-python This is to replicate a macho shark into a mechanical robot. import olefile # set this to your file f = r'C:\MRP\Shortfin_Mako_Shark_Rigged_scanline.max' def cleanString(data,isArray=False): # remove first 6 bytes + last byte data = data[6:] if isArray: data = data[:-1] return data with olefile.OleFileIO(f) as ole: ole.listdir() print(ole.listdir()) i = 0 for entry in ole.listdir(): i = i + 1 print(entry) if i > 2: fin = ole.openstream(entry) # myString = fin.read().decode("utf-16") # myString = cleanString(myString, isArray=True) fout = open(entry[0], "wb") print(fout) while True: s = fin.read(8192) if not s: break fout.write(s) Please advise. https://www.turbosquid.com/fr/3d-models/max-shortfin-mako-shark-rigged/991102# I also tried this: with olefile.OleFileIO(f) as ole: ole.listdir() print(ole.listdir()) i = 0 for entry in ole.listdir(): i = i + 1 print(entry) if i > 2: fin = ole.openstream(entry) #myString = fin.read().decode("utf-16") #myString = cleanString(myString, isArray=True) fout = open(entry[0], "w") print(fout) while True: s = fin.read(8192) if not s: break fout.write(cleanString(s, isArray = True).decode("utf-8")) # stream = ole.openstream('CustomFileStreamDataStorage/MyString') # myString = stream.read().decode('utf-16') # myString = cleanString(myString) # stream = ole.openstream('CustomFileStreamDataStorage/MyGeometry') # myGeometry = stream.read().decode('utf-16') # myGeometry = cleanString(myGeometry, isArray=True) # myGeometry = myGeometry.split('\x00') # stream = ole.openstream('CustomFileStreamDataStorage/MyLayers') # myLayers = stream.read().decode('utf-16') # myLayers = cleanString(myLayers, isArray=True) # myLayers = myLayers.split('\x00') # print ("My String: {}\nMy Geometry: {}\nMy Layers: {}".format (myString, myGeometry, myLayers)) What is the right encoding to decode from? Exception has occurred: UnicodeDecodeError 'utf-8' codec can't decode bytes in position 4-5: invalid continuation byte File "C:\MRP\ALG_LIN.py", line 59, in fout.write(cleanString(s, isArray = True).decode("utf-8")) Exception has occurred: UnicodeEncodeError 'charmap' codec can't encode characters in position 2-5: character maps to File "C:\MRP\ALG_LIN.py", line 59, in fout.write(cleanString(s, isArray = True).decode("utf-16")) KR, Ludo A: Try opening in binary mode instead of text mode
Python Trouble Parsing a .max translated to OLE File => output unreadable in text format
The following script outputs files unreadable in .txt format. Please advise. I inspired myself with: https://area.autodesk.com/m/drew.avis/tutorials/writing-and-reading-3ds-max-scene-sidecar-data-in-python This is to replicate a macho shark into a mechanical robot. import olefile # set this to your file f = r'C:\MRP\Shortfin_Mako_Shark_Rigged_scanline.max' def cleanString(data,isArray=False): # remove first 6 bytes + last byte data = data[6:] if isArray: data = data[:-1] return data with olefile.OleFileIO(f) as ole: ole.listdir() print(ole.listdir()) i = 0 for entry in ole.listdir(): i = i + 1 print(entry) if i > 2: fin = ole.openstream(entry) # myString = fin.read().decode("utf-16") # myString = cleanString(myString, isArray=True) fout = open(entry[0], "wb") print(fout) while True: s = fin.read(8192) if not s: break fout.write(s) Please advise. https://www.turbosquid.com/fr/3d-models/max-shortfin-mako-shark-rigged/991102# I also tried this: with olefile.OleFileIO(f) as ole: ole.listdir() print(ole.listdir()) i = 0 for entry in ole.listdir(): i = i + 1 print(entry) if i > 2: fin = ole.openstream(entry) #myString = fin.read().decode("utf-16") #myString = cleanString(myString, isArray=True) fout = open(entry[0], "w") print(fout) while True: s = fin.read(8192) if not s: break fout.write(cleanString(s, isArray = True).decode("utf-8")) # stream = ole.openstream('CustomFileStreamDataStorage/MyString') # myString = stream.read().decode('utf-16') # myString = cleanString(myString) # stream = ole.openstream('CustomFileStreamDataStorage/MyGeometry') # myGeometry = stream.read().decode('utf-16') # myGeometry = cleanString(myGeometry, isArray=True) # myGeometry = myGeometry.split('\x00') # stream = ole.openstream('CustomFileStreamDataStorage/MyLayers') # myLayers = stream.read().decode('utf-16') # myLayers = cleanString(myLayers, isArray=True) # myLayers = myLayers.split('\x00') # print ("My String: {}\nMy Geometry: {}\nMy Layers: {}".format (myString, myGeometry, myLayers)) What is the right encoding to decode from? Exception has occurred: UnicodeDecodeError 'utf-8' codec can't decode bytes in position 4-5: invalid continuation byte File "C:\MRP\ALG_LIN.py", line 59, in fout.write(cleanString(s, isArray = True).decode("utf-8")) Exception has occurred: UnicodeEncodeError 'charmap' codec can't encode characters in position 2-5: character maps to File "C:\MRP\ALG_LIN.py", line 59, in fout.write(cleanString(s, isArray = True).decode("utf-16")) KR, Ludo
[ "Try opening in binary mode instead of text mode\n" ]
[ 0 ]
[]
[]
[ "3dsmax", "python" ]
stackoverflow_0074673023_3dsmax_python.txt
Q: How do I call my dialog before multiple async/await starts and close after those calls are completed? I want call my dialog box before the sequence of multiple async/await calls. This is my code: document.getElementById("dialog").showModal(); if(condition 1 is true){ if(condition 2 is true){ (async()=>{ await f1(); })(); } } if(condition 3 is true){ if(condition 4 is true){ (async()=>{ await f2(); })(); } } if(condition 5 is true){ if(condition 6 is true){ (async()=>{ await f3(); })(); } } document.getElementById("dialog").close(); Upon executing the code, the dialog opens and closes instantly before the async/await calls even complete. How do I close the dialog only when all the server calls are completed? A: The only code that will wait for the promise to resolve is other code in the same async function, after the await. Code outside the async function will not wait. So your tiny async functions do next to nothing, because there is no code after their awaits. You need to write this code as one large async function. const someFunction = async () => { document.getElementById("dialog").showModal(); if(condition 1 is true){ if(condition 2 is true){ await f1(); } } if(condition 3 is true){ if(condition 4 is true){ await f2(); } } if(condition 5 is true){ if(condition 6 is true){ await f3(); } } document.getElementById("dialog").close(); }
How do I call my dialog before multiple async/await starts and close after those calls are completed?
I want call my dialog box before the sequence of multiple async/await calls. This is my code: document.getElementById("dialog").showModal(); if(condition 1 is true){ if(condition 2 is true){ (async()=>{ await f1(); })(); } } if(condition 3 is true){ if(condition 4 is true){ (async()=>{ await f2(); })(); } } if(condition 5 is true){ if(condition 6 is true){ (async()=>{ await f3(); })(); } } document.getElementById("dialog").close(); Upon executing the code, the dialog opens and closes instantly before the async/await calls even complete. How do I close the dialog only when all the server calls are completed?
[ "The only code that will wait for the promise to resolve is other code in the same async function, after the await. Code outside the async function will not wait. So your tiny async functions do next to nothing, because there is no code after their awaits.\nYou need to write this code as one large async function.\nconst someFunction = async () => {\n document.getElementById(\"dialog\").showModal();\n\n if(condition 1 is true){\n if(condition 2 is true){\n await f1();\n }\n }\n\n if(condition 3 is true){\n if(condition 4 is true){\n await f2();\n }\n }\n\n if(condition 5 is true){\n if(condition 6 is true){\n await f3();\n }\n }\n\n document.getElementById(\"dialog\").close();\n}\n\n" ]
[ 1 ]
[]
[]
[ "async_await", "javascript" ]
stackoverflow_0074673058_async_await_javascript.txt
Q: Number of vtable that will be created Here if I leave class B as empty then total how many vtables will be created here ? #include <bits/stdc++.h> using namespace std; class A{ public: virtual void display(){ cout<<"A Class"<<endl; } }; class B: public A{ public: }; int main() { A *ob = new B(); ob->display();//A Class return 0; } I was assuming still 2 vtable will be created one in A and 1 in B but for Class B it will be empty and as per design of c++ if we call display function then if it doesn't find the function in its vtable then it will look for the vtable in parent class and will set the binding of that function with vptr but, I am not sure of that. Can anybody explain with the exact concept I tired finding the answer over the internet but, didn't get the desired answer A: Practically B needs some run time type information, which is typically stored as part of the "vtable" , that is distinct from A. This is because: bool test(A* a) { return dynamic_cast<B*>(a); } has to behave differently if we pass a pointer-to-B or a pointer-to-A. A "typical" way to implement vtables in C++ looks like this: using vfunc = void(*)(void*); template<auto creator> static auto const* get_vtable() { static const auto table = creator(); return &table; } struct A_vtable { void const* rtti; void(*display)(void*); }; A_vtable create_A_vtable_A() { return { "This is class A!", [](void* self) { std::cout<<"A Class"<<std::endl; } }; } struct A { A_vtable const* vtable; A():vtable(get_vtable<&create_A_vtable_A>()) {} }; struct B_vtable:A_vtable { }; B_vtable create_B_vtable_B() { B_vtable vtable = create_A_vtable_A; vtable.rtti = "This is class B!"; } struct B:A { B() { vtable = get_vtable<&create_B_vtable_B>(); } }; with the note that my runtime type information is intentionally a joke. That RTTI information in a real situation will tell you how what the runtime type is, and how to get a pointer to the most-derived type. Here I just store a void pointer to a string. But you'll notice I moved the vtable pointer to a different table in the constructor of B. This is basically how compilers do it (the standard gives compilers lots of freedom, so you cannot assume it looks anything at all like the above, it might not even have a vtable).
Number of vtable that will be created
Here if I leave class B as empty then total how many vtables will be created here ? #include <bits/stdc++.h> using namespace std; class A{ public: virtual void display(){ cout<<"A Class"<<endl; } }; class B: public A{ public: }; int main() { A *ob = new B(); ob->display();//A Class return 0; } I was assuming still 2 vtable will be created one in A and 1 in B but for Class B it will be empty and as per design of c++ if we call display function then if it doesn't find the function in its vtable then it will look for the vtable in parent class and will set the binding of that function with vptr but, I am not sure of that. Can anybody explain with the exact concept I tired finding the answer over the internet but, didn't get the desired answer
[ "Practically B needs some run time type information, which is typically stored as part of the \"vtable\" , that is distinct from A.\nThis is because:\nbool test(A* a) {\n return dynamic_cast<B*>(a);\n}\n\nhas to behave differently if we pass a pointer-to-B or a pointer-to-A.\nA \"typical\" way to implement vtables in C++ looks like this:\nusing vfunc = void(*)(void*);\ntemplate<auto creator>\nstatic auto const* get_vtable() {\n static const auto table = creator();\n return &table;\n}\nstruct A_vtable {\n void const* rtti;\n void(*display)(void*);\n};\nA_vtable create_A_vtable_A() {\n return {\n \"This is class A!\",\n [](void* self) {\n std::cout<<\"A Class\"<<std::endl;\n }\n };\n}\nstruct A {\n A_vtable const* vtable;\n A():vtable(get_vtable<&create_A_vtable_A>()) {}\n};\nstruct B_vtable:A_vtable {\n};\nB_vtable create_B_vtable_B() {\n B_vtable vtable = create_A_vtable_A;\n vtable.rtti = \"This is class B!\";\n}\nstruct B:A {\n B() {\n vtable = get_vtable<&create_B_vtable_B>();\n }\n};\n\nwith the note that my runtime type information is intentionally a joke.\nThat RTTI information in a real situation will tell you how what the runtime type is, and how to get a pointer to the most-derived type. Here I just store a void pointer to a string.\nBut you'll notice I moved the vtable pointer to a different table in the constructor of B. This is basically how compilers do it (the standard gives compilers lots of freedom, so you cannot assume it looks anything at all like the above, it might not even have a vtable).\n" ]
[ 1 ]
[]
[]
[ "c++", "c++11" ]
stackoverflow_0074670436_c++_c++11.txt
Q: useEffect doesn't work when switching screens Hi I am still new to react-native and has been trying to create an app. My stuck is that I don't know why useEffect doesn't work when switching screens by react-navigation-bottom-tab. Below is my HomeScreen.js where I wrot useEffect to fetch all data from Firestore. As you can see I wrote two useEffects because I thought it'd work. The first one was thought to fetch data when I switch to Home from like ProfileScreen. import { View, FlatList, StyleSheet, } from "react-native"; import { RideCard } from "./RideCard"; import { OneTouchFilter } from "./OneTouchFilter"; import { useFirestoreContext } from "../../contexts/FirestoreContext"; import { useEffect } from "react"; export const HomeScreen = ({ navigation }) => { console.log("HomeScreen.js useEffect"); const { selectedBoardType, cityFromText, cityToText, fetchRides, rides } = useFirestoreContext(); useEffect(() => { fetchRides(); }, []); useEffect(() => { fetchRides(); }, [selectedBoardType, cityFromText, cityToText]); return ( <View style={styles.inner}> <OneTouchFilter /> <FlatList data={rides} renderItem={(itemData) => ( <RideCard ride={itemData.item} index={itemData.index} id={itemData.item.id} numOfRides={rides.length} /> )} /> </View> ); }; App.js this is a file where react-navigation-bottom-tab placed in. import React, { useContext } from "react"; import { StyleSheet } from "react-native"; import { NavigationContainer, DefaultTheme } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; import { HomeScreen } from "./screens/Home/HomeScreen"; import { PostScreen } from "./screens/Post/PostScreen"; import { ProfileScreen } from "./screens/Profile/ProfileScreen"; import Ionicons from "react-native-vector-icons/Ionicons"; import { NativeBaseProvider } from "native-base"; // create another file for contexts Provider import { AuthContextProvider } from "./contexts/AuthContext"; import { FirestoreContextProvider } from "./contexts/FirestoreContext"; import { FormContextProvider } from "./contexts/FormContext"; const MyTheme = { ...DefaultTheme, colors: { ...DefaultTheme.colors, background: "white", }, }; export default function App() { const Stack = createStackNavigator(); // ใ‚ฟใƒ–็งปๅ‹•ใฎ่จญๅฎšใ‚’ๆ–ฐ่ฆ่ฟฝๅŠ  // createBottomTabNavigator ... ใ‚ฟใƒ–็งปๅ‹•ใ‚’่จญๅฎšใ™ใ‚‹้–ขๆ•ฐ const Tab = createBottomTabNavigator(); // ๆ–ฐ่ฆ่ฟฝๅŠ  // - ็งปๅ‹•ใ‚’้–ขๆ•ฐใซๆŒใŸใ›ใฆใ€ใ‚ฟใƒ–็งปๅ‹•ใฎ่จญๅฎšใงๅˆฉ็”จ // - ๆ„ๅ›ณ ... ใ‚ฟใƒ–็งปๅ‹•ใฎ็ฎ‡ๆ‰€ใฎใ‚ณใƒผใƒ‰ใŒ่ชญใฟใซใใใชใ‚‹ใŸใ‚ const Home = () => { return ( <Stack.Navigator> <Stack.Screen options={{ headerShown: false }} name="Home" component={HomeScreen} /> </Stack.Navigator> ); }; const Post = () => { return ( <Stack.Navigator headerMode="screen" screenOptions={{ headerShown: false }} > <Stack.Screen name="Post" component={PostScreen} /> {/* <Stack.Screen name="่ฉณ็ดฐ" component={DetailsScreen} /> */} </Stack.Navigator> ); }; const Profile = () => { return ( <Stack.Navigator headerMode="screen" screenOptions={{ headerShown: false }} > <Stack.Screen name="Profile" component={ProfileScreen} /> {/* <Stack.Screen name="่ฉณ็ดฐ" component={DetailsScreen} /> */} </Stack.Navigator> ); }; return ( <AuthContextProvider> <FirestoreContextProvider> <FormContextProvider> <NativeBaseProvider> <NavigationContainer theme={MyTheme}> <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconName; // icon swithcer which depends on the route name if (route.name === "Home") { iconName = focused ? "ios-home" : "ios-home"; } else if (route.name === "Post") { iconName = focused ? "ios-add" : "ios-add"; } else if (route.name === "Profile") { iconName = focused ? "md-person" : "md-person"; } return ( <Ionicons name={iconName} size={size} color={color} /> ); }, })} tabBarOptions={{ activeTintColor: "rgb(0, 110, 182)", inactiveTintColor: "gray", }} > <Tab.Screen name="Home" component={Home} /> <Tab.Screen name="Post" component={Post} /> <Tab.Screen name="Profile" component={Profile} /> </Tab.Navigator> </NavigationContainer> </NativeBaseProvider> </FormContextProvider> </FirestoreContextProvider> </AuthContextProvider> ); } A: It's because, even though you switch screens, the other screen is not unmounted --- it's still in memory but not visible. This is a design decision of react-navigation intended for better performance (it doesn't have to reload the screen when you go back, as it's already there). Since it is not unmounted, when the user returns to it, it just triggers a rerender of the already-instantiated component, so the effect does not run. What you need to use instead is useFocusEffect which is an effect bound to if the screen is in focus.
useEffect doesn't work when switching screens
Hi I am still new to react-native and has been trying to create an app. My stuck is that I don't know why useEffect doesn't work when switching screens by react-navigation-bottom-tab. Below is my HomeScreen.js where I wrot useEffect to fetch all data from Firestore. As you can see I wrote two useEffects because I thought it'd work. The first one was thought to fetch data when I switch to Home from like ProfileScreen. import { View, FlatList, StyleSheet, } from "react-native"; import { RideCard } from "./RideCard"; import { OneTouchFilter } from "./OneTouchFilter"; import { useFirestoreContext } from "../../contexts/FirestoreContext"; import { useEffect } from "react"; export const HomeScreen = ({ navigation }) => { console.log("HomeScreen.js useEffect"); const { selectedBoardType, cityFromText, cityToText, fetchRides, rides } = useFirestoreContext(); useEffect(() => { fetchRides(); }, []); useEffect(() => { fetchRides(); }, [selectedBoardType, cityFromText, cityToText]); return ( <View style={styles.inner}> <OneTouchFilter /> <FlatList data={rides} renderItem={(itemData) => ( <RideCard ride={itemData.item} index={itemData.index} id={itemData.item.id} numOfRides={rides.length} /> )} /> </View> ); }; App.js this is a file where react-navigation-bottom-tab placed in. import React, { useContext } from "react"; import { StyleSheet } from "react-native"; import { NavigationContainer, DefaultTheme } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; import { HomeScreen } from "./screens/Home/HomeScreen"; import { PostScreen } from "./screens/Post/PostScreen"; import { ProfileScreen } from "./screens/Profile/ProfileScreen"; import Ionicons from "react-native-vector-icons/Ionicons"; import { NativeBaseProvider } from "native-base"; // create another file for contexts Provider import { AuthContextProvider } from "./contexts/AuthContext"; import { FirestoreContextProvider } from "./contexts/FirestoreContext"; import { FormContextProvider } from "./contexts/FormContext"; const MyTheme = { ...DefaultTheme, colors: { ...DefaultTheme.colors, background: "white", }, }; export default function App() { const Stack = createStackNavigator(); // ใ‚ฟใƒ–็งปๅ‹•ใฎ่จญๅฎšใ‚’ๆ–ฐ่ฆ่ฟฝๅŠ  // createBottomTabNavigator ... ใ‚ฟใƒ–็งปๅ‹•ใ‚’่จญๅฎšใ™ใ‚‹้–ขๆ•ฐ const Tab = createBottomTabNavigator(); // ๆ–ฐ่ฆ่ฟฝๅŠ  // - ็งปๅ‹•ใ‚’้–ขๆ•ฐใซๆŒใŸใ›ใฆใ€ใ‚ฟใƒ–็งปๅ‹•ใฎ่จญๅฎšใงๅˆฉ็”จ // - ๆ„ๅ›ณ ... ใ‚ฟใƒ–็งปๅ‹•ใฎ็ฎ‡ๆ‰€ใฎใ‚ณใƒผใƒ‰ใŒ่ชญใฟใซใใใชใ‚‹ใŸใ‚ const Home = () => { return ( <Stack.Navigator> <Stack.Screen options={{ headerShown: false }} name="Home" component={HomeScreen} /> </Stack.Navigator> ); }; const Post = () => { return ( <Stack.Navigator headerMode="screen" screenOptions={{ headerShown: false }} > <Stack.Screen name="Post" component={PostScreen} /> {/* <Stack.Screen name="่ฉณ็ดฐ" component={DetailsScreen} /> */} </Stack.Navigator> ); }; const Profile = () => { return ( <Stack.Navigator headerMode="screen" screenOptions={{ headerShown: false }} > <Stack.Screen name="Profile" component={ProfileScreen} /> {/* <Stack.Screen name="่ฉณ็ดฐ" component={DetailsScreen} /> */} </Stack.Navigator> ); }; return ( <AuthContextProvider> <FirestoreContextProvider> <FormContextProvider> <NativeBaseProvider> <NavigationContainer theme={MyTheme}> <Tab.Navigator screenOptions={({ route }) => ({ tabBarIcon: ({ focused, color, size }) => { let iconName; // icon swithcer which depends on the route name if (route.name === "Home") { iconName = focused ? "ios-home" : "ios-home"; } else if (route.name === "Post") { iconName = focused ? "ios-add" : "ios-add"; } else if (route.name === "Profile") { iconName = focused ? "md-person" : "md-person"; } return ( <Ionicons name={iconName} size={size} color={color} /> ); }, })} tabBarOptions={{ activeTintColor: "rgb(0, 110, 182)", inactiveTintColor: "gray", }} > <Tab.Screen name="Home" component={Home} /> <Tab.Screen name="Post" component={Post} /> <Tab.Screen name="Profile" component={Profile} /> </Tab.Navigator> </NavigationContainer> </NativeBaseProvider> </FormContextProvider> </FirestoreContextProvider> </AuthContextProvider> ); }
[ "It's because, even though you switch screens, the other screen is not unmounted --- it's still in memory but not visible. This is a design decision of react-navigation intended for better performance (it doesn't have to reload the screen when you go back, as it's already there). Since it is not unmounted, when the user returns to it, it just triggers a rerender of the already-instantiated component, so the effect does not run.\nWhat you need to use instead is useFocusEffect which is an effect bound to if the screen is in focus.\n" ]
[ 1 ]
[]
[]
[ "javascript", "react_hooks", "react_native", "reactjs" ]
stackoverflow_0074672780_javascript_react_hooks_react_native_reactjs.txt
Q: Bootstrap datepicker disabling past dates without current date I wanted to disable all past date before current date, not with current date. I am trying by bootstrap datepicker library "bootstrap-datepicker" and using following code: $('#date').datepicker({ startDate: new Date() }); It works fine. But it is disabling date till today. As example if today is 04-20-2013 and i disable past dates by setting startDate: new Date(). but I am able to select date from 04-21-2013. UPDATED: i can solve it as following for UTC zone: var d = new Date(); options["startDate"] = new Date(d.setDate(d.getDate() - 1)); or startDate: "+0d" But these methods don't work when UTC is a day ahead. For my client in California that means at 5:00 pm my client can no longer select his local current date as a valid date. In order to fix this I am temporarily using startDate: "-1d", but of course before 5 that means yesterday is visible. Has anyone come up with a better method for now as I do not want to tell users to put in a UTC date? Thanks in advance. A: var date = new Date(); date.setDate(date.getDate()-1); $('#date').datepicker({ startDate: date }); A: Use minDate var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()); $('#date').datepicker({ minDate: today }); A: HTML <input type="text" name="my_date" value="4/26/2015" class="datepicker"> JS jQuery(function() { var datepicker = $('input.datepicker'); if (datepicker.length > 0) { datepicker.datepicker({ format: "mm/dd/yyyy", startDate: new Date() }); } }); That will highlight the default date as 4/26/2015 (Apr 26, 2015) in the calendar when opened and disable all the dates before current date. A: use startDate: '-0d' Like $("#datepicker").datepicker({ startDate: '-0d', changeMonth: true }); A: You can use the data attribute: <div class="datepicker" data-date-start-date="+1d"></div> A: var nowDate = new Date(); var today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0); $('#date').datetimepicker({ startDate: today }); A: The solution is much simpler: $('#date').datepicker({ startDate: "now()" }); Try Online Demo and fill input Start date: now() A: <script type="text/javascript"> $('.datepicker').datepicker({ format: 'dd/mm/yyyy', todayHighlight:'TRUE', startDate: '-0d', autoclose: true, }) A: Here it is <script> $(function () { var date = new Date(); date.setDate(date.getDate() - 7); $('#datetimepicker1').datetimepicker({ maxDate: 'now', showTodayButton: true, showClear: true, minDate: date }); }); </script> A: Try it : $(function () { $('#datetimepicker').datetimepicker({ minDate:new Date()}); }); A: To disable past dates & highlight today's date: $(function () { $('.input-daterange').datepicker({ startDate : new Date(), todayHighlight : true }); }); To disable future dates & highlight today's date: $(function () { $('.input-daterange').datepicker({ endDate : new Date(), todayHighlight : true }); }); For more details check this out https://bootstrap-datepicker.readthedocs.io/en/latest/options.html?highlight=startdate#quick-reference A: Disable all past date <script type="text/javascript"> $(function () { /*--FOR DATE----*/ var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()); //Date1 $('#ctl00_ContentPlaceHolder1_txtTranDate').datepicker({ format: 'dd-mm-yyyy', todayHighlight:'TRUE', startDate: today, endDate:0, autoclose: true }); }); </script> Disable all future date var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()); //Date1 $('#ctl00_ContentPlaceHolder1_txtTranDate').datepicker({ format: 'dd-mm-yyyy', todayHighlight:'TRUE', minDate: today, autoclose: true }); A: Please refer to the fiddle http://jsfiddle.net/Ritwika/gsvh83ry/ **With three fields having date greater than the ** <input type="text" type="text" class="form-control datepickstart" /> <input type="text" type="text" class="form-control datepickend" /> <input type="text" type="text" class="form-control datepickthird" /> var date = new Date(); date.setDate(date.getDate()-1); $('.datepickstart').datepicker({ autoclose: true, todayHighlight: true, format: 'dd/mm/yyyy', startDate: date }); $('.datepickstart').datepicker().on('changeDate', function() { var temp = $(this).datepicker('getDate'); var d = new Date(temp); d.setDate(d.getDate() + 1); $('.datepickend').datepicker({ autoclose: true, format: 'dd/mm/yyyy', startDate: d }).on('changeDate', function() { var temp1 = $(this).datepicker('getDate'); var d1 = new Date(temp1); d1.setDate(d1.getDate() + 1); $('.datepickthird').datepicker({ autoclose: true, format: 'dd/mm/yyyy', startDate: d1 }); }); }); A: You can simply add data attribute in html input tag: In rails html : <%= form.text_field :appointment_date, 'data-provide': 'datepicker', 'data-date-start-date': "+0d" %> HTML : <input data-provide="datepicker" data-date-start-date="+0d" type="text" name="appointment_date" id="appointment_date"> A: In html <input class="required form-control" id="d_start_date" name="d_start_date" type="text" value=""> In Js side <script type="text/javascript"> $(document).ready(function () { var dateToday = new Date(); dateToday.setDate(dateToday.getDate()); $('#d_start_date').datepicker({ autoclose: true, startDate: dateToday }) }); A: to disable past date just use : $('.input-group.date').datepicker({ format: 'dd/mm/yyyy', startDate: 'today' }); A: The following worked for me $('.input-group.date').datepicker({ format: 'dd/mm/yyyy', startDate: new Date() }); A: It depends on what format you put on the datepicker So first we gave it the format. var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10){ dd='0'+dd; } if(mm<10){ mm='0'+mm; } var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want Then Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case ) //Datetimepicker $(function () { $('#datetimepicker1').datetimepicker({ minDate: today, //pass today's date daysOfWeekDisabled: [0], locale: 'es', inline: true, format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin) sideBySide: true }); }); A: You can find your solution in this link below: https://codepen.io/ahmetcadirci25/pen/NpMNzJ Thats work for me. My code: var date = new Date(); date.setDate(date.getDate()); $('#datetimepicker1').datetimepicker({ isRTL: false, format: 'dd.mm.yyyy hh:ii', autoclose: true, language: 'tr', startDate: date }); A: If your requirement is to disable the startDate and endDate dynamically based on one on another you can you this. $('#date2').datepicker({ todayHighlight: true, autoclose: true, format: "dd/mm/yyyy", clearBtn : true }).on('show', function(e){ var date = $('#date3').datepicker('getDate'); if(date){ $('#date2').datepicker('setEndDate', date); } }); $('#date3').datepicker({ todayHighlight: true, autoclose: true, format: "dd/mm/yyyy", clearBtn : true }).on('show', function(e){ var date = $('#date2').datepicker('getDate'); if(date){ $('#date3').datepicker('setStartDate', date); } }); If your requirement is just disabled past dates then you can use below snippet. $('#date2').datepicker({ todayHighlight: true, autoclose: true, format: "dd/mm/yyyy", clearBtn : true, startDate : new Date() }) If your requirement is just disabled future dates then you can use below snippet. $('#date2').datepicker({ todayHighlight: true, autoclose: true, format: "dd/mm/yyyy", clearBtn : true, endDate : new Date() }) I hope it will help someone. A: var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()); $('.datePicker').datepicker({ dateFormat: 'DD-MM-YYYY', orientation: "auto", startDate: today, autoclose: true });
Bootstrap datepicker disabling past dates without current date
I wanted to disable all past date before current date, not with current date. I am trying by bootstrap datepicker library "bootstrap-datepicker" and using following code: $('#date').datepicker({ startDate: new Date() }); It works fine. But it is disabling date till today. As example if today is 04-20-2013 and i disable past dates by setting startDate: new Date(). but I am able to select date from 04-21-2013. UPDATED: i can solve it as following for UTC zone: var d = new Date(); options["startDate"] = new Date(d.setDate(d.getDate() - 1)); or startDate: "+0d" But these methods don't work when UTC is a day ahead. For my client in California that means at 5:00 pm my client can no longer select his local current date as a valid date. In order to fix this I am temporarily using startDate: "-1d", but of course before 5 that means yesterday is visible. Has anyone come up with a better method for now as I do not want to tell users to put in a UTC date? Thanks in advance.
[ "var date = new Date();\ndate.setDate(date.getDate()-1);\n\n$('#date').datepicker({ \n startDate: date\n});\n\n", "Use minDate\nvar date = new Date();\nvar today = new Date(date.getFullYear(), date.getMonth(), date.getDate());\n\n$('#date').datepicker({ \n minDate: today\n});\n\n", "HTML\n<input type=\"text\" name=\"my_date\" value=\"4/26/2015\" class=\"datepicker\">\n\nJS\njQuery(function() {\n var datepicker = $('input.datepicker');\n\n if (datepicker.length > 0) {\n datepicker.datepicker({\n format: \"mm/dd/yyyy\",\n startDate: new Date()\n });\n }\n});\n\nThat will highlight the default date as 4/26/2015 (Apr 26, 2015) in the calendar when opened and\ndisable all the dates before current date.\n", "use \nstartDate: '-0d'\n\nLike \n$(\"#datepicker\").datepicker({\n startDate: '-0d',\n changeMonth: true\n});\n\n", "You can use the data attribute:\n<div class=\"datepicker\" data-date-start-date=\"+1d\"></div>\n\n", "\n\nvar nowDate = new Date();\r\nvar today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);\r\n $('#date').datetimepicker({\r\n startDate: today\r\n });\n\n\n\n", "The solution is much simpler:\n$('#date').datepicker({ \n startDate: \"now()\" \n});\n\nTry Online Demo and fill input Start date: now()\n", "<script type=\"text/javascript\">\n$('.datepicker').datepicker({\n format: 'dd/mm/yyyy',\n todayHighlight:'TRUE',\n startDate: '-0d',\n autoclose: true,\n})\n\n", "Here it is \n <script>\n $(function () {\n var date = new Date();\n date.setDate(date.getDate() - 7);\n\n $('#datetimepicker1').datetimepicker({\n maxDate: 'now',\n showTodayButton: true,\n showClear: true,\n minDate: date\n });\n });\n </script>\n\n", "Try it :\n$(function () {\n $('#datetimepicker').datetimepicker({ minDate:new Date()});\n});\n\n", "To disable past dates & highlight today's date:\n$(function () {\n $('.input-daterange').datepicker({\n startDate : new Date(),\n todayHighlight : true\n });\n});\n\nTo disable future dates & highlight today's date:\n$(function () {\n $('.input-daterange').datepicker({\n endDate : new Date(),\n todayHighlight : true\n });\n});\n\nFor more details check this out https://bootstrap-datepicker.readthedocs.io/en/latest/options.html?highlight=startdate#quick-reference\n", "Disable all past date\n<script type=\"text/javascript\">\n $(function () {\n /*--FOR DATE----*/\n var date = new Date();\n var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());\n\n //Date1\n $('#ctl00_ContentPlaceHolder1_txtTranDate').datepicker({\n format: 'dd-mm-yyyy',\n todayHighlight:'TRUE',\n startDate: today,\n endDate:0,\n autoclose: true\n });\n\n });\n</script>\n\nDisable all future date\n var date = new Date();\n var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());\n\n //Date1\n $('#ctl00_ContentPlaceHolder1_txtTranDate').datepicker({\n format: 'dd-mm-yyyy',\n todayHighlight:'TRUE',\n minDate: today,\n autoclose: true\n });\n\n", "Please refer to the fiddle http://jsfiddle.net/Ritwika/gsvh83ry/\n**With three fields having date greater than the **\n<input type=\"text\" type=\"text\" class=\"form-control datepickstart\" />\n<input type=\"text\" type=\"text\" class=\"form-control datepickend\" />\n<input type=\"text\" type=\"text\" class=\"form-control datepickthird\" />\n\nvar date = new Date();\n date.setDate(date.getDate()-1);\n$('.datepickstart').datepicker({\n autoclose: true,\n todayHighlight: true,\n format: 'dd/mm/yyyy',\n startDate: date\n});\n$('.datepickstart').datepicker().on('changeDate', function() {\n var temp = $(this).datepicker('getDate');\n var d = new Date(temp);\n d.setDate(d.getDate() + 1);\n $('.datepickend').datepicker({\n autoclose: true,\n format: 'dd/mm/yyyy',\n startDate: d\n}).on('changeDate', function() {\n var temp1 = $(this).datepicker('getDate');\n var d1 = new Date(temp1);\n d1.setDate(d1.getDate() + 1);\n $('.datepickthird').datepicker({\n autoclose: true,\n format: 'dd/mm/yyyy',\n startDate: d1\n});\n});\n});\n\n", "You can simply add data attribute in html input tag:\nIn rails html :\n<%= form.text_field :appointment_date, 'data-provide': 'datepicker', 'data-date-start-date': \"+0d\" %>\n\nHTML :\n<input data-provide=\"datepicker\" data-date-start-date=\"+0d\" type=\"text\" name=\"appointment_date\" id=\"appointment_date\">\n\n", "In html\n<input class=\"required form-control\" id=\"d_start_date\" name=\"d_start_date\" type=\"text\" value=\"\">\n\nIn Js side\n<script type=\"text/javascript\">\n $(document).ready(function () {\n var dateToday = new Date();\n dateToday.setDate(dateToday.getDate());\n\n $('#d_start_date').datepicker({\n autoclose: true,\n startDate: dateToday\n })\n\n });\n\n", "to disable past date just use :\n $('.input-group.date').datepicker({\n format: 'dd/mm/yyyy',\n startDate: 'today'\n });\n\n", "The following worked for me\n$('.input-group.date').datepicker({\n format: 'dd/mm/yyyy',\n startDate: new Date()\n});\n\n", "It depends on what format you put on the datepicker\nSo first we gave it the format.\n var today = new Date();\n var dd = today.getDate();\n var mm = today.getMonth()+1; //January is 0!\n\n var yyyy = today.getFullYear();\n if(dd<10){\n dd='0'+dd;\n } \n if(mm<10){\n mm='0'+mm;\n } \n var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want\n\nThen Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case )\n //Datetimepicker\n $(function () {\n $('#datetimepicker1').datetimepicker({\n minDate: today, //pass today's date\n daysOfWeekDisabled: [0],\n locale: 'es',\n inline: true,\n format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin)\n sideBySide: true\n });\n });\n\n", "You can find your solution in this link below: https://codepen.io/ahmetcadirci25/pen/NpMNzJ\nThats work for me.\nMy code:\n var date = new Date();\n date.setDate(date.getDate());\n\n $('#datetimepicker1').datetimepicker({\n isRTL: false,\n format: 'dd.mm.yyyy hh:ii',\n autoclose: true,\n language: 'tr',\n startDate: date\n });\n\n", "If your requirement is to disable the startDate and endDate dynamically based on one on another you can you this. \n$('#date2').datepicker({\n todayHighlight: true,\n autoclose: true,\n format: \"dd/mm/yyyy\",\n clearBtn : true\n }).on('show', function(e){\n var date = $('#date3').datepicker('getDate');\n if(date){\n $('#date2').datepicker('setEndDate', date);\n }\n });\n\n $('#date3').datepicker({\n todayHighlight: true,\n autoclose: true,\n format: \"dd/mm/yyyy\",\n clearBtn : true\n }).on('show', function(e){\n var date = $('#date2').datepicker('getDate');\n if(date){\n $('#date3').datepicker('setStartDate', date);\n }\n });\n\nIf your requirement is just disabled past dates then you can use below snippet.\n$('#date2').datepicker({\n todayHighlight: true,\n autoclose: true,\n format: \"dd/mm/yyyy\",\n clearBtn : true,\n startDate : new Date()\n })\n\nIf your requirement is just disabled future dates then you can use below snippet.\n $('#date2').datepicker({\n todayHighlight: true,\n autoclose: true,\n format: \"dd/mm/yyyy\",\n clearBtn : true,\n endDate : new Date()\n })\n\nI hope it will help someone. \n", "var date = new Date();\nvar today = new Date(date.getFullYear(), date.getMonth(), date.getDate());\n\n$('.datePicker').datepicker({\n dateFormat: 'DD-MM-YYYY',\n orientation: \"auto\",\n startDate: today,\n autoclose: true\n});\n\n" ]
[ 59, 24, 23, 18, 8, 7, 6, 5, 4, 4, 4, 3, 3, 3, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "bootstrap_datepicker", "javascript", "jquery", "twitter_bootstrap" ]
stackoverflow_0016123056_bootstrap_datepicker_javascript_jquery_twitter_bootstrap.txt
Q: How can two CSV files with the same data but different column orders be validated in Java? I am trying to compare two CSV files that have the same data but columns in different orders. When the column orders match, the following code works: How can I tweak my following code to make it work when column orders don't match between the CSV files? Set<String> source = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(sourceFile))); Set<String> target = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(targetFile))); return source.containsAll(target) && target.containsAll(source) For example, the above test pass when the source file and target file are in this way: source file: a,b,c 1,2,3 4,5,6 target file: a,b,c 1,2,3 4,5,6 However, the source file is same, but if the target file is in the following way, it doesn't work. target file: a,c,b 1,3,2 4,6,5 A: Here is some code that could work. It relies on the first line of each file containing column headers. It's a bit more than a tweak, though. It's an "old dog" approach. The original code in the question has these lines: Set<String> source = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(sourceFile))); Set<String> target = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(targetFile))); With this solution, the data coming in needs more processing before it will be ready to be put into a Set. Those two lines get changed as follows: List<String> source = (org.apache.commons.io.FileUtils.readLines(new File(sourceFile))); List<String> target = (org.apache.commons.io.FileUtils.readLines(new File(targetFile))); This approach will compare column headers in the target file and the source file. It will use that to build an int [] that indicates the difference in column order. After the order difference array is filled, the data in the file will be put into a pair of Set<List<String>>. Each List<String> will represent one line from the source and target data files. Each String in the List will be data from one column. In the following code, main is the test driver. Only for my testing purposes, the data files have been replaced by a pair of String [] and reading the file with org.apache.commons.io.FileUtils.readLines has been replaced with Arrays.asList. package comparecsv; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class CompareCSV { private static int [] columnReorder; private static void headersOrder (String sourceHeader, String targetHeader) { String [] columnHeader = sourceHeader.split (","); List<String> sourceColumn = Arrays.asList (columnHeader); columnReorder = new int [columnHeader.length]; String [] targetColumn = targetHeader.split (","); for (int i = 0; i < targetColumn.length; ++i) { int j = sourceColumn.indexOf(targetColumn[i]); columnReorder [i] = j; } } private static Set<List<String>> toSet (List<String> data, boolean reorder) { Set<List<String>> dataSet = new HashSet<> (); for (String s: data) { String [] byColumn = s.split (","); if (reorder) { String [] reordered = new String [byColumn.length]; for (int i = 0; i < byColumn.length; ++i) { reordered[columnReorder[i]] = byColumn [i]; } dataSet.add (Arrays.asList (reordered)); } else { dataSet.add (Arrays.asList(byColumn)); } } return dataSet; } public static void main(String[] args) { String [] sourceData = {"a,b,c,d,e", "1,2,3,4,5", "6,7,8,9,10" ,"11,12,13,14,15", "16,17,18,19,20"}; String [] targetData = {"c,b,e,d,a", "3,2,5,4,1", "8,7,10,9,6" ,"13,12,15,14,11", "18,17,20,19,16"}; List<String> source = Arrays.asList(sourceData); List<String> target = Arrays.asList (targetData); headersOrder (source.get(0), target.get(0)); Set<List<String>> sourceSet = toSet (source, false); Set<List<String>> targetSet = toSet (target, true); System.out.println ( sourceSet.containsAll (targetSet) + " " + targetSet.containsAll (sourceSet) + " " + ( sourceSet.containsAll (targetSet) && targetSet.containsAll (sourceSet))); } } MethodheadersOrder compares the headers, column by column, and populates the columnReorder array. Method toSet creates the Set<List<String>>, either reordering the columns or not, according to the value of the boolean argument. For the sake of simplification, this assumes lines are easily split using comma. Data such as dog, "Reginald, III", 3 will cause failure. In testing this, I found lines in the file can be matched with their counterpart in the other file, regardless of order of the lines. Here is an example: Source: a,b,c 1,2,3 4,5,6 7,8,9 Target: a,b,c 4,5,6 7,8,9 1,2,3 The result would be the contents match. I believe this would match a result from the O/P question code. However, for this solution to work, the first line in each file must contain column headers.
How can two CSV files with the same data but different column orders be validated in Java?
I am trying to compare two CSV files that have the same data but columns in different orders. When the column orders match, the following code works: How can I tweak my following code to make it work when column orders don't match between the CSV files? Set<String> source = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(sourceFile))); Set<String> target = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(targetFile))); return source.containsAll(target) && target.containsAll(source) For example, the above test pass when the source file and target file are in this way: source file: a,b,c 1,2,3 4,5,6 target file: a,b,c 1,2,3 4,5,6 However, the source file is same, but if the target file is in the following way, it doesn't work. target file: a,c,b 1,3,2 4,6,5
[ "Here is some code that could work. It relies on the first line of each file containing column headers.\nIt's a bit more than a tweak, though. It's an \"old dog\" approach.\nThe original code in the question has these lines:\nSet<String> source = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(sourceFile)));\nSet<String> target = new HashSet<>(org.apache.commons.io.FileUtils.readLines(new File(targetFile)));\n\nWith this solution, the data coming in needs more processing before it will be ready to be put into a Set. Those two lines get changed as follows:\nList<String> source = (org.apache.commons.io.FileUtils.readLines(new File(sourceFile)));\nList<String> target = (org.apache.commons.io.FileUtils.readLines(new File(targetFile)));\n\nThis approach will compare column headers in the target file and the source file. It will use that to build an int [] that indicates the difference in column order.\nAfter the order difference array is filled, the data in the file will be put into a pair of Set<List<String>>. Each List<String> will represent one line from the source and target data files. Each String in the List will be data from one column.\nIn the following code, main is the test driver. Only for my testing purposes, the data files have been replaced by a pair of String [] and reading the file with org.apache.commons.io.FileUtils.readLines has been replaced with Arrays.asList.\npackage comparecsv;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class CompareCSV {\n\n private static int [] columnReorder;\n\n private static void headersOrder\n (String sourceHeader, String targetHeader) {\n String [] columnHeader = sourceHeader.split (\",\");\n List<String> sourceColumn = Arrays.asList (columnHeader);\n columnReorder = new int [columnHeader.length];\n String [] targetColumn = targetHeader.split (\",\");\n for (int i = 0; i < targetColumn.length; ++i) {\n int j = sourceColumn.indexOf(targetColumn[i]);\n columnReorder [i] = j;\n }\n }\n\n private static Set<List<String>> toSet\n (List<String> data, boolean reorder) {\n Set<List<String>> dataSet = new HashSet<> ();\n for (String s: data) {\n String [] byColumn = s.split (\",\");\n if (reorder) {\n String [] reordered = new String [byColumn.length];\n for (int i = 0; i < byColumn.length; ++i) {\n reordered[columnReorder[i]] = byColumn [i];\n }\n dataSet.add (Arrays.asList (reordered));\n } else {\n dataSet.add (Arrays.asList(byColumn));\n }\n }\n return dataSet;\n }\n\n public static void main(String[] args) {\n String [] sourceData = {\"a,b,c,d,e\", \"1,2,3,4,5\", \"6,7,8,9,10\"\n ,\"11,12,13,14,15\", \"16,17,18,19,20\"};\n String [] targetData = {\"c,b,e,d,a\", \"3,2,5,4,1\", \"8,7,10,9,6\"\n ,\"13,12,15,14,11\", \"18,17,20,19,16\"};\n List<String> source = Arrays.asList(sourceData);\n List<String> target = Arrays.asList (targetData);\n\n headersOrder (source.get(0), target.get(0));\n Set<List<String>> sourceSet = toSet (source, false);\n Set<List<String>> targetSet = toSet (target, true);\n System.out.println ( sourceSet.containsAll (targetSet)\n + \" \" + targetSet.containsAll (sourceSet) + \" \" +\n ( sourceSet.containsAll (targetSet)\n && targetSet.containsAll (sourceSet)));\n }\n}\n\nMethodheadersOrder compares the headers, column by column, and populates the columnReorder array. Method toSet creates the Set<List<String>>, either reordering the columns or not, according to the value of the boolean argument.\nFor the sake of simplification, this assumes lines are easily split using comma. Data such as dog, \"Reginald, III\", 3 will cause failure.\nIn testing this, I found lines in the file can be matched with their counterpart in the other file, regardless of order of the lines. Here is an example:\nSource:\na,b,c\n1,2,3\n4,5,6\n7,8,9\n\nTarget:\na,b,c\n4,5,6\n7,8,9\n1,2,3 \n\nThe result would be the contents match.\nI believe this would match a result from the O/P question code. However, for this solution to work, the first line in each file must contain column headers.\n" ]
[ 0 ]
[]
[]
[ "csv", "csvreader", "file_comparison", "java", "java_11" ]
stackoverflow_0074650317_csv_csvreader_file_comparison_java_java_11.txt
Q: TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace I am using Python 3.9, PyCharm 2022. My purpose (Ultimate goal of this question): create a command line application receive 2 parameters: Path of directory Extension of files then get size of files (Per file size, not sum of files size). import os import argparse from os import listdir from os.path import isfile, join def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="Path of directory.") parser.add_argument("ext", help="Extension of files (for example: jpg, png, exe, mp4, etc.") args1 = parser.parse_args() args2 = parser.parse_args() print(args1) arr = os.listdir(args1) print(arr) # os.path.getsize(args.path) # bytes_size = os.path.getsize(args1.path) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, "MB") if __name__ == '__main__': main() My command and according error: (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> python size.py 'D:' 'jpg' Traceback (most recent call last): File "C:\Users\donhu\PycharmProjects\pythonProject4\size.py", line 22, in <module> (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> python size.py 'D:' 'jpg' Namespace(path='D:', ext='jpg') Traceback (most recent call last): File "C:\Users\donhu\PycharmProjects\pythonProject4\size.py", line 23, in <module> main() File "C:\Users\donhu\PycharmProjects\pythonProject4\size.py", line 13, in main arr = os.listdir(args1) TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> How to fix? Update, I tried something import os import argparse from os import listdir from os.path import isfile, join from pathlib import * def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="ฤฦฐแปng dแบซn cแปงa thฦฐ mแปฅc") parser.add_argument("ext", help="ฤแป‹nh dแบกng tแบญp tin cแบงn liแป‡t kรช kรญch thฦฐแป›c.") args1 = parser.parse_args() args2 = parser.parse_args() foo = args1.path # arr = os.listdir('D:/') files = [x for x in foo.iterdir() if x.is_file()] print(files) # os.path.getsize(args.path) # bytes_size = os.path.getsize(args1.path) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, "MB") if __name__ == '__main__': main() but not work. A: The os module holds the traditional interface into the file system. It closely follows the Clib interface so you'll see functions like listdir and stat. pathlib is a new object oriented "pythonic" interface to the file system. One can argue whether its better, but I use it, so its gotta be, right? It looks like you are mixing "old" and "new" ways of doing things, which gets confusing. If you want to use pathlib, try to use it for everything. Here is your script re-imagined for pathlib. You only need to parse the command line once and then build a Path object for the directory of interest. import argparse from pathlib import Path def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="ฤฦฐแปng dแบซn cแปงa thฦฐ mแปฅc") parser.add_argument("ext", help="ฤแป‹nh dแบกng tแบญp tin cแบงn liแป‡t kรช kรญch thฦฐแป›c.") args = parser.parse_args() foo = Path(args.path) if not foo.is_dir(): print("Error: Must be a directory") exit(1) files = [x for x in foo.iterdir() if x.is_file()] print(files) # os.path.getsize(args.path) bytes_size = sum(file.stat().st_size for file in files) print("total bytes", bytes_size) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, "MB") if __name__ == '__main__': main() If you want to use the ext parameter, you would change from iterdir to glob. files = [x for x in foo.glob(f"*.{args.ext}") if x.is_file()] or files = [x for x in foo.glob(f"**/*.{args.ext}") if x.is_file()] depending on whether you want just the directory or its subtree. A: Argparse's parse_args() function returns a Namespace object. I believe your goal was to pass the path argument, you have to access it as an attribute. os.listdir(args1.path) A: Program import os import argparse from pathlib import Path def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="Path of directory/folder") parser.add_argument("ext", help="Extension of file what need get size.") args = parser.parse_args() foo = Path(args.path) files = [x for x in foo.glob(f"*.{args.ext}") if x.is_file()] for file in files: print(file.__str__(), os.path.getsize(file)) if __name__ == '__main__': main() # python size.py "D:\" 'jpg' # (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> python size.py "D:\" 'jpg' # D:\1496231_10152440570407564_3432420_o.jpg 241439 # D:\15002366_278058419262140_505451777021235_o.jpg 598063 # D:\1958485_703442046353041_1444502_n.jpg 63839 # D:\277522952_5065319530178162_680264454398630_n.jpg 335423
TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace
I am using Python 3.9, PyCharm 2022. My purpose (Ultimate goal of this question): create a command line application receive 2 parameters: Path of directory Extension of files then get size of files (Per file size, not sum of files size). import os import argparse from os import listdir from os.path import isfile, join def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="Path of directory.") parser.add_argument("ext", help="Extension of files (for example: jpg, png, exe, mp4, etc.") args1 = parser.parse_args() args2 = parser.parse_args() print(args1) arr = os.listdir(args1) print(arr) # os.path.getsize(args.path) # bytes_size = os.path.getsize(args1.path) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, "MB") if __name__ == '__main__': main() My command and according error: (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> python size.py 'D:' 'jpg' Traceback (most recent call last): File "C:\Users\donhu\PycharmProjects\pythonProject4\size.py", line 22, in <module> (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> python size.py 'D:' 'jpg' Namespace(path='D:', ext='jpg') Traceback (most recent call last): File "C:\Users\donhu\PycharmProjects\pythonProject4\size.py", line 23, in <module> main() File "C:\Users\donhu\PycharmProjects\pythonProject4\size.py", line 13, in main arr = os.listdir(args1) TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace (base) PS C:\Users\donhu\PycharmProjects\pythonProject4> How to fix? Update, I tried something import os import argparse from os import listdir from os.path import isfile, join from pathlib import * def main(): parser = argparse.ArgumentParser() parser.add_argument("path", help="ฤฦฐแปng dแบซn cแปงa thฦฐ mแปฅc") parser.add_argument("ext", help="ฤแป‹nh dแบกng tแบญp tin cแบงn liแป‡t kรช kรญch thฦฐแป›c.") args1 = parser.parse_args() args2 = parser.parse_args() foo = args1.path # arr = os.listdir('D:/') files = [x for x in foo.iterdir() if x.is_file()] print(files) # os.path.getsize(args.path) # bytes_size = os.path.getsize(args1.path) # mb_size = int(bytes_size / 1024 / 1024) # print(mb_size, "MB") if __name__ == '__main__': main() but not work.
[ "The os module holds the traditional interface into the file system. It closely follows the Clib interface so you'll see functions like listdir and stat. pathlib is a new object oriented \"pythonic\" interface to the file system. One can argue whether its better, but I use it, so its gotta be, right?\nIt looks like you are mixing \"old\" and \"new\" ways of doing things, which gets confusing. If you want to use pathlib, try to use it for everything.\nHere is your script re-imagined for pathlib. You only need to parse the command line once and then build a Path object for the directory of interest.\nimport argparse\nfrom pathlib import Path\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"ฤฦฐแปng dแบซn cแปงa thฦฐ mแปฅc\")\n parser.add_argument(\"ext\", help=\"ฤแป‹nh dแบกng tแบญp tin cแบงn liแป‡t kรช kรญch thฦฐแป›c.\")\n args = parser.parse_args()\n foo = Path(args.path)\n if not foo.is_dir():\n print(\"Error: Must be a directory\")\n exit(1)\n files = [x for x in foo.iterdir() if x.is_file()]\n print(files)\n # os.path.getsize(args.path)\n bytes_size = sum(file.stat().st_size for file in files)\n print(\"total bytes\", bytes_size)\n # mb_size = int(bytes_size / 1024 / 1024)\n # print(mb_size, \"MB\")\n\nif __name__ == '__main__':\n main()\n\nIf you want to use the ext parameter, you would change from iterdir to glob.\nfiles = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n\nor\nfiles = [x for x in foo.glob(f\"**/*.{args.ext}\") if x.is_file()]\n\ndepending on whether you want just the directory or its subtree.\n", "Argparse's parse_args() function returns a Namespace object. I believe your goal was to pass the path argument, you have to access it as an attribute.\nos.listdir(args1.path)\n\n", "Program\nimport os\nimport argparse\nfrom pathlib import Path\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", help=\"Path of directory/folder\")\n parser.add_argument(\"ext\", help=\"Extension of file what need get size.\")\n args = parser.parse_args()\n foo = Path(args.path)\n files = [x for x in foo.glob(f\"*.{args.ext}\") if x.is_file()]\n for file in files:\n print(file.__str__(), os.path.getsize(file))\n\n\nif __name__ == '__main__':\n main()\n \n# python size.py \"D:\\\" 'jpg'\n\n# (base) PS C:\\Users\\donhu\\PycharmProjects\\pythonProject4> python size.py \"D:\\\" 'jpg'\n# D:\\1496231_10152440570407564_3432420_o.jpg 241439\n# D:\\15002366_278058419262140_505451777021235_o.jpg 598063\n# D:\\1958485_703442046353041_1444502_n.jpg 63839\n# D:\\277522952_5065319530178162_680264454398630_n.jpg 335423\n\n" ]
[ 1, 0, 0 ]
[ "Your two command line arguments are being returned as a single object of the argparse.Namespace class, both stored identically in your args1 and (the superfluous) args2 variables.\nInserting the following line after your calls to parse_args() and commenting out the subsequent code would illuminate this a little more:\nprint(type(args1))\n\nTo access the values you named in your calls to add_argument(), use this syntax:\nargs1.path\nargs1.ext\n\nsuch as\narr = os.listdir(args1.path)\n\nFor further discussion, see this answer: Accessing argument values for argparse in Python\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074672824_python.txt
Q: I can't understand what's wrong - Python multiple text replace dictionary I can't understand what happen. I'm trying to make this script to replace multiple text files using a list of pairs, but only the first pair is working, the others are not processed. Did I make any mistakes in the loops? replacements = [ ('Dog', 'Cat'), ('Lazy', 'Smart'), ('Fat', 'Slim'), ] import re import sys if __name__ == "__main__": if len(sys.argv) < 2 or len(sys.argv) > 4: print("Invalid argument(s)") exit() with open(sys.argv[1], "r") as f: print(f"Reading {sys.argv[1]}") new_lines = "" for old, new in replacements: for l in f: new_lines += re.sub(old, new, l) with open(sys.argv[2] or sys.argv[1], "w") as f: print(f"Writing into '{sys.argv[2] or sys.argv[1]}'") f.write(new_lines) A: The double for loop is causing the issue. Reading the file contents only once fixes the issue. replacements = [ ('Dog', 'Cat'), ('Lazy', 'Smart'), ('Fat', 'Slim'), ] import re import sys if __name__ == "__main__": if len(sys.argv) < 2 or len(sys.argv) > 4: print("Invalid argument(s)") exit() with open(sys.argv[1], "r") as f: print(f"Reading {sys.argv[1]}") new_lines = f.read() for old, new in replacements: new_lines = re.sub(old, new, new_lines) with open(sys.argv[2] or sys.argv[1], "w") as f: print(f"Writing into '{sys.argv[2] or sys.argv[1]}'") f.write(new_lines) The file will be read only once for the first replacement pairs, then it will be exhausted as all elements of the file have already been read once. Therefore, for the next replacements, pairs file contents will not be read. That's why it's only working for Dog and Cat pair and not the rest.
I can't understand what's wrong - Python multiple text replace dictionary
I can't understand what happen. I'm trying to make this script to replace multiple text files using a list of pairs, but only the first pair is working, the others are not processed. Did I make any mistakes in the loops? replacements = [ ('Dog', 'Cat'), ('Lazy', 'Smart'), ('Fat', 'Slim'), ] import re import sys if __name__ == "__main__": if len(sys.argv) < 2 or len(sys.argv) > 4: print("Invalid argument(s)") exit() with open(sys.argv[1], "r") as f: print(f"Reading {sys.argv[1]}") new_lines = "" for old, new in replacements: for l in f: new_lines += re.sub(old, new, l) with open(sys.argv[2] or sys.argv[1], "w") as f: print(f"Writing into '{sys.argv[2] or sys.argv[1]}'") f.write(new_lines)
[ "The double for loop is causing the issue. Reading the file contents only once fixes the issue.\nreplacements = [\n ('Dog', 'Cat'),\n ('Lazy', 'Smart'),\n ('Fat', 'Slim'),\n]\n\nimport re\nimport sys\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2 or len(sys.argv) > 4:\n print(\"Invalid argument(s)\")\n exit()\n with open(sys.argv[1], \"r\") as f:\n print(f\"Reading {sys.argv[1]}\")\n new_lines = f.read()\n\n for old, new in replacements:\n new_lines = re.sub(old, new, new_lines)\n \n \n with open(sys.argv[2] or sys.argv[1], \"w\") as f:\n print(f\"Writing into '{sys.argv[2] or sys.argv[1]}'\")\n f.write(new_lines)\n\nThe file will be read only once for the first replacement pairs, then it will be exhausted as all elements of the file have already been read once.\nTherefore, for the next replacements, pairs file contents will not be read. That's why it's only working for Dog and Cat pair and not the rest.\n" ]
[ 0 ]
[]
[]
[ "list", "python", "replace", "text" ]
stackoverflow_0074672969_list_python_replace_text.txt
Q: How to pass a command funcion over an event one on discordpy? I made a bot that changes nicknames of members when they type !nick + their nickname and id of a game. The problem is, some people are unaware of how to use the commands to do that, so they get stuck in my registrarion text-chat. Here is the code: @client.event async def on_message(message): channel = message.channel if message.content.startswith('!nick'): pass else: await channel.send("Algo deu errado aqui. Nรฃo esqueรงa de escrever !nick antes de digitar seu nome e ID do servidor.") @client.command(pass_context=True) async def nick(ctx, nickname, sobrenick, ident=''): autor = ctx.message.author channel = client.get_channel(channel_id) if ctx.message.content.startswith('!nick'): if ident == '': await autor.edit(nick=nickname + " | " + sobrenick) await ctx.send(f'Seu nick foi alterado para: {nickname} | {sobrenick}, se confirma digite !entrar pra continuar, se nรฃo redigite o nick') else: await autor.edit(nick=nickname + " " + sobrenick + " | " + ident) await ctx.send(f'Seu nick foi alterado para: {nickname} {sobrenick} | {ident}, se confirma digite !entrar pra continuar, se nรฃo redigite o nick') As you guys can see, to solve that I've tried to make an event before the command that triggers whenever a person types something that doesnt start with '!nick', and then made the bot sent a message explaining that they need to use !nick before their actual info to make it work. I don't know if its because of the 'pass' after the if, or if its because event classes rules above command ones, but I'm a little bit new to python and what I was expecting with that was to the bot just send a message on the channel telling the member to use the right command until he does it right. But the else condition on the event class just doesnt work. I've tried to include the same else condition on the command class too, following the "if ctx.message.content.startswith('!nick'):", and it doesnt work also... A: If you override the default on_message event, you need to add client.process_commands to allow the bot to process the registered commands. @client.event async def on_message(message): ... await client.process_commands(message) Or you can use client.listen instead of client.event @client.listen("on_message") async def my_on_message(message): ... Here is the FAQ from discord.py about this issue.
How to pass a command funcion over an event one on discordpy?
I made a bot that changes nicknames of members when they type !nick + their nickname and id of a game. The problem is, some people are unaware of how to use the commands to do that, so they get stuck in my registrarion text-chat. Here is the code: @client.event async def on_message(message): channel = message.channel if message.content.startswith('!nick'): pass else: await channel.send("Algo deu errado aqui. Nรฃo esqueรงa de escrever !nick antes de digitar seu nome e ID do servidor.") @client.command(pass_context=True) async def nick(ctx, nickname, sobrenick, ident=''): autor = ctx.message.author channel = client.get_channel(channel_id) if ctx.message.content.startswith('!nick'): if ident == '': await autor.edit(nick=nickname + " | " + sobrenick) await ctx.send(f'Seu nick foi alterado para: {nickname} | {sobrenick}, se confirma digite !entrar pra continuar, se nรฃo redigite o nick') else: await autor.edit(nick=nickname + " " + sobrenick + " | " + ident) await ctx.send(f'Seu nick foi alterado para: {nickname} {sobrenick} | {ident}, se confirma digite !entrar pra continuar, se nรฃo redigite o nick') As you guys can see, to solve that I've tried to make an event before the command that triggers whenever a person types something that doesnt start with '!nick', and then made the bot sent a message explaining that they need to use !nick before their actual info to make it work. I don't know if its because of the 'pass' after the if, or if its because event classes rules above command ones, but I'm a little bit new to python and what I was expecting with that was to the bot just send a message on the channel telling the member to use the right command until he does it right. But the else condition on the event class just doesnt work. I've tried to include the same else condition on the command class too, following the "if ctx.message.content.startswith('!nick'):", and it doesnt work also...
[ "If you override the default on_message event, you need to add client.process_commands to allow the bot to process the registered commands.\[email protected]\nasync def on_message(message):\n ...\n await client.process_commands(message)\n\nOr you can use client.listen instead of client.event\[email protected](\"on_message\")\nasync def my_on_message(message):\n ...\n\nHere is the FAQ from discord.py about this issue.\n" ]
[ 0 ]
[]
[]
[ "discord.py" ]
stackoverflow_0074672654_discord.py.txt
Q: How do I type a function's arguments but leave the return type "inferred"? Below I have two functions originalhelloWorld which is untyped and helloWorld which has a type. You can see that the return of type o returns the "inferred" return type (what is the name for this), and type x returns "any". How can I have the ExampleFunction type the functions arguments but leave the return type inferred? I've tried several combinations of generics, and nothing seems to work. Typescript Playground const originalhelloWorld = (greeting: string | boolean) => { if (typeof greeting === 'boolean') return greeting return `hello ${greeting}` } type o = ReturnType<typeof originalhelloWorld> // ^? type o = string | boolean /* ------------------------------------ */ type ExampleFunction = (greeting: string | boolean) => any const helloWorld: ExampleFunction = (greeting) => { if (typeof greeting === 'boolean') return greeting return `hello ${greeting}` } type x = ReturnType<typeof helloWorld> // ^? type x = any A: The new satisfies operator in typescript 4.9 works: Playground Link: const originalhelloWorld = (greeting: string | boolean) => { if (typeof greeting === 'boolean') return greeting return `hello ${greeting}` } type o = ReturnType<typeof originalhelloWorld> // ^? /* ------------------------------------ */ type ExampleFunction = (greeting: string | boolean) => any const helloWorld = ((greeting) => { if (typeof greeting === 'boolean') return greeting return `hello ${greeting}` }) satisfies ExampleFunction type x = ReturnType<typeof helloWorld> // ^?
How do I type a function's arguments but leave the return type "inferred"?
Below I have two functions originalhelloWorld which is untyped and helloWorld which has a type. You can see that the return of type o returns the "inferred" return type (what is the name for this), and type x returns "any". How can I have the ExampleFunction type the functions arguments but leave the return type inferred? I've tried several combinations of generics, and nothing seems to work. Typescript Playground const originalhelloWorld = (greeting: string | boolean) => { if (typeof greeting === 'boolean') return greeting return `hello ${greeting}` } type o = ReturnType<typeof originalhelloWorld> // ^? type o = string | boolean /* ------------------------------------ */ type ExampleFunction = (greeting: string | boolean) => any const helloWorld: ExampleFunction = (greeting) => { if (typeof greeting === 'boolean') return greeting return `hello ${greeting}` } type x = ReturnType<typeof helloWorld> // ^? type x = any
[ "The new satisfies operator in typescript 4.9 works:\nPlayground Link:\nconst originalhelloWorld = (greeting: string | boolean) => {\n if (typeof greeting === 'boolean') return greeting\n return `hello ${greeting}`\n}\n\ntype o = ReturnType<typeof originalhelloWorld>\n// ^?\n\n/* ------------------------------------ */\n\ntype ExampleFunction = (greeting: string | boolean) => any\n\nconst helloWorld = ((greeting) => {\n if (typeof greeting === 'boolean') return greeting\n return `hello ${greeting}`\n}) satisfies ExampleFunction\n\ntype x = ReturnType<typeof helloWorld>\n// ^?\n\n" ]
[ 0 ]
[]
[]
[ "typescript" ]
stackoverflow_0073737298_typescript.txt
Q: Is there a int to string format that turns zero into a blank? I'm displaying int values to the screen as strings, but if the value is zero (or less, I suppose) I want the string to be blank. To check that I'd need a set of if statements and to store the int value temporarily just to check it (or else retrieve it twice.) I'm wondering if there is a ToString format that will automatically do that, like how I can use ToString("N0") to add commas. That way I can just directly set the string value in a single line. A: I found that 0.ToString("#") results in "" Hope this helps! A: The ";" conditional format specifier will format positive;negative;zero values as needed, yielding "blank when zero" functionality. Example one-line usage: yourIntVariable.ToString("#;;''"); Lots of flexibility to format the output, depending on what you formatting option you put in each section. Full details of how to use this in different scenarios: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator Further reading from Rick Strahl: https://weblog.west-wind.com/posts/2021/Jan/05/Blank-Zero-Values-in-CSharp-Number-Format-Strings A: Here is an example of that functionality: int x = 0; int y = 5; Console.WriteLine(string.Format("test 1: {0}", x <= 0 ? "" : x)); Console.WriteLine(string.Format("test 2: {0}", y <= 0 ? "" : y)); Output: test 1: test 2: 5 A: You can make use of an extension method as shown below: namespace System { public static class StringExtensions { public static string FormartIntZeroORLessToEmpty(this int value) { if(value <= 0) { return string.Empty; } return value.ToString(); } } }
Is there a int to string format that turns zero into a blank?
I'm displaying int values to the screen as strings, but if the value is zero (or less, I suppose) I want the string to be blank. To check that I'd need a set of if statements and to store the int value temporarily just to check it (or else retrieve it twice.) I'm wondering if there is a ToString format that will automatically do that, like how I can use ToString("N0") to add commas. That way I can just directly set the string value in a single line.
[ "I found that 0.ToString(\"#\") results in \"\"\nHope this helps!\n", "The \";\" conditional format specifier will format positive;negative;zero values as needed, yielding \"blank when zero\" functionality. Example one-line usage:\nyourIntVariable.ToString(\"#;;''\");\nLots of flexibility to format the output, depending on what you formatting option you put in each section.\nFull details of how to use this in different scenarios:\nhttps://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator\nFurther reading from Rick Strahl:\nhttps://weblog.west-wind.com/posts/2021/Jan/05/Blank-Zero-Values-in-CSharp-Number-Format-Strings\n", "Here is an example of that functionality:\nint x = 0;\nint y = 5;\nConsole.WriteLine(string.Format(\"test 1: {0}\", x <= 0 ? \"\" : x));\nConsole.WriteLine(string.Format(\"test 2: {0}\", y <= 0 ? \"\" : y));\n\nOutput:\ntest 1: \ntest 2: 5\n\n", "You can make use of an extension method as shown below:\nnamespace System\n{\n public static class StringExtensions\n {\n public static string FormartIntZeroORLessToEmpty(this int value)\n {\n if(value <= 0)\n {\n return string.Empty;\n }\n return value.ToString();\n }\n }\n}\n\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "c#", "string" ]
stackoverflow_0071189869_c#_string.txt
Q: How to return an instance of a dataframe in a loop? I have several files that I want to use to create unique Dataframes in python. I created a class that takes each file and generates the Dataframe, but I cannot return the dataframe output (but I can print it). For example, this structure works for me: class myclass: def __init__(self, x): self.x=x df =pd.DataFrame({'A':[2,3,4]}) self.output = df y = myclass(x=1) y.output but this version does not work: import pandas as pd class myclass: def __init__(self, x): self.x=x df =pd.DataFrame({'A':[2,3,4]}) self.output = df for n in range (0,5): y = myclass(x=n) y.output So I tried to dynamically create and assign variables during the loop but it's not clear to me what's wrong with it: import pandas as pd class myclass: def __init__(self, x): self.x=x df =pd.DataFrame({'A':[2,3,4]}) self.output = df i=0 for n in range (0,5): i+=1 var = 'var'+str(i) var = myclass(x=n) var.output print (var) A: You need to print var.output: for n in range (0,5): var = myclass(x=f'var{n+1}') print(var.output) Output: A 0 2 1 3 2 4 A 0 2 1 3 2 4 A 0 2 1 3 2 4 A 0 2 1 3 2 4 A 0 2 1 3 2 4 if you want to be able to index then use a dictionary: dfs = {} for n in range (0,5): dfs[f'var{n+1}'] = myclass(x=f'var{n+1}').output dfs['var3'] Output: A 0 2 1 3 2 4
How to return an instance of a dataframe in a loop?
I have several files that I want to use to create unique Dataframes in python. I created a class that takes each file and generates the Dataframe, but I cannot return the dataframe output (but I can print it). For example, this structure works for me: class myclass: def __init__(self, x): self.x=x df =pd.DataFrame({'A':[2,3,4]}) self.output = df y = myclass(x=1) y.output but this version does not work: import pandas as pd class myclass: def __init__(self, x): self.x=x df =pd.DataFrame({'A':[2,3,4]}) self.output = df for n in range (0,5): y = myclass(x=n) y.output So I tried to dynamically create and assign variables during the loop but it's not clear to me what's wrong with it: import pandas as pd class myclass: def __init__(self, x): self.x=x df =pd.DataFrame({'A':[2,3,4]}) self.output = df i=0 for n in range (0,5): i+=1 var = 'var'+str(i) var = myclass(x=n) var.output print (var)
[ "You need to print var.output:\nfor n in range (0,5):\n var = myclass(x=f'var{n+1}')\n print(var.output)\n\nOutput:\n A\n0 2\n1 3\n2 4\n A\n0 2\n1 3\n2 4\n A\n0 2\n1 3\n2 4\n A\n0 2\n1 3\n2 4\n A\n0 2\n1 3\n2 4\n\nif you want to be able to index then use a dictionary:\ndfs = {}\nfor n in range (0,5):\n dfs[f'var{n+1}'] = myclass(x=f'var{n+1}').output\n\ndfs['var3']\n\nOutput:\n A\n0 2\n1 3\n2 4\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas" ]
stackoverflow_0074673068_dataframe_pandas.txt
Q: Validate if my mini project game can be past through Test_Python.py? So basically i am creating my version of rock ,paper, scissor game as a python project and i need help running it through by testing or passing it which i forgot how to becuase i took a few days break working on my project and forgot how to test it and this is my project: import random import math def play(): user = input("What's your choice? 'g' for gun, 'i' for ice, 'k' for knife\n") user = user.lower() computer = random.choice(['g', 'i', 'k']) if user == computer: return (0, user, computer) if is_win(user, computer): return (1, user, computer) return (-1, user, computer) def is_win(player, opponent): if (player == 'g' and opponent == 'k') or (player == 'k' and opponent == 'i') or (player == 'i' and opponent == 'k'): return True return False def play_best_of(n): player_wins = 0 computer_wins = 0 wins_necessary = math.ceil(n/2) while player_wins < wins_necessary and computer_wins < wins_necessary: result, user, computer = play() if result == 0: print('It is a tie. You and the Machine have both chosen {}. \n'.format(user)) elif result == 1: player_wins += 1 print('You chose {} and the Machine chose {}. Yippy You won! ;[\n'.format(user, computer)) else: computer_wins += 1 print('You chose {} and the Machine chose {}. Darn it You lost! :[\n'.format(user, computer)) if player_wins > computer_wins: print('You have won the best of {} games Congrats! What a player :D'.format(n)) else: print('Sadly, the Machine has won the best of {} games. Better luck next time!'.format(n)) if __name__ == '__main__': play_best_of(3) (Note: This is all i came up with i just need help passing through it, how do i test it basically?) i did tr but i keep getting pops up of a few problems here and there. i do have from project import play, is_win, play_best_of def play(): def is_win(): def play_best_of(n): if __name__ == '__main__': play_best_of(3) for my test prompt but i forgot how to assert i think? PLEASE HELP! A: I believe you're talking about writing unit tests. There are two libraries commonly used for unit testing in Python, the built in unittest library and the third-party pytest. I would personally recommend that you use pytest because the syntax is much simpler. Refer to the unittest and pytest docs for further usage information. A basic passing pytest example: test_win.py from project import is_win def test_win_gk(): assert is_win('g', 'k') == True You can run this test by executing pytest in the same directory. This will execute every test in each file prefixed or suffixed with test. (test_something.py or something_test.py)
Validate if my mini project game can be past through Test_Python.py?
So basically i am creating my version of rock ,paper, scissor game as a python project and i need help running it through by testing or passing it which i forgot how to becuase i took a few days break working on my project and forgot how to test it and this is my project: import random import math def play(): user = input("What's your choice? 'g' for gun, 'i' for ice, 'k' for knife\n") user = user.lower() computer = random.choice(['g', 'i', 'k']) if user == computer: return (0, user, computer) if is_win(user, computer): return (1, user, computer) return (-1, user, computer) def is_win(player, opponent): if (player == 'g' and opponent == 'k') or (player == 'k' and opponent == 'i') or (player == 'i' and opponent == 'k'): return True return False def play_best_of(n): player_wins = 0 computer_wins = 0 wins_necessary = math.ceil(n/2) while player_wins < wins_necessary and computer_wins < wins_necessary: result, user, computer = play() if result == 0: print('It is a tie. You and the Machine have both chosen {}. \n'.format(user)) elif result == 1: player_wins += 1 print('You chose {} and the Machine chose {}. Yippy You won! ;[\n'.format(user, computer)) else: computer_wins += 1 print('You chose {} and the Machine chose {}. Darn it You lost! :[\n'.format(user, computer)) if player_wins > computer_wins: print('You have won the best of {} games Congrats! What a player :D'.format(n)) else: print('Sadly, the Machine has won the best of {} games. Better luck next time!'.format(n)) if __name__ == '__main__': play_best_of(3) (Note: This is all i came up with i just need help passing through it, how do i test it basically?) i did tr but i keep getting pops up of a few problems here and there. i do have from project import play, is_win, play_best_of def play(): def is_win(): def play_best_of(n): if __name__ == '__main__': play_best_of(3) for my test prompt but i forgot how to assert i think? PLEASE HELP!
[ "I believe you're talking about writing unit tests. There are two libraries commonly used for unit testing in Python, the built in unittest library and the third-party pytest.\nI would personally recommend that you use pytest because the syntax is much simpler. Refer to the unittest and pytest docs for further usage information.\nA basic passing pytest example:\ntest_win.py\nfrom project import is_win\n\ndef test_win_gk():\n assert is_win('g', 'k') == True\n\nYou can run this test by executing pytest in the same directory. This will execute every test in each file prefixed or suffixed with test. (test_something.py or something_test.py)\n" ]
[ 0 ]
[]
[]
[ "project", "python", "unit_testing" ]
stackoverflow_0074673060_project_python_unit_testing.txt
Q: Jfrog Xray services is Up and Running but not Reflecting in Jfrog UI I have installed Xray in seperate server, while starting the service it is throwing below error. โ— xray.service - Xray service Loaded: loaded (/usr/lib/systemd/system/xray.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sat 2022-12-03 12:36:50 IST; 1min 17s ago Process: 1217 ExecStart=/opt/jfrog/xray/app/bin/xray.sh start (code=exited, status=1/FAILURE) Main PID: 1217 (code=exited, status=1/FAILURE) And in systemDiagnostics.log it says yaml file doesn't exists, but i can able to see the system.yarml file in exact location. [WARN ] Error while initializing File resolver : Config file does not exists : /opt/jfrog/xray/var/etc/system.yaml [INFO ] Router external port (8082) is open [INFO ] Router internal port (8046) is open [INFO ] Router traefik port (8049) is open [INFO ] Router grpc port (8047) is open [INFO ] XrayServer port (8000) is open [INFO ] XrayAnalysis port (7000) is open [INFO ] XrayIndexer port (7002) is open [INFO ] XrayPersist port (7003) is open [INFO ] Ulimit level for processes is satisfactory--no change required ulimit value(4096) is below expected value(100000) [ERROR] Ulimit level for open files is less than the recommended minimum 100000 [INFO ] Router external port (8082) is not blocked by firewall [INFO ] Router internal port (8046) is not blocked by firewall [INFO ] Router grpc port (8047) is not blocked by firewall [INFO ] Router traefik port (8049) is not blocked by firewall [INFO ] XrayServer port (8000) is not blocked by firewall [INFO ] XrayAnalysis port (7000) is not blocked by firewall [INFO ] XrayIndexer port (7002) is not blocked by firewall [INFO ] XrayPersist port (7003) is not blocked by firewall [INFO ] Router external port (8082) is not blocked by iptables [INFO ] Router internal port (8046) is not blocked by iptables [INFO ] Router grpc port (8047) is not blocked by iptables [INFO ] Router traefik port (8049) is not blocked by iptables [INFO ] XrayServer port (8000) is not blocked by iptables [INFO ] XrayAnalysis port (7000) is not blocked by iptables [INFO ] XrayIndexer port (7002) is not blocked by iptables [INFO ] XrayPersist port (7003) is not blocked by iptables [INFO ] Router external port (8082) is not blocked by ip6tables Edit 1: console.log It says master.key file is not present, but i can see it is there in that location. [INFO ] JFrog Observability (jfob) service initialization started. Version: 1.11.0 (revision: 38bcc4c00d, build date: 2022-09-16T11:08:32Z) PID: 5922 Home: /opt/jfrog/xray [DEBUG] Resolved system configuration file path: /opt/jfrog/xray/var/etc/system.yaml Logging configuration has both console=true and filepath='router-service.log'; ignoring console. 2022-12-03T07:05:40.342Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:77 ] [main ] [] - Router (jfrou) service initialization started. Version: 7.51.0-1 Revision: fd36933e55dfc526ec51ec35f5face80a80debac PID: 5895 Home: /opt/jfrog/xray 2022-12-03T07:05:40.342Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:80 ] [main ] [] - JFrog Router IP: 192.168.71.30 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [49203c85e5fdf6fe] [run_main:351 ] [main ] Loading config, service name: analysis 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [49203c85e5fdf6fe] [start_xray_server:288 ] [main ] Xray Analysis (analysis) service initialization started 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [ ] [fileutil:73 ] [main ] no master key found, cause: failed resolving 'shared.security.masterKey' key; file does not exist: /opt/jfrog/xray/var/etc/security/master.key 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [ ] [connection_pool_holder:94 ] [main ] connecting to postgresql attempt #1 2022-12-03T07:05:41.343Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:130 ] [main ] [] - System configuration encryption report: shared.database.password: encrypted successfully shared.multiTenant.tenantRegistryClient.clientCertKey: does not exist in the config file shared.newrelic.licenseKey: does not exist in the config file shared.rabbitMq.password: encrypted successfully shared.security.joinKey: encrypted successfully shared.security.joinKeyFile: file '/opt/jfrog/xray/var/etc/security/join.key' - open /opt/jfrog/xray/var/etc/security/join.key: no such file or directory 2022-12-03T07:05:41.344Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:85 ] [main ] [] - JFrog Router Service ID: jfrou@0abcdefgh 2022-12-03T07:05:41.344Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:86 Edit 2 Now Xray is Service is Up and Running but there is not changes in Jfrog UI when i click on Xray Tab??? below is the error am gettig in jfrog systemlog Forbidden UI REST: Xray is not configured on the repo 'libs-release-local' or file 'db2jcc4/db2jcc4/10.5.0.5/db2jcc4-10.5.0.5.jar' is not handled by Xray Xray Service.log 2022-12-04T02:28:38.441Z ^[[33m[jfxr ]^[[0m ^[[34m[INFO ]^[[0m [ ] [access_client_bootstrap:182 ] [main ] (--wrapper--)Cluster join: Retry 85: Service registry ping failed, will retry. Error: Error while trying to connect to local router at address 'http://localhost:8046/access': Get "http://localhost:8046/access/api/v1/system/ping": dial tcp [::1]:8046: connect: connection refused Do i need to make any manual changes in Jfrog UI to enable the Xray at UI level? Thanks in advance. A: The shared details are not helping to find out the cause. Can you navigate to location $JFROG_HOME/xray/var/log (mostly /opt/jfrog/xray/var/log) and check for console.log. This should have right details of the issue. You may also want to have a look at xray-server-service.log. If nothing is identified from these files, share the relevant log snippet. You can also navigate to $JFROG_HOME/xray/app/bin and start the application manually as part of troubleshooting. A: Could you please confirm if you are trying to open Artifactory platform url and not able to see Xray in it ? If yes, can you make sure the below two details are present in xray server. JfrogUrl - URL to the machine where JFrog Artifactory is deployed, or the load balancer pointing to it. It is recommended to use DNS names rather than direct IPs. For example: "http://jfrog.acme.com or http://10.20.30.40:8082". Note that /artifactory context is not longer required. Set it in the Shared Configurations section of the $JFROG_HOME/xray/var/etc/system.yaml file. join.key - This is the "secret" key required by Artifactory for registering and authenticating the Xray server. You can fetch the Artifactory joinKey (join Key) from the JPD UI in the User Management | Settings | Join Key. Set the join.key used by your Artifactory server in the Shared Configurations section of the $JFROG_HOME/xray/var/etc/system.yaml file. If Xray is connected successfully, ideally, you should be able to see Xray in Artifactory platform UI. If not, revisit the console log again.
Jfrog Xray services is Up and Running but not Reflecting in Jfrog UI
I have installed Xray in seperate server, while starting the service it is throwing below error. โ— xray.service - Xray service Loaded: loaded (/usr/lib/systemd/system/xray.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sat 2022-12-03 12:36:50 IST; 1min 17s ago Process: 1217 ExecStart=/opt/jfrog/xray/app/bin/xray.sh start (code=exited, status=1/FAILURE) Main PID: 1217 (code=exited, status=1/FAILURE) And in systemDiagnostics.log it says yaml file doesn't exists, but i can able to see the system.yarml file in exact location. [WARN ] Error while initializing File resolver : Config file does not exists : /opt/jfrog/xray/var/etc/system.yaml [INFO ] Router external port (8082) is open [INFO ] Router internal port (8046) is open [INFO ] Router traefik port (8049) is open [INFO ] Router grpc port (8047) is open [INFO ] XrayServer port (8000) is open [INFO ] XrayAnalysis port (7000) is open [INFO ] XrayIndexer port (7002) is open [INFO ] XrayPersist port (7003) is open [INFO ] Ulimit level for processes is satisfactory--no change required ulimit value(4096) is below expected value(100000) [ERROR] Ulimit level for open files is less than the recommended minimum 100000 [INFO ] Router external port (8082) is not blocked by firewall [INFO ] Router internal port (8046) is not blocked by firewall [INFO ] Router grpc port (8047) is not blocked by firewall [INFO ] Router traefik port (8049) is not blocked by firewall [INFO ] XrayServer port (8000) is not blocked by firewall [INFO ] XrayAnalysis port (7000) is not blocked by firewall [INFO ] XrayIndexer port (7002) is not blocked by firewall [INFO ] XrayPersist port (7003) is not blocked by firewall [INFO ] Router external port (8082) is not blocked by iptables [INFO ] Router internal port (8046) is not blocked by iptables [INFO ] Router grpc port (8047) is not blocked by iptables [INFO ] Router traefik port (8049) is not blocked by iptables [INFO ] XrayServer port (8000) is not blocked by iptables [INFO ] XrayAnalysis port (7000) is not blocked by iptables [INFO ] XrayIndexer port (7002) is not blocked by iptables [INFO ] XrayPersist port (7003) is not blocked by iptables [INFO ] Router external port (8082) is not blocked by ip6tables Edit 1: console.log It says master.key file is not present, but i can see it is there in that location. [INFO ] JFrog Observability (jfob) service initialization started. Version: 1.11.0 (revision: 38bcc4c00d, build date: 2022-09-16T11:08:32Z) PID: 5922 Home: /opt/jfrog/xray [DEBUG] Resolved system configuration file path: /opt/jfrog/xray/var/etc/system.yaml Logging configuration has both console=true and filepath='router-service.log'; ignoring console. 2022-12-03T07:05:40.342Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:77 ] [main ] [] - Router (jfrou) service initialization started. Version: 7.51.0-1 Revision: fd36933e55dfc526ec51ec35f5face80a80debac PID: 5895 Home: /opt/jfrog/xray 2022-12-03T07:05:40.342Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:80 ] [main ] [] - JFrog Router IP: 192.168.71.30 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [49203c85e5fdf6fe] [run_main:351 ] [main ] Loading config, service name: analysis 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [49203c85e5fdf6fe] [start_xray_server:288 ] [main ] Xray Analysis (analysis) service initialization started 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [ ] [fileutil:73 ] [main ] no master key found, cause: failed resolving 'shared.security.masterKey' key; file does not exist: /opt/jfrog/xray/var/etc/security/master.key 2022-12-03T07:05:40.505Z ^[[33m[jfxan]^[[0m ^[[34m[INFO ]^[[0m [ ] [connection_pool_holder:94 ] [main ] connecting to postgresql attempt #1 2022-12-03T07:05:41.343Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:130 ] [main ] [] - System configuration encryption report: shared.database.password: encrypted successfully shared.multiTenant.tenantRegistryClient.clientCertKey: does not exist in the config file shared.newrelic.licenseKey: does not exist in the config file shared.rabbitMq.password: encrypted successfully shared.security.joinKey: encrypted successfully shared.security.joinKeyFile: file '/opt/jfrog/xray/var/etc/security/join.key' - open /opt/jfrog/xray/var/etc/security/join.key: no such file or directory 2022-12-03T07:05:41.344Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:85 ] [main ] [] - JFrog Router Service ID: jfrou@0abcdefgh 2022-12-03T07:05:41.344Z ^[[36m[jfrou]^[[0m ^[[34m[INFO ]^[[0m [7a8ced89c2f6d1db] [bootstrap.go:86 Edit 2 Now Xray is Service is Up and Running but there is not changes in Jfrog UI when i click on Xray Tab??? below is the error am gettig in jfrog systemlog Forbidden UI REST: Xray is not configured on the repo 'libs-release-local' or file 'db2jcc4/db2jcc4/10.5.0.5/db2jcc4-10.5.0.5.jar' is not handled by Xray Xray Service.log 2022-12-04T02:28:38.441Z ^[[33m[jfxr ]^[[0m ^[[34m[INFO ]^[[0m [ ] [access_client_bootstrap:182 ] [main ] (--wrapper--)Cluster join: Retry 85: Service registry ping failed, will retry. Error: Error while trying to connect to local router at address 'http://localhost:8046/access': Get "http://localhost:8046/access/api/v1/system/ping": dial tcp [::1]:8046: connect: connection refused Do i need to make any manual changes in Jfrog UI to enable the Xray at UI level? Thanks in advance.
[ "The shared details are not helping to find out the cause. Can you navigate to location $JFROG_HOME/xray/var/log (mostly /opt/jfrog/xray/var/log) and check for console.log. This should have right details of the issue.\nYou may also want to have a look at xray-server-service.log. If nothing is identified from these files, share the relevant log snippet.\nYou can also navigate to $JFROG_HOME/xray/app/bin and start the application manually as part of troubleshooting.\n", "Could you please confirm if you are trying to open Artifactory platform url and not able to see Xray in it ?\nIf yes, can you make sure the below two details are present in xray server.\n\nJfrogUrl - URL to the machine where JFrog Artifactory is deployed, or the load balancer pointing to it. It is recommended to use DNS names rather than direct IPs. For example: \"http://jfrog.acme.com or http://10.20.30.40:8082\". Note that /artifactory context is not longer required.\nSet it in the Shared Configurations section of the $JFROG_HOME/xray/var/etc/system.yaml file.\n\njoin.key - This is the \"secret\" key required by Artifactory for registering and authenticating the Xray server.\nYou can fetch the Artifactory joinKey (join Key) from the JPD UI in the User Management | Settings | Join Key.\nSet the join.key used by your Artifactory server in the Shared Configurations section of the $JFROG_HOME/xray/var/etc/system.yaml file.\n\n\nIf Xray is connected successfully, ideally, you should be able to see Xray in Artifactory platform UI. If not, revisit the console log again.\n" ]
[ 1, 0 ]
[]
[]
[ "jenkins", "jfrog", "jfrog_cli", "jfrog_xray" ]
stackoverflow_0074664784_jenkins_jfrog_jfrog_cli_jfrog_xray.txt
Q: Prevent the tooltip from disappearing in chart.js line graph Is it possible to prevent the tooltip from disappearing when clicking outside the line graph itself? I want it to always be visible on the latest datapoint clicked. Im using chart.js 3.9.1 in vue Thanks :) A: Please try it: Namespace: options.plugins.tooltip, the global options for the chart tooltips is defined in Chart.defaults.plugins.tooltip. for complete details, you can check this link, my friend.
Prevent the tooltip from disappearing in chart.js line graph
Is it possible to prevent the tooltip from disappearing when clicking outside the line graph itself? I want it to always be visible on the latest datapoint clicked. Im using chart.js 3.9.1 in vue Thanks :)
[ "Please try it:\nNamespace: options.plugins.tooltip, the global options for the chart tooltips is defined in Chart.defaults.plugins.tooltip.\nfor complete details, you can check this link, my friend.\n" ]
[ 0 ]
[]
[]
[ "chart.js", "chart.jsv3", "typescript", "vue.js" ]
stackoverflow_0074670238_chart.js_chart.jsv3_typescript_vue.js.txt
Q: Node path relative same directory missing "./" prefix Node's path.relative has an unexpected quirk when resolving a file that is in the from directory. Below the path.relative returns meta_url.ts instead of ./meta_url.ts, is there a node path function to help me convert meta_url.ts to ./meta_url.ts in an os-agnostic way? const from = "/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import" const to = "./meta_url.ts" path.relative(from, to) // meta_url.ts A: Yes, there is a way to convert meta_url.ts to ./meta_url.ts in a way that is independent of the operating system. You can use the path.join() method for this. The path.join() method takes any number of arguments and automatically concatenates them together with the appropriate path separator for the current operating system. Here's how you can use path.join() to convert meta_url.ts to ./meta_url.ts const from = "/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import" const to = "./meta_url.ts" const relativePath = path.join('.', path.relative(from, to)); console.log(relativePath); // prints "./meta_url.ts" This will work on any operating system, because path.join() automatically inserts the appropriate path separator for the current operating system. A: Posting what ChatGPT gave me which is wrong. Yes, you can use the path.resolve() method to get the absolute path of a file, and then use the path.relative() method to get the relative path of that file from the from directory. Here is an example of how you could do this: const from = "/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import"; const to = "./meta_url.ts"; // Use path.resolve() to get the absolute path of the "to" file. const toAbsolute = path.resolve(to); // Use path.relative() to get the relative path of the "to" file from the "from" directory. const relativePath = path.relative(from, toAbsolute); console.log(relativePath); // ./meta_url.ts In this example, we first use the path.resolve() method to get the absolute path of the to file. Then we use the path.relative() method to get the relative path of the to file from the from directory. This ensures that the relative path always starts with a ./ prefix, regardless of the current working directory.
Node path relative same directory missing "./" prefix
Node's path.relative has an unexpected quirk when resolving a file that is in the from directory. Below the path.relative returns meta_url.ts instead of ./meta_url.ts, is there a node path function to help me convert meta_url.ts to ./meta_url.ts in an os-agnostic way? const from = "/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import" const to = "./meta_url.ts" path.relative(from, to) // meta_url.ts
[ "Yes, there is a way to convert meta_url.ts to ./meta_url.ts in a way that is independent of the operating system. You can use the path.join() method for this. The path.join() method takes any number of arguments and automatically concatenates them together with the appropriate path separator for the current operating system.\nHere's how you can use path.join() to convert meta_url.ts to ./meta_url.ts\nconst from = \"/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import\"\nconst to = \"./meta_url.ts\"\n\nconst relativePath = path.join('.', path.relative(from, to));\n\nconsole.log(relativePath); // prints \"./meta_url.ts\"\n\nThis will work on any operating system, because path.join() automatically inserts the appropriate path separator for the current operating system.\n", "\nPosting what ChatGPT gave me which is wrong.\n\nYes, you can use the path.resolve() method to get the absolute path of a file, and then use the path.relative() method to get the relative path of that file from the from directory.\nHere is an example of how you could do this:\nconst from = \"/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import\";\nconst to = \"./meta_url.ts\";\n\n// Use path.resolve() to get the absolute path of the \"to\" file.\nconst toAbsolute = path.resolve(to);\n\n// Use path.relative() to get the relative path of the \"to\" file from the \"from\" directory.\nconst relativePath = path.relative(from, toAbsolute);\n\nconsole.log(relativePath); // ./meta_url.ts\n\nIn this example, we first use the path.resolve() method to get the absolute path of the to file. Then we use the path.relative() method to get the relative path of the to file from the from directory. This ensures that the relative path always starts with a ./ prefix, regardless of the current working directory.\n" ]
[ 0, 0 ]
[]
[]
[ "node.js", "path" ]
stackoverflow_0074538224_node.js_path.txt
Q: variable initialized in loop but cannot be resolved in body trying to iterate through an array list with a for loop and initialized a variable p in the loop. when using the variable as an index to get from the arraylist it is giving me a p cannot be resolved to a variable. for (int p = 0; p < this.playerList.size(); p++); Player tempPlayer = this.playerList.get(p); StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()}; tempPlayer.setHoleCards(tempHoleCards); The variable p is already initialized in the loop but cannot be found when using it for the get method for the array list A: Try removing the semicolon and replacing it with brackets: for (int p = 0; p < this.playerList.size(); p++){ Player tempPlayer = this.playerList.get(p); StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()}; tempPlayer.setHoleCards(tempHoleCards); } A: You have a for loop with no body. Remove the ; at the end of the for loop. Also, your intention is to have the three statements within the body of the for loop. So, you should enclose them within braces. for (int p = 0; p < this.playerList.size(); p++) { Player tempPlayer = this.playerList.get(p); StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()}; tempPlayer.setHoleCards(tempHoleCards); .... } A: The contents of the loop need to be in {}. So this should work: for (int p = 0; p < this.playerList.size(); p++) { Player tempPlayer = this.playerList.get(p); StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()}; tempPlayer.setHoleCards(tempHoleCards); }
variable initialized in loop but cannot be resolved in body
trying to iterate through an array list with a for loop and initialized a variable p in the loop. when using the variable as an index to get from the arraylist it is giving me a p cannot be resolved to a variable. for (int p = 0; p < this.playerList.size(); p++); Player tempPlayer = this.playerList.get(p); StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()}; tempPlayer.setHoleCards(tempHoleCards); The variable p is already initialized in the loop but cannot be found when using it for the get method for the array list
[ "Try removing the semicolon and replacing it with brackets:\nfor (int p = 0; p < this.playerList.size(); p++){\n Player tempPlayer = this.playerList.get(p);\n StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()};\n tempPlayer.setHoleCards(tempHoleCards);\n}\n\n", "You have a for loop with no body. Remove the ; at the end of the for loop.\nAlso, your intention is to have the three statements within the body of the for loop. So, you should enclose them within braces.\nfor (int p = 0; p < this.playerList.size(); p++) {\n Player tempPlayer = this.playerList.get(p);\n StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()};\n tempPlayer.setHoleCards(tempHoleCards);\n ....\n}\n\n", "The contents of the loop need to be in {}. So this should work:\nfor (int p = 0; p < this.playerList.size(); p++) {\n Player tempPlayer = this.playerList.get(p);\n StandardCard[] tempHoleCards = {gameDeck.getNextCard(), gameDeck.getNextCard()};\n tempPlayer.setHoleCards(tempHoleCards);\n}\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "java" ]
stackoverflow_0074673110_java.txt
Q: How do I create a magic square matrix using python A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the diagonal of the matrix remain same This code is working only for odd numbers but not even numbers. here's my code that i tried but it didn't work ` def matrix(n): m = [[0 for x in range(n)] for y in range(n)] i = n / 2 j = n - 1 num = 1 while num <= (n * n): if i == -1 and j == n: j = n - 2 i = 0 else: if j == n: j = 0 if i < 0: i = n - 1 if m[int(i)][int(j)]: j = j - 2 i = i + 1 continue else: m[int(i)][int(j)] = num num = num + 1 j = j + 1 i = i - 1 print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n") for i in range(0, n): for j in range(0, n): print('%2d ' % (m[i][j]),end = '') if j == n - 1: print() n=int(input("Number of rows of matrix:")) matrix(n) ` A: def matrix(n): m = [[0 for x in range(n)] for y in range(n)] i = n / 2 j = n - 1 num = 1 while num <= (n * n): if i == -1 and j == n: j = n - 2 i = 0 else: if j == n: j = 0 if i < 0: i = n - 1 if m[int(i)][int(j)]: j = j - 2 i = i + 1 continue else: m[int(i)][int(j)] = num num = num + 1 j = j + 1 i = i - 1 print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n") for i in range(0, n): for j in range(0, n): print('%2d ' % (m[i][j]),end = '') if j == n - 1: print() n=int(input("Number of rows of matrix:")) matrix(n)
How do I create a magic square matrix using python
A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the diagonal of the matrix remain same This code is working only for odd numbers but not even numbers. here's my code that i tried but it didn't work ` def matrix(n): m = [[0 for x in range(n)] for y in range(n)] i = n / 2 j = n - 1 num = 1 while num <= (n * n): if i == -1 and j == n: j = n - 2 i = 0 else: if j == n: j = 0 if i < 0: i = n - 1 if m[int(i)][int(j)]: j = j - 2 i = i + 1 continue else: m[int(i)][int(j)] = num num = num + 1 j = j + 1 i = i - 1 print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n") for i in range(0, n): for j in range(0, n): print('%2d ' % (m[i][j]),end = '') if j == n - 1: print() n=int(input("Number of rows of matrix:")) matrix(n) `
[ "def matrix(n): \nm = [[0 for x in range(n)] \n for y in range(n)]\ni = n / 2\nj = n - 1\nnum = 1\nwhile num <= (n * n): \n if i == -1 and j == n:\n j = n - 2\n i = 0\n else:\n if j == n: \n j = 0 \n if i < 0: \n i = n - 1\n if m[int(i)][int(j)]:\n j = j - 2\n i = i + 1\n continue\n else: \n m[int(i)][int(j)] = num \n num = num + 1\n j = j + 1\n i = i - 1\nprint (\"Sum of eggs in each row or column and diagonal \",n * (n * n + 1) / 2, \"\\n\") \nfor i in range(0, n): \n for j in range(0, n): \n print('%2d ' % (m[i][j]),end = '') \n if j == n - 1: \n print()\n\nn=int(input(\"Number of rows of matrix:\"))\nmatrix(n)\n" ]
[ 0 ]
[]
[]
[ "computer_science", "magic_square", "matrix", "python", "python_3.x" ]
stackoverflow_0074384748_computer_science_magic_square_matrix_python_python_3.x.txt
Q: referencing a non primary key attribute from another table I'm trying to "reference" (or something like it) a non-primary attribute from a table. Say I have two tables from a database called DoctorsOffice. CREATE TABLE DOCTOR ( Doctor_ID varchar(10) NOT NULL, -- PRIMARY KEY Last_name varchar(15) NOT NULL, First_name varchar(20) NOT NULL, Phone_num varchar(15), Specialty varchar(12) NOT NULL, Salary DEC(10, 2), PRIMARY KEY (Doctor_ID) ); CREATE TABLE APPOINTMENT( Appointment_num varchar(9) NOT NULL, -- PRIMARY KEY Test_given varchar(9) NOT NULL, Patient_ssn char(9) NOT NULL, Doctor_name varchar(20) NOT NULL, Doctor_ID varchar(10) NOT NULL, Date Date, Room_num char(2) NOT NULL, PRIMARY KEY (Appointment_num), FOREIGN KEY (Doctor_name) REFERENCES DOCTOR(First_name), -- the above line of code gives me an error FOREIGN KEY (Doctor_ID) REFERENCES DOCTOR(Doctor_ID) ); Foreign keys only reference primary keys from other tables. Still, the relational diagram I'm supposed to follow shows an Appointment table attribute Doctor_ID referencing the primary key Doctor_ID and Doctor_name from the Appointment table referencing First_name from the DOCTOR table. First_name isn't a primary key from the DOCTOR table. So, how would I reference an attribute that isn't a primary key? There are arrows from the Appointment table attributes Doctor_name and Doctor_ID pointing at the primary key DOCTOR_ID and normal attribute First_name from the DOCTOR table. A: If First_name were a key then it could be referenced from another table. For example: CREATE TABLE DOCTOR ( Doctor_ID varchar(10) NOT NULL, Last_name varchar(15) NOT NULL, First_name varchar(20) UNIQUE NOT NULL, -- UNIQUE NOT NULL makes it a key Phone_num varchar(15), Specialty varchar(12) NOT NULL, Salary DEC(10, 2), PRIMARY KEY (Doctor_ID) ); See running example at db<>fiddle. Note: I don't think the doctor first name is unique. Though the solution above will work from the technical standpoint, I think you need to rethink the database model.
referencing a non primary key attribute from another table
I'm trying to "reference" (or something like it) a non-primary attribute from a table. Say I have two tables from a database called DoctorsOffice. CREATE TABLE DOCTOR ( Doctor_ID varchar(10) NOT NULL, -- PRIMARY KEY Last_name varchar(15) NOT NULL, First_name varchar(20) NOT NULL, Phone_num varchar(15), Specialty varchar(12) NOT NULL, Salary DEC(10, 2), PRIMARY KEY (Doctor_ID) ); CREATE TABLE APPOINTMENT( Appointment_num varchar(9) NOT NULL, -- PRIMARY KEY Test_given varchar(9) NOT NULL, Patient_ssn char(9) NOT NULL, Doctor_name varchar(20) NOT NULL, Doctor_ID varchar(10) NOT NULL, Date Date, Room_num char(2) NOT NULL, PRIMARY KEY (Appointment_num), FOREIGN KEY (Doctor_name) REFERENCES DOCTOR(First_name), -- the above line of code gives me an error FOREIGN KEY (Doctor_ID) REFERENCES DOCTOR(Doctor_ID) ); Foreign keys only reference primary keys from other tables. Still, the relational diagram I'm supposed to follow shows an Appointment table attribute Doctor_ID referencing the primary key Doctor_ID and Doctor_name from the Appointment table referencing First_name from the DOCTOR table. First_name isn't a primary key from the DOCTOR table. So, how would I reference an attribute that isn't a primary key? There are arrows from the Appointment table attributes Doctor_name and Doctor_ID pointing at the primary key DOCTOR_ID and normal attribute First_name from the DOCTOR table.
[ "If First_name were a key then it could be referenced from another table. For example:\nCREATE TABLE DOCTOR (\n Doctor_ID varchar(10) NOT NULL,\n Last_name varchar(15) NOT NULL,\n First_name varchar(20) UNIQUE NOT NULL, -- UNIQUE NOT NULL makes it a key\n Phone_num varchar(15),\n Specialty varchar(12) NOT NULL,\n Salary DEC(10, 2),\n PRIMARY KEY (Doctor_ID)\n);\n\nSee running example at db<>fiddle.\nNote: I don't think the doctor first name is unique. Though the solution above will work from the technical standpoint, I think you need to rethink the database model.\n" ]
[ 1 ]
[ "I guess that it is not possible, i tried to do in workbench but when you gonna do a reference you need a primary key\n", "In SQL, you cannot define a foreign key that references a non-primary key attribute in another table. A foreign key is used to establish a relationship between two tables, and in order for that relationship to be valid, the foreign key must reference a primary key in the other table.\nIn your example, you are trying to define a foreign key in the APPOINTMENT table that references the First_name attribute in the DOCTOR table. However, First_name is not the primary key in the DOCTOR table; the primary key is Doctor_ID. Therefore, you cannot define a foreign key that references First_name in the APPOINTMENT table.\nInstead, you should define your foreign key to reference the Doctor_ID attribute in the DOCTOR table, since that is the primary key. Here is how you would do that:\nCREATE TABLE APPOINTMENT(\n Appointment_num varchar(9) NOT NULL, -- PRIMARY KEY\n Test_given varchar(9) NOT NULL,\n Patient_ssn char(9) NOT NULL,\n Doctor_name varchar(20) NOT NULL,\n Doctor_ID varchar(10) NOT NULL,\n Date Date,\n Room_num char(2) NOT NULL,\n PRIMARY KEY (Appointment_num),\n FOREIGN KEY (Doctor_ID) REFERENCES DOCTOR(Doctor_ID)\n);\n\n\nThis will define the foreign key Doctor_ID in the APPOINTMENT table, which will reference the primary key Doctor_ID in the DOCTOR table. This will establish a valid relationship between the two tables, and you will be able to use the Doctor_ID attribute in the APPOINTMENT table to refer to the corresponding row in the DOCTOR table.\nIf you want to reference the First_name attribute in the APPOINTMENT table, you can do that without using a foreign key. You can simply include the First_name attribute in the APPOINTMENT table and use it to store the first name of the doctor associated with each appointment. However, this will not establish a relationship between the two tables, and you will not be able to enforce referential integrity using a foreign key constraint. You will have to manage the relationship between the two tables manually.\n" ]
[ -1, -1 ]
[ "database", "database_normalization", "mysql", "relational_database", "sql" ]
stackoverflow_0074672164_database_database_normalization_mysql_relational_database_sql.txt
Q: Get confidence interval from sklearn linear regression in python I want to get a confidence interval of the result of a linear regression. I'm working with the boston house price dataset. I've found this question: How to calculate the 99% confidence interval for the slope in a linear regression model in python? However, this doesn't quite answer my question. Here is my code: import numpy as np import matplotlib.pyplot as plt from math import pi import pandas as pd import seaborn as sns from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score # import the data boston_dataset = load_boston() boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) boston['MEDV'] = boston_dataset.target X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns=['LSTAT', 'RM']) Y = boston['MEDV'] # splits the training and test data set in 80% : 20% # assign random_state to any value.This ensures consistency. X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=5) lin_model = LinearRegression() lin_model.fit(X_train, Y_train) # model evaluation for training set y_train_predict = lin_model.predict(X_train) rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict))) r2 = r2_score(Y_train, y_train_predict) # model evaluation for testing set y_test_predict = lin_model.predict(X_test) # root mean square error of the model rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict))) # r-squared score of the model r2 = r2_score(Y_test, y_test_predict) plt.scatter(Y_test, y_test_predict) plt.show() How can I get, for instance, the 95% or 99% confidence interval from this? Is there some sort of in-built function or piece of code? A: I am not sure if there is any in-built function for this purpose, but what I do is create a loop on n no. of times and compare the accuracy of all the models and save the model with highest accuracy with pickle and use reuse it later. Here goes the code: for _ in range(30): x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.1) linear = linear_model.LinearRegression() linear.fit(x_train, y_train) acc = linear.score(x_test, y_test) print("Accuracy: " + str(acc)) if acc > best: best = acc with open("confidence_interval.pickle", "wb") as f: pickle.dump(linear, f) print("The best Accuracy: ", best) You can always make changes to the given variables as I know the variables that you have provided varies greatly from mine. and if you want to predict the class possibilities you can use predict_proba. Refer to this link for difference between predict and predict_proba https://www.kaggle.com/questions-and-answers/82657 A: If you're looking to compute the confidence interval of the regression parameters, one way is to manually compute it using the results of LinearRegression from scikit-learn and numpy methods. The code below computes the 95%-confidence interval (alpha=0.05). alpha=0.01 would compute 99%-confidence interval etc. import numpy as np import pandas as pd from scipy import stats from sklearn.linear_model import LinearRegression alpha = 0.05 # for 95% confidence interval; use 0.01 for 99%-CI. # fit a sklearn LinearRegression model lin_model = LinearRegression().fit(X_train, Y_train) # the coefficients of the regression model coefs = np.r_[[lin_model.intercept_], lin_model.coef_] # build an auxiliary dataframe with the constant term in it X_aux = X_train.copy() X_aux.insert(0, 'const', 1) # degrees of freedom dof = -np.diff(X_aux.shape)[0] # Student's t-distribution table lookup t_val = stats.t.isf(alpha/2, dof) # MSE of the residuals mse = np.sum((Y_train - lin_model.predict(X_train)) ** 2) / dof # inverse of the variance of the parameters var_params = np.diag(np.linalg.inv(X_aux.T.dot(X_aux))) # distance between lower and upper bound of CI gap = t_val * np.sqrt(mse * var_params) conf_int = pd.DataFrame({'lower': coefs - gap, 'upper': coefs + gap}, index=X_aux.columns) Using the Boston housing dataset, the above code produces the dataframe below: If this is too much manual code, you can always resort to the statsmodels and use its conf_int method: import statsmodels.api as sm alpha = 0.05 # 95% confidence interval lr = sm.OLS(Y_train, sm.add_constant(X_train)).fit() conf_interval = lr.conf_int(alpha) Since it uses the same formula, it produces the same output as above. Stats reference
Get confidence interval from sklearn linear regression in python
I want to get a confidence interval of the result of a linear regression. I'm working with the boston house price dataset. I've found this question: How to calculate the 99% confidence interval for the slope in a linear regression model in python? However, this doesn't quite answer my question. Here is my code: import numpy as np import matplotlib.pyplot as plt from math import pi import pandas as pd import seaborn as sns from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score # import the data boston_dataset = load_boston() boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) boston['MEDV'] = boston_dataset.target X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns=['LSTAT', 'RM']) Y = boston['MEDV'] # splits the training and test data set in 80% : 20% # assign random_state to any value.This ensures consistency. X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=5) lin_model = LinearRegression() lin_model.fit(X_train, Y_train) # model evaluation for training set y_train_predict = lin_model.predict(X_train) rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict))) r2 = r2_score(Y_train, y_train_predict) # model evaluation for testing set y_test_predict = lin_model.predict(X_test) # root mean square error of the model rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict))) # r-squared score of the model r2 = r2_score(Y_test, y_test_predict) plt.scatter(Y_test, y_test_predict) plt.show() How can I get, for instance, the 95% or 99% confidence interval from this? Is there some sort of in-built function or piece of code?
[ "I am not sure if there is any in-built function for this purpose, but what I do is create a loop on n no. of times and compare the accuracy of all the models and save the model with highest accuracy with pickle and use reuse it later.\nHere goes the code:\nfor _ in range(30):\nx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.1)\n\nlinear = linear_model.LinearRegression()\n\nlinear.fit(x_train, y_train)\nacc = linear.score(x_test, y_test)\nprint(\"Accuracy: \" + str(acc))\n\nif acc > best:\n best = acc\n with open(\"confidence_interval.pickle\", \"wb\") as f:\n pickle.dump(linear, f)\n print(\"The best Accuracy: \", best)\n\nYou can always make changes to the given variables as I know the variables that you have provided varies greatly from mine. and if you want to predict the class possibilities you can use predict_proba. Refer to this link for difference between predict and predict_proba https://www.kaggle.com/questions-and-answers/82657\n", "If you're looking to compute the confidence interval of the regression parameters, one way is to manually compute it using the results of LinearRegression from scikit-learn and numpy methods.\nThe code below computes the 95%-confidence interval (alpha=0.05). alpha=0.01 would compute 99%-confidence interval etc.\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom sklearn.linear_model import LinearRegression\n\nalpha = 0.05 # for 95% confidence interval; use 0.01 for 99%-CI.\n\n# fit a sklearn LinearRegression model\nlin_model = LinearRegression().fit(X_train, Y_train)\n\n# the coefficients of the regression model\ncoefs = np.r_[[lin_model.intercept_], lin_model.coef_]\n# build an auxiliary dataframe with the constant term in it\nX_aux = X_train.copy()\nX_aux.insert(0, 'const', 1)\n# degrees of freedom\ndof = -np.diff(X_aux.shape)[0]\n# Student's t-distribution table lookup\nt_val = stats.t.isf(alpha/2, dof)\n# MSE of the residuals\nmse = np.sum((Y_train - lin_model.predict(X_train)) ** 2) / dof\n# inverse of the variance of the parameters\nvar_params = np.diag(np.linalg.inv(X_aux.T.dot(X_aux)))\n# distance between lower and upper bound of CI\ngap = t_val * np.sqrt(mse * var_params)\n\nconf_int = pd.DataFrame({'lower': coefs - gap, 'upper': coefs + gap}, index=X_aux.columns)\n\nUsing the Boston housing dataset, the above code produces the dataframe below:\n\n\nIf this is too much manual code, you can always resort to the statsmodels and use its conf_int method:\nimport statsmodels.api as sm\nalpha = 0.05 # 95% confidence interval\nlr = sm.OLS(Y_train, sm.add_constant(X_train)).fit()\nconf_interval = lr.conf_int(alpha)\n\nSince it uses the same formula, it produces the same output as above.\nStats reference\n" ]
[ 0, 0 ]
[]
[]
[ "linear_regression", "python", "scikit_learn" ]
stackoverflow_0061292464_linear_regression_python_scikit_learn.txt
Q: cant enter password in twine pypi package upload PS D:\Python> cd ClockBlock PS D:\Python\ClockBlock> python3 -m twine upload --repository testpypi dist/* Uploading distributions to https://test.pypi.org/legacy/ Enter your username: MYNAME Enter your password: Desc for img I cant enter anything in password, can someone help, i bashed a bunch of keys and it didnt output anything
cant enter password in twine pypi package upload
PS D:\Python> cd ClockBlock PS D:\Python\ClockBlock> python3 -m twine upload --repository testpypi dist/* Uploading distributions to https://test.pypi.org/legacy/ Enter your username: MYNAME Enter your password: Desc for img I cant enter anything in password, can someone help, i bashed a bunch of keys and it didnt output anything
[]
[]
[ "SO.. it just didnt show the password for privacy reasons it underastood what i was typing though\n" ]
[ -1 ]
[ "pypi", "python", "python_3.x", "python_packaging", "twine" ]
stackoverflow_0074672962_pypi_python_python_3.x_python_packaging_twine.txt
Q: I want to solve this question but I am finding some difficulty help me to find the solution Help me to find out the solution of this question Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. Function Description average has the following parameters: int arr: an array of integers Returns float: the resulting float value rounded to 3 places after the decimal I want the output of the problem I am finding some difficulty in it. A: I think giving you the answer would probably defeat the purpose of the question, but I'll try to reframe the crux of the problem: The height of each plant may be repeated multiple times in the input array, we need to make sure that we only count each height once when computing the total height. There exists a data structure that is very effective at counting such elements. If you don't know of this data structure, consider using an array to store a "key" (the number that has been seen), and corresponding "value" (the count of times the number has been seen) locally. (The optimal data structure might not even need this value!)
I want to solve this question but I am finding some difficulty help me to find the solution
Help me to find out the solution of this question Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. Function Description average has the following parameters: int arr: an array of integers Returns float: the resulting float value rounded to 3 places after the decimal I want the output of the problem I am finding some difficulty in it.
[ "I think giving you the answer would probably defeat the purpose of the question, but I'll try to reframe the crux of the problem:\nThe height of each plant may be repeated multiple times in the input array, we need to make sure that we only count each height once when computing the total height.\nThere exists a data structure that is very effective at counting such elements. If you don't know of this data structure, consider using an array to store a \"key\" (the number that has been seen), and corresponding \"value\" (the count of times the number has been seen) locally. (The optimal data structure might not even need this value!)\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074673111_python.txt
Q: Tuple of Tuple as data in DataFrame results in AttributeError: 'tuple' object has no attribute 'encode' Say I've got sample data: sdata = [(1,(10,20,30)), (2,(100,20)), (3,(100,200,300))] columns = [('Sn','Products')] df1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns) Getting error: AttributeError: 'tuple' object has no attribute 'encode' How to load this variable length data ? A: You can represent tuples as StructType; but it has fixed fields. I am not sure about "variable length" tuples; but if your requirement is to support variable number of elements in a collection type, then you can either define an explicit schema: sdata = [(1,(10,20,30)), (2,(100,20)), (3,(100,200,300))] schema = StructType([ StructField('Sn', LongType()), StructField('Products', ArrayType(LongType())), ]) df1 = spark.createDataFrame(sdata, schema=schema) [Out]: +---+---------------+ | Sn| Products| +---+---------------+ | 1| [10, 20, 30]| | 2| [100, 20]| | 3|[100, 200, 300]| +---+---------------+ or use field directly as an array: sdata = [(1,[10,20,30]), (2,[100,20]), (3,[100,200,300])] columns = ['Sn','Products'] df1 = spark.createDataFrame(sdata, schema=columns) [Out]: +---+---------------+ | Sn| Products| +---+---------------+ | 1| [10, 20, 30]| | 2| [100, 20]| | 3|[100, 200, 300]| +---+---------------+ A: To load variable-length data into a PySpark DataFrame, you can use the ArrayType() function from the pyspark.sql.types module to define the schema of your DataFrame. The ArrayType() function allows you to specify the data type of the elements in an array, which can be used to define a column in a DataFrame that contains a variable number of elements. Here is an example of how to use the ArrayType() function to define the schema of a DataFrame that contains variable-length data: # Import the ArrayType() function from pyspark.sql.types import ArrayType # Define the sample data sdata = [(1,(10,20,30)), (2,(100,20)), (3,(100,200,300))] # Use the ArrayType() function to define the schema of the DataFrame columns = [('Sn', IntegerType()), ('Products', ArrayType(IntegerType()))] # Create the DataFrame with the defined schema df1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns) # Print the schema of the DataFrame df1.printSchema()
Tuple of Tuple as data in DataFrame results in AttributeError: 'tuple' object has no attribute 'encode'
Say I've got sample data: sdata = [(1,(10,20,30)), (2,(100,20)), (3,(100,200,300))] columns = [('Sn','Products')] df1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns) Getting error: AttributeError: 'tuple' object has no attribute 'encode' How to load this variable length data ?
[ "You can represent tuples as StructType; but it has fixed fields. I am not sure about \"variable length\" tuples; but if your requirement is to support variable number of elements in a collection type, then you can either define an explicit schema:\nsdata = [(1,(10,20,30)),\n (2,(100,20)),\n (3,(100,200,300))]\n\nschema = StructType([\n StructField('Sn', LongType()),\n StructField('Products', ArrayType(LongType())),\n])\n\ndf1 = spark.createDataFrame(sdata, schema=schema)\n\n[Out]:\n+---+---------------+\n| Sn| Products|\n+---+---------------+\n| 1| [10, 20, 30]|\n| 2| [100, 20]|\n| 3|[100, 200, 300]|\n+---+---------------+\n\nor use field directly as an array:\nsdata = [(1,[10,20,30]),\n (2,[100,20]),\n (3,[100,200,300])]\n\ncolumns = ['Sn','Products']\n\ndf1 = spark.createDataFrame(sdata, schema=columns)\n\n[Out]:\n+---+---------------+\n| Sn| Products|\n+---+---------------+\n| 1| [10, 20, 30]|\n| 2| [100, 20]|\n| 3|[100, 200, 300]|\n+---+---------------+\n\n", "To load variable-length data into a PySpark DataFrame, you can use the ArrayType() function from the pyspark.sql.types module to define the schema of your DataFrame. The ArrayType() function allows you to specify the data type of the elements in an array, which can be used to define a column in a DataFrame that contains a variable number of elements.\nHere is an example of how to use the ArrayType() function to define the schema of a DataFrame that contains variable-length data:\n# Import the ArrayType() function\nfrom pyspark.sql.types import ArrayType\n\n# Define the sample data\nsdata = [(1,(10,20,30)),\n (2,(100,20)),\n (3,(100,200,300))]\n\n# Use the ArrayType() function to define the schema of the DataFrame\ncolumns = [('Sn', IntegerType()),\n ('Products', ArrayType(IntegerType()))]\n\n# Create the DataFrame with the defined schema\ndf1 = spark.createDataFrame(([x[0],*x[1]] for x in sdata), schema=columns)\n\n# Print the schema of the DataFrame\ndf1.printSchema()\n\n" ]
[ 1, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "bigdata", "dataframe", "pyspark" ]
stackoverflow_0074670430_apache_spark_apache_spark_sql_bigdata_dataframe_pyspark.txt
Q: java.lang.IllegalStateException: Connection pool shut down at While downloading file from S3 it is failing and giving me this exception java.lang.IllegalStateException: Connection pool shut down at org.apache.http.util.Asserts.check(Asserts.java:34) at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:184) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:251) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76) at com.amazonaws.http.conn.$Proxy70.requestConnection(Unknown Source) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:175) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1190) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:742) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667) at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4221) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4168) at com.amazonaws.services.s3.AmazonS3Client.getObjectMetadata(AmazonS3Client.java:1249) at com.amazonaws.services.s3.transfer.TransferManager.doDownload(TransferManager.java:1053) at com.amazonaws.services.s3.transfer.TransferManager.doDownload(TransferManager.java:1007) at com.amazonaws.services.s3.transfer.TransferManager.download(TransferManager.java:845) at com.amazonaws.services.s3.transfer.TransferManager.download(TransferManager.java:801) at com.capitalone.homeloans.imaging.common.s3communicator.AsyncS3Manager.lambda$download$0(AsyncS3Manager.java:82) at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) A: in the databricks runtime environment, i found success using the solution from this article mixed with a small variation on the prefix for the configuration key: spark.hadoop.fs.s3a.connection.maximum 3 the original article solution said to use: fs.s3a.connection.maximum https://kb.databricks.com/en_US/jobs/job-fails-connection-pool
java.lang.IllegalStateException: Connection pool shut down at
While downloading file from S3 it is failing and giving me this exception java.lang.IllegalStateException: Connection pool shut down at org.apache.http.util.Asserts.check(Asserts.java:34) at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:184) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:251) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76) at com.amazonaws.http.conn.$Proxy70.requestConnection(Unknown Source) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:175) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1190) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:742) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667) at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4221) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4168) at com.amazonaws.services.s3.AmazonS3Client.getObjectMetadata(AmazonS3Client.java:1249) at com.amazonaws.services.s3.transfer.TransferManager.doDownload(TransferManager.java:1053) at com.amazonaws.services.s3.transfer.TransferManager.doDownload(TransferManager.java:1007) at com.amazonaws.services.s3.transfer.TransferManager.download(TransferManager.java:845) at com.amazonaws.services.s3.transfer.TransferManager.download(TransferManager.java:801) at com.capitalone.homeloans.imaging.common.s3communicator.AsyncS3Manager.lambda$download$0(AsyncS3Manager.java:82) at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)
[ "in the databricks runtime environment, i found success using the solution from this article mixed with a small variation on the prefix for the configuration key:\nspark.hadoop.fs.s3a.connection.maximum 3\nthe original article solution said to use:\nfs.s3a.connection.maximum\nhttps://kb.databricks.com/en_US/jobs/job-fails-connection-pool\n" ]
[ 0 ]
[ "Do not close your client after a request if you are pooling the connections.\nThat is, you are probably doing something like this:\nPoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();\n...\nCloseableHttpClient httpclient = HttpClients.custom()\n .setConnectionManager(pool)\n .build();\n\ntry { // try-with-resources\n HttpGet httpget = new HttpGet(url.toURI());\n try (CloseableHttpResponse response = httpclient.execute(httpget);\n InputStream fis = response.getEntity().getContent();\n ReadableByteChannel channel = Channels.newChannel(fis)) {\n // ... get data ...\n } finally {\n httpclient.close(); <====== !!\n }\n} catch (IOException | URISyntaxException e) {\n // exception handling ...\n}\n\nThat httpclient.close() is causing your next pooled connection to fail.\n\nTaken from: https://stackoverflow.com/a/59033548/1329340\n" ]
[ -1 ]
[ "amazon_s3", "amazon_web_services", "aws_sdk", "java" ]
stackoverflow_0045651144_amazon_s3_amazon_web_services_aws_sdk_java.txt
Q: Unable to properly show content in all devices I'm making a car research/ranking website using React. Coming to the issue, I have 3 cards, with content on it once you hover over it. It works perfectly well in desktops, but it doesn't properly show content in smaller devices: it overflows to the other section. To fix this, I have added a media query to it, but it doesn't work either. Please check my code: .sec2 { height: 100vh; width: 100%; color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; background: linear-gradient(to left, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(https://static.feber.se/article_images/48/81/62/488162_1920.jpg) no-repeat top center; } .wrapper { display: flex; width: 90%; justify-content: space-around; } .card { width: 350px; height: 370px; border-radius: 15px; padding: 1.5rem; position: relative; object-fit: fill; display: flex; align-items: flex-end; transition: 0.4s ease-out; box-shadow: 0px 7px 10px rgba(0, 0, 0, 0.5); } .card:hover { transform: translateY(20px); } .card:hover:before { opacity: 1; } .card:hover .info { opacity: 1; transform: translateY(0px); } .card:before { content: ""; position: absolute; top: 0; left: 0; display: block; width: 100%; height: 100%; border-radius: 15px; background: rgba(0, 0, 0, 0.6); z-index: 2; transition: 0.5s; opacity: 0; } .card img { width: 100%; height: 100%; object-fit: cover; position: absolute; top: 0; left: 0; border-radius: 15px; } .card .info { position: relative; z-index: 3; color: white; opacity: 0; transform: translateY(30px); transition: 0.5s; } .card .info h1 { margin: 0px; font-size: 2rem; } .card .info p { letter-spacing: 1px; font-size: 15px; margin-top: 8px; } .card .info button { padding: 0.6rem; outline: none; border: none; border-radius: 3px; background: white; color: black; font-weight: bold; cursor: pointer; transition: 0.4s ease; } .card .info button:hover { background: dodgerblue; color: white; } @media only screen and (min-width: 600px) and (max-width: 768px) { .wrapper { flex-direction: column; justify-content: center; align-items: center; } .card { height: 270px; padding: 1rem; width: 250px; margin-bottom: 10px; } .card .info h1 { font-size: 1rem; } .card .info p { font-size: 15px; } .card .info button { padding: 0.4rem; font-weight: normal; font-size: 12px; } } @media (max-width: 600px) { .wrapper { flex-direction: column; justify-content: center; align-items: center; } .card { height: 15%; padding: 0.3rem; width: 180px; margin-bottom: 5px; } .card .info h1 { font-size: 1rem; } .card .info p { font-size: 10px; } .card .info button { padding: 0.3rem; font-weight: normal; font-size: 10px; } } And <div> <header className="sec2" id="section2"> <h1> What is in this website? </h1> <div class="wrapper"> <div class="card"> <img src="https://cdn.jdpower.com/JDPA_2022%20Genesis%20G70%20Red%20Front%20Quarter%20View.jpg" /> <div class="info"> <h1>Car Rankings</h1> <p> It contains cars ranked based on body type, done after comprehensive research. </p> <button>Go</button> </div> </div> <div class="card"> <img src="https://i0.wp.com/autonxt.net/wp-content/uploads/2018/01/autocontentexp.com2018-Lincoln-Navigator5-5b1aebecc618f268352b037fb2253a291d670994-1.jpg?resize=2500%2C1500&ssl=1" /> <div class="info"> <h1>Car Reviews</h1> <p>Contains reviews of selective cars written by us.</p> <button>Read More</button> </div> </div> <div class="card"> <img src="https://static0.hotcarsimages.com/wordpress/wp-content/uploads/2020/09/AWD-e1600115646672.jpg" /> <div class="info"> <h1>Used Cars/h1> <p> We rank used cars so that you will only get the best out of it. </p> <button>Read More</button> </div> </div> </div> </header> </div> Image in computer: click, and Image in smaller devices: click A: first add the margin: auto in .wrapper class and some margin: 5px; to .card class because this make content in the center and looks good. .wrapper { display: flex; width: 90%; margin: auto; justify-content: space-around; } .card { /* your code */ margin: 5px; } Now, add just update margin: 15px; of all .card instead of margin-bottom Here is the full code, https://codesandbox.io/s/laughing-gwen-4i47v5?file=/src/Home.jsx
Unable to properly show content in all devices
I'm making a car research/ranking website using React. Coming to the issue, I have 3 cards, with content on it once you hover over it. It works perfectly well in desktops, but it doesn't properly show content in smaller devices: it overflows to the other section. To fix this, I have added a media query to it, but it doesn't work either. Please check my code: .sec2 { height: 100vh; width: 100%; color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; background: linear-gradient(to left, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(https://static.feber.se/article_images/48/81/62/488162_1920.jpg) no-repeat top center; } .wrapper { display: flex; width: 90%; justify-content: space-around; } .card { width: 350px; height: 370px; border-radius: 15px; padding: 1.5rem; position: relative; object-fit: fill; display: flex; align-items: flex-end; transition: 0.4s ease-out; box-shadow: 0px 7px 10px rgba(0, 0, 0, 0.5); } .card:hover { transform: translateY(20px); } .card:hover:before { opacity: 1; } .card:hover .info { opacity: 1; transform: translateY(0px); } .card:before { content: ""; position: absolute; top: 0; left: 0; display: block; width: 100%; height: 100%; border-radius: 15px; background: rgba(0, 0, 0, 0.6); z-index: 2; transition: 0.5s; opacity: 0; } .card img { width: 100%; height: 100%; object-fit: cover; position: absolute; top: 0; left: 0; border-radius: 15px; } .card .info { position: relative; z-index: 3; color: white; opacity: 0; transform: translateY(30px); transition: 0.5s; } .card .info h1 { margin: 0px; font-size: 2rem; } .card .info p { letter-spacing: 1px; font-size: 15px; margin-top: 8px; } .card .info button { padding: 0.6rem; outline: none; border: none; border-radius: 3px; background: white; color: black; font-weight: bold; cursor: pointer; transition: 0.4s ease; } .card .info button:hover { background: dodgerblue; color: white; } @media only screen and (min-width: 600px) and (max-width: 768px) { .wrapper { flex-direction: column; justify-content: center; align-items: center; } .card { height: 270px; padding: 1rem; width: 250px; margin-bottom: 10px; } .card .info h1 { font-size: 1rem; } .card .info p { font-size: 15px; } .card .info button { padding: 0.4rem; font-weight: normal; font-size: 12px; } } @media (max-width: 600px) { .wrapper { flex-direction: column; justify-content: center; align-items: center; } .card { height: 15%; padding: 0.3rem; width: 180px; margin-bottom: 5px; } .card .info h1 { font-size: 1rem; } .card .info p { font-size: 10px; } .card .info button { padding: 0.3rem; font-weight: normal; font-size: 10px; } } And <div> <header className="sec2" id="section2"> <h1> What is in this website? </h1> <div class="wrapper"> <div class="card"> <img src="https://cdn.jdpower.com/JDPA_2022%20Genesis%20G70%20Red%20Front%20Quarter%20View.jpg" /> <div class="info"> <h1>Car Rankings</h1> <p> It contains cars ranked based on body type, done after comprehensive research. </p> <button>Go</button> </div> </div> <div class="card"> <img src="https://i0.wp.com/autonxt.net/wp-content/uploads/2018/01/autocontentexp.com2018-Lincoln-Navigator5-5b1aebecc618f268352b037fb2253a291d670994-1.jpg?resize=2500%2C1500&ssl=1" /> <div class="info"> <h1>Car Reviews</h1> <p>Contains reviews of selective cars written by us.</p> <button>Read More</button> </div> </div> <div class="card"> <img src="https://static0.hotcarsimages.com/wordpress/wp-content/uploads/2020/09/AWD-e1600115646672.jpg" /> <div class="info"> <h1>Used Cars/h1> <p> We rank used cars so that you will only get the best out of it. </p> <button>Read More</button> </div> </div> </div> </header> </div> Image in computer: click, and Image in smaller devices: click
[ "\nfirst add the margin: auto in .wrapper class and some margin: 5px; to .card class because this make content in the center and looks good.\n\n.wrapper {\n display: flex;\n width: 90%;\n margin: auto;\n justify-content: space-around;\n}\n.card {\n /* your code */\n margin: 5px;\n}\n\n\nNow, add just update margin: 15px; of all .card instead of margin-bottom\n\nHere is the full code, https://codesandbox.io/s/laughing-gwen-4i47v5?file=/src/Home.jsx\n" ]
[ 0 ]
[]
[]
[ "css", "html", "javascript", "media_queries", "reactjs" ]
stackoverflow_0074673027_css_html_javascript_media_queries_reactjs.txt
Q: How to split a string but keep multiple delimiters with the original chunk Say my string is st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm' I would like to split on 'am' or 'pm', but I want those deliminters to be a part of the original chunk. So the desired result is splitlist = ['Walking happened at 8 am', 'breakfast happened at 9am', 'baseball happened at 12 pm', 'lunch happened at 1pm'] There are many solutions for keeping the delimiter, but keeping it as a separate item in the list like this one In Python, how do I split a string and keep the separators? A: You can use a lookbehind: import re splitlist = re.split(r'(?<=[ap]m)\s+', st) Output: ['Walking happened at 8 am', 'breakfast happened at 9am', 'baseball happened at 12 pm', 'lunch happened at 1pm'] If you want to ensure having a word boundary or a digit before am/pm (i.e not splitting after words such as "program"): import re splitlist = re.split(r'(?:(?<=\d[ap]m)|(?<=\b[ap]m))\s+', st) Example: ['Walking happened at 8 am', 'breakfast happened at 9am', 'baseball happened at 12 pm', 'beginning of program happened at 1pm']
How to split a string but keep multiple delimiters with the original chunk
Say my string is st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm' I would like to split on 'am' or 'pm', but I want those deliminters to be a part of the original chunk. So the desired result is splitlist = ['Walking happened at 8 am', 'breakfast happened at 9am', 'baseball happened at 12 pm', 'lunch happened at 1pm'] There are many solutions for keeping the delimiter, but keeping it as a separate item in the list like this one In Python, how do I split a string and keep the separators?
[ "You can use a lookbehind:\nimport re\n\nsplitlist = re.split(r'(?<=[ap]m)\\s+', st)\n\nOutput:\n['Walking happened at 8 am',\n 'breakfast happened at 9am',\n 'baseball happened at 12 pm',\n 'lunch happened at 1pm']\n\nIf you want to ensure having a word boundary or a digit before am/pm (i.e not splitting after words such as \"program\"):\nimport re\n\nsplitlist = re.split(r'(?:(?<=\\d[ap]m)|(?<=\\b[ap]m))\\s+', st)\n\nExample:\n['Walking happened at 8 am',\n 'breakfast happened at 9am',\n 'baseball happened at 12 pm',\n 'beginning of program happened at 1pm']\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074673121_python.txt
Q: How to extract all timestamps of badminton shot sound in an audio clip using Neural Networks? I am trying to find the instances in a source audio file taken from a badminton match where a shot was hit by either of the players. For the same purpose, I have marked the timestamps with positive (hit sounds) and negative (no hit sound: commentary/crowd sound etc) labels like so: shot_timestamps = [0,6.5,8, 11, 18.5, 23, 27, 29, 32, 37, 43.5, 47.5, 52, 55.5, 63, 66, 68, 72, 75, 79, 94.5, 96, 99, 105, 122, 115, 118.5, 122, 126, 130.5, 134, 140, 144, 147, 154, 158, 164, 174.5, 183, 186, 190, 199, 238, 250, 253, 261, 267, 269, 270, 274] shot_labels = ['no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no','no','no', 'no', 'yes', 'yes', 'no', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'yes', 'yes', 'no', 'no', 'yes', 'yes', 'no'] I have been taking 1 second windows around these timestamps like so: rate, source = wavfile.read(source) def get_audio_snippets(shot_timestamps): shot_snippets = [] # Collection of all audio snippets in the timestamps above for timestamp in shot_timestamps: start = math.ceil(timestamp*rate) end = math.ceil((timestamp + 1)*rate) if start >= source.shape[0]: start = source.shape[0] - 1 if end >= source.shape[0]: end = source.shape[0] - 1 shot_snippets.append(source[start:end]) return shot_snippets and converting that to spectrogram images for the model. The model doesn't seem to be learning anything with an accuracy of around 50%. What can I do to improve the model? Edit: The audio file: Google Drive The timestamps labels: Google Drive Code: Github These timestamps were made recently and haven't been used in the code above as I don't exactly know what window sizes to take for labelling purposes. The annotation file above has all the timestamps of hitting the shots. PS: Also added this on Data Science Stackexchange as recommended: https://datascience.stackexchange.com/q/116629/98765 A: To improve the model, some possible solutions are: Adjust the window size for the snippets you are creating. Increase the number of data points. Augment your existing data with additional data. Try different architectures, such as convolutional neural networks and recurrent neural networks. Try different feature extraction techniques, such as Mel-Frequency Cepstral Coefficients (MFCCs). Tune the hyperparameters of the model. Try different optimizers and learning rates. Experiment with different loss functions. A: Detecting when a particular sound happens is know as Sound Event Detection. There are a wide range of approaches to this topic, as it has been actively researched for many decades. Your existing solution, using correlation in the waveform domain with some template sounds is unlikely to work well as the amount of variation between shot sounds in a match is likely to be quite high. The recommended approach would be to first collect a small dataset. Say for example to take data from 20 different matches (preferably with different), and then annotate each short from time-periods, to get at least 50 shots from each match. Then you can apply supervised machine learning to learn a detector. Some level of feature engineering should be done to the audio, for example to transform it into a spectrogram. A: There are several things you can try to improve the performance of your model. Here are some suggestions: You may want to try using a larger or smaller window size when extracting the audio snippets. A window size of 1 second may not be the optimal size for your model, so you could try using a different size to see if it improves the model's performance. You could also try using different parameters when generating the spectrogram images. For example, you could try changing the size of the window or the overlap between windows to see if it improves the model's performance. You may also want to try preprocessing the audio data in other ways. For example, you could try applying a filter to the data to remove background noise, or you could try using a different feature extraction method, such as mel-frequency cepstral coefficients (MFCCs). In addition, you could try using a different model architecture or training algorithm. For example, you could try using a convolutional neural network (CNN) instead of a fully-connected network, or you could try using a different optimizer or learning rate. Finally, you may want to try using more data. If you have access to a larger dataset, you could try training your model on that data to see if it improves the model's performance. Overall, the key is to experiment with different approaches and see what works best for your particular problem. A: This is a challenging task as it requires a lot of complex audio processing. The first step is to extract the audio features from the audio clip. This can be done by using various techniques such as Fast Fourier Transform (FFT), Mel-Frequency Cepstral Coefficients (MFCC), and Wavelet Transform (WT). Once the features are extracted, they need to be fed into a neural network model such as Convolutional Neural Network (CNN) or Long Short Term Memory (LSTM) to detect the timestamps of badminton shot sound. The model can be trained over a dataset of audio clips with the timestamps of badminton shot sound. After the model is trained, it can be used for identifying the timestamps of badminton shot sound in the given audio clip. A: One possible way to improve the model's performance would be to increase the length of the audio snippets that you are using to train the model. Right now, you are using 1-second long snippets around each timestamp, which may not be enough to capture the characteristics of a hit sound. Increasing the length of the snippets to, for example, 2 or 3 seconds, might allow the model to learn more from the data and improve its accuracy. A: One thing you can try to improve your model's performance is to use a different audio feature representation. Instead of using a spectrogram image, you could try using a Mel-frequency cepstral coefficient (MFCC) representation of the audio snippets. MFCCs are commonly used in speech recognition and are known to be effective in capturing the characteristics of a sound. Another thing you can try is to use a different machine learning model. Instead of using a neural network, you could try using a support vector machine (SVM) or a random forest classifier. These models are known to be effective in classifying audio data. Additionally, you may want to consider augmenting your training data. This could involve adding noise to the audio snippets or applying other transformations to them to make the model more robust. Finally, you may want to experiment with different model hyperparameters such as the learning rate, the number of hidden layers, and the number of units in each layer. Finding the optimal values for these hyperparameters can often improve a model's performance. A: There are a few things you could try to improve the performance of your model. Here are a few ideas: Use a longer window size when generating the spectrogram images. You are currently using a 1-second window, which may not be enough to capture the full range of sounds that are present in a shot. You could try using a longer window, such as 2 or 3 seconds, to see if that improves the model's performance. Use a different type of spectrogram. The spectrogram you are currently using is a simple power spectrogram, which only shows the power of the different frequencies present in the audio. You could try using a more advanced type of spectrogram, such as a mel-frequency cepstral coefficients (MFCC) spectrogram, which is commonly used in speech recognition applications. This may provide more information for the model to learn from. Augment your dataset. You may be able to improve the model's performance by augmenting your dataset with additional data. For example, you could try adding additional shots with different types of hits, such as backhand shots or overhead shots, to the dataset. You could also try adding different types of background noise to the shots, such as crowd noise or commentary, to make the dataset more representative of real-world situations. Try a different model architecture. The model you are currently using may not be well-suited to the task at hand. You could try using a different model architecture, such as a convolutional neural network (CNN) or a recurrent neural network (RNN), to see if that performs better on the task. You could also try tuning the hyperparameters of the model, such as the learning rate and the number of layers, to see if that improves performance. Use transfer learning. If you have access to a pre-trained model that has been trained on a similar task, you may be able to improve performance by using transfer learning. This involves using the pre-trained model as the starting point for your own model, and then fine-tuning it on your own dataset. This can help the model learn faster and improve performance, since it will already have learned some relevant features from the pre-trained model. Hope this helps!
How to extract all timestamps of badminton shot sound in an audio clip using Neural Networks?
I am trying to find the instances in a source audio file taken from a badminton match where a shot was hit by either of the players. For the same purpose, I have marked the timestamps with positive (hit sounds) and negative (no hit sound: commentary/crowd sound etc) labels like so: shot_timestamps = [0,6.5,8, 11, 18.5, 23, 27, 29, 32, 37, 43.5, 47.5, 52, 55.5, 63, 66, 68, 72, 75, 79, 94.5, 96, 99, 105, 122, 115, 118.5, 122, 126, 130.5, 134, 140, 144, 147, 154, 158, 164, 174.5, 183, 186, 190, 199, 238, 250, 253, 261, 267, 269, 270, 274] shot_labels = ['no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no','no','no', 'no', 'yes', 'yes', 'no', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'yes', 'yes', 'no', 'no', 'yes', 'yes', 'no'] I have been taking 1 second windows around these timestamps like so: rate, source = wavfile.read(source) def get_audio_snippets(shot_timestamps): shot_snippets = [] # Collection of all audio snippets in the timestamps above for timestamp in shot_timestamps: start = math.ceil(timestamp*rate) end = math.ceil((timestamp + 1)*rate) if start >= source.shape[0]: start = source.shape[0] - 1 if end >= source.shape[0]: end = source.shape[0] - 1 shot_snippets.append(source[start:end]) return shot_snippets and converting that to spectrogram images for the model. The model doesn't seem to be learning anything with an accuracy of around 50%. What can I do to improve the model? Edit: The audio file: Google Drive The timestamps labels: Google Drive Code: Github These timestamps were made recently and haven't been used in the code above as I don't exactly know what window sizes to take for labelling purposes. The annotation file above has all the timestamps of hitting the shots. PS: Also added this on Data Science Stackexchange as recommended: https://datascience.stackexchange.com/q/116629/98765
[ "To improve the model, some possible solutions are:\n\nAdjust the window size for the snippets you are creating.\nIncrease the number of data points.\nAugment your existing data with additional data.\nTry different architectures, such as convolutional neural networks and recurrent neural networks.\nTry different feature extraction techniques, such as Mel-Frequency Cepstral Coefficients (MFCCs).\nTune the hyperparameters of the model.\nTry different optimizers and learning rates.\nExperiment with different loss functions.\n\n", "Detecting when a particular sound happens is know as Sound Event Detection. There are a wide range of approaches to this topic, as it has been actively researched for many decades.\nYour existing solution, using correlation in the waveform domain with some template sounds is unlikely to work well as the amount of variation between shot sounds in a match is likely to be quite high.\nThe recommended approach would be to first collect a small dataset. Say for example to take data from 20 different matches (preferably with different), and then annotate each short from time-periods, to get at least 50 shots from each match. Then you can apply supervised machine learning to learn a detector. Some level of feature engineering should be done to the audio, for example to transform it into a spectrogram.\n", "There are several things you can try to improve the performance of your model. Here are some suggestions:\n\nYou may want to try using a larger or smaller window size when extracting the audio snippets. A window size of 1 second may not be the optimal size for your model, so you could try using a different size to see if it improves the model's performance.\n\nYou could also try using different parameters when generating the spectrogram images. For example, you could try changing the size of the window or the overlap between windows to see if it improves the model's performance.\n\nYou may also want to try preprocessing the audio data in other ways. For example, you could try applying a filter to the data to remove background noise, or you could try using a different feature extraction method, such as mel-frequency cepstral coefficients (MFCCs).\n\nIn addition, you could try using a different model architecture or training algorithm. For example, you could try using a convolutional neural network (CNN) instead of a fully-connected network, or you could try using a different optimizer or learning rate.\n\nFinally, you may want to try using more data. If you have access to a larger dataset, you could try training your model on that data to see if it improves the model's performance.\n\n\nOverall, the key is to experiment with different approaches and see what works best for your particular problem.\n", "This is a challenging task as it requires a lot of complex audio processing. The first step is to extract the audio features from the audio clip. This can be done by using various techniques such as Fast Fourier Transform (FFT), Mel-Frequency Cepstral Coefficients (MFCC), and Wavelet Transform (WT).\nOnce the features are extracted, they need to be fed into a neural network model such as Convolutional Neural Network (CNN) or Long Short Term Memory (LSTM) to detect the timestamps of badminton shot sound. The model can be trained over a dataset of audio clips with the timestamps of badminton shot sound. After the model is trained, it can be used for identifying the timestamps of badminton shot sound in the given audio clip.\n", "One possible way to improve the model's performance would be to increase the length of the audio snippets that you are using to train the model. Right now, you are using 1-second long snippets around each timestamp, which may not be enough to capture the characteristics of a hit sound. Increasing the length of the snippets to, for example, 2 or 3 seconds, might allow the model to learn more from the data and improve its accuracy.\n", "One thing you can try to improve your model's performance is to use a different audio feature representation. Instead of using a spectrogram image, you could try using a Mel-frequency cepstral coefficient (MFCC) representation of the audio snippets. MFCCs are commonly used in speech recognition and are known to be effective in capturing the characteristics of a sound.\nAnother thing you can try is to use a different machine learning model. Instead of using a neural network, you could try using a support vector machine (SVM) or a random forest classifier. These models are known to be effective in classifying audio data.\nAdditionally, you may want to consider augmenting your training data. This could involve adding noise to the audio snippets or applying other transformations to them to make the model more robust.\nFinally, you may want to experiment with different model hyperparameters such as the learning rate, the number of hidden layers, and the number of units in each layer. Finding the optimal values for these hyperparameters can often improve a model's performance.\n", "There are a few things you could try to improve the performance of your model. Here are a few ideas:\n\nUse a longer window size when generating the spectrogram images. You are currently using a 1-second window, which may not be enough to capture the full range of sounds that are present in a shot. You could try using a longer window, such as 2 or 3 seconds, to see if that improves the model's performance.\n\nUse a different type of spectrogram. The spectrogram you are currently using is a simple power spectrogram, which only shows the power of the different frequencies present in the audio. You could try using a more advanced type of spectrogram, such as a mel-frequency cepstral coefficients (MFCC) spectrogram, which is commonly used in speech recognition applications. This may provide more information for the model to learn from.\n\nAugment your dataset. You may be able to improve the model's performance by augmenting your dataset with additional data. For example, you could try adding additional shots with different types of hits, such as backhand shots or overhead shots, to the dataset. You could also try adding different types of background noise to the shots, such as crowd noise or commentary, to make the dataset more representative of real-world situations.\n\nTry a different model architecture. The model you are currently using may not be well-suited to the task at hand. You could try using a different model architecture, such as a convolutional neural network (CNN) or a recurrent neural network (RNN), to see if that performs better on the task. You could also try tuning the hyperparameters of the model, such as the learning rate and the number of layers, to see if that improves performance.\n\nUse transfer learning. If you have access to a pre-trained model that has been trained on a similar task, you may be able to improve performance by using transfer learning. This involves using the pre-trained model as the starting point for your own model, and then fine-tuning it on your own dataset. This can help the model learn faster and improve performance, since it will already have learned some relevant features from the pre-trained model.\n\n\nHope this helps!\n" ]
[ 3, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "audio", "deep_learning", "librosa", "machine_learning", "python" ]
stackoverflow_0074471111_audio_deep_learning_librosa_machine_learning_python.txt
Q: Rendering a firestore timestamp in react I have been trying for months to figure out how to display a firestore timestamp in react. In December 2019, the solution I accepted on this post worked. It no longer works. I'm back to stuck. I have a firebase.js helper to record dates with: class Firebase { constructor() { app.initializeApp(config) this.firestore = app.firestore(); this.auth = app.auth(); this.serverTimestamp = app.firestore.FieldValue.serverTimestamp; } I use that helper in forms to record the date an entry is created like so: await Firebase.firestore.collection("blog").doc().set({ title: values.title, createdAt: Firebase.serverTimestamp() That correctly saves a date into the firestore document that looks like this: When I hover over the date, it shows 'timestamp'. I am able to order the data returned from firestore by reference to the createdAt date - so it's curious that the timestamp can be used to sort the documents but cannot be used to print the date on the screen. When it then comes to outputting the date, I am back to getting all the same errors I reported in the previous post - but the solution that worked in December, no longer works. I have seen a discussion in the firebase slack channel that a recent release of firebase has had some unintended consequences - is there any way to check if broken timestamps is one of them? When I try: {currentPost.createdAt.toDate().toISOString()} TypeError: Cannot read property 'toDate' of undefined When I try: {currentPost.createdAt.toDate()} TypeError: Cannot read property 'toDate' of undefined When I try: {new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")} TypeError: Cannot read property 'seconds' of undefined When I try (I know this won't work but just trying to find insights that might help solve this problem): {currentPost.createdAt} Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead. I have seen some posts which say the date is undefined because the call on firebase hasn't returned a value yet, but when I console.log the whole currentPost, I get a value for created At, which is: createdAt: t seconds: 1586495818 nanoseconds: 888000000 The part of this that looks suspicious is the "t". Does it represent something that I'm supposed to do something with in order to access the timestamp? Does anyone know how to investigate what the 't' represents? I have seen this post and this post, and note that each of the answers to it suggest that the .toDate() extension should help to convert a firestore timestamp to something that can be output. None of those solutions work here. Has anyone figured out a current solution that allows to both save and output a date from firestore? A: Strange - I don't understand why or how this works, but it does. I changed the useEffect to be async - as follows. function ReadBlogPost () { const [loading, setLoading] = useState(true); const [currentPost, setCurrentPost] = useState({}); let { slug } = useParams(); useEffect(() => { const fetchData = async() => { try { const response = await Firebase.firestore .collection("blog") .doc(slug) .get(); console.log('response', response); let data = { title: 'not found' }; if (response.exists) { data = response.data(); } setCurrentPost(data); setLoading(false); } catch(err) { console.error(err); } }; fetchData(); }, []); Then in the render, I can use: {!loading && new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")} Fingers crossed this works for more than a few months. A: I was facing the same problem. The solution is simple for me, You have to first check if the timestamp exists or not. {data.time === undefined ? ( <div>Time is not defined</div> ) : ( <div> {data.time.toDate().toLocaleTimeString("en-US")}</div> )} After that, you can do whatever you want. (Frist time answering any questions, If i made any mistake, please do tell) A: This worked for me: {data.timestamp.toDate().toLocaleTimeString("en-IN")}
Rendering a firestore timestamp in react
I have been trying for months to figure out how to display a firestore timestamp in react. In December 2019, the solution I accepted on this post worked. It no longer works. I'm back to stuck. I have a firebase.js helper to record dates with: class Firebase { constructor() { app.initializeApp(config) this.firestore = app.firestore(); this.auth = app.auth(); this.serverTimestamp = app.firestore.FieldValue.serverTimestamp; } I use that helper in forms to record the date an entry is created like so: await Firebase.firestore.collection("blog").doc().set({ title: values.title, createdAt: Firebase.serverTimestamp() That correctly saves a date into the firestore document that looks like this: When I hover over the date, it shows 'timestamp'. I am able to order the data returned from firestore by reference to the createdAt date - so it's curious that the timestamp can be used to sort the documents but cannot be used to print the date on the screen. When it then comes to outputting the date, I am back to getting all the same errors I reported in the previous post - but the solution that worked in December, no longer works. I have seen a discussion in the firebase slack channel that a recent release of firebase has had some unintended consequences - is there any way to check if broken timestamps is one of them? When I try: {currentPost.createdAt.toDate().toISOString()} TypeError: Cannot read property 'toDate' of undefined When I try: {currentPost.createdAt.toDate()} TypeError: Cannot read property 'toDate' of undefined When I try: {new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")} TypeError: Cannot read property 'seconds' of undefined When I try (I know this won't work but just trying to find insights that might help solve this problem): {currentPost.createdAt} Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead. I have seen some posts which say the date is undefined because the call on firebase hasn't returned a value yet, but when I console.log the whole currentPost, I get a value for created At, which is: createdAt: t seconds: 1586495818 nanoseconds: 888000000 The part of this that looks suspicious is the "t". Does it represent something that I'm supposed to do something with in order to access the timestamp? Does anyone know how to investigate what the 't' represents? I have seen this post and this post, and note that each of the answers to it suggest that the .toDate() extension should help to convert a firestore timestamp to something that can be output. None of those solutions work here. Has anyone figured out a current solution that allows to both save and output a date from firestore?
[ "Strange - I don't understand why or how this works, but it does.\nI changed the useEffect to be async - as follows.\nfunction ReadBlogPost () {\n const [loading, setLoading] = useState(true);\n const [currentPost, setCurrentPost] = useState({});\n let { slug } = useParams();\n\n\n useEffect(() => {\n\n const fetchData = async() => {\n\n try {\n\n const response = await Firebase.firestore\n .collection(\"blog\")\n .doc(slug)\n .get();\n\n console.log('response', response);\n\n let data = { title: 'not found' };\n\n if (response.exists) {\n data = response.data();\n }\n\n setCurrentPost(data);\n setLoading(false);\n\n } catch(err) {\n console.error(err);\n }\n\n };\n\n fetchData();\n\n }, []);\n\nThen in the render, I can use: \n {!loading && new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString(\"en-US\")}\n\nFingers crossed this works for more than a few months.\n", "I was facing the same problem. The solution is simple for me, You have to first check if the timestamp exists or not.\n {data.time === undefined ? (\n <div>Time is not defined</div>\n ) : (\n <div> {data.time.toDate().toLocaleTimeString(\"en-US\")}</div>\n )}\n\nAfter that, you can do whatever you want.\n(Frist time answering any questions, If i made any mistake, please do tell)\n", "This worked for me:\n{data.timestamp.toDate().toLocaleTimeString(\"en-IN\")}\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "firebase", "google_cloud_firestore", "reactjs" ]
stackoverflow_0061166977_firebase_google_cloud_firestore_reactjs.txt
Q: pop() for built-in sets The HashSet in std/sets has a pop() function that removes and returns an arbitrary element from the set. Is there an equivalent for built-in sets in Nim? If not, is there some other recommended way to get an arbitrary element from a set? It doesn't matter if it's destructive (like pop()) or not. A: One option is to loop over the set, and then break after obtaining a single item: func takeOne[T](items: set[T]): T = for item in items: return item You might want to add some error handling around empty sets. Also I'd be surprised if this was the recommended way, so I will not accept my own answer (yet).
pop() for built-in sets
The HashSet in std/sets has a pop() function that removes and returns an arbitrary element from the set. Is there an equivalent for built-in sets in Nim? If not, is there some other recommended way to get an arbitrary element from a set? It doesn't matter if it's destructive (like pop()) or not.
[ "One option is to loop over the set, and then break after obtaining a single item:\nfunc takeOne[T](items: set[T]): T =\n for item in items:\n return item\n\nYou might want to add some error handling around empty sets.\nAlso I'd be surprised if this was the recommended way, so I will not accept my own answer (yet).\n" ]
[ 0 ]
[]
[]
[ "nim", "set" ]
stackoverflow_0074673080_nim_set.txt
Q: i18next module does not compile within React-Typescript application I have a React-Typescript application and had recently configured i18next setup for multi-language support. I believe all of the setups have been done correctly by following the guidelines of the official documentation. However, when I run the app, it gives me a bunch of compilation errors, such as; Property 'changeLanguage' does not exist on type 'typeof import("...some_path_info.../node_modules/i18next/index")'. or Module '"i18next"' has no exported member 'Module' I tried a bunch of different tsconfig.json configurations, such as including the type definition file from the node_modules folder of i18next, and other things, but none of them solved the issue, here is the current version of my tsconfig.json file; "include": ["src"], "compilerOptions": { "target": "ES2019", "lib": ["esnext", "dom", "dom.iterable"], "importHelpers": true, "declaration": true, "sourceMap": true, "rootDir": "./src", "baseUrl": "." /* Specify the base directory to resolve non-relative module names. */, "paths": { "libdefs/*": ["src/libdefs/*"] }, "strict": false, "noImplicitReturns": false, "noFallthroughCasesInSwitch": true, "noUnusedLocals": false, "noUnusedParameters": false, "moduleResolution": "node", "jsx": "react", "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "downlevelIteration": true, "resolveJsonModule": true } } After spending lots of time searching and testing, I found a way to make it work, and can lead me to the real solution, however, I still couldn't figure it out. The thing is, when I go to the node_modules folder of the i18next, the default file structure looks like this; Within this package, when I tried to move the index.d.ts type definition file inside the dist folder and then build my project, everything started to work magically without any further configuration or change. However, obviously, it is not a permanent solution. Finally, I need a permanent solution to this problem, and my last finding about manipulating the package folder of i18next can give some hints. Here are the versions for related packages; "i18next": "^22.0.6", "react-i18next": "^12.0.0", Thanks. A: It looks like the problem is with the way the type definitions for the i18next package are being imported in your project. The error message mentions that the property 'changeLanguage' does not exist on the imported type, which suggests that the correct type definitions are not being imported. One possible solution would be to explicitly import the type definitions for i18next from the node_modules folder. You can do this by adding the following import statement at the top of your file: import * as i18next from 'i18next/dist/cjs/i18next'; This will import the correct type definitions for the i18next package, and should fix the compilation errors you are seeing. Alternatively, you can also update your tsconfig.json file to include the type definitions for i18next automatically. You can do this by adding the following entry to the "paths" section of the tsconfig.json file: "i18next": ["node_modules/i18next/dist/cjs/i18next"] This will tell the TypeScript compiler to look for the type definitions for the i18next package in the specified location, and should fix the compilation errors. It's worth noting that the solution with moving the index.d.ts file inside the dist folder is not recommended, as it can cause issues with future updates to the i18next package. It's best to use one of the above solutions instead. A: It looks like the issue is with the way you are importing the i18next module in your code. The error message indicates that the TypeScript compiler is unable to find the changeLanguage method on the i18next module. To fix this, you can try importing the i18next module using the import * as i18n from 'i18next' syntax. This will import the module as an object, and you can then access the changeLanguage method using the i18n.changeLanguage syntax. Additionally, you can try specifying the type definition file for the i18next module in your tsconfig.json file. You can do this by adding the following entry to the compilerOptions object in your tsconfig.json file: "typeRoots": ["node_modules/@types", "./src/libdefs"], This will tell the TypeScript compiler to look for type definitions in the specified directories. You can then import the i18next module using the import i18n from 'i18next' syntax, and the TypeScript compiler should be able to find the type definition for the i18next module and provide you with proper type information and error checking. A: It looks like you are encountering this error because the TypeScript compiler is unable to find the type definitions for the i18next module. To fix this, you can do one of the following: Install the @types/i18next package, which contains the type definitions for i18next. This can be done by running the following command: npm install @types/i18next --save-dev After installing this package, the TypeScript compiler will be able to find the type definitions for i18next, and the compilation errors should go away. In your tsconfig.json file, you can add a "types" property that specifies the type definition files that should be included in your project. This can be done like this: { "compilerOptions": { // Other compiler options... }, "types": ["i18next"] } This will tell the TypeScript compiler to include the type definitions for i18next when compiling your project. Either of these solutions should fix the compilation errors that you are experiencing. I hope this helps! Let me know if you have any other questions. A: I think the package that you used is not using in React.js that is for Next.js. I suggest using React-intl package for supporting multi language in react applications. React-intl documentation and also have a look on this blog which done localization using react-intl React i18n: A step-by-step guide to React-intl
i18next module does not compile within React-Typescript application
I have a React-Typescript application and had recently configured i18next setup for multi-language support. I believe all of the setups have been done correctly by following the guidelines of the official documentation. However, when I run the app, it gives me a bunch of compilation errors, such as; Property 'changeLanguage' does not exist on type 'typeof import("...some_path_info.../node_modules/i18next/index")'. or Module '"i18next"' has no exported member 'Module' I tried a bunch of different tsconfig.json configurations, such as including the type definition file from the node_modules folder of i18next, and other things, but none of them solved the issue, here is the current version of my tsconfig.json file; "include": ["src"], "compilerOptions": { "target": "ES2019", "lib": ["esnext", "dom", "dom.iterable"], "importHelpers": true, "declaration": true, "sourceMap": true, "rootDir": "./src", "baseUrl": "." /* Specify the base directory to resolve non-relative module names. */, "paths": { "libdefs/*": ["src/libdefs/*"] }, "strict": false, "noImplicitReturns": false, "noFallthroughCasesInSwitch": true, "noUnusedLocals": false, "noUnusedParameters": false, "moduleResolution": "node", "jsx": "react", "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "downlevelIteration": true, "resolveJsonModule": true } } After spending lots of time searching and testing, I found a way to make it work, and can lead me to the real solution, however, I still couldn't figure it out. The thing is, when I go to the node_modules folder of the i18next, the default file structure looks like this; Within this package, when I tried to move the index.d.ts type definition file inside the dist folder and then build my project, everything started to work magically without any further configuration or change. However, obviously, it is not a permanent solution. Finally, I need a permanent solution to this problem, and my last finding about manipulating the package folder of i18next can give some hints. Here are the versions for related packages; "i18next": "^22.0.6", "react-i18next": "^12.0.0", Thanks.
[ "It looks like the problem is with the way the type definitions for the i18next package are being imported in your project. The error message mentions that the property 'changeLanguage' does not exist on the imported type, which suggests that the correct type definitions are not being imported.\nOne possible solution would be to explicitly import the type definitions for i18next from the node_modules folder. You can do this by adding the following import statement at the top of your file:\nimport * as i18next from 'i18next/dist/cjs/i18next';\n\nThis will import the correct type definitions for the i18next package, and should fix the compilation errors you are seeing.\nAlternatively, you can also update your tsconfig.json file to include the type definitions for i18next automatically. You can do this by adding the following entry to the \"paths\" section of the tsconfig.json file:\n\"i18next\": [\"node_modules/i18next/dist/cjs/i18next\"]\n\nThis will tell the TypeScript compiler to look for the type definitions for the i18next package in the specified location, and should fix the compilation errors.\nIt's worth noting that the solution with moving the index.d.ts file inside the dist folder is not recommended, as it can cause issues with future updates to the i18next package. It's best to use one of the above solutions instead.\n", "It looks like the issue is with the way you are importing the i18next module in your code. The error message indicates that the TypeScript compiler is unable to find the changeLanguage method on the i18next module.\nTo fix this, you can try importing the i18next module using the import * as i18n from 'i18next' syntax. This will import the module as an object, and you can then access the changeLanguage method using the i18n.changeLanguage syntax.\nAdditionally, you can try specifying the type definition file for the i18next module in your tsconfig.json file. You can do this by adding the following entry to the compilerOptions object in your tsconfig.json file:\n\"typeRoots\": [\"node_modules/@types\", \"./src/libdefs\"],\n\nThis will tell the TypeScript compiler to look for type definitions in the specified directories. You can then import the i18next module using the import i18n from 'i18next' syntax, and the TypeScript compiler should be able to find the type definition for the i18next module and provide you with proper type information and error checking.\n", "It looks like you are encountering this error because the TypeScript compiler is unable to find the type definitions for the i18next module. To fix this, you can do one of the following:\nInstall the @types/i18next package, which contains the type definitions for i18next. This can be done by running the following command:\nnpm install @types/i18next --save-dev\n\nAfter installing this package, the TypeScript compiler will be able to find the type definitions for i18next, and the compilation errors should go away.\nIn your tsconfig.json file, you can add a \"types\" property that specifies the type definition files that should be included in your project. This can be done like this:\n{\n \"compilerOptions\": {\n // Other compiler options...\n },\n \"types\": [\"i18next\"]\n}\n\nThis will tell the TypeScript compiler to include the type definitions for i18next when compiling your project.\nEither of these solutions should fix the compilation errors that you are experiencing. I hope this helps! Let me know if you have any other questions.\n", "I think the package that you used is not using in React.js that is for Next.js. I suggest using React-intl package for supporting multi language in react applications.\nReact-intl documentation\nand also have a look on this blog which done localization using react-intl React i18n: A step-by-step guide to React-intl\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "i18next", "reactjs", "tsdx", "typescript" ]
stackoverflow_0074565837_i18next_reactjs_tsdx_typescript.txt
Q: how to avoid a type error when finding the median of a list I am working on a project to get the mean, median and mode of a list. I have it almost all down but the median function is giving me the following error: return (list[midIndex]+list[midIndex-1])/2.0 TypeError: list indices must be integers or slices, not float def median(list): if len(list) == 0: return 0 list.sort() midIndex = len(list)/2 if len(list)%2 == 0: return (list[midIndex]+list[midIndex-1])/2 else: return list[midIndex] def mean(list): if len(list) == 0: return 0 list.sort() total = 0 for number in list: total += number return total / len(list) def mode(list): numberDictionary = {} for digit in list: number = numberDictionary.get(digit, None) if number == None: numberDictionary[digit] = 1 else: numberDictionary[digit] = number+1 maxValue = max(numberDictionary.values()) modeList = [] for key in numberDictionary: if numberDictionary[key] == maxValue: modeList.append(key) return modeList def main(): lyst = [3, 1, 7, 1, 4, 10] print("List:", lyst) print("Mode", mode(lyst)) print("Median:", median(lyst)) print("Mean:", mean(lyst)) main() The answer should be 3.5. A: Try this to see that len division by two will result in a float type and can't be used as an index (python error message is clear). list = {1,2,3,4} midIndex = len(list)/2 print(f"midIndex = {midIndex}") print(type(midIndex)) Output: midIndex = 2.0 <class 'float'>
how to avoid a type error when finding the median of a list
I am working on a project to get the mean, median and mode of a list. I have it almost all down but the median function is giving me the following error: return (list[midIndex]+list[midIndex-1])/2.0 TypeError: list indices must be integers or slices, not float def median(list): if len(list) == 0: return 0 list.sort() midIndex = len(list)/2 if len(list)%2 == 0: return (list[midIndex]+list[midIndex-1])/2 else: return list[midIndex] def mean(list): if len(list) == 0: return 0 list.sort() total = 0 for number in list: total += number return total / len(list) def mode(list): numberDictionary = {} for digit in list: number = numberDictionary.get(digit, None) if number == None: numberDictionary[digit] = 1 else: numberDictionary[digit] = number+1 maxValue = max(numberDictionary.values()) modeList = [] for key in numberDictionary: if numberDictionary[key] == maxValue: modeList.append(key) return modeList def main(): lyst = [3, 1, 7, 1, 4, 10] print("List:", lyst) print("Mode", mode(lyst)) print("Median:", median(lyst)) print("Mean:", mean(lyst)) main() The answer should be 3.5.
[ "Try this to see that len division by two will result in a float type and can't be used as an index (python error message is clear).\nlist = {1,2,3,4}\nmidIndex = len(list)/2\nprint(f\"midIndex = {midIndex}\")\nprint(type(midIndex))\n\nOutput:\nmidIndex = 2.0\n<class 'float'>\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074673114_python.txt
Q: Get the id of the user who created the new user in Laravel I have a users table and a column supervised_by where I want the id of the user who created the new user. For example: get the id of the admin in supervised_by column of the user the admin creates. users table //migration file public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->boolean('verified')->default(false); $table->timestamp('verified_at')->nullable(); $table->string('password'); $table->string('is_verified'); $table->boolean('active')->nullable(); $table->integer('supervised_by')->references('id')->on('users'); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); } usercontroller public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|max:180', 'email' => 'required|email|unique:users', 'password' => 'required|max:15|min:8', // 'role' => 'required' ]); if ($validator->fails()) { return response()->json([ 'validation_errors' => $validator->messages(), ]); } else { $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password, 'verified' => false, 'role' => $request->role ]); return response()->json([ 'status' => 200, 'code' => 'register', 'message' => 'Registered successfully! You\'ll be able to log in once you are approved.', 'data' => null, 'error' => null, ]); } } A: You can use auth()->user()->id to get who created the user. $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password, 'verified' => false, 'role' => $request->role, 'supervised_by' => auth()->user()->id, ]); You can read the documentation about it from here A: (If i understood correctly), the admin who creates the new users is always logged in, so you can track the admin id with following line: $admin_id = Auth::user()->id; or, $admin_id = Auth::id(); Also, dont forget to: use Illuminate\Support\Facades\Auth;
Get the id of the user who created the new user in Laravel
I have a users table and a column supervised_by where I want the id of the user who created the new user. For example: get the id of the admin in supervised_by column of the user the admin creates. users table //migration file public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->boolean('verified')->default(false); $table->timestamp('verified_at')->nullable(); $table->string('password'); $table->string('is_verified'); $table->boolean('active')->nullable(); $table->integer('supervised_by')->references('id')->on('users'); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); }); } usercontroller public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|max:180', 'email' => 'required|email|unique:users', 'password' => 'required|max:15|min:8', // 'role' => 'required' ]); if ($validator->fails()) { return response()->json([ 'validation_errors' => $validator->messages(), ]); } else { $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password, 'verified' => false, 'role' => $request->role ]); return response()->json([ 'status' => 200, 'code' => 'register', 'message' => 'Registered successfully! You\'ll be able to log in once you are approved.', 'data' => null, 'error' => null, ]); } }
[ "You can use auth()->user()->id to get who created the user.\n$user = User::create([\n 'name' => $request->name,\n 'email' => $request->email,\n 'password' => $request->password,\n 'verified' => false,\n 'role' => $request->role,\n 'supervised_by' => auth()->user()->id,\n ]);\n\nYou can read the documentation about it from here\n", "(If i understood correctly), the admin who creates the new users is always logged in, so you can track the admin id with following line:\n$admin_id = Auth::user()->id;\n\nor,\n$admin_id = Auth::id();\n\nAlso, dont forget to:\nuse Illuminate\\Support\\Facades\\Auth;\n\n" ]
[ 1, 0 ]
[]
[]
[ "database", "laravel", "postgresql" ]
stackoverflow_0074673132_database_laravel_postgresql.txt
Q: Error initializing React Native app: "Your Ruby version is 2.6.10, but your Gemfile specified 2.7.5" I know similar questions exist. I've gone through most of them but, so far, none of the solutions worked. Here is the context: Operating system: macOS Ventura 13.0.1 (Intel processor) Here are some commands output: $ ruby -v ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin22] $ which ruby /Users/..../.rbenv/shims/ruby $ bundler -v Bundler version 2.3.26 $ which bundler /Users/..../.rbenv/shims/bundler My ~/.bash_profile and ~/.zshrc contain: export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" export PATH="$HOME/.rbenv/shims:$PATH" eval "$(rbenv init -)" I know nothing about ruby, I'm using rbenv to manage ruby versions. I've done a similar setup on another macOS system but for some reason, on this system, nothing I have tried works. Any helps is appreciated. Thanks. A: In the directory where you run npx react-native init, try following code : rbenv init rbenv shell 2.7.5 eval "$(rbenv init - bash)"; A: I've managed to make it work. I'm not sure what did it. I've upgraded node from 14 to 19 which also upgraded react-native to 0.70.6 Also, I've added if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi to .bash_profile and .zshrc
Error initializing React Native app: "Your Ruby version is 2.6.10, but your Gemfile specified 2.7.5"
I know similar questions exist. I've gone through most of them but, so far, none of the solutions worked. Here is the context: Operating system: macOS Ventura 13.0.1 (Intel processor) Here are some commands output: $ ruby -v ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin22] $ which ruby /Users/..../.rbenv/shims/ruby $ bundler -v Bundler version 2.3.26 $ which bundler /Users/..../.rbenv/shims/bundler My ~/.bash_profile and ~/.zshrc contain: export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" export PATH="$HOME/.rbenv/shims:$PATH" eval "$(rbenv init -)" I know nothing about ruby, I'm using rbenv to manage ruby versions. I've done a similar setup on another macOS system but for some reason, on this system, nothing I have tried works. Any helps is appreciated. Thanks.
[ "In the directory where you run npx react-native init, try following code :\nrbenv init\nrbenv shell 2.7.5\neval \"$(rbenv init - bash)\";\n\n", "I've managed to make it work.\nI'm not sure what did it.\nI've upgraded node from 14 to 19 which also upgraded react-native to 0.70.6\nAlso, I've added if which rbenv > /dev/null; then eval \"$(rbenv init -)\"; fi to .bash_profile and .zshrc\n" ]
[ 0, 0 ]
[]
[]
[ "macos", "react_native", "ruby" ]
stackoverflow_0074668561_macos_react_native_ruby.txt
Q: How to use Rust OpenCV imdecode I'd like decode a PNG image into an OpenCV Mat object using imdecode. I'm working on a function like fn handle_frame(buf: &[u8]) -> Result<(), opencv::Error> { original_image: Mat = imgcodecs::imdecode(buf, imgcodecs::IMREAD_COLOR)?; let width = original_image.cols()?; let height = original_image.rows()?; println!("Success! Dimensions are {}x{}", width, height); Ok(()) } But I cannot pass by byte buffer to imdecode because I'd first need to convert it to something that has the ToInputArray trait. How to do this? A: I found out that when I change the type of the input buffer to Vec<u8> I can do this: let original_image: Mat = imgcodecs::imdecode(&VectorOfuchar :: from_iter(buf), imgcodecs::IMREAD_COLOR)?; A: Here is a mostly complete example: let filename = "somepicture.png"; let mut reader: Box<dyn BufRead> = Box::new(BufReader::new(File::open(filename)?)); let mut buffer : Vec<u8> = Vec::new(); let _read_count = reader.read_to_end(&mut buffer)?; let result = cv::imgcodecs::imdecode(&cv::types::VectorOfu8::from_iter(buffer), cv::imgcodecs::IMREAD_COLOR)?; cv::highgui::imshow(&filename, &result)?; let _key = cv::highgui::wait_key(0)?;
How to use Rust OpenCV imdecode
I'd like decode a PNG image into an OpenCV Mat object using imdecode. I'm working on a function like fn handle_frame(buf: &[u8]) -> Result<(), opencv::Error> { original_image: Mat = imgcodecs::imdecode(buf, imgcodecs::IMREAD_COLOR)?; let width = original_image.cols()?; let height = original_image.rows()?; println!("Success! Dimensions are {}x{}", width, height); Ok(()) } But I cannot pass by byte buffer to imdecode because I'd first need to convert it to something that has the ToInputArray trait. How to do this?
[ "I found out that when I change the type of the input buffer to Vec<u8> I can do this:\nlet original_image: Mat = imgcodecs::imdecode(&VectorOfuchar :: from_iter(buf), imgcodecs::IMREAD_COLOR)?;\n\n", "Here is a mostly complete example:\nlet filename = \"somepicture.png\";\nlet mut reader: Box<dyn BufRead> = Box::new(BufReader::new(File::open(filename)?));\nlet mut buffer : Vec<u8> = Vec::new();\nlet _read_count = reader.read_to_end(&mut buffer)?;\nlet result = cv::imgcodecs::imdecode(&cv::types::VectorOfu8::from_iter(buffer), cv::imgcodecs::IMREAD_COLOR)?;\n\ncv::highgui::imshow(&filename, &result)?;\nlet _key = cv::highgui::wait_key(0)?;\n\n" ]
[ 4, 0 ]
[]
[]
[ "opencv", "rust" ]
stackoverflow_0058155836_opencv_rust.txt
Q: What character set should be set for session id column in database As in question, what character set should be set for session id column in database, if key consist of ascii characters only ? A: uuid or similar implementation is preferred as SessionId by many platform such as laravel, they use data type as Varchar(20), Word of caution is you are using mysql as you db it can cause performance issue if you set varchar/string as a primary key. Read More
What character set should be set for session id column in database
As in question, what character set should be set for session id column in database, if key consist of ascii characters only ?
[ "uuid or similar implementation is preferred as SessionId by many platform such as laravel, they use data type as Varchar(20), Word of caution is you are using mysql as you db it can cause performance issue if you set varchar/string as a primary key. Read More\n" ]
[ 0 ]
[]
[]
[ "character_set", "mysql", "php", "session" ]
stackoverflow_0074672653_character_set_mysql_php_session.txt
Q: Is there a way to hide/disable textfield in ReactJS based on a RadioGroup(FormControlLabel) selection using material ui (mui)? screenshot of webpage I am working on a project for a hospital webpage using ReactJS and mui and am stuck on the SignUp page.. The Sign up page has a radio option to choose the type of user- Patient or Doctor and then fill out some information. I am trying to hide/disable certain TextFields (BloodGroup,FamilyDoctor,EmergencyContact) when the Doctor option is chosen and revert back when patient is chosen. This is how the code looks so far-- I have tried adding handling functions for both the FormControlLabel and Textfield but I don't know how to connect the two. I have added disabled tag to the textfields but I am not able to revert it back using the radio button. function SignUp(props) { //.... const bloodgroup = document.getElementById("Blood Group"); const emergencycontact = document.getElementById("Emergencycontact"); const familydoc = document.getElementById("Family doctor"); const StyledTextField = styled(TextField)` & .Mui-disabled .MuiOutlinedInput-notchedOutline{ disabled:false; } `; function MyTextField(props) { const radioGroup = useRadioGroup(); let checked = false; if (radioGroup) { if (radioGroup.value === "Doctor") checked = true; else checked = false; } return <StyledTextField checked={checked} {...props} />; } const StyledFormControlLabel = styled((props) => ( <FormControlLabel {...props} /> ))(({ theme, checked }) => ({ ".MuiFormControlLabel-label": checked && { // Change color here color: "red", }, })); function MyFormControlLabel(props) { // MUI UseRadio Group const radioGroup = useRadioGroup(); let checked = false; if (radioGroup) { if (radioGroup.value === props.value) checked = true; else checked = false; } return <StyledFormControlLabel checked={checked} {...props} />; } return ( <> <Grid item xs={12} style={{ textAlign: "left" }}> <FormLabel id="typeOfLabel">Type Of User</FormLabel> <RadioGroup row aria-labelledby="typeOfLabel" name="typeofuser"> <MyFormControlLabel value="Patient" control={<Radio />} label="Patient" /> <MyFormControlLabel value="Doctor" control={<Radio />} label="Health Care Provider" /> </RadioGroup> </Grid> <Grid item xs={12}> <MyTextField disabled={true} required fullWidth name="BloodGroup" label="BloodGroup" type="BloodGroup" id="Blood Group" /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="Contactinfo" label="Contactinfo" type="email" id="Contact info" autoComplete="emailaddress" /> </Grid> <Grid item xs={12}> <MyTextField disabled={true} required fullWidth name="Emergencycontact" label="Emergencycontact" type="email" id="Emergencycontact" autoComplete="Emergencycontact" /> </Grid> <Grid item xs={12}> <MyTextField disabled={true} required fullWidth name="Familydoctor" label="Familydoctor" type="email" id="Family doctor" autoComplete="Familydoctor" /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="password" label="Password" type="password" id="password" autoComplete="new-password" /> </Grid> </> //.... ); } A: Hi @gbatra, As I understood. You want to display a particular input field. When a specific radio button is selected, for that purpose, You can use condition rendering to achieve that. I make two components, DoctorField and PatientField and two radio button Doctor and Patient and store the value of that radio in the state. if the state is equal to the patient or doctor. We render the DoctorField or PatientField components based on state value. Here, You could try this. Codesandbox
Is there a way to hide/disable textfield in ReactJS based on a RadioGroup(FormControlLabel) selection using material ui (mui)?
screenshot of webpage I am working on a project for a hospital webpage using ReactJS and mui and am stuck on the SignUp page.. The Sign up page has a radio option to choose the type of user- Patient or Doctor and then fill out some information. I am trying to hide/disable certain TextFields (BloodGroup,FamilyDoctor,EmergencyContact) when the Doctor option is chosen and revert back when patient is chosen. This is how the code looks so far-- I have tried adding handling functions for both the FormControlLabel and Textfield but I don't know how to connect the two. I have added disabled tag to the textfields but I am not able to revert it back using the radio button. function SignUp(props) { //.... const bloodgroup = document.getElementById("Blood Group"); const emergencycontact = document.getElementById("Emergencycontact"); const familydoc = document.getElementById("Family doctor"); const StyledTextField = styled(TextField)` & .Mui-disabled .MuiOutlinedInput-notchedOutline{ disabled:false; } `; function MyTextField(props) { const radioGroup = useRadioGroup(); let checked = false; if (radioGroup) { if (radioGroup.value === "Doctor") checked = true; else checked = false; } return <StyledTextField checked={checked} {...props} />; } const StyledFormControlLabel = styled((props) => ( <FormControlLabel {...props} /> ))(({ theme, checked }) => ({ ".MuiFormControlLabel-label": checked && { // Change color here color: "red", }, })); function MyFormControlLabel(props) { // MUI UseRadio Group const radioGroup = useRadioGroup(); let checked = false; if (radioGroup) { if (radioGroup.value === props.value) checked = true; else checked = false; } return <StyledFormControlLabel checked={checked} {...props} />; } return ( <> <Grid item xs={12} style={{ textAlign: "left" }}> <FormLabel id="typeOfLabel">Type Of User</FormLabel> <RadioGroup row aria-labelledby="typeOfLabel" name="typeofuser"> <MyFormControlLabel value="Patient" control={<Radio />} label="Patient" /> <MyFormControlLabel value="Doctor" control={<Radio />} label="Health Care Provider" /> </RadioGroup> </Grid> <Grid item xs={12}> <MyTextField disabled={true} required fullWidth name="BloodGroup" label="BloodGroup" type="BloodGroup" id="Blood Group" /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="Contactinfo" label="Contactinfo" type="email" id="Contact info" autoComplete="emailaddress" /> </Grid> <Grid item xs={12}> <MyTextField disabled={true} required fullWidth name="Emergencycontact" label="Emergencycontact" type="email" id="Emergencycontact" autoComplete="Emergencycontact" /> </Grid> <Grid item xs={12}> <MyTextField disabled={true} required fullWidth name="Familydoctor" label="Familydoctor" type="email" id="Family doctor" autoComplete="Familydoctor" /> </Grid> <Grid item xs={12}> <TextField required fullWidth name="password" label="Password" type="password" id="password" autoComplete="new-password" /> </Grid> </> //.... ); }
[ "Hi @gbatra,\nAs I understood. You want to display a particular input field. When a specific radio button is selected, for that purpose, You can use condition rendering to achieve that. I make two components, DoctorField and PatientField and two radio button Doctor and Patient and store the value of that radio in the state.\nif the state is equal to the patient or doctor. We render the DoctorField or PatientField components based on state value. Here, You could try this. Codesandbox\n" ]
[ 0 ]
[]
[]
[ "form_control", "material_ui", "reactjs" ]
stackoverflow_0074673000_form_control_material_ui_reactjs.txt
Q: Codeigniter error when trying to connect to database using mysqli I am getting Following error in my CodeIgniter application which is live on server. Here is the output of the error: A PHP Error was encountered Severity: Warning Message: mysqli::real_connect(): (HY000/1044): Access denied for user 'xxx'@'localhost' to database 'xxx' Filename: mysqli/mysqli_driver.php Line Number: 161 Backtrace: File: /home/arya123/public_html/application/controllers/Home.php Line: 7 Function: __construct File: /home/arya123/public_html/index.php Line: 292 Function: require_once A: you have to set mysql port number which is by default 3306 check this in database.php use either 'dbport' => '3306', or 'hostname' => 'mysql.hostingprovider.com:3306', A: Connect localhost with port solves the problem for me. $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost:3308', //Added port here 'username' => 'root', 'password' => '1234', 'database' => 'my_database', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE ); A: The same error I was getting when I upload my codeigniter project from localhost to Live server. What solution I find is to make some changes into the application => config => database.php Following is the database setting for the localhost $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'creator', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE ); Following database setting for live server (Just demo, setting differ as per hosting provider) 1) First you have to create database. 2) find MySql Databases(or anything related database) on dashboard, 3) create new database and put database name, username, password. 4) export database from localhost 5) open phpmyadmin on live server and import it. 6) change the setting of application=>config=>database.php by using FTP client or dashboard. $db['default'] = array( 'dsn' => '', 'hostname' => 'mysql.hostingprovider.com', 'username' => 'abc.username', 'password' => 'abc.password', 'database' => 'abc.databasename', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE ); A: u can add new user and pass and give it all privileges, like below: CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost'; FLUSH PRIVILEGES; then, u should update your config.php file, with new user and pass. A: Do the following: In applications/config/database.php, add dbport => '3306', to the default array $db['default'] = array(); In system/database/DB_driver.php, change public $port = ''; to public $port = '3306'; A: Try to use the plain password with no special characters, below is the example: $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'password', 'password' => 'Mynewpass@756', 'database' => 'database_name', ); A: You can edit your server's php.ini file to define the port that CodeIgniter will use by default. C:\wamp64\bin\apache\apache2.4.41\bin\php.ini Default port number for mysqli_connect(). mysqli.default_port = 3308 A: Try to set config/database.php 'username' => 'xxx' to 'username' => 'root' without any password. $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', A: verify is user has the rights privilege declare on database A: i was having the same issue in CodeIgniter code. database and everything was correct but i fixed it by changing these lines Before 'dsn' => 'mysql:host=localhost;dbname=kiuurduapp', 'hostname' => 'localhost', 'username' => 'kiuurdu', After 'dsn' => 'mysql:host=127.0.0.1;dbname=kiuurduapp', 'hostname' => '', 'username' => 'kiuurdu', and it works for me
Codeigniter error when trying to connect to database using mysqli
I am getting Following error in my CodeIgniter application which is live on server. Here is the output of the error: A PHP Error was encountered Severity: Warning Message: mysqli::real_connect(): (HY000/1044): Access denied for user 'xxx'@'localhost' to database 'xxx' Filename: mysqli/mysqli_driver.php Line Number: 161 Backtrace: File: /home/arya123/public_html/application/controllers/Home.php Line: 7 Function: __construct File: /home/arya123/public_html/index.php Line: 292 Function: require_once
[ "you have to set mysql port number which is by default 3306 check this in database.php\nuse either\n'dbport' => '3306',\n\nor \n 'hostname' => 'mysql.hostingprovider.com:3306', \n\n", "Connect localhost with port solves the problem for me. \n$db['default'] = array(\n 'dsn' => '',\n 'hostname' => 'localhost:3308', //Added port here\n 'username' => 'root',\n 'password' => '1234',\n 'database' => 'my_database',\n 'dbdriver' => 'mysqli',\n 'dbprefix' => '',\n 'pconnect' => FALSE,\n 'db_debug' => (ENVIRONMENT !== 'production'),\n 'cache_on' => FALSE,\n 'cachedir' => '',\n 'char_set' => 'utf8',\n 'dbcollat' => 'utf8_general_ci',\n 'swap_pre' => '',\n 'encrypt' => FALSE,\n 'compress' => FALSE,\n 'stricton' => FALSE,\n 'failover' => array(),\n 'save_queries' => TRUE\n);\n\n", "The same error I was getting when I upload my codeigniter project from localhost to Live server.\nWhat solution I find is to make some changes into the application => config => database.php\nFollowing is the database setting for the \n\nlocalhost\n\n$db['default'] = array(\n 'dsn' => '',\n 'hostname' => 'localhost',\n 'username' => 'root',\n 'password' => '',\n 'database' => 'creator',\n 'dbdriver' => 'mysqli',\n 'dbprefix' => '',\n 'pconnect' => FALSE,\n 'db_debug' => (ENVIRONMENT !== 'production'),\n 'cache_on' => FALSE,\n 'cachedir' => '',\n 'char_set' => 'utf8',\n 'dbcollat' => 'utf8_general_ci',\n 'swap_pre' => '',\n 'encrypt' => FALSE,\n 'compress' => FALSE,\n 'stricton' => FALSE,\n 'failover' => array(),\n 'save_queries' => TRUE\n);\n\nFollowing database setting for \n\nlive server (Just demo, setting differ as per hosting provider)\n\n1) First you have to create database.\n2) find MySql Databases(or anything related database) on dashboard,\n3) create new database and put database name, username, password. \n4) export database from localhost\n5) open phpmyadmin on live server and import it.\n6) change the setting of application=>config=>database.php by using FTP client or dashboard. \n$db['default'] = array(\n 'dsn' => '',\n 'hostname' => 'mysql.hostingprovider.com', \n 'username' => 'abc.username',\n 'password' => 'abc.password',\n 'database' => 'abc.databasename',\n 'dbdriver' => 'mysqli',\n 'dbprefix' => '',\n 'pconnect' => FALSE,\n 'db_debug' => (ENVIRONMENT !== 'production'),\n 'cache_on' => FALSE,\n 'cachedir' => '',\n 'char_set' => 'utf8',\n 'dbcollat' => 'utf8_general_ci',\n 'swap_pre' => '',\n 'encrypt' => FALSE,\n 'compress' => FALSE,\n 'stricton' => FALSE,\n 'failover' => array(),\n 'save_queries' => TRUE\n);\n\n", "u can add new user and pass and give it all privileges, like below:\nCREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';\nGRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';\nFLUSH PRIVILEGES;\n\nthen, u should update your config.php file, with new user and pass.\n", "Do the following:\n\nIn applications/config/database.php, add dbport => '3306', to the default array $db['default'] = array();\nIn system/database/DB_driver.php, change public $port = ''; to public $port = '3306';\n\n", "Try to use the plain password with no special characters, below is the example:\n$db['default'] = array(\n 'dsn' => '',\n 'hostname' => 'localhost',\n 'username' => 'password',\n 'password' => 'Mynewpass@756',\n 'database' => 'database_name',\n);\n\n", "You can edit your server's php.ini file to define the port that CodeIgniter will use by default.\nC:\\wamp64\\bin\\apache\\apache2.4.41\\bin\\php.ini\nDefault port number for mysqli_connect().\nmysqli.default_port = 3308\n", "Try to set config/database.php 'username' => 'xxx' to 'username' => 'root' without any password.\n$db['default'] = array( \n'dsn' => '',\n'hostname' => 'localhost',\n'username' => 'root',\n'password' => '',\n\n", "verify is user has the rights privilege declare on database\n", "i was having the same issue in CodeIgniter code. database and everything was correct but i fixed it by changing these lines\nBefore\n\n 'dsn' => 'mysql:host=localhost;dbname=kiuurduapp',\n 'hostname' => 'localhost',\n 'username' => 'kiuurdu',\n\n\nAfter\n\n 'dsn' => 'mysql:host=127.0.0.1;dbname=kiuurduapp',\n 'hostname' => '',\n 'username' => 'kiuurdu',\n\nand it works for me\n" ]
[ 6, 3, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "$db['default'] = array(\n 'dsn' => '',\n 'hostname' => 'localhost',\n 'username' => 'root',\n 'password' => '',\n 'database' => 'xxx',\n 'dbdriver' => 'mysqli',\n 'dbprefix' => '',\n 'pconnect' => FALSE,\n 'db_debug' => (ENVIRONMENT !== 'production'),\n 'cache_on' => FALSE,\n 'cachedir' => '',\n 'char_set' => 'utf8',\n 'dbcollat' => 'utf8_general_ci',\n 'swap_pre' => '',\n 'encrypt' => FALSE,\n 'compress' => FALSE,\n 'stricton' => FALSE,\n 'failover' => array(),\n 'save_queries' => TRUE\n);\n\n", "I had the same trouble.\nSince I use xampp and I was running my codeigniter app locally, the problem at the end I solved it by remplacing:\n'hostname' => 'localhost ' \n by\n'hostname' => '127.0.0.1:33065' \n the :33065 is the port assigned by default by xampp for phpmyadmin. \nIf you are running your proyect in the xampp default options, changing this, should be enough (hopefully).\nBut if you donยดt, I guess, you can search which port you are using for the database conection, and add it to your hostname with \":\" (if you are not sure which port you are using, you always can see in your D.B. administration tool -phpmyadmin or the one you are using- on the options, which port is taking).\n" ]
[ -1, -1 ]
[ "codeigniter", "mysqli", "php" ]
stackoverflow_0035852956_codeigniter_mysqli_php.txt
Q: What is the alternative of EfInMemory.CreateOptions for .NET Core 6.0 from package EfCore.TestSupport I am upgrading my .NET projects from .NET Core 3.1 to .NET 6.0. I was using Efcore.TestSupport.EfInMemory v3.2.0 as a database for my test, but now the current version of Efcore.TestSupport v5.3.0 it is not supporting EfInMemory for .NET 6.0. What is the alternative to var options = EfInMemory.CreateOptions<ApplicationDbContext> () Full code: using TestSupport.EfHelpers; using Xunit; namespace TestProject1 { [Fact] public async Task GetData_WhenNotExist_ShouldReturnNull() { var options = EfInMemory.CreateOptions<ApplicationDbContext>(); // EfInMemory not available in `Efcore.TestSupport` v5.3.0 } } A: As the Upgrade document says (at the 6th item of the summery) ef in memory is removed and no longer supported.and as the document says: If you need it then use EF Core's In Memory database provider! But the better option would be to use SQLLite in memory instead. Take a look at here
What is the alternative of EfInMemory.CreateOptions for .NET Core 6.0 from package EfCore.TestSupport
I am upgrading my .NET projects from .NET Core 3.1 to .NET 6.0. I was using Efcore.TestSupport.EfInMemory v3.2.0 as a database for my test, but now the current version of Efcore.TestSupport v5.3.0 it is not supporting EfInMemory for .NET 6.0. What is the alternative to var options = EfInMemory.CreateOptions<ApplicationDbContext> () Full code: using TestSupport.EfHelpers; using Xunit; namespace TestProject1 { [Fact] public async Task GetData_WhenNotExist_ShouldReturnNull() { var options = EfInMemory.CreateOptions<ApplicationDbContext>(); // EfInMemory not available in `Efcore.TestSupport` v5.3.0 } }
[ "As the Upgrade document says (at the 6th item of the summery) ef in memory is removed and no longer supported.and as the document says:\n\nIf you need it then use EF Core's In Memory database provider!\n\nBut the better option would be to use SQLLite in memory instead. Take a look at here\n" ]
[ 0 ]
[]
[]
[ ".net", "c#", "ef_core_6.0" ]
stackoverflow_0074671861_.net_c#_ef_core_6.0.txt
Q: Hello i was trying to create a todo list using python and i met with a ValueError which i don't know how to solve this is the error message i am getting Error message:- line 37, in number = int(user_action[5:]) ValueError: invalid literal for int() with base 10: '' the code below:- def get_todos(filepath): with open(filepath, 'r') as file_local: todos_local = file_local.readlines() return todos_local def write_todos(filepath): with open(filepath, 'w') as file: file.writelines(todos_arg) while True: user_action = input("Type add, show, edit, complete or exit: ") user_action = user_action.strip() if user_action.startswith('add'): todo = user_action[4:] todos = get_todos("todos.txt") todos.append(todo + '\n' ) write_todos("todos.txt", todos) elif user_action.startswith('show'): todos = get_todos("todos.txt") for index,item in enumerate(todos): item = item.strip('\n') row = f"{index + 1}-{item}" print(row) elif user_action.startswith('edit'): try: number = int(user_action[5:]) print(number) number = number - 1 todos = get_todos("todos.txt") print('Here is the existing', todos) new_todo = input("Enter new todo: ") todos[number] = new_todo + '\n' print('Here is the new',todos) write_todos("todos.txt", todos) except IndexError: print("Your command is not valid") continue elif user_action.startswith('complete'): try: number = int(user_action[9:]) todos = get_todos("todos.txt") index = number - 1 todos_to_remove = todos[index].strip('\n') todos.pop(index) write_todos("todos.txt", todos) message = f"Todo {todos_to_remove} was removed from the list." print(message) except IndexError: print("There is no item with that number.") continue elif user_action.startswith('exit'): break else: print("Command is not acceptable. ") print('bye') i was expecting the code to work properly the edit and complete feature to work properly A: It looks like you are trying to convert a string to an integer, but the string is empty. You can add a check to make sure that user_action is long enough before trying to convert it to an integer. if len(user_action) >= 5: number = int(user_action[5:]) else: print("Your command is not valid")
Hello i was trying to create a todo list using python and i met with a ValueError which i don't know how to solve
this is the error message i am getting Error message:- line 37, in number = int(user_action[5:]) ValueError: invalid literal for int() with base 10: '' the code below:- def get_todos(filepath): with open(filepath, 'r') as file_local: todos_local = file_local.readlines() return todos_local def write_todos(filepath): with open(filepath, 'w') as file: file.writelines(todos_arg) while True: user_action = input("Type add, show, edit, complete or exit: ") user_action = user_action.strip() if user_action.startswith('add'): todo = user_action[4:] todos = get_todos("todos.txt") todos.append(todo + '\n' ) write_todos("todos.txt", todos) elif user_action.startswith('show'): todos = get_todos("todos.txt") for index,item in enumerate(todos): item = item.strip('\n') row = f"{index + 1}-{item}" print(row) elif user_action.startswith('edit'): try: number = int(user_action[5:]) print(number) number = number - 1 todos = get_todos("todos.txt") print('Here is the existing', todos) new_todo = input("Enter new todo: ") todos[number] = new_todo + '\n' print('Here is the new',todos) write_todos("todos.txt", todos) except IndexError: print("Your command is not valid") continue elif user_action.startswith('complete'): try: number = int(user_action[9:]) todos = get_todos("todos.txt") index = number - 1 todos_to_remove = todos[index].strip('\n') todos.pop(index) write_todos("todos.txt", todos) message = f"Todo {todos_to_remove} was removed from the list." print(message) except IndexError: print("There is no item with that number.") continue elif user_action.startswith('exit'): break else: print("Command is not acceptable. ") print('bye') i was expecting the code to work properly the edit and complete feature to work properly
[ "It looks like you are trying to convert a string to an integer, but the string is empty. You can add a check to make sure that user_action is long enough before trying to convert it to an integer.\nif len(user_action) >= 5:\n number = int(user_action[5:])\nelse:\n print(\"Your command is not valid\")\n\n" ]
[ 0 ]
[]
[]
[ "python_3.x", "valueerror" ]
stackoverflow_0074673088_python_3.x_valueerror.txt
Q: Adding Git-Bash to the new Windows Terminal I'm trying to add a new terminal (Git Bash) to the new Windows Terminal. However, I can't get it to work. I tried changing the commandline property in the profiles array to git-bash.exe but no luck. Does anyone have an idea how to get this to work? A: Overview Open settings with Ctrl+, You'll want to append one of the profiles options below (depending on what version of git you have installed) to the "list": portion of the settings.json file: { "$schema": "https://aka.ms/terminal-profiles-schema", "defaultProfile": "{00000000-0000-0000-ba54-000000000001}", "profiles": { "defaults": { // Put settings here that you want to apply to all profiles }, "list": [ <put one of the configuration below right here> ] } } Profile options Uncomment correct paths for commandline and icon if you are using: Git for Windows in %PROGRAMFILES% Git for Windows in %USERPROFILE% If you're using scoop { "guid": "{00000000-0000-0000-ba54-000000000002}", "commandline": "%PROGRAMFILES%/Git/usr/bin/bash.exe -i -l", // "commandline": "%USERPROFILE%/AppData/Local/Programs/Git/bin/bash.exe -l -i", // "commandline": "%USERPROFILE%/scoop/apps/git/current/usr/bin/bash.exe -l -i", "icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico", // "icon": "%USERPROFILE%/AppData/Local/Programs/Git/mingw64/share/git/git-for-windows.ico", // "icon": "%USERPROFILE%/scoop/apps/git/current/usr/share/git/git-for-windows.ico", "name" : "Bash", "startingDirectory" : "%USERPROFILE%" }, You can also add other options like: { "guid": "{00000000-0000-0000-ba54-000000000002}", // ... "acrylicOpacity" : 0.75, "closeOnExit" : true, "colorScheme" : "Campbell", "cursorColor" : "#FFFFFF", "cursorShape" : "bar", "fontFace" : "Consolas", "fontSize" : 10, "historySize" : 9001, "padding" : "0, 0, 0, 0", "snapOnInput" : true, "useAcrylic" : true } Notes make your own guid as of https://github.com/microsoft/terminal/pull/2475 this is no longer generated. the guid can be used in in the globals > defaultProfile so you can press you can press CtrlShiftT or start a Windows terminal and it will start up bash by default "defaultProfile" : "{00000000-0000-0000-ba54-000000000001}", -l -i to make sure that .bash_profile gets loaded use environment variables so they can map to different systems correctly. target git/bin/bash.exe to avoid spawning off additional processes which saves about 10MB per process according to Process Explorer compared to using bin/bash or git-bash I have my configuration that uses Scoop in https://gist.github.com/trajano/24f4edccd9a997fad8b4de29ea252cc8 A: There are below things to do. Make sure the git command runs successfully in Command Prompt. That means you need to add git to path when install git or add it to system environment later. Update the file profile.json: open Settings by pressing Ctrl+, in Windows Terminal, click on Open JSON file in the sidebar, and add following snippet inside the word profiles: { "tabTitle": "Git Bash", "acrylicOpacity" : 0.75, "closeOnExit" : true, "colorScheme" : "Campbell", "commandline" : "C:/Program Files/Git/bin/bash.exe --login", "cursorColor" : "#FFFFFF", "cursorShape" : "bar", "fontFace" : "Consolas", "fontSize" : 12, "guid" : "{14ad203f-52cc-4110-90d6-d96e0f41b64d}", "historySize" : 9001, "icon": "ms-appdata:///roaming/git-bash_32px.ico", "name" : "Git Bash", "padding" : "0, 0, 0, 0", "snapOnInput" : true, "useAcrylic" : true } The icon can be obtained here: git-bash_32px.ico You can add icons for Tab to this location: %LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState Put 32x32 PNG/icons in this folder, and then in profile.json you can reference the image resource with the path starting with ms-appdata://. Note that, please make sure the Guidis correct and it matches the corresponding correct configurations. Test that git bash works in Windows Terminal. The final result is below: A: This is the complete answer (GitBash + color scheme + icon + context menu) Set default profile: "globals": { "defaultProfile" : "{00000000-0000-0000-0000-000000000001}", ... Add GitBash profile "profiles": [ { "guid": "{00000000-0000-0000-0000-000000000001}", "acrylicOpacity": 0.75, "closeOnExit": true, "colorScheme": "GitBash", "commandline": "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" --login -i", "cursorColor": "#FFFFFF", "cursorShape": "bar", "fontFace": "Consolas", "fontSize": 10, "historySize": 9001, "icon": "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico", "name": "GitBash", "padding": "0, 0, 0, 0", "snapOnInput": true, "startingDirectory": "%USERPROFILE%", "useAcrylic": false } ] Add GitBash color scheme "schemes": [ { "background": "#000000", "black": "#0C0C0C", "blue": "#6060ff", "brightBlack": "#767676", "brightBlue": "#3B78FF", "brightCyan": "#61D6D6", "brightGreen": "#16C60C", "brightPurple": "#B4009E", "brightRed": "#E74856", "brightWhite": "#F2F2F2", "brightYellow": "#F9F1A5", "cyan": "#3A96DD", "foreground": "#bfbfbf", "green": "#00a400", "name": "GitBash", "purple": "#bf00bf", "red": "#bf0000", "white": "#ffffff", "yellow": "#bfbf00", "grey": "#bfbfbf" } ] To add a right-click context menu "Windows Terminal Here" Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Directory\Background\shell\wt] @="Windows terminal here" "Icon"="C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\{YOUR_ICONS_FOLDER}\\icon.ico" [HKEY_CLASSES_ROOT\Directory\Background\shell\wt\command] @="\"C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\wt.exe\"" Replace {YOUR_WINDOWS_USERNAME} with your Windows username. Create an icon folder, put the icon there and replace {YOUR_ICONS_FOLDER} with your icon folder. Save this in a .reg file and run it. A: It's Sept 2021, thankfully the latest Git Installation installer for Windows (mine was using 2.33.0.2) already has this option covered for us, for the sake of our laziness (and convenience, of course!) Please install the Windows Terminal first before installing Git, although I haven't try the otherway around, but better follow the sensible order. If the installation order is not the case, please let me know to update this answer. You may find this handful checkbox at the bottom within the installation stage Select Components, just tick the box there and you're good to go. The settings.json file will be added the Git Bash profile automatically with correct Git Bash icon. My generated Git Bash profile is pretty standard and minimal. { "guid": "{2ece5bfe-50ed-5f3a-ab87-5cd4baafed2b}", "hidden": false, "name": "Git Bash", "source": "Git" } If Windows Terminal is running, close and launch again for the Git Bash option to be visible. A: Because most answers either show a lot of unrelated configuration or don't show the configuration, I created my own answer that tries to be more focused. It is mainly based on the profile settings reference and Archimedes Trajano's answer. Steps Open PowerShell and enter [guid]::NewGuid() to generate a new GUID. We will use it at step 3. > [guid]::NewGuid() Guid ---- a3da8d92-2f3f-4e36-9714-98876b6cb480 Open the settings of Windows Terminal. (CTRL+,) Add the following JSON object to profiles.list. Replace guid with the one you generated at step 1. { "guid": "{a3da8d92-2f3f-4e36-9714-98876b6cb480}", "name": "Git Bash", "commandline": "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" -i -l", "icon": "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico", "startingDirectory" : "%USERPROFILE%" }, Notes There is currently an issue that you cannot use your arrow keys (and some other keys). It seems to work with the latest preview version, though. (issue #6859) Specifying "startingDirectory" : "%USERPROFILE%" shouldn't be necessary according to the reference. However, if I don't specify it, the starting directory was different depending on how I started the terminal initially. Settings that shall apply to all terminals can be specified in profiles.defaults. I recommend to set "antialiasingMode": "cleartype" in profiles.defaults. You have to remove "useAcrylic" (if you have added it as suggested by some other answers) to make it work. It improves the quality of text rendering. However, you cannot have transparent background without useAcrylic. See issue #1298. If you have problems with the cursor, you can try another shape like "cursorShape": "filledBox". See cursor settings for more information. A: That's how I've added mine in profiles json table, { "guid": "{00000000-0000-0000-ba54-000000000002}", "name": "Git", "commandline": "C:/Program Files/Git/bin/bash.exe --login", "icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico", "startingDirectory": "%USERPROFILE%", "hidden": false } A: In case anyone is looking for a UI-Based solution. Here it is: Go to the Terminal's settings. At the Right buttom side, look for the "Add new profile" option. Screenshot for the Terminal's settings. Select "New Empty Profile" Now complete the fields with the information about your bash. If your installation locations are the default ones, you could use these: Name: Git-Bash Command line: C:\Program Files\Git\bin\bash.exe Startin directory: [Leave as default] Icon: C:\Program Files\Git\mingw64\share\git\git-for-windows.ico Tab title: Git-Bash Temrinal Settings completed You could also browse for the right files in case you need to. Hit Save button. Final Result Final Result. Bash terminal A: Another item to note - in settings.json I discovered if you don't use "commandline": "C:/Program Files/Git/bin/bash.exe" and instead use: "commandline": "C:/Program Files/Git/git-bash.exe" the Git shell will open up in an independent window outside of Windows Terminal instead of on a tab - which is not the desired behavior. In addition, the tab in Windows Terminal that opens will also need to be closed manually as it will display process exited information - [process exited with code 3221225786] etc. Might save someone some headache A: Change the profiles parameter to "commandline": "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" This works for me and allows for my .bash_profile alias autocomplete scripts to run. A: The new version of windows terminal can be configured through its GUI. Setting -> Add new Under "command line" add the path -> path/to/Git/bin/bash.exe A: If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here C:\Program Files\Git\mingw64\share\git\git-for-windows I copied it into. %LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState and named it git-bash_32px as suggested above. Control the opacity with CTRL + SHIFT + scrolling. { "acrylicOpacity" : 0.75, "closeOnExit" : true, "colorScheme" : "Campbell", "commandline" : "\"%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\" -i -l", "cursorColor" : "#FFFFFF", "cursorShape" : "bar", "fontFace" : "Consolas", "fontSize" : 10, "guid" : "{73225108-7633-47ae-80c1-5d00111ef646}", "historySize" : 9001, "icon" : "ms-appdata:///roaming/git-bash_32px.ico", "name" : "Bash", "padding" : "0, 0, 0, 0", "snapOnInput" : true, "startingDirectory" : "%USERPROFILE%", "useAcrylic" : true }, A: I did as follows: Add "%programfiles%\Git\Bin" to your PATH On the profiles.json, set the desired command-line as "commandline" : "sh --cd-to-home" Restart the Windows Terminal It worked for me. A: Adding "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command "C:\Program" instead of "C:\Program Files\Git\bin\bash.exe -l -i". The solution should be something like adding quotation marks in json file, but I didn't figure out how. The only solution is to add "C:\Program Files\Git\bin" to %PATH% and write "commandline": "bash.exe" in profiles.json A: To anyone who may suffer from missing bash history: in already opened git bash, try initiate another bash - that supposed to load your profile if env vars are properly configured If this is your case, you can automate it by adding following command line on startup: C:\progra~1\git\usr\bin\bash.exe --login -l -i -c /c/progra~1/git/usr/bin/bash.exe A: Linux guy, here, sorry I am late; I am just installing git-bash for the first time and looking into what its command should be in Windows Terminal. As far as I know Cygwin is not Windows, but it provides a POSIX translation layer (cygwin*.dll) so that all those non-Windows executables can run. Even when a new computer program is compiled and built with cygwin, it still turns out a non-Windows executable and it still needs cygwin*.dll to run. MSYS2 is mostly Windows with only a few tools that are probably difficult to port remaining non-Windows and requiring a POSIX translation layer to run (msys*.dll); but, most programs are actually Windows native executables. Even when a new computer program is compiled and built, it is my understanding that turns out a Windows native *.exe. But I still don't know how important it is that some of these MSYSTEM* and MINGW* environment variables be set or not, when I am going to be using MINGW compiler, anyway. I did notice that, throughout this thread, both command lines keep showing up, namely, ./bin/bash and ./usr/bin/bash; so, I went ahead and launched them to compare their environments...they can turn out rather different. Let it be known that, PREVIOUS to launching any of the shells below, I already have C:\Git\mingw64\bin and C:\Git\usr\bin as part of System variable PATH; I do this because I want to have the ability to use bash commands directly from CMD. But I don't think this does anything to the results below. c:\Git\bin\bash.exe --login c:\Git\usr\bin\bash.exe --login Environment Variable c:\Git\bin\bash.exe c:\Git\usr\bin\bash.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - EXEPATH c:\git\bin c:\git\bin n n HOSTNAME n MDXXXXXX n MDXXXXXX MINGW_CHOST n x86_64-w64-mingw32 n n MINGW_PACKAGE_PREFIX n mingw-w64-x86_64 n n MINGW_PREFIX n /mingw64 n n MSYSTEM_CARCH n x86_64 n x86_64 MSYSTEM_CHOST n x86_64-w64-mingw32 n x86_64-pc-msys MSYSTEM_PREFIX n /mingw64 n /usr MSYSTEM MINGW64 MINGW64 n MSYS PLINK_PROTOCOL ssh ssh n n SHELL n /usr/bin/bash n /usr/bin/bash TMPDIR n /tmp n /tmp ORIGINAL_PATH n y n y ORIGINAL_TEMP n y n y ORIGINAL_TMP n y n y PATH /mingw64/bin:/usr/bin:$HOME/bin:$PATH PATH $HOME/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:$HOME/bin:$PATH PATh $PATH PATH $HOME/bin:/usr/local/bin:/usr/bin:/bin:/opt/bin:$PATH So, for good measure, it looks to me as if the more correct thing would be to use ./bin/bash --login; but I at this very moment, I am not sure what the difference will be, say, when it comes to actually compiling a brand new program with MINGW64/GCC; we shall see. A: As far as I know from my current windows terminal version 1.15.2874.0, you can get what you want with a simple manual click to configure it. The prerequisites are your git bash client is installed. at least windows terminal version 1.15.2874.0 or higher. Then complete the setup by following these steps. Open windows terminal and find "Settings" in the drop-down list in the top right corner of the menu bar (or use the shortcut ctrl+,); Click on "Add new profile" at the bottom of the left hand column, then the settings template screen will pop up automatically. interactive mouse click you want to set the "name", "executable path command line", "startup directory", "icon" value. For example, I set mine to "gitBash", "C:\Program Files\Git\bin\bash.exe", "%USERPROFILE%", and "%USERPROFILE%" in order of customisation. "C:\Program Files\Git\mingw64\share\git\git-for-windows.ico". save. The following screenshots are for reference.
Adding Git-Bash to the new Windows Terminal
I'm trying to add a new terminal (Git Bash) to the new Windows Terminal. However, I can't get it to work. I tried changing the commandline property in the profiles array to git-bash.exe but no luck. Does anyone have an idea how to get this to work?
[ "Overview\n\nOpen settings with Ctrl+,\nYou'll want to append one of the profiles options below (depending on what version of git you have installed) to the \"list\": portion of the settings.json file:\n\n\n{\n \"$schema\": \"https://aka.ms/terminal-profiles-schema\",\n\n \"defaultProfile\": \"{00000000-0000-0000-ba54-000000000001}\",\n\n \"profiles\":\n {\n \"defaults\":\n {\n // Put settings here that you want to apply to all profiles\n },\n \"list\":\n [\n <put one of the configuration below right here>\n ]\n }\n}\n\nProfile options\nUncomment correct paths for commandline and icon if you are using:\n\nGit for Windows in %PROGRAMFILES%\nGit for Windows in %USERPROFILE%\nIf you're using scoop\n\n{\n \"guid\": \"{00000000-0000-0000-ba54-000000000002}\",\n \"commandline\": \"%PROGRAMFILES%/Git/usr/bin/bash.exe -i -l\",\n // \"commandline\": \"%USERPROFILE%/AppData/Local/Programs/Git/bin/bash.exe -l -i\",\n // \"commandline\": \"%USERPROFILE%/scoop/apps/git/current/usr/bin/bash.exe -l -i\",\n \"icon\": \"%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico\",\n // \"icon\": \"%USERPROFILE%/AppData/Local/Programs/Git/mingw64/share/git/git-for-windows.ico\",\n // \"icon\": \"%USERPROFILE%/scoop/apps/git/current/usr/share/git/git-for-windows.ico\",\n \"name\" : \"Bash\",\n \"startingDirectory\" : \"%USERPROFILE%\"\n},\n\nYou can also add other options like:\n{\n \"guid\": \"{00000000-0000-0000-ba54-000000000002}\",\n // ...\n \"acrylicOpacity\" : 0.75,\n \"closeOnExit\" : true,\n \"colorScheme\" : \"Campbell\",\n \"cursorColor\" : \"#FFFFFF\",\n \"cursorShape\" : \"bar\",\n \"fontFace\" : \"Consolas\",\n \"fontSize\" : 10,\n \"historySize\" : 9001,\n \"padding\" : \"0, 0, 0, 0\",\n \"snapOnInput\" : true,\n \"useAcrylic\" : true\n}\n\nNotes\n\nmake your own guid as of https://github.com/microsoft/terminal/pull/2475 this is no longer generated.\nthe guid can be used in in the globals > defaultProfile so you can press you can press CtrlShiftT\nor start a Windows terminal and it will start up bash by default\n\n\"defaultProfile\" : \"{00000000-0000-0000-ba54-000000000001}\",\n\n\n-l -i to make sure that .bash_profile gets loaded\nuse environment variables so they can map to different systems correctly.\ntarget git/bin/bash.exe to avoid spawning off additional processes which saves about 10MB per process according to Process Explorer compared to using bin/bash or git-bash\n\nI have my configuration that uses Scoop in https://gist.github.com/trajano/24f4edccd9a997fad8b4de29ea252cc8\n", "There are below things to do.\n\nMake sure the git command runs successfully in Command Prompt.\n\nThat means you need to add git to path when install git or add it to system environment later.\n\n\nUpdate the file profile.json: open Settings by pressing Ctrl+, in Windows Terminal, click on Open JSON file in the sidebar, and add following snippet inside the word profiles:\n\n\n { \n \"tabTitle\": \"Git Bash\",\n \"acrylicOpacity\" : 0.75, \n \"closeOnExit\" : true, \n \"colorScheme\" : \"Campbell\", \n \"commandline\" : \"C:/Program Files/Git/bin/bash.exe --login\", \n \"cursorColor\" : \"#FFFFFF\", \n \"cursorShape\" : \"bar\", \n \"fontFace\" : \"Consolas\", \n \"fontSize\" : 12, \n \"guid\" : \"{14ad203f-52cc-4110-90d6-d96e0f41b64d}\", \n \"historySize\" : 9001, \n \"icon\": \"ms-appdata:///roaming/git-bash_32px.ico\",\n \"name\" : \"Git Bash\", \n \"padding\" : \"0, 0, 0, 0\", \n \"snapOnInput\" : true, \n \"useAcrylic\" : true \n }\n\nThe icon can be obtained here: git-bash_32px.ico\nYou can add icons for Tab to this location:\n%LOCALAPPDATA%\\packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\RoamingState\nPut 32x32 PNG/icons in this folder, and then in profile.json you can reference the image resource with the path starting with ms-appdata://.\nNote that, please make sure the Guidis correct and it matches the corresponding correct configurations.\n\nTest that git bash works in Windows Terminal.\n\nThe final result is below:\n\n", "This is the complete answer (GitBash + color scheme + icon + context menu)\n\nSet default profile:\n\n\"globals\": \n{\n \"defaultProfile\" : \"{00000000-0000-0000-0000-000000000001}\",\n ...\n\n\nAdd GitBash profile\n\n\"profiles\": [\n {\n \"guid\": \"{00000000-0000-0000-0000-000000000001}\",\n \"acrylicOpacity\": 0.75,\n \"closeOnExit\": true,\n \"colorScheme\": \"GitBash\",\n \"commandline\": \"\\\"%PROGRAMFILES%\\\\Git\\\\usr\\\\bin\\\\bash.exe\\\" --login -i\",\n \"cursorColor\": \"#FFFFFF\",\n \"cursorShape\": \"bar\",\n \"fontFace\": \"Consolas\",\n \"fontSize\": 10,\n \"historySize\": 9001,\n \"icon\": \"%PROGRAMFILES%\\\\Git\\\\mingw64\\\\share\\\\git\\\\git-for-windows.ico\",\n \"name\": \"GitBash\",\n \"padding\": \"0, 0, 0, 0\",\n \"snapOnInput\": true,\n \"startingDirectory\": \"%USERPROFILE%\",\n \"useAcrylic\": false\n }\n]\n\n\nAdd GitBash color scheme\n\n \"schemes\": [\n {\n \"background\": \"#000000\",\n \"black\": \"#0C0C0C\",\n \"blue\": \"#6060ff\",\n \"brightBlack\": \"#767676\",\n \"brightBlue\": \"#3B78FF\",\n \"brightCyan\": \"#61D6D6\",\n \"brightGreen\": \"#16C60C\",\n \"brightPurple\": \"#B4009E\",\n \"brightRed\": \"#E74856\",\n \"brightWhite\": \"#F2F2F2\",\n \"brightYellow\": \"#F9F1A5\",\n \"cyan\": \"#3A96DD\",\n \"foreground\": \"#bfbfbf\",\n \"green\": \"#00a400\",\n \"name\": \"GitBash\",\n \"purple\": \"#bf00bf\",\n \"red\": \"#bf0000\",\n \"white\": \"#ffffff\",\n \"yellow\": \"#bfbf00\",\n \"grey\": \"#bfbfbf\"\n }\n ]\n\n\nTo add a right-click context menu \"Windows Terminal Here\"\n\nWindows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\wt]\n@=\"Windows terminal here\"\n\"Icon\"=\"C:\\\\Users\\\\{YOUR_WINDOWS_USERNAME}\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps\\\\{YOUR_ICONS_FOLDER}\\\\icon.ico\"\n\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\wt\\command]\n@=\"\\\"C:\\\\Users\\\\{YOUR_WINDOWS_USERNAME}\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps\\\\wt.exe\\\"\"\n\n\nReplace {YOUR_WINDOWS_USERNAME} with your Windows username.\nCreate an icon folder, put the icon there and replace {YOUR_ICONS_FOLDER} with your icon folder.\nSave this in a .reg file and run it.\n\n", "It's Sept 2021, thankfully the latest Git Installation installer for Windows (mine was using 2.33.0.2) already has this option covered for us, for the sake of our laziness (and convenience, of course!)\nPlease install the Windows Terminal first before installing Git, although I haven't try the otherway around, but better follow the sensible order. If the installation order is not the case, please let me know to update this answer.\nYou may find this handful checkbox at the bottom within the installation stage Select Components, just tick the box there and you're good to go.\n\nThe settings.json file will be added the Git Bash profile automatically with correct Git Bash icon. My generated Git Bash profile is pretty standard and minimal.\n{\n \"guid\": \"{2ece5bfe-50ed-5f3a-ab87-5cd4baafed2b}\",\n \"hidden\": false,\n \"name\": \"Git Bash\",\n \"source\": \"Git\"\n}\n\nIf Windows Terminal is running, close and launch again for the Git Bash option to be visible.\n", "Because most answers either show a lot of unrelated configuration or don't show the configuration, I created my own answer that tries to be more focused. It is mainly based on the profile settings reference and Archimedes Trajano's answer.\nSteps\n\nOpen PowerShell and enter [guid]::NewGuid() to generate a new GUID. We will use it at step 3.\n> [guid]::NewGuid()\n\nGuid\n----\na3da8d92-2f3f-4e36-9714-98876b6cb480\n\n\nOpen the settings of Windows Terminal. (CTRL+,)\n\nAdd the following JSON object to profiles.list. Replace guid with the one you generated at step 1.\n{\n \"guid\": \"{a3da8d92-2f3f-4e36-9714-98876b6cb480}\",\n \"name\": \"Git Bash\",\n \"commandline\": \"\\\"%PROGRAMFILES%\\\\Git\\\\usr\\\\bin\\\\bash.exe\\\" -i -l\",\n \"icon\": \"%PROGRAMFILES%\\\\Git\\\\mingw64\\\\share\\\\git\\\\git-for-windows.ico\",\n \"startingDirectory\" : \"%USERPROFILE%\"\n},\n\n\n\nNotes\n\nThere is currently an issue that you cannot use your arrow keys (and some other keys). It seems to work with the latest preview version, though. (issue #6859)\n\nSpecifying \"startingDirectory\" : \"%USERPROFILE%\" shouldn't be necessary according to the reference. However, if I don't specify it, the starting directory was different depending on how I started the terminal initially.\n\nSettings that shall apply to all terminals can be specified in profiles.defaults.\n\nI recommend to set \"antialiasingMode\": \"cleartype\" in profiles.defaults. You have to remove \"useAcrylic\" (if you have added it as suggested by some other answers) to make it work. It improves the quality of text rendering. However, you cannot have transparent background without useAcrylic. See issue #1298.\n\nIf you have problems with the cursor, you can try another shape like \"cursorShape\": \"filledBox\". See cursor settings for more information.\n\n\n", "That's how I've added mine in profiles json table,\n{\n \"guid\": \"{00000000-0000-0000-ba54-000000000002}\",\n \"name\": \"Git\",\n \"commandline\": \"C:/Program Files/Git/bin/bash.exe --login\",\n \"icon\": \"%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico\",\n \"startingDirectory\": \"%USERPROFILE%\",\n \"hidden\": false\n}\n\n", "In case anyone is looking for a UI-Based solution. Here it is:\n\nGo to the Terminal's settings.\n\nAt the Right buttom side, look for the \"Add new profile\" option.\nScreenshot for the Terminal's settings.\n\nSelect \"New Empty Profile\"\n\nNow complete the fields with the information about your bash. If your installation locations are the default ones, you could use these:\n\n\n\nName: Git-Bash\nCommand line: C:\\Program Files\\Git\\bin\\bash.exe\nStartin directory: [Leave as default]\nIcon: C:\\Program Files\\Git\\mingw64\\share\\git\\git-for-windows.ico\nTab title: Git-Bash\nTemrinal Settings completed\nYou could also browse for the right files in case you need to.\n\n\nHit Save button.\n\nFinal Result\nFinal Result. Bash terminal\n", "Another item to note - in settings.json\nI discovered if you don't use\n\"commandline\": \"C:/Program Files/Git/bin/bash.exe\"\nand instead use:\n\"commandline\": \"C:/Program Files/Git/git-bash.exe\"\nthe Git shell will open up in an independent window outside of Windows Terminal instead of on a tab - which is not the desired behavior.\nIn addition, the tab in Windows Terminal that opens will also need to be closed manually as it will display process exited information - [process exited with code 3221225786] etc.\nMight save someone some headache\n", "Change the profiles parameter to \"commandline\": \"%PROGRAMFILES%\\\\Git\\\\bin\\\\bash.exe -l -i\"\nThis works for me and allows for my .bash_profile alias autocomplete scripts to run.\n", "The new version of windows terminal can be configured through its GUI.\nSetting -> Add new\nUnder \"command line\" add the path -> path/to/Git/bin/bash.exe\n\n", "If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here\nC:\\Program Files\\Git\\mingw64\\share\\git\\git-for-windows I copied it into.\n%LOCALAPPDATA%\\packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\RoamingState\n\nand named it git-bash_32px as suggested above.\nControl the opacity with CTRL + SHIFT + scrolling.\n {\n \"acrylicOpacity\" : 0.75,\n \"closeOnExit\" : true,\n \"colorScheme\" : \"Campbell\",\n \"commandline\" : \"\\\"%PROGRAMFILES%\\\\git\\\\usr\\\\bin\\\\bash.exe\\\" -i -l\",\n \"cursorColor\" : \"#FFFFFF\",\n \"cursorShape\" : \"bar\",\n \"fontFace\" : \"Consolas\",\n \"fontSize\" : 10,\n \"guid\" : \"{73225108-7633-47ae-80c1-5d00111ef646}\",\n \"historySize\" : 9001,\n \"icon\" : \"ms-appdata:///roaming/git-bash_32px.ico\",\n \"name\" : \"Bash\",\n \"padding\" : \"0, 0, 0, 0\",\n \"snapOnInput\" : true,\n \"startingDirectory\" : \"%USERPROFILE%\",\n \"useAcrylic\" : true\n },\n\n", "I did as follows:\n\nAdd \"%programfiles%\\Git\\Bin\" to your PATH\nOn the profiles.json, set the desired command-line as \"commandline\" : \"sh --cd-to-home\"\nRestart the Windows Terminal\n\nIt worked for me.\n", "Adding \"%PROGRAMFILES%\\\\Git\\\\bin\\\\bash.exe -l -i\" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command \"C:\\Program\" instead of \"C:\\Program Files\\Git\\bin\\bash.exe -l -i\". The solution should be something like adding quotation marks in json file, but I didn't figure out how. \nThe only solution is to add \"C:\\Program Files\\Git\\bin\" to %PATH% and write \"commandline\": \"bash.exe\" in profiles.json\n", "To anyone who may suffer from missing bash history:\nin already opened git bash, try initiate another bash - that supposed to load your profile if env vars are properly configured\nIf this is your case, you can automate it by adding following command line on startup:\nC:\\progra~1\\git\\usr\\bin\\bash.exe --login -l -i -c /c/progra~1/git/usr/bin/bash.exe\n\n", "Linux guy, here, sorry I am late; I am just installing git-bash for the first time and looking into what its command should be in Windows Terminal.\nAs far as I know\n\nCygwin is not Windows, but it provides a POSIX translation layer (cygwin*.dll) so that all those non-Windows executables can run. Even when a new computer program is compiled and built with cygwin, it still turns out a non-Windows executable and it still needs cygwin*.dll to run.\nMSYS2 is mostly Windows with only a few tools that are probably difficult to port remaining non-Windows and requiring a POSIX translation layer to run (msys*.dll); but, most programs are actually Windows native executables. Even when a new computer program is compiled and built, it is my understanding that turns out a Windows native *.exe.\n\nBut I still don't know how important it is that some of these MSYSTEM* and MINGW* environment variables be set or not, when I am going to be using MINGW compiler, anyway.\nI did notice that, throughout this thread, both command lines keep showing up, namely, ./bin/bash and ./usr/bin/bash; so, I went ahead and launched them to compare their environments...they can turn out rather different.\nLet it be known that, PREVIOUS to launching any of the shells below, I already have C:\\Git\\mingw64\\bin and C:\\Git\\usr\\bin as part of System variable PATH; I do this because I want to have the ability to use bash commands directly from CMD. But I don't think this does anything to the results below.\n c:\\Git\\bin\\bash.exe --login c:\\Git\\usr\\bin\\bash.exe --login\nEnvironment Variable c:\\Git\\bin\\bash.exe c:\\Git\\usr\\bin\\bash.exe\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nEXEPATH c:\\git\\bin c:\\git\\bin n n\nHOSTNAME n MDXXXXXX n MDXXXXXX\nMINGW_CHOST n x86_64-w64-mingw32 n n\nMINGW_PACKAGE_PREFIX n mingw-w64-x86_64 n n\nMINGW_PREFIX n /mingw64 n n\nMSYSTEM_CARCH n x86_64 n x86_64\nMSYSTEM_CHOST n x86_64-w64-mingw32 n x86_64-pc-msys\nMSYSTEM_PREFIX n /mingw64 n /usr\nMSYSTEM MINGW64 MINGW64 n MSYS\nPLINK_PROTOCOL ssh ssh n n\nSHELL n /usr/bin/bash n /usr/bin/bash\nTMPDIR n /tmp n /tmp\n\nORIGINAL_PATH n y n y\nORIGINAL_TEMP n y n y\nORIGINAL_TMP n y n y\nPATH /mingw64/bin:/usr/bin:$HOME/bin:$PATH\nPATH $HOME/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:$HOME/bin:$PATH\nPATh $PATH\nPATH $HOME/bin:/usr/local/bin:/usr/bin:/bin:/opt/bin:$PATH\n\nSo, for good measure, it looks to me as if the more correct thing would be to use ./bin/bash --login; but I at this very moment, I am not sure what the difference will be, say, when it comes to actually compiling a brand new program with MINGW64/GCC; we shall see.\n", "As far as I know from my current windows terminal version 1.15.2874.0, you can get what you want with a simple manual click to configure it.\nThe prerequisites are\n\nyour git bash client is installed.\nat least windows terminal version 1.15.2874.0 or higher.\n\nThen complete the setup by following these steps.\n\nOpen windows terminal and find \"Settings\" in the drop-down list in the top right corner of the menu bar (or use the shortcut ctrl+,);\nClick on \"Add new profile\" at the bottom of the left hand column, then the settings template screen will pop up automatically.\ninteractive mouse click you want to set the \"name\", \"executable path command line\", \"startup directory\", \"icon\" value. For example, I set mine to \"gitBash\", \"C:\\Program Files\\Git\\bin\\bash.exe\", \"%USERPROFILE%\", and \"%USERPROFILE%\" in order of customisation. \"C:\\Program Files\\Git\\mingw64\\share\\git\\git-for-windows.ico\".\nsave.\n\nThe following screenshots are for reference.\n\n\n" ]
[ 749, 137, 118, 85, 57, 34, 18, 14, 11, 8, 6, 0, 0, 0, 0, 0 ]
[]
[]
[ "git_bash", "windows_terminal" ]
stackoverflow_0056839307_git_bash_windows_terminal.txt
Q: How to apply a theme / style in android without restarting the activity? I have an application where the user can chose between several different colored themes from a PreferenceActivity and thereby change the theme / color of the entire application. But the changes selected in the PreferenceActivity do not apply immediately. The changes are applied only when the user reenters the PreferenceActivity. I know I can call recreate() every time a theme is chosen, but I want to know if a better solution exists without recreating the entire activity. Here is an video of how it currently works: https://www.youtube.com/watch?v=oU8xIUi_48A This is where I set the chosen value from the preferenceList in my PreferenceActivity: @Override public void onCreate(Bundle savedInstanceState) { setTheme(); themecolorList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch (themecolorList.getValue()) { case "grey": themecolorList.getEditor().putString("grey", "green").apply(); break; case "green": themecolorList.getEditor().putString("green", "green").apply(); setTheme(R.style.AppTheme_default); break; case "blue": themecolorList.getEditor().putString("blue", "green").apply(); break; case "yellow": themecolorList.getEditor().putString("yellow", "green").apply(); break; case "red": themecolorList.getEditor().putString("red", "green").apply(); break; case "pink": themecolorList.getEditor().putString("pink", "green").apply(); break; default: themecolorList.getEditor().putString("green", "green").apply(); break; } recreate(); return true; } }); } The method setTheme(); is called in my PreferenceActivitys onCreate(); method private void setTheme() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); switch (sharedPreferences.getString("THEME_KEY", "green")) { case "grey": setTheme(R.style.AppTheme_Grey); break; case "green": setTheme(R.style.AppTheme_default); break; case "blue": setTheme(R.style.AppTheme_Blue); break; case "yellow": setTheme(R.style.AppTheme_Yellow); break; case "red": setTheme(R.style.AppTheme_Red); break; case "pink": setTheme(R.style.AppTheme_Pink); break; default: getApplication().setTheme(R.style.AppTheme_default); setTheme(R.style.AppTheme_default); break; } } A: It seems to be that the best solution is to use recreate(); since there is no other way to refresh a whole layout for an activity: For everytime the user presses on a options from the list of themes the key/value for the pressed one is saved via OnPreferenceChangeListener in a SharedPreference and recreate(); is then called. themecolorList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { recreate(); return true; } }); In my PreferenceActivitys onCreate(); I call a custom made method setTheme(); which is called after recreate(); is called. The setTheme(); just looks up what is saved in SharedPreference from the OnPreferenceChangeListener and set the theme to corresponding value @Override public void onCreate(Bundle savedInstanceState) { setTheme(); super.onCreate(savedInstanceState); } A: You can't. You can start a new activity for selecting theme and when user selects finish that activity. A: Triggering a layout update (by rotating the device, or making the app think it's rotated) should normally cause it to reload its resources. I don't remember exactly how to do it at the moment, but it was a common practice the last time I investigated how to do something similar. Just remember to specify (in the manifest?) that your activity will handle layout changes/screen rotation to avoid a full restart (and loss of any unsaved data). A: You can use this. It works for me. @HiltAndroidApp class App : Application(){ companion object{ private var isOpening = true fun appIsOpening(sync : (Boolean) -> Unit){ sync(isOpening) isOpening = false } } } and @AndroidEntryPoint class SingleActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() setContentView(R.layout.activity_main) App.appIsOpening { it -> if (it)setStartDestination() } } }
How to apply a theme / style in android without restarting the activity?
I have an application where the user can chose between several different colored themes from a PreferenceActivity and thereby change the theme / color of the entire application. But the changes selected in the PreferenceActivity do not apply immediately. The changes are applied only when the user reenters the PreferenceActivity. I know I can call recreate() every time a theme is chosen, but I want to know if a better solution exists without recreating the entire activity. Here is an video of how it currently works: https://www.youtube.com/watch?v=oU8xIUi_48A This is where I set the chosen value from the preferenceList in my PreferenceActivity: @Override public void onCreate(Bundle savedInstanceState) { setTheme(); themecolorList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch (themecolorList.getValue()) { case "grey": themecolorList.getEditor().putString("grey", "green").apply(); break; case "green": themecolorList.getEditor().putString("green", "green").apply(); setTheme(R.style.AppTheme_default); break; case "blue": themecolorList.getEditor().putString("blue", "green").apply(); break; case "yellow": themecolorList.getEditor().putString("yellow", "green").apply(); break; case "red": themecolorList.getEditor().putString("red", "green").apply(); break; case "pink": themecolorList.getEditor().putString("pink", "green").apply(); break; default: themecolorList.getEditor().putString("green", "green").apply(); break; } recreate(); return true; } }); } The method setTheme(); is called in my PreferenceActivitys onCreate(); method private void setTheme() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); switch (sharedPreferences.getString("THEME_KEY", "green")) { case "grey": setTheme(R.style.AppTheme_Grey); break; case "green": setTheme(R.style.AppTheme_default); break; case "blue": setTheme(R.style.AppTheme_Blue); break; case "yellow": setTheme(R.style.AppTheme_Yellow); break; case "red": setTheme(R.style.AppTheme_Red); break; case "pink": setTheme(R.style.AppTheme_Pink); break; default: getApplication().setTheme(R.style.AppTheme_default); setTheme(R.style.AppTheme_default); break; } }
[ "It seems to be that the best solution is to use recreate(); since there is no other way to refresh a whole layout for an activity:\nFor everytime the user presses on a options from the list of themes\nthe key/value for the pressed one is saved via OnPreferenceChangeListener in a SharedPreference and recreate(); is then called.\nthemecolorList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {\n @Override\n public boolean onPreferenceChange(Preference preference, Object newValue) {\n recreate();\n return true;\n }\n });\n\nIn my PreferenceActivitys onCreate(); I call a custom made method setTheme(); which is called after recreate(); is called. The setTheme(); just looks up what is saved in SharedPreference from the OnPreferenceChangeListener and set the theme to corresponding value\n @Override\n public void onCreate(Bundle savedInstanceState) {\n setTheme();\n super.onCreate(savedInstanceState);\n}\n\n", "You can't.\nYou can start a new activity for selecting theme and when user selects finish that activity.\n", "Triggering a layout update (by rotating the device, or making the app think it's rotated) should normally cause it to reload its resources. \nI don't remember exactly how to do it at the moment, but it was a common practice the last time I investigated how to do something similar. \nJust remember to specify (in the manifest?) that your activity will handle layout changes/screen rotation to avoid a full restart (and loss of any unsaved data). \n", "You can use this. It works for me.\n@HiltAndroidApp\nclass App : Application(){\n\n companion object{\n private var isOpening = true\n fun appIsOpening(sync : (Boolean) -> Unit){\n sync(isOpening)\n isOpening = false\n }\n }\n\n}\n\nand\n@AndroidEntryPoint\nclass SingleActivity : AppCompatActivity() {\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n installSplashScreen()\n setContentView(R.layout.activity_main)\n\n App.appIsOpening { it ->\n if (it)setStartDestination()\n }\n }\n\n\n}\n\n" ]
[ 8, 0, 0, 0 ]
[ "It looks like there is a method called invalidate() to be called on views that need to be redrawn.\nLink\nWhich should allow you to call on individual views that only need redrawing. Not the whole activity.\n" ]
[ -1 ]
[ "android" ]
stackoverflow_0037823231_android.txt
Q: Is there a way to force text in flex box to be centered vertically, no matter what other CSS codes we have? I have the following CSS code, which is part of a much bigger CSS code used in the website I am working on: .cards-u { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; } .card-u { margin: 20px; padding: 20px; width: 160px; height: 160px; line-height: 120px; justify-content: center; align-items: center; text-align: center; align-self: center; flex-direction: column; border-radius: 10px; box-shadow: 0px 6px 10px rgba(0, 0, 0, 0.25); transition: all 0.2s; text-decoration: none; } .card-1-u { background: radial-gradient(#1fe4f5, #3fbafe); } and in the HTML code I have: <div class="cards-u"> <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;"> <h3>Text Sample 1</h3> </a> <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;"> <h3>Text Sample 2</h3> </a> </div> but the texts Text Sample 1 and Text Sample 2 are not centered vertically and are at the top of the flexbox. It seems something from my large CSS code is interfering, but I don't know what. My question is assuming we don't know what is the rest of the CSS, can we force this part to do what we want, which is centering the text vertically inside the flex boxs? A: This is happening becuase .cards-u doesn't have any height defined. Its taking the content's height as its own height and keeping the content within that area. You should either give .cards-u full page height using 100vh or do like: .cards-u{ position: relative; } .card-u{ position: absolute; top: 50%; transform: translateY(-50%); }
Is there a way to force text in flex box to be centered vertically, no matter what other CSS codes we have?
I have the following CSS code, which is part of a much bigger CSS code used in the website I am working on: .cards-u { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; } .card-u { margin: 20px; padding: 20px; width: 160px; height: 160px; line-height: 120px; justify-content: center; align-items: center; text-align: center; align-self: center; flex-direction: column; border-radius: 10px; box-shadow: 0px 6px 10px rgba(0, 0, 0, 0.25); transition: all 0.2s; text-decoration: none; } .card-1-u { background: radial-gradient(#1fe4f5, #3fbafe); } and in the HTML code I have: <div class="cards-u"> <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;"> <h3>Text Sample 1</h3> </a> <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;"> <h3>Text Sample 2</h3> </a> </div> but the texts Text Sample 1 and Text Sample 2 are not centered vertically and are at the top of the flexbox. It seems something from my large CSS code is interfering, but I don't know what. My question is assuming we don't know what is the rest of the CSS, can we force this part to do what we want, which is centering the text vertically inside the flex boxs?
[ "This is happening becuase .cards-u doesn't have any height defined. Its taking the content's height as its own height and keeping the content within that area.\nYou should either give .cards-u full page height using 100vh or do like:\n.cards-u{\n position: relative;\n}\n\n.card-u{\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n\n}\n\n" ]
[ 0 ]
[]
[]
[ "css", "flexbox", "html", "vertical_alignment" ]
stackoverflow_0074673163_css_flexbox_html_vertical_alignment.txt
Q: Unable to see 4688 events in event viewer I have all the settings as per https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing However, I am unable to see any 4688 events in my event viewer.This started happening when I updated my windows(I have windows 11). Has anyone faced a similar issue. Also, how do I make sure I have all the settings in place using command line? A: KB5020044 Fixes Process Creation Audit Logging - Event ID 4688/1108 Issue To resolve the issue, install the November 29, 2022โ€”KB5020044 (OS Build 22621.900) Preview Cumulative Update. Improvements: It addresses an issue that affects process creation. It fails to create security audits for it and other related audit events.
Unable to see 4688 events in event viewer
I have all the settings as per https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing However, I am unable to see any 4688 events in my event viewer.This started happening when I updated my windows(I have windows 11). Has anyone faced a similar issue. Also, how do I make sure I have all the settings in place using command line?
[ "KB5020044 Fixes Process Creation Audit Logging - Event ID 4688/1108 Issue\nTo resolve the issue, install the November 29, 2022โ€”KB5020044 (OS Build 22621.900) Preview Cumulative Update.\nImprovements:\n\nIt addresses an issue that affects process creation. It fails to\ncreate security audits for it and other related audit events.\n\n" ]
[ 0 ]
[]
[]
[ "audit_logging", "event_viewer", "security" ]
stackoverflow_0073981520_audit_logging_event_viewer_security.txt
Q: How to fix the quiz countdown timer? Can someone or anyone please help me to fix the quiz countdown timer. The problem is the quiz countdown timer is stuck to question #1, if the user is not answered it will be go to the next questions. And also the Submit & Next button I can't click it after I answered the question it will be go to the next questions too. Where codes I should fix, please help. quiz preview Here's my quiz_php <?php $quiz_questions = $this->crud_model->get_quiz_questions($lesson_details['id']); ?> <div id="quiz-body"> <div class="" id="quiz-header"> <?php echo get_phrase("quiz_title"); ?> : <strong><?php echo $lesson_details['title']; ?></strong><br> <?php echo get_phrase("number_of_questions"); ?> : <strong><?php echo count($quiz_questions->result_array()); ?></strong><br> <?php if (count($quiz_questions->result_array()) > 0): ?> <button id="start_page" type="button" name="button" class="btn btn-sign-up mt-2" style="color: #fff;" onclick="getStarted(1)"><?php echo get_phrase("get_started"); ?></button> <?php endif; ?> </div> <form class="" id="quiz_form" action="" method="post"> <?php if (count($quiz_questions->result_array()) > 0): ?> <?php foreach ($quiz_questions->result_array() as $key => $quiz_question): $options = json_decode($quiz_question['options']); ?> <input type="hidden" name="lesson_id" value="<?php echo $lesson_details['id']; ?>"> <div class="hidden" id = "question-number-<?php echo $key+1; ?>"> <div class="row justify-content-center"> <div class="col-lg-8"> <div class="card text-left"> <div class="card-body"> <h6 class="card-title"><?php echo get_phrase("question").' '.($key+1); ?> : <strong><?php echo $quiz_question['title']; ?></strong></h6> </div> <ul class="list-group list-group-flush"> <?php foreach ($options as $key2 => $option): ?> <li class="list-group-item quiz-options"> <div class="form-check"> <input class="form-check-input" type="checkbox" name="<?php echo $quiz_question['id']; ?>[]" value="<?php echo $key2+1; ?>" id="quiz-id-<?php echo $quiz_question['id']; ?>-option-id-<?php echo $key2+1; ?>" onclick="enableNextButton('<?php echo $quiz_question['id'];?>')"> <label class="form-check-label" for="quiz-id-<?php echo $quiz_question['id']; ?>-option-id-<?php echo $key2+1; ?>"> <?php echo $option; ?> </label> </div> </li> <?php endforeach; ?> </ul> </div> <div class="justify-content-end" style="float: right; margin: 5px 0px 40px 40px;"> <div class="card"> <div class="card-body" id="clock"> <h5 class="text-right m-1"> Quiz Time: 00:<span class="" id="time">00</span></h5> </div> </div> </div> </div> </div> <button type="button" name="button" class="btn btn-sign-up mt-2 mb-2" id="next-btn-<?php echo $quiz_question['id'];?>" style="color: #fff;" <?php if(count($quiz_questions->result_array()) == $key+1):?> onclick="submitQuiz()"<?php else: ?>onclick="showNextQuestion('<?php echo $key+2; ?>')"<?php endif; ?> disabled> <?php echo count($quiz_questions->result_array()) == $key+1 ? get_phrase("check_result") : get_phrase("submit_&_next"); ?></button> </div> <?php endforeach; ?> <?php endif; ?> </form> </div> <div id="quiz-result" class="text-left"> </div> <script type="text/javascript"> // Quiz with Countdown Timer function getStarted(first_quiz_question) { $('#quiz-header').hide(); $('#lesson-summary').hide(); $('#question-number-'+first_quiz_question).show(); var timer = 30; // Time counter var quiz_questionsCount = 0; // Questions counter // Questions array var questions = 'quiz_form'; questionDivId = document.getElementById('start_page'); setInterval(function () { timer--; if (timer >= 0) { id = document.getElementById('time'); id.innerHTML = timer; } if (timer === 0) { id.innerHTML = alert('Time is over. Next Question...'); timer = 30; quiz_questionsCount++; } // To check if all questions are completed or not will be show the quiz result if (quiz_questionsCount === questions.length){ questionDivId.innerHTML = alert('Your time has finally over. It seems some of your quiz has not been answered.'); id.innerHTML = ""; function submitQuiz() { $.ajax({ url: '<?php echo site_url('home/submit_quiz'); ?>', type: 'post', data: $('form#quiz_form').serialize(), success: function(response) { $('#quiz-body').hide(); $('#quiz-result').html(response); } }); } } else{ questionDivId.innerHTML = questions[quiz_questionsCount]; } }, 1000) // To go to the next question function showNextQuestion(next_question) { $('#question-number-'+(next_question-1)).show(); $('#question-number-'+next_question).show(); quiz_questionsCount++; timer = 30; } } function submitQuiz() { $.ajax({ url: '<?php echo site_url('home/submit_quiz'); ?>', type: 'post', data: $('form#quiz_form').serialize(), success: function(response) { $('#quiz-body').hide(); $('#quiz-result').html(response); } }); } function enableNextButton(quizID) { $('#next-btn-'+quizID).prop('disabled', false); } </script> I am expecting the result of quiz with the quiz countdown timer works perfectly if the user is answered it will pause the time (example 25secs) then user click next button it will be go to the next questions where the timer will continue last timer and so on. And if the user is not answered or away from keyboard it will show alert message the 'Time is over' it will be disabled the question's choices, user will go to the next questions. A: you are using setInterval() in js to calculate the time which is not accurate and data/timer is deemed to fail at time point in time, i would recommend to do it with date-time use below function to get time diff and call it insude setInterval so that values doesn't get effected by language. function getTimeRemaining(expire) { var t = utcDate(new Date(Date.parse(expire))) - utcDate(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); var hours = Math.floor((t / (1000 * 60 * 60)) % 24); var days = Math.floor(t / (1000 * 60 * 60 * 24)); return { 'total': t, 'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds }; } var expire = "<?php echo $exp; ?>"; getTimeRemaining(expire);
How to fix the quiz countdown timer?
Can someone or anyone please help me to fix the quiz countdown timer. The problem is the quiz countdown timer is stuck to question #1, if the user is not answered it will be go to the next questions. And also the Submit & Next button I can't click it after I answered the question it will be go to the next questions too. Where codes I should fix, please help. quiz preview Here's my quiz_php <?php $quiz_questions = $this->crud_model->get_quiz_questions($lesson_details['id']); ?> <div id="quiz-body"> <div class="" id="quiz-header"> <?php echo get_phrase("quiz_title"); ?> : <strong><?php echo $lesson_details['title']; ?></strong><br> <?php echo get_phrase("number_of_questions"); ?> : <strong><?php echo count($quiz_questions->result_array()); ?></strong><br> <?php if (count($quiz_questions->result_array()) > 0): ?> <button id="start_page" type="button" name="button" class="btn btn-sign-up mt-2" style="color: #fff;" onclick="getStarted(1)"><?php echo get_phrase("get_started"); ?></button> <?php endif; ?> </div> <form class="" id="quiz_form" action="" method="post"> <?php if (count($quiz_questions->result_array()) > 0): ?> <?php foreach ($quiz_questions->result_array() as $key => $quiz_question): $options = json_decode($quiz_question['options']); ?> <input type="hidden" name="lesson_id" value="<?php echo $lesson_details['id']; ?>"> <div class="hidden" id = "question-number-<?php echo $key+1; ?>"> <div class="row justify-content-center"> <div class="col-lg-8"> <div class="card text-left"> <div class="card-body"> <h6 class="card-title"><?php echo get_phrase("question").' '.($key+1); ?> : <strong><?php echo $quiz_question['title']; ?></strong></h6> </div> <ul class="list-group list-group-flush"> <?php foreach ($options as $key2 => $option): ?> <li class="list-group-item quiz-options"> <div class="form-check"> <input class="form-check-input" type="checkbox" name="<?php echo $quiz_question['id']; ?>[]" value="<?php echo $key2+1; ?>" id="quiz-id-<?php echo $quiz_question['id']; ?>-option-id-<?php echo $key2+1; ?>" onclick="enableNextButton('<?php echo $quiz_question['id'];?>')"> <label class="form-check-label" for="quiz-id-<?php echo $quiz_question['id']; ?>-option-id-<?php echo $key2+1; ?>"> <?php echo $option; ?> </label> </div> </li> <?php endforeach; ?> </ul> </div> <div class="justify-content-end" style="float: right; margin: 5px 0px 40px 40px;"> <div class="card"> <div class="card-body" id="clock"> <h5 class="text-right m-1"> Quiz Time: 00:<span class="" id="time">00</span></h5> </div> </div> </div> </div> </div> <button type="button" name="button" class="btn btn-sign-up mt-2 mb-2" id="next-btn-<?php echo $quiz_question['id'];?>" style="color: #fff;" <?php if(count($quiz_questions->result_array()) == $key+1):?> onclick="submitQuiz()"<?php else: ?>onclick="showNextQuestion('<?php echo $key+2; ?>')"<?php endif; ?> disabled> <?php echo count($quiz_questions->result_array()) == $key+1 ? get_phrase("check_result") : get_phrase("submit_&_next"); ?></button> </div> <?php endforeach; ?> <?php endif; ?> </form> </div> <div id="quiz-result" class="text-left"> </div> <script type="text/javascript"> // Quiz with Countdown Timer function getStarted(first_quiz_question) { $('#quiz-header').hide(); $('#lesson-summary').hide(); $('#question-number-'+first_quiz_question).show(); var timer = 30; // Time counter var quiz_questionsCount = 0; // Questions counter // Questions array var questions = 'quiz_form'; questionDivId = document.getElementById('start_page'); setInterval(function () { timer--; if (timer >= 0) { id = document.getElementById('time'); id.innerHTML = timer; } if (timer === 0) { id.innerHTML = alert('Time is over. Next Question...'); timer = 30; quiz_questionsCount++; } // To check if all questions are completed or not will be show the quiz result if (quiz_questionsCount === questions.length){ questionDivId.innerHTML = alert('Your time has finally over. It seems some of your quiz has not been answered.'); id.innerHTML = ""; function submitQuiz() { $.ajax({ url: '<?php echo site_url('home/submit_quiz'); ?>', type: 'post', data: $('form#quiz_form').serialize(), success: function(response) { $('#quiz-body').hide(); $('#quiz-result').html(response); } }); } } else{ questionDivId.innerHTML = questions[quiz_questionsCount]; } }, 1000) // To go to the next question function showNextQuestion(next_question) { $('#question-number-'+(next_question-1)).show(); $('#question-number-'+next_question).show(); quiz_questionsCount++; timer = 30; } } function submitQuiz() { $.ajax({ url: '<?php echo site_url('home/submit_quiz'); ?>', type: 'post', data: $('form#quiz_form').serialize(), success: function(response) { $('#quiz-body').hide(); $('#quiz-result').html(response); } }); } function enableNextButton(quizID) { $('#next-btn-'+quizID).prop('disabled', false); } </script> I am expecting the result of quiz with the quiz countdown timer works perfectly if the user is answered it will pause the time (example 25secs) then user click next button it will be go to the next questions where the timer will continue last timer and so on. And if the user is not answered or away from keyboard it will show alert message the 'Time is over' it will be disabled the question's choices, user will go to the next questions.
[ "you are using setInterval() in js to calculate the time which is not accurate and data/timer is deemed to fail at time point in time, i would recommend to do it with date-time use below function to get time diff and call it insude setInterval so that values doesn't get effected by language.\nfunction getTimeRemaining(expire) {\n var t = utcDate(new Date(Date.parse(expire))) - utcDate(new Date());\n var seconds = Math.floor((t / 1000) % 60);\n var minutes = Math.floor((t / 1000 / 60) % 60);\n var hours = Math.floor((t / (1000 * 60 * 60)) % 24);\n var days = Math.floor(t / (1000 * 60 * 60 * 24));\n return {\n 'total': t,\n 'days': days,\n 'hours': hours,\n 'minutes': minutes,\n 'seconds': seconds\n };\n}\n\nvar expire = \"<?php echo $exp; ?>\";\ngetTimeRemaining(expire);\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "php" ]
stackoverflow_0074673092_javascript_php.txt
Q: How to run a function periodically with Flask and Celery? I have a flask app that roughly looks like this: app = Flask(__name__) @app.route('/',methods=['POST']) def foo(): data = json.loads(request.data) # do some stuff return "OK" Now in addition I would like to run a function every ten seconds from that script. I don't want to use sleep for that. I have the following celery script in addition: from celery import Celery from datetime import timedelta celery = Celery('__name__') CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': timedelta(seconds=10) }, } @celery.task(name='tasks.add') def hello(): app.logger.info('run my function') The script works fine, but the logger.info is not executed. What am I missing? A: Do you have Celery worker and Celery beat running? Scheduled tasks are handled by beat, which queues the task mentioned when appropriate. Worker then actually crunches the numbers and executes your task. celery worker --app myproject--loglevel=info celery beat --app myproject Your task however looks like it's calling the Flask app's logger. When using the worker, you probably don't have the Flask application around (since it's in another process). Try using a normal Python logger for the demo task. A: Well, celery beat can be embedded in regular celery worker as well, with -B parameter in your command. celery -A --app myproject --loglevel=info -B It is only recommended for the development environment. For production, you should run beat and celery workers separately as documentation mentions. Otherwise, your periodic task will run more than one time. A: A celery task by default will run outside of the Flask app context and thus it won't have access to Flask app instance. However it's very easy to create the Flask app context while running a task by using app_context method of the Flask app object. app = Flask(__name__) celery = Celery(app.name) @celery.task def task(): with app.app_context(): app.logger.info('running my task') This article by Miguel Grinberg is a very good place to get a primer on the basics of using Celery in a Flask application. A: First install the redis on machine and check it is running or not. install the python dependencies celery redis flask folder structure project app init.py task.py main.py write task.py from celery import Celery from celery.schedules import crontab from app import app from app.scrap import product_data from celery.utils.log import get_task_logger logger = get_task_logger(__name__) def make_celery(app): #Celery configuration app.config['CELERY_BROKER_URL'] = 'redis://127.0.0.1:6379' app.config['CELERY_RESULT_BACKEND'] = 'db+postgresql://user:[email protected]:5432/mydatabase' app.config['CELERY_RESULT_EXTENDED']=True app.config['CELERYBEAT_SCHEDULE'] = { # Executes every minute 'periodic_task-every-minute': { 'task': 'periodic_task', 'schedule': crontab(minute="*") } } celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(app) @celery.task(name="periodic_task",bind=True) def testing(self): file1 = open("../myfile.txt", "a") # writing newline character file1.write("\n") file1.write("Today") #faik print("Running") self.request.task_name = "state" logger.info("Hello! from periodic task") return "Done" write init.py from flask import Flask, Blueprint,request from flask_restx import Api,Resource,fields from flask_sqlalchemy import SQLAlchemy import redis from rq import Queue app = Flask(__name__) app.config['SECRET_KEY']='7c09ebc8801a0ce8fb82b3d2ec51b4db' app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db' db=SQLAlchemy(app) command to run celery beat and worker celery -A app.task.celery beat celery -A app.task.celery worker --loglevel=info
How to run a function periodically with Flask and Celery?
I have a flask app that roughly looks like this: app = Flask(__name__) @app.route('/',methods=['POST']) def foo(): data = json.loads(request.data) # do some stuff return "OK" Now in addition I would like to run a function every ten seconds from that script. I don't want to use sleep for that. I have the following celery script in addition: from celery import Celery from datetime import timedelta celery = Celery('__name__') CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': timedelta(seconds=10) }, } @celery.task(name='tasks.add') def hello(): app.logger.info('run my function') The script works fine, but the logger.info is not executed. What am I missing?
[ "Do you have Celery worker and Celery beat running? Scheduled tasks are handled by beat, which queues the task mentioned when appropriate. Worker then actually crunches the numbers and executes your task.\ncelery worker --app myproject--loglevel=info\ncelery beat --app myproject\n\nYour task however looks like it's calling the Flask app's logger. When using the worker, you probably don't have the Flask application around (since it's in another process). Try using a normal Python logger for the demo task.\n", "Well, celery beat can be embedded in regular celery worker as well, with -B parameter in your command.\ncelery -A --app myproject --loglevel=info -B \nIt is only recommended for the development environment. For production, you should run beat and celery workers separately as documentation mentions. Otherwise, your periodic task will run more than one time.\n", "A celery task by default will run outside of the Flask app context and thus it won't have access to Flask app instance. However it's very easy to create the Flask app context while running a task by using app_context method of the Flask app object.\napp = Flask(__name__)\ncelery = Celery(app.name)\n\[email protected]\ndef task():\n with app.app_context():\n app.logger.info('running my task')\n\nThis article by Miguel Grinberg is a very good place to get a primer on the basics of using Celery in a Flask application.\n", "First install the redis on machine and check it is running or not.\ninstall the python dependencies\n\ncelery\nredis\nflask\n\nfolder structure\n\nproject\n\napp\n\ninit.py\ntask.py\n\n\nmain.py\n\n\n\nwrite task.py\nfrom celery import Celery\nfrom celery.schedules import crontab\nfrom app import app\nfrom app.scrap import product_data\nfrom celery.utils.log import get_task_logger\nlogger = get_task_logger(__name__)\ndef make_celery(app):\n #Celery configuration\n app.config['CELERY_BROKER_URL'] = 'redis://127.0.0.1:6379'\n app.config['CELERY_RESULT_BACKEND'] = 'db+postgresql://user:[email protected]:5432/mydatabase'\n app.config['CELERY_RESULT_EXTENDED']=True\n app.config['CELERYBEAT_SCHEDULE'] = {\n # Executes every minute\n 'periodic_task-every-minute': {\n 'task': 'periodic_task',\n 'schedule': crontab(minute=\"*\")\n }\n }\n\n\n celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])\n celery.conf.update(app.config)\n TaskBase = celery.Task\n class ContextTask(TaskBase):\n abstract = True\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return TaskBase.__call__(self, *args, **kwargs)\n celery.Task = ContextTask\n return celery\ncelery = make_celery(app)\n\[email protected](name=\"periodic_task\",bind=True)\ndef testing(self):\n file1 = open(\"../myfile.txt\", \"a\")\n\n # writing newline character\n file1.write(\"\\n\")\n file1.write(\"Today\")\n #faik\n print(\"Running\")\n self.request.task_name = \"state\"\n logger.info(\"Hello! from periodic task\")\n return \"Done\"\n\nwrite init.py\nfrom flask import Flask, Blueprint,request\nfrom flask_restx import Api,Resource,fields\nfrom flask_sqlalchemy import SQLAlchemy\nimport redis\nfrom rq import Queue\n\napp = Flask(__name__)\napp.config['SECRET_KEY']='7c09ebc8801a0ce8fb82b3d2ec51b4db'\napp.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'\ndb=SQLAlchemy(app)\n\ncommand to run celery beat and worker\ncelery -A app.task.celery beat\ncelery -A app.task.celery worker --loglevel=info\n\n" ]
[ 11, 5, 4, 0 ]
[]
[]
[ "celery", "flask", "python" ]
stackoverflow_0028761750_celery_flask_python.txt
Q: center image use with "position: absolute" <!DOCTYPE html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../css/style.css"> <title>Document</title> </head> <body> <!-- <img id="button" src="../art/button/menu.png" onclick="viewMenu()"> --> <div class="images"> <img id="clock" src="../art/namArt/clock/clock.png"> <img id="time" src="../art/namArt/clock/time.png"> <img id="minus" src="../art/namArt/clock/minus.png"> <img id="second" src="../art/namArt/clock/second.png"> </div> </body> </html> body{ background-color: greenyellow; } #clock, #minus, #second, #time{ position: absolute; /* display: block; margin-left: auto; margin-right: auto; */ } #clock{ /* background-image: url(../art/namArt/clock/time.png); */ height: 350px; } .images{ /* size: 300px; width: 100%; */ /* background-image: url("../art/namArt/clock/clock.png") ; background-repeat: no-repeat; background-size: contain; */ /* display: block; margin-left: auto; margin-right: auto; */ text-align: center; } i want to create clock use with art. But when i override and align center image by use position: absolute and text-align: center but it just center left of image, not center of image. (thanks for reading and i'm so sorry for my bad english) A: May be you should try: #clock, #minus, #second, #time{ position:absolute; left: 0; right: 0; margin: auto; text-align: center; }
center image use with "position: absolute"
<!DOCTYPE html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../css/style.css"> <title>Document</title> </head> <body> <!-- <img id="button" src="../art/button/menu.png" onclick="viewMenu()"> --> <div class="images"> <img id="clock" src="../art/namArt/clock/clock.png"> <img id="time" src="../art/namArt/clock/time.png"> <img id="minus" src="../art/namArt/clock/minus.png"> <img id="second" src="../art/namArt/clock/second.png"> </div> </body> </html> body{ background-color: greenyellow; } #clock, #minus, #second, #time{ position: absolute; /* display: block; margin-left: auto; margin-right: auto; */ } #clock{ /* background-image: url(../art/namArt/clock/time.png); */ height: 350px; } .images{ /* size: 300px; width: 100%; */ /* background-image: url("../art/namArt/clock/clock.png") ; background-repeat: no-repeat; background-size: contain; */ /* display: block; margin-left: auto; margin-right: auto; */ text-align: center; } i want to create clock use with art. But when i override and align center image by use position: absolute and text-align: center but it just center left of image, not center of image. (thanks for reading and i'm so sorry for my bad english)
[ "May be you should try:\n#clock, #minus, #second, #time{\nposition:absolute;\nleft: 0;\nright: 0;\nmargin: auto;\ntext-align: center;\n}\n\n" ]
[ 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074673106_css_html.txt
Q: Warning: Functions are not valid as a React child.This may happen if you return a Component instead of from render I get the above error when I try to display {props.child}.The page remains blank.The detailed warning is index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in div (at CustomLayout.js:28) in main (created by Basic) in Basic (created by Context.Consumer) in Content (at CustomLayout.js:22) in section (created by BasicLayout) in BasicLayout (created by Context.Consumer) in Layout (at CustomLayout.js:8) in CustomLayout (at App.js:10) in div (at App.js:9) in App (at src/index.js:7) Below are the project files. Article.js is a component and ArticleListView and CustomLayout are containers to it. I am trying to access the child elements in CustomLayout.js by {props.children} App.js import React from 'react'; import './App.css'; import 'antd/dist/antd.css'; import CustomLayout from './containers/CustomLayout' import ArticleListView from './containers/ArticleListView'; function App() { return ( <div className="App"> <CustomLayout> {ArticleListView} </CustomLayout> </div> ); } export default App ArticleListView.js import React from 'react' import Article from '../components/Article' class ArticleListView extends React.Component{ render(){ return( <Article/> ); } } export default ArticleListView Article.js import React from 'react' import { List, Avatar, Icon } from 'antd'; const listData = []; for (let i = 0; i < 23; i++) { listData.push({ href: 'http://ant.design', title: `ant design part ${i}`, avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.', content: 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', }); } const IconText = ({ type, text }) => ( <span> <Icon type={type} style={{ marginRight: 8 }} /> {text} </span> ); function Article(props){ return( <List itemLayout="vertical" size="large" pagination={{ onChange: page => { console.log(page); }, pageSize: 3, }} dataSource={listData} footer={ <div> <b>ant design</b> footer part </div> } renderItem={item => ( <List.Item key={item.title} actions={[ <IconText type="star-o" text="156" key="list-vertical-star-o" />, <IconText type="like-o" text="156" key="list-vertical-like-o" />, <IconText type="message" text="2" key="list-vertical-message" />, ]} extra={ <img width={272} alt="logo" src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png" /> } > <List.Item.Meta avatar={<Avatar src={item.avatar} />} title={<a href={item.href}>{item.title}</a>} description={item.description} /> {item.content} </List.Item> )} /> ); } export default <Article/> CustomLayout.js import React from 'react' import { Layout, Menu, Breadcrumb } from 'antd'; const { Header, Content, Footer } = Layout; function CustomLayout(props){ return( <Layout className="layout"> <Header> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']} style={{ lineHeight: '64px' }} > <Menu.Item key="1">nav 1</Menu.Item> <Menu.Item key="2">nav 2</Menu.Item> <Menu.Item key="3">nav 3</Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>List</Breadcrumb.Item> <Breadcrumb.Item>App</Breadcrumb.Item> </Breadcrumb> <div style={{ background: '#fff', padding: 24, minHeight: 280 }}>{props.children}</div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ยฉ2018 Created by Ant UED</Footer> </Layout> ); } export default CustomLayout A: If you are using any javascript expression then only use curly braces like - {a+b}. but form html tags or react component you need to import as per react standard. Use like this <CustomLayout> <ArticleListView /> </CustomLayout> and change your export default <Article/> to export default Article A: It should be <ArticleListView/>, not {ArticleListView} A: Try <CustomLayout> <ArticleListView /> </CustomLayout> rather than <CustomLayout> {ArticleListView} </CustomLayout> A: in javascript we work like isConditionTrue ? screenOne :screenTwo but in typescript we have to change isConditionTrue ? :
Warning: Functions are not valid as a React child.This may happen if you return a Component instead of from render
I get the above error when I try to display {props.child}.The page remains blank.The detailed warning is index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in div (at CustomLayout.js:28) in main (created by Basic) in Basic (created by Context.Consumer) in Content (at CustomLayout.js:22) in section (created by BasicLayout) in BasicLayout (created by Context.Consumer) in Layout (at CustomLayout.js:8) in CustomLayout (at App.js:10) in div (at App.js:9) in App (at src/index.js:7) Below are the project files. Article.js is a component and ArticleListView and CustomLayout are containers to it. I am trying to access the child elements in CustomLayout.js by {props.children} App.js import React from 'react'; import './App.css'; import 'antd/dist/antd.css'; import CustomLayout from './containers/CustomLayout' import ArticleListView from './containers/ArticleListView'; function App() { return ( <div className="App"> <CustomLayout> {ArticleListView} </CustomLayout> </div> ); } export default App ArticleListView.js import React from 'react' import Article from '../components/Article' class ArticleListView extends React.Component{ render(){ return( <Article/> ); } } export default ArticleListView Article.js import React from 'react' import { List, Avatar, Icon } from 'antd'; const listData = []; for (let i = 0; i < 23; i++) { listData.push({ href: 'http://ant.design', title: `ant design part ${i}`, avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.', content: 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', }); } const IconText = ({ type, text }) => ( <span> <Icon type={type} style={{ marginRight: 8 }} /> {text} </span> ); function Article(props){ return( <List itemLayout="vertical" size="large" pagination={{ onChange: page => { console.log(page); }, pageSize: 3, }} dataSource={listData} footer={ <div> <b>ant design</b> footer part </div> } renderItem={item => ( <List.Item key={item.title} actions={[ <IconText type="star-o" text="156" key="list-vertical-star-o" />, <IconText type="like-o" text="156" key="list-vertical-like-o" />, <IconText type="message" text="2" key="list-vertical-message" />, ]} extra={ <img width={272} alt="logo" src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png" /> } > <List.Item.Meta avatar={<Avatar src={item.avatar} />} title={<a href={item.href}>{item.title}</a>} description={item.description} /> {item.content} </List.Item> )} /> ); } export default <Article/> CustomLayout.js import React from 'react' import { Layout, Menu, Breadcrumb } from 'antd'; const { Header, Content, Footer } = Layout; function CustomLayout(props){ return( <Layout className="layout"> <Header> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']} style={{ lineHeight: '64px' }} > <Menu.Item key="1">nav 1</Menu.Item> <Menu.Item key="2">nav 2</Menu.Item> <Menu.Item key="3">nav 3</Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>List</Breadcrumb.Item> <Breadcrumb.Item>App</Breadcrumb.Item> </Breadcrumb> <div style={{ background: '#fff', padding: 24, minHeight: 280 }}>{props.children}</div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ยฉ2018 Created by Ant UED</Footer> </Layout> ); } export default CustomLayout
[ "If you are using any javascript expression then only use curly braces like - {a+b}.\nbut form html tags or react component you need to import as per react standard.\nUse like this\n<CustomLayout>\n <ArticleListView />\n</CustomLayout>\n\nand change your export default <Article/> to export default Article\n", "It should be <ArticleListView/>, not {ArticleListView}\n", "Try\n<CustomLayout>\n <ArticleListView />\n</CustomLayout>\n\nrather than \n<CustomLayout>\n {ArticleListView}\n</CustomLayout>\n\n", "in javascript we work like isConditionTrue ? screenOne :screenTwo\nbut in typescript we have to change isConditionTrue ? : \n" ]
[ 3, 2, 0, 0 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0060444734_javascript_reactjs.txt
Q: How to ignore undefined input from array table I have bot code to input some text then show specific data base on that input. But when I input data that is not defined in array, my bot crashed. How to ignore that wrong input? const arrayTable = { array1 : ['A1', 'A2'], array2 : ['B1', 'B2'] //there are array 3 and more }; function selectedData(input) { return arrayTable[input]; } selectedData("array1"); // Output A1 A2 selectedData("wronginput"); // Crash. I want this input ignored selectedData("wronginput"); I want this input ignored A: You can check if the arrayTable contains value. If it contains, only then set the value. ... function selectedData(input) { return arrayTable[input] ? arrayTable[input] : false ; // if input doesn't exists, it will return false }
How to ignore undefined input from array table
I have bot code to input some text then show specific data base on that input. But when I input data that is not defined in array, my bot crashed. How to ignore that wrong input? const arrayTable = { array1 : ['A1', 'A2'], array2 : ['B1', 'B2'] //there are array 3 and more }; function selectedData(input) { return arrayTable[input]; } selectedData("array1"); // Output A1 A2 selectedData("wronginput"); // Crash. I want this input ignored selectedData("wronginput"); I want this input ignored
[ "You can check if the arrayTable contains value. If it contains, only then set the value.\n...\nfunction selectedData(input) {\n return arrayTable[input] ? arrayTable[input] : false ; // if input doesn't exists, it will return false\n }\n\n" ]
[ 0 ]
[]
[]
[ "discord.js", "node.js" ]
stackoverflow_0074673192_discord.js_node.js.txt
Q: Set mat-menu style Im having alot of trouble with this, and the apparent solutions aren't working or im doing something wrong (probably the latter). I want to style my mat-menu and the mat-menu-item's, ive tried doing this: ::ng-deep .mat-menu{ background-color:red; } But it doesnt work, my menu looks like this (nothing abornomal) <mat-menu #infoMenu="matMenu"> <button mat-menu-item> <mat-icon>dialpad</mat-icon> <span>Resume</span> </button> <button mat-menu-item> <mat-icon>voicemail</mat-icon> <span>Portfolio</span> </button> <button mat-menu-item> <mat-icon>notifications_off</mat-icon> <span>References</span> </button> <button mat-menu-item> <mat-icon>notifications_off</mat-icon> <span>Contact</span> </button> </mat-menu> I have also tried /deep/ but I know that shouldn't work and in fact should be depreciated in Angular 4 but I did it to test, I am not sure how to style the elements at this point. A: Easier Way If you want to change your component only without affecting other components, you should add a class to the menu. <mat-menu #infoMenu="matMenu" class="customize"></mat-menu> Then style your menu with ::ng-deep. ::ng-deep .customize { background: red; } voila!! your customization will not affect other components. Another Way: you can add backdropClass to the menu. <mat-menu #infoMenu="matMenu" backdropClass="customize"></mat-menu> Then add CSS style class with +* in your styles.css .customize+* .mat-menu-panel { background: red; } This is also accomplished without affecting others, but adding css in styles.css may be a bit inconvenient. A: app.component.ts import { Component, ViewEncapsulation ... } from '@angular/core'; @Component({ ... encapsulation: ViewEncapsulation.None }) export class AppComponent { constructor() { } } my.component.css .mat-menu-content { background-color: 'red' !important; } I typically use this to style the height and overflow css, but the general idea should still stand for background-color. Please note that there may be other overlaying divs with background-colors, but you should be able to access them in this way by their .mat-menu-<item name> css and change children items in the same manner. A: Define original background-color and mouseover color both in the CSS: .mat-menu-item { color: blue !important; } button.mat-menu-item{ background-color: white; } button.mat-menu-item:hover { background-color: blue; color: #fff !important; } A: Another solution which (1) allows us to keep our default ViewEncapsulation and (2) does not require the deprecated ::ng-deep app.component.html <mat-menu #infoMenu="matMenu" class="my-class">... And then in your global styles sheet styles.css .mat-menu-panel.my-class { background-color: red; } This solution was provided in the Angular/Components git repository: https://github.com/angular/components/issues/16742 The original author of this solution provided a stackblitz here: https://stackblitz.com/edit/angular-y3jqzt A: I customized angular material element mat-menu by using ::ng-deep <mat-menu #createPlan="matMenu" class="custom-menu"> <button mat-menu-item [matMenuTriggerFor]="profilestypes">Client Profile</button> <button mat-menu-item>Supplier Profile</button> <button mat-menu-item>Advisor Profile</button> </mat-menu> while css class was as follows ::ng-deep .custom-menu{ margin-top: 15px; } and it got applied to each and every internal class of mat-menu A: Since ::ng-deep is deprecated, this is how I customize mat-menu <mat-menu class="user-menu" #menu="matMenu"> <button mat-menu-item>Profile</button> <button mat-menu-item>Settings</button> </mat-menu> In the new version of Angular Material, I used the base class of mat-menu, which is mat-mdc-menu-panel .mat-mdc-menu-panel.user-menu { background-color: red; }
Set mat-menu style
Im having alot of trouble with this, and the apparent solutions aren't working or im doing something wrong (probably the latter). I want to style my mat-menu and the mat-menu-item's, ive tried doing this: ::ng-deep .mat-menu{ background-color:red; } But it doesnt work, my menu looks like this (nothing abornomal) <mat-menu #infoMenu="matMenu"> <button mat-menu-item> <mat-icon>dialpad</mat-icon> <span>Resume</span> </button> <button mat-menu-item> <mat-icon>voicemail</mat-icon> <span>Portfolio</span> </button> <button mat-menu-item> <mat-icon>notifications_off</mat-icon> <span>References</span> </button> <button mat-menu-item> <mat-icon>notifications_off</mat-icon> <span>Contact</span> </button> </mat-menu> I have also tried /deep/ but I know that shouldn't work and in fact should be depreciated in Angular 4 but I did it to test, I am not sure how to style the elements at this point.
[ "Easier Way\nIf you want to change your component only without affecting other components, you should add a class to the menu.\n<mat-menu #infoMenu=\"matMenu\" class=\"customize\"></mat-menu>\n\nThen style your menu with ::ng-deep.\n::ng-deep .customize {\n background: red;\n}\n\nvoila!! your customization will not affect other components.\nAnother Way:\nyou can add backdropClass to the menu.\n <mat-menu #infoMenu=\"matMenu\" backdropClass=\"customize\"></mat-menu>\n\nThen add CSS style class with +* in your styles.css\n.customize+* .mat-menu-panel {\n background: red;\n}\n\nThis is also accomplished without affecting others, but adding css in styles.css may be a bit inconvenient.\n", "app.component.ts\nimport { Component, ViewEncapsulation ... } from '@angular/core';\n\n@Component({\n ...\n encapsulation: ViewEncapsulation.None\n})\n\nexport class AppComponent {\n constructor() { }\n}\n\nmy.component.css\n.mat-menu-content {\n background-color: 'red' !important;\n}\n\nI typically use this to style the height and overflow css, but the general idea should still stand for background-color. Please note that there may be other overlaying divs with background-colors, but you should be able to access them in this way by their .mat-menu-<item name> css and change children items in the same manner.\n", "Define original background-color and mouseover color both in the CSS:\n.mat-menu-item {\n color: blue !important;\n}\n\nbutton.mat-menu-item{\n background-color: white;\n}\n\nbutton.mat-menu-item:hover {\n background-color: blue;\n color: #fff !important;\n}\n\n", "Another solution which (1) allows us to keep our default ViewEncapsulation and (2) does not require the deprecated ::ng-deep\napp.component.html\n<mat-menu #infoMenu=\"matMenu\" class=\"my-class\">...\n\nAnd then in your global styles sheet\nstyles.css\n.mat-menu-panel.my-class {\n background-color: red;\n}\n\nThis solution was provided in the Angular/Components git repository: https://github.com/angular/components/issues/16742\nThe original author of this solution provided a stackblitz here: https://stackblitz.com/edit/angular-y3jqzt\n", "I customized angular material element mat-menu by using ::ng-deep\n<mat-menu #createPlan=\"matMenu\" class=\"custom-menu\">\n <button mat-menu-item [matMenuTriggerFor]=\"profilestypes\">Client Profile</button>\n <button mat-menu-item>Supplier Profile</button>\n <button mat-menu-item>Advisor Profile</button>\n</mat-menu>\n\nwhile css class was as follows\n::ng-deep .custom-menu{\n margin-top: 15px;\n}\n\nand it got applied to each and every internal class of mat-menu\n", "Since ::ng-deep is deprecated, this is how I customize mat-menu\n<mat-menu class=\"user-menu\" #menu=\"matMenu\">\n <button mat-menu-item>Profile</button>\n <button mat-menu-item>Settings</button>\n</mat-menu>\n\nIn the new version of Angular Material, I used the base class of mat-menu, which is mat-mdc-menu-panel\n.mat-mdc-menu-panel.user-menu {\n background-color: red;\n}\n\n" ]
[ 33, 18, 10, 4, 0, 0 ]
[]
[]
[ "angular", "angular_material2", "css", "sass" ]
stackoverflow_0046821027_angular_angular_material2_css_sass.txt
Q: How to open file explorer and highlight file in flutter? I'm developing a flutter desktop app, currently my solution is use url_launcher, but it only does open folder, not support highlight file, is there similar to electron e.g shell.showItemInFolder('filepath') in flutter? Link๏ผšhttps://github.com/flutter/flutter/issues/100361#issuecomment-1072303822 A: yes, you can write cmd line through your dart code ex: if you have file located at D:\test\test\text.txt your dart code will be Process.run('explorer.exe ', [ '/select,', 'D:\test\test\text.txt', ]);
How to open file explorer and highlight file in flutter?
I'm developing a flutter desktop app, currently my solution is use url_launcher, but it only does open folder, not support highlight file, is there similar to electron e.g shell.showItemInFolder('filepath') in flutter? Link๏ผšhttps://github.com/flutter/flutter/issues/100361#issuecomment-1072303822
[ "yes, you can write cmd line through your dart code\nex: if you have file located at D:\\test\\test\\text.txt your dart code will be\nProcess.run('explorer.exe ', [\n'/select,',\n'D:\\test\\test\\text.txt',\n]);\n" ]
[ 0 ]
[]
[]
[ "flutter", "flutter_desktop" ]
stackoverflow_0074050426_flutter_flutter_desktop.txt
Q: Implementing push notifications for both iOS and Android for Angular PWA project I have successfully adapted Android push notifications using Angular's service-worker lib: package json: "@angular/service-worker": "~12.2.16" import: import { SwPush } from '@angular/service-worker'; frontend code: public subscribe() { // my endpoint this.httpClient.get(`${this.baseURL}/backgroundPush/subscriptions/key`, { responseType: 'text' }) .subscribe(publicKey => { this.swPush.requestSubscription({ serverPublicKey: publicKey }).then((subscription) => { this.endpoint = subscription.endpoint; //my endpoint this.httpClient.post(`${this.baseURL}/backgroundPush/subscriptions/add`, subscription).subscribe(() => { }, error => this.handleSubscriptionFailure(error)) }) .catch((error) => this.handleSubscriptionFailure(error)); }, error => this.handleSubscriptionFailure(error)); } on backend side I use c# and following lib to deliver push messages: <PackageReference Include="Lib.Net.Http.WebPush" Version="3.2.1" /> and it works perfectly to deliver messages for Android devices! However, this solution doesn't work on iOS devices. I've got following error in console when someone tries to subscribe for push messages: TypeError: undefined is not an object (evaluating t.pushManager) What are the possibilities to extend push notifications to make them work on iOS/Safari taking into account that I already use service-worker? What else would you suggest instead of service-worker and why? A: According to this source: https://pushalert.co/blog/ios-web-push-notifications-safari-available/ It is not possible to send web-push notifications using service worker at the moment, but will be possible in the next year: Update - June 2022: Apple has now confirmed at WWDC 2022, that it will be adding web push notifications support to Safari on iOS in Early 2023 with iOS 16. You can expect all browsers on iPhones and iPads to support web push notifications early next year. Update - February 2022: Apple has finally added experimental web push support to Safari on iOS and other browsers like Chrome and Firefox. So we should see Web Push Notifications on iPhones and iPads by end of 2022 โ€“ more details here. A: Answering the specific questions you asked. 1. What are the possibilities to extend push notifications to make them work on iOS/Safari taking into account that I already use service-worker? In iOS Safari, you can't (As of now). But Apple confirmed that this feature will be available with an update to iOS16 in 2023 - https://engagespot.co/blog/send-web-push-notification-ios-safari 2. What else would you suggest instead of service-worker and why? Nothing else works for web push notifications. You need to wait till web push is available in iOS.
Implementing push notifications for both iOS and Android for Angular PWA project
I have successfully adapted Android push notifications using Angular's service-worker lib: package json: "@angular/service-worker": "~12.2.16" import: import { SwPush } from '@angular/service-worker'; frontend code: public subscribe() { // my endpoint this.httpClient.get(`${this.baseURL}/backgroundPush/subscriptions/key`, { responseType: 'text' }) .subscribe(publicKey => { this.swPush.requestSubscription({ serverPublicKey: publicKey }).then((subscription) => { this.endpoint = subscription.endpoint; //my endpoint this.httpClient.post(`${this.baseURL}/backgroundPush/subscriptions/add`, subscription).subscribe(() => { }, error => this.handleSubscriptionFailure(error)) }) .catch((error) => this.handleSubscriptionFailure(error)); }, error => this.handleSubscriptionFailure(error)); } on backend side I use c# and following lib to deliver push messages: <PackageReference Include="Lib.Net.Http.WebPush" Version="3.2.1" /> and it works perfectly to deliver messages for Android devices! However, this solution doesn't work on iOS devices. I've got following error in console when someone tries to subscribe for push messages: TypeError: undefined is not an object (evaluating t.pushManager) What are the possibilities to extend push notifications to make them work on iOS/Safari taking into account that I already use service-worker? What else would you suggest instead of service-worker and why?
[ "According to this source:\nhttps://pushalert.co/blog/ios-web-push-notifications-safari-available/\nIt is not possible to send web-push notifications using service worker at the moment, but will be possible in the next year:\n\nUpdate - June 2022:\nApple has now confirmed at WWDC 2022, that it will be adding web push notifications support to Safari on iOS in Early 2023 with iOS 16. You can expect all browsers on iPhones and iPads to support web push notifications early next year.\nUpdate - February 2022:\nApple has finally added experimental web push support to Safari on iOS and other browsers like Chrome and Firefox. So we should see Web Push Notifications on iPhones and iPads by end of 2022 โ€“ more details here.\n", "Answering the specific questions you asked.\n1. What are the possibilities to extend push notifications to make them work on iOS/Safari taking into account that I already use service-worker?\nIn iOS Safari, you can't (As of now). But Apple confirmed that this feature will be available with an update to iOS16 in 2023 - https://engagespot.co/blog/send-web-push-notification-ios-safari\n2. What else would you suggest instead of service-worker and why?\nNothing else works for web push notifications. You need to wait till web push is available in iOS.\n" ]
[ 0, 0 ]
[]
[]
[ "android", "angular", "c#", "ios", "push" ]
stackoverflow_0074107237_android_angular_c#_ios_push.txt
Q: kotlin unit was compile with an incompatible version of kotlin Please i need help on how to resolve this error, I have searched all the answers in stack overflow but non of it solve the problem for me. I updated my kotlin when recently and when i wanted to run a new kotlin application, i got this error. I tried all the steps in stack overflow but non of it work. Here is the error message failed :app:compileDebugKotlin Runtime JAR files in the classpath should have the same version. These files were found in the classpath: C:/Users/HP/newfolder/caches/transforms-3/a8b763bee6c7278a49a4c205da65b911/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar (version 1.5) C:/Users/HP/newfolder/caches/transforms-3/e478bf55927823f4da54fcc6c8971874/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar (version 1.5) C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar (version 1.6) C:/Users/HP/newfolder/caches/transforms-3/a891d209549d183ec22b0fd6f8a659f5/transformed/jetified-kotlin-stdlib-common-1.6.0.jar (version 1.6) C:/Users/HP/newfolder/caches/transforms-3/18ec897b17c934613389ac8a536f0724/transformed/navigation-common-2.4.1-api.jar!/META-INF/navigation-common_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/345269ef286a72cb64a64bd63517dfe5/transformed/navigation-fragment-2.4.1-api.jar!/META-INF/navigation-fragment_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/5b512e38ccc4fbafd5962c1a47398a65/transformed/navigation-ui-2.4.1-api.jar!/META-INF/navigation-ui_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/9bfb36f4d787787665db8c5d2d65e8be/transformed/navigation-runtime-2.4.1-api.jar!/META-INF/navigation-runtime_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/a891d209549d183ec22b0fd6f8a659f5/transformed/jetified-kotlin-stdlib-common-1.6.0.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/ae232c4ce48fac963ba307d71d188737/transformed/slidingpanelayout-1.2.0-api.jar!/META-INF/slidingpanelayout_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. app/src/main/java/com/elijah/ukeme/messengerapp/MainActivity.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class app/src/main/java/com/elijah/ukeme/messengerapp/fragments/ChatFragment.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class app/src/main/java/com/elijah/ukeme/messengerapp/fragments/SearchFragment.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class app/src/main/java/com/elijah/ukeme/messengerapp/fragments/SettingsFragment.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Here is my buil.gradle file plugins { id 'com.android.application' id 'kotlin-android' id 'com.google.gms.google-services' } android { compileSdkVersion 31 buildToolsVersion "30.0.2" defaultConfig { applicationId "com.elijah.ukeme.messengerapp" minSdkVersion 19 targetSdkVersion 31 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } } dependencies { //noinspection GradleDependency implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.4.1' implementation 'com.google.android.material:material:1.5.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.3' implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1' implementation 'androidx.navigation:navigation-ui-ktx:2.4.1' implementation 'com.google.firebase:firebase-auth:21.0.1' implementation 'com.google.firebase:firebase-database:20.0.3' implementation 'com.google.firebase:firebase-firestore:24.0.1' implementation 'com.google.firebase:firebase-storage:20.0.0' implementation 'com.google.firebase:firebase-messaging:23.0.0' implementation 'de.hdodenhof:circleimageview:2.2.0' implementation 'com.squareup.picasso:picasso:2.71828' implementation 'androidx.cardview:cardview:1.0.0' implementation 'com.rengwuxian.materialedittext:library:2.1.4' implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } And this is the build.gradle for app // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = "1.4.32" repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:4.1.3" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.10' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } This is the gradle-wrapper.properties #Sat Mar 05 12:09:03 PST 2022 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-bin.zip A: change the kotlin-gradle version to : classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31" If you face error: resource android:attr/lStar not found" then change version of your android app to: buildToolsVersion = "31.0.0" compileSdkVersion = 31 targetSdkVersion = 31 if you face issue More than one file was found with OS independent path 'lib/armeabi-v7a/libfbjni.so' then add this inside app/build.gradle inside of android{...} packagingOptions { pickFirst '**/*.so' } A: down grade your kotlinx.core version to 1.6.0 , because 1.7.0 required java 11 implementation 'androidx.core:core-ktx:1.6.0' and probably some of your dependencies also required java 11, like this one, implementation 'com.google.android.material:material:1.5.0' down to 1.4.0 i advice you to downgrade some of your dependencies version, or update your android studio to the latest version A: in file android/buid.gradlew on top : def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim()) in allprojects : allprojects { configurations.all { resolutionStrategy { force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION } } }
kotlin unit was compile with an incompatible version of kotlin
Please i need help on how to resolve this error, I have searched all the answers in stack overflow but non of it solve the problem for me. I updated my kotlin when recently and when i wanted to run a new kotlin application, i got this error. I tried all the steps in stack overflow but non of it work. Here is the error message failed :app:compileDebugKotlin Runtime JAR files in the classpath should have the same version. These files were found in the classpath: C:/Users/HP/newfolder/caches/transforms-3/a8b763bee6c7278a49a4c205da65b911/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar (version 1.5) C:/Users/HP/newfolder/caches/transforms-3/e478bf55927823f4da54fcc6c8971874/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar (version 1.5) C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar (version 1.6) C:/Users/HP/newfolder/caches/transforms-3/a891d209549d183ec22b0fd6f8a659f5/transformed/jetified-kotlin-stdlib-common-1.6.0.jar (version 1.6) C:/Users/HP/newfolder/caches/transforms-3/18ec897b17c934613389ac8a536f0724/transformed/navigation-common-2.4.1-api.jar!/META-INF/navigation-common_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/345269ef286a72cb64a64bd63517dfe5/transformed/navigation-fragment-2.4.1-api.jar!/META-INF/navigation-fragment_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/5b512e38ccc4fbafd5962c1a47398a65/transformed/navigation-ui-2.4.1-api.jar!/META-INF/navigation-ui_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/9bfb36f4d787787665db8c5d2d65e8be/transformed/navigation-runtime-2.4.1-api.jar!/META-INF/navigation-runtime_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/a891d209549d183ec22b0fd6f8a659f5/transformed/jetified-kotlin-stdlib-common-1.6.0.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. C:/Users/HP/newfolder/caches/transforms-3/ae232c4ce48fac963ba307d71d188737/transformed/slidingpanelayout-1.2.0-api.jar!/META-INF/slidingpanelayout_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. app/src/main/java/com/elijah/ukeme/messengerapp/MainActivity.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class app/src/main/java/com/elijah/ukeme/messengerapp/fragments/ChatFragment.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class app/src/main/java/com/elijah/ukeme/messengerapp/fragments/SearchFragment.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class app/src/main/java/com/elijah/ukeme/messengerapp/fragments/SettingsFragment.kt Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.4.2. The class is loaded from C:/Users/HP/newfolder/caches/transforms-3/84c66d4f4ecf6f746e3716128956475c/transformed/jetified-kotlin-stdlib-1.6.0.jar!/kotlin/Unit.class Here is my buil.gradle file plugins { id 'com.android.application' id 'kotlin-android' id 'com.google.gms.google-services' } android { compileSdkVersion 31 buildToolsVersion "30.0.2" defaultConfig { applicationId "com.elijah.ukeme.messengerapp" minSdkVersion 19 targetSdkVersion 31 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } } dependencies { //noinspection GradleDependency implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.4.1' implementation 'com.google.android.material:material:1.5.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.3' implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1' implementation 'androidx.navigation:navigation-ui-ktx:2.4.1' implementation 'com.google.firebase:firebase-auth:21.0.1' implementation 'com.google.firebase:firebase-database:20.0.3' implementation 'com.google.firebase:firebase-firestore:24.0.1' implementation 'com.google.firebase:firebase-storage:20.0.0' implementation 'com.google.firebase:firebase-messaging:23.0.0' implementation 'de.hdodenhof:circleimageview:2.2.0' implementation 'com.squareup.picasso:picasso:2.71828' implementation 'androidx.cardview:cardview:1.0.0' implementation 'com.rengwuxian.materialedittext:library:2.1.4' implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } And this is the build.gradle for app // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = "1.4.32" repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:4.1.3" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.10' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } This is the gradle-wrapper.properties #Sat Mar 05 12:09:03 PST 2022 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-bin.zip
[ "change the kotlin-gradle version to :\nclasspath \"org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31\"\nIf you face error: resource android:attr/lStar not found\"\nthen change version of your android app to:\nbuildToolsVersion = \"31.0.0\" compileSdkVersion = 31 targetSdkVersion = 31\nif you face issue More than one file was found with OS independent path 'lib/armeabi-v7a/libfbjni.so'\nthen add this inside app/build.gradle inside of android{...}\npackagingOptions { pickFirst '**/*.so' }\n", "down grade your kotlinx.core version to 1.6.0 , because 1.7.0 required java 11\nimplementation 'androidx.core:core-ktx:1.6.0'\nand probably some of your dependencies also required java 11, like this one,\nimplementation 'com.google.android.material:material:1.5.0' down to 1.4.0\ni advice you to downgrade some of your dependencies version, or update your android studio to the latest version\n", "in file android/buid.gradlew\non top :\ndef REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\n\nin allprojects :\nallprojects {\n configurations.all {\n resolutionStrategy {\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n}\n\n}\n" ]
[ 1, 0, 0 ]
[]
[]
[ "compiler_errors", "kotlin", "metadata", "updates", "version" ]
stackoverflow_0071382842_compiler_errors_kotlin_metadata_updates_version.txt
Q: Kafka-connect can't send schemaless JSON I have a Zabbix-webhook service which sends data to kafka in JSON format: "value": { "name": "Zabbix server: Trend write cache, % used", "key": "zabbix[wcache,trend,pused]", "host": "Zabbix server", "groups": [ "Zabbix servers" ], "applications": [], "itemid": 23276, "clock": 1670102276, "ns": 427825202, "value": 0.129509 } I need to send these data to postgres via kafka-connect's JdbcSinkConnector: curl -X POST "http://localhost:8082/connectors" -H "Content-Type: application/json" -d '{ "name": "zabbix-sink-connector", "config": { "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector", "tasks.max": 1, "topics": "zabbix-webhook", "connection.url": "jdbc:postgresql://<host>/etl?currentSchema=test", "connection.user": "<username>", "connection.password": "<password>", "auto.create": "true" } }' But when i'm trying to execute this curl, i get an error: ERROR WorkerSinkTask{id=zabbix-sink-connector-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted. Error: Sink connector 'zabbix-sink-connector' is configured with 'delete.enabled=false' and 'pk.mode=none' and therefore requires records with a non-null Struct value and non-null Struct schema, but found record at (topic='zabbix-webhook',partition=1,offset=566370,timestamp=1670104965261) with a HashMap value and null value schema. (org.apache.kafka.connect.runtime.WorkerSinkTask) org.apache.kafka.connect.errors.ConnectException: Sink connector 'zabbix-sink-connector' is configured with 'delete.enabled=false' and 'pk.mode=none' and therefore requires records with a non-null Struct value and non-null Struct schema, but found record at (topic='zabbix-webhook',partition=1,offset=566370,timestamp=1670104965261) with a HashMap value and null value schema According to this post https://www.confluent.io/blog/kafka-connect-deep-dive-converters-serialization-explained/#applying-schema I changed variable CONNECT_VALUE_CONVERTER_SCHEMAS_ENABLE to false, but I still get the same error. How should I send these JSON-data? A: The JDBC Sink connector requires a schema. It cannot accept JSON without value.converter.schemas.enable=true, for the JSONConverter. You cannot disable it. More specifically, the JDBC connector requires a schema because it cannot guarantee/extract known key names in plain JSON, or know they'll have consistent value types. It needs that information to create the SQL statements. Since you don't control the Kafka producer, in order to get schema'd data, you can use ksqlDB to convert consume JSON data into JSONSchema, or other binary structured format, after which you can use Connect to write to the database
Kafka-connect can't send schemaless JSON
I have a Zabbix-webhook service which sends data to kafka in JSON format: "value": { "name": "Zabbix server: Trend write cache, % used", "key": "zabbix[wcache,trend,pused]", "host": "Zabbix server", "groups": [ "Zabbix servers" ], "applications": [], "itemid": 23276, "clock": 1670102276, "ns": 427825202, "value": 0.129509 } I need to send these data to postgres via kafka-connect's JdbcSinkConnector: curl -X POST "http://localhost:8082/connectors" -H "Content-Type: application/json" -d '{ "name": "zabbix-sink-connector", "config": { "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector", "tasks.max": 1, "topics": "zabbix-webhook", "connection.url": "jdbc:postgresql://<host>/etl?currentSchema=test", "connection.user": "<username>", "connection.password": "<password>", "auto.create": "true" } }' But when i'm trying to execute this curl, i get an error: ERROR WorkerSinkTask{id=zabbix-sink-connector-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted. Error: Sink connector 'zabbix-sink-connector' is configured with 'delete.enabled=false' and 'pk.mode=none' and therefore requires records with a non-null Struct value and non-null Struct schema, but found record at (topic='zabbix-webhook',partition=1,offset=566370,timestamp=1670104965261) with a HashMap value and null value schema. (org.apache.kafka.connect.runtime.WorkerSinkTask) org.apache.kafka.connect.errors.ConnectException: Sink connector 'zabbix-sink-connector' is configured with 'delete.enabled=false' and 'pk.mode=none' and therefore requires records with a non-null Struct value and non-null Struct schema, but found record at (topic='zabbix-webhook',partition=1,offset=566370,timestamp=1670104965261) with a HashMap value and null value schema According to this post https://www.confluent.io/blog/kafka-connect-deep-dive-converters-serialization-explained/#applying-schema I changed variable CONNECT_VALUE_CONVERTER_SCHEMAS_ENABLE to false, but I still get the same error. How should I send these JSON-data?
[ "The JDBC Sink connector requires a schema. It cannot accept JSON without value.converter.schemas.enable=true, for the JSONConverter. You cannot disable it.\nMore specifically, the JDBC connector requires a schema because it cannot guarantee/extract known key names in plain JSON, or know they'll have consistent value types. It needs that information to create the SQL statements.\nSince you don't control the Kafka producer, in order to get schema'd data, you can use ksqlDB to convert consume JSON data into JSONSchema, or other binary structured format, after which you can use Connect to write to the database\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "apache_kafka_connect" ]
stackoverflow_0074671178_apache_kafka_apache_kafka_connect.txt
Q: @ changing to %40 I am using sqlalchemy and creating the url using url = url.URL( drivername, host, username, password, database) this does not work url = url.URL( drivername='mysql+pymysql', host='abc.com', username='app', password=u'56f@;', database='app') logging.info(f'url : {url}') gives mysql+pymysql://app:6f%40;@abc.com/app url = create_engine(url) results = url.execute(sql_query).fetchall() Password contains an ampersand '@' which is getting converted to %40. I do not want the conversion to take place. How can I avoid it. A: To avoid encoding of special characters in the password when creating a SQLAlchemy engine URL, you can use the quote() method from the urllib.parse module to encode the password before passing it to the url.URL() method. import sqlalchemy as sa from urllib.parse import quote # Create the URL object with the encoded password engine_url = sa.engine.url.URL( drivername, host, username, quote(password), database, ) This will encode any special characters in the password, such as the ampersand &, so that they are not interpreted as URL syntax by SQLAlchemy.
@ changing to %40
I am using sqlalchemy and creating the url using url = url.URL( drivername, host, username, password, database) this does not work url = url.URL( drivername='mysql+pymysql', host='abc.com', username='app', password=u'56f@;', database='app') logging.info(f'url : {url}') gives mysql+pymysql://app:6f%40;@abc.com/app url = create_engine(url) results = url.execute(sql_query).fetchall() Password contains an ampersand '@' which is getting converted to %40. I do not want the conversion to take place. How can I avoid it.
[ "To avoid encoding of special characters in the password when creating a SQLAlchemy engine URL, you can use the quote() method from the urllib.parse module to encode the password before passing it to the url.URL() method.\nimport sqlalchemy as sa\nfrom urllib.parse import quote\n\n# Create the URL object with the encoded password\nengine_url = sa.engine.url.URL(\n drivername,\n host,\n username,\n quote(password),\n database,\n)\n\nThis will encode any special characters in the password, such as the ampersand &, so that they are not interpreted as URL syntax by SQLAlchemy.\n" ]
[ 0 ]
[]
[]
[ "database", "python", "python_unicode", "sqlalchemy", "unicode" ]
stackoverflow_0074673195_database_python_python_unicode_sqlalchemy_unicode.txt
Q: Expo React Native App crashing on android Ever since I started programming in React Native with Expo, I have been using an ios physical device together with Expo app. I never had any major issues. Now i wanted to start fixing any bugs on android, but when running the Expo app on my android physical device the Expo app crashes (shuts down) while downloading bundle. It doesn't print any errors into my console, so i don't even know where to start... Here is my app.json: { "expo": { "name": "PointoUserApp", "slug": "PointoUserApp", "version": "1.0.0", "platforms": [ "ios", "android", "web" ], "orientation": "portrait", "icon": "./assets/Images/icon.png", "splash": { "image": "./assets/Images/splash.png", "resizeMode":"contain", "backgroundColor": "#ffffff" }, "updates": { "fallbackToCacheTimeout": 0 }, "assetBundlePatterns": [ "**/*" ], "ios": { "bundleIdentifier": "com.meretc23.PointoUserApp" }, "android":{ }, "web": { "favicon": "./assets/Images/favicon.png" } } } notice it is empty under android because i dont know what is required. Below is my package.json file as well. { "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", "eject": "expo eject" }, "dependencies": { "@expo-google-fonts/inter": "^0.1.0", "@fortawesome/fontawesome-svg-core": "^1.2.30", "@fortawesome/free-brands-svg-icons": "^5.14.0", "@fortawesome/free-solid-svg-icons": "^5.14.0", "@fortawesome/react-native-fontawesome": "^0.2.5", "@ionic/react": "^5.3.1", "@react-native-community/art": "^1.2.0", "@react-native-community/async-storage": "~1.11.0", "@react-native-community/datetimepicker": "2.4.0", "@react-native-community/masked-view": "0.1.10", "@react-navigation/bottom-tabs": "^5.7.3", "@react-navigation/material-top-tabs": "^5.2.16", "@react-navigation/native": "^5.7.2", "@react-navigation/stack": "^5.8.0", "@types/react-native-snap-carousel": "^3.8.2", "core-js": "^3.6.5", "expo": "^38.0.0", "expo-constants": "~9.1.1", "expo-font": "~8.2.1", "expo-linking": "^1.0.3", "expo-localization": "~8.2.1", "expo-location": "~8.2.1", "expo-permissions": "~9.0.1", "expo-status-bar": "^1.0.0", "firebase": "^7.21.1", "geolib": "^3.3.1", "i18n-js": "^3.7.1", "react": "16.11.0", "react-dom": "16.11.0", "react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz", "react-native-check-box": "^2.1.7", "react-native-gesture-handler": "~1.6.0", "react-native-localize": "^1.4.1", "react-native-map-clustering": "^3.3.9", "react-native-map-link": "^2.7.17", "react-native-maps": "0.27.1", "react-native-modal": "^11.5.6", "react-native-picker-select": "^8.0.0", "react-native-progress": "^4.1.2", "react-native-progress-circle": "^2.1.0", "react-native-qrcode-svg": "^6.0.6", "react-native-reanimated": "~1.9.0", "react-native-restart": "0.0.17", "react-native-safe-area-context": "^3.0.7", "react-native-screens": "~2.9.0", "react-native-snap-carousel": "^4.0.0-beta.5", "react-native-svg": "12.1.0", "react-native-tab-view": "^2.15.1", "react-native-web": "~0.11.7", "react-navigation": "^4.4.0", "react-navigation-stack": "^2.8.2", "react-redux": "^7.2.1", "redux": "^4.0.5", "redux-thunk": "^2.3.0", "yargs-parser": "^18.1.3" }, "devDependencies": { "@babel/core": "^7.8.6", "babel-preset-expo": "^8.2.3" }, "private": true } Lesson learned: if you want to run an app on both ios and android, always monitor on both simultaneously before your app is too big to know where the issue is coming from.... Help appreciated A: I'm running into the same issue right now. In my situation I've narrowed it down to the android adaptiveIcon configuration. If I use a path to a real png, the app crashes on bundle download. If I don't include adaptiveIcon under android, the app crashes. The only way it won't crash is to include adaptiveIcon linked to a file that doesn't even exist. This logs an error that Expo can't find the file, but the app will actually load. Extremely strange. Try adding this to your app.json file. "android": { "adaptiveIcon": { "foregroundImage": "./assets/anImageThatDoesNotExist.png", "backgroundColor": "#FFFFFF" } }, A: My last expo project did not even have an android property, and my ios property only has supportsTablet as true. Try removing the android property altogether A: I just learnt the very hard way! I found that android is less tolerant of react native StyleSheet discrepancies. If your Expo Go app crashes on android and works well with ios, check at what navigation stage it is crashing. Then take a look closely at your StyleSheet props. In my case I had this causing the error: container: { flex: 1, backgroundColor: '#3f3939', alignItems: 'left' // this made my android app crash but not on ios }, so changed to container: { flex: 1, backgroundColor: '#3f3939', alignItems: 'center' }, and it works just fine. I think I made the mistake of this in my early learning of StyleSheet A: I ran into this exact same problem. Changing your foregroundImage to a non-existent location works but it's not a good solution as you have to use a real image for your play store build. When you use the real image some of your users will experience the same immediate crashes you're seeing on the emulator. // Not a good solution "android": { "adaptiveIcon": { "foregroundImage": "./assets/adaptive-icon.png", // use for release build // "foregroundImage": "./assets/anImageThatDoesNotExist.png", // use for development build "backgroundColor": "#FFFFFF" }, The real problem turned out to be that my splash screen image was much too large (~13MB). I replaced it with a smaller image (~750KB) and that fixed the seemingly unrelated adaptive-icon.png crash. It couldn't hurt to check the sizes of all your app images as well.
Expo React Native App crashing on android
Ever since I started programming in React Native with Expo, I have been using an ios physical device together with Expo app. I never had any major issues. Now i wanted to start fixing any bugs on android, but when running the Expo app on my android physical device the Expo app crashes (shuts down) while downloading bundle. It doesn't print any errors into my console, so i don't even know where to start... Here is my app.json: { "expo": { "name": "PointoUserApp", "slug": "PointoUserApp", "version": "1.0.0", "platforms": [ "ios", "android", "web" ], "orientation": "portrait", "icon": "./assets/Images/icon.png", "splash": { "image": "./assets/Images/splash.png", "resizeMode":"contain", "backgroundColor": "#ffffff" }, "updates": { "fallbackToCacheTimeout": 0 }, "assetBundlePatterns": [ "**/*" ], "ios": { "bundleIdentifier": "com.meretc23.PointoUserApp" }, "android":{ }, "web": { "favicon": "./assets/Images/favicon.png" } } } notice it is empty under android because i dont know what is required. Below is my package.json file as well. { "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", "eject": "expo eject" }, "dependencies": { "@expo-google-fonts/inter": "^0.1.0", "@fortawesome/fontawesome-svg-core": "^1.2.30", "@fortawesome/free-brands-svg-icons": "^5.14.0", "@fortawesome/free-solid-svg-icons": "^5.14.0", "@fortawesome/react-native-fontawesome": "^0.2.5", "@ionic/react": "^5.3.1", "@react-native-community/art": "^1.2.0", "@react-native-community/async-storage": "~1.11.0", "@react-native-community/datetimepicker": "2.4.0", "@react-native-community/masked-view": "0.1.10", "@react-navigation/bottom-tabs": "^5.7.3", "@react-navigation/material-top-tabs": "^5.2.16", "@react-navigation/native": "^5.7.2", "@react-navigation/stack": "^5.8.0", "@types/react-native-snap-carousel": "^3.8.2", "core-js": "^3.6.5", "expo": "^38.0.0", "expo-constants": "~9.1.1", "expo-font": "~8.2.1", "expo-linking": "^1.0.3", "expo-localization": "~8.2.1", "expo-location": "~8.2.1", "expo-permissions": "~9.0.1", "expo-status-bar": "^1.0.0", "firebase": "^7.21.1", "geolib": "^3.3.1", "i18n-js": "^3.7.1", "react": "16.11.0", "react-dom": "16.11.0", "react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz", "react-native-check-box": "^2.1.7", "react-native-gesture-handler": "~1.6.0", "react-native-localize": "^1.4.1", "react-native-map-clustering": "^3.3.9", "react-native-map-link": "^2.7.17", "react-native-maps": "0.27.1", "react-native-modal": "^11.5.6", "react-native-picker-select": "^8.0.0", "react-native-progress": "^4.1.2", "react-native-progress-circle": "^2.1.0", "react-native-qrcode-svg": "^6.0.6", "react-native-reanimated": "~1.9.0", "react-native-restart": "0.0.17", "react-native-safe-area-context": "^3.0.7", "react-native-screens": "~2.9.0", "react-native-snap-carousel": "^4.0.0-beta.5", "react-native-svg": "12.1.0", "react-native-tab-view": "^2.15.1", "react-native-web": "~0.11.7", "react-navigation": "^4.4.0", "react-navigation-stack": "^2.8.2", "react-redux": "^7.2.1", "redux": "^4.0.5", "redux-thunk": "^2.3.0", "yargs-parser": "^18.1.3" }, "devDependencies": { "@babel/core": "^7.8.6", "babel-preset-expo": "^8.2.3" }, "private": true } Lesson learned: if you want to run an app on both ios and android, always monitor on both simultaneously before your app is too big to know where the issue is coming from.... Help appreciated
[ "I'm running into the same issue right now. In my situation I've narrowed it down to the android adaptiveIcon configuration. If I use a path to a real png, the app crashes on bundle download. If I don't include adaptiveIcon under android, the app crashes. The only way it won't crash is to include adaptiveIcon linked to a file that doesn't even exist. This logs an error that Expo can't find the file, but the app will actually load. Extremely strange. Try adding this to your app.json file.\n\"android\": {\n \"adaptiveIcon\": {\n \"foregroundImage\": \"./assets/anImageThatDoesNotExist.png\",\n \"backgroundColor\": \"#FFFFFF\"\n }\n },\n\n", "My last expo project did not even have an android property, and my ios property only has supportsTablet as true. Try removing the android property altogether\n", "I just learnt the very hard way! I found that android is less tolerant of react native StyleSheet discrepancies. If your Expo Go app crashes on android and works well with ios, check at what navigation stage it is crashing. Then take a look closely at your StyleSheet props. In my case I had this causing the error:\ncontainer: {\n flex: 1,\n backgroundColor: '#3f3939',\n alignItems: 'left' // this made my android app crash but not on ios\n },\n\nso changed to\ncontainer: {\n flex: 1,\n backgroundColor: '#3f3939',\n alignItems: 'center'\n },\n\nand it works just fine. I think I made the mistake of this in my early learning of StyleSheet \n", "I ran into this exact same problem. Changing your foregroundImage to a non-existent location works but it's not a good solution as you have to use a real image for your play store build. When you use the real image some of your users will experience the same immediate crashes you're seeing on the emulator.\n// Not a good solution\n\"android\": {\n \"adaptiveIcon\": {\n \"foregroundImage\": \"./assets/adaptive-icon.png\", // use for release build\n // \"foregroundImage\": \"./assets/anImageThatDoesNotExist.png\", // use for development build\n \"backgroundColor\": \"#FFFFFF\"\n },\n\nThe real problem turned out to be that my splash screen image was much too large (~13MB). I replaced it with a smaller image (~750KB) and that fixed the seemingly unrelated adaptive-icon.png crash. It couldn't hurt to check the sizes of all your app images as well.\n" ]
[ 5, 1, 1, 0 ]
[]
[]
[ "android", "expo", "node.js", "react_native", "reactjs" ]
stackoverflow_0064944647_android_expo_node.js_react_native_reactjs.txt
Q: How to implement a numpy equation in the call of a tensorflow layer for a tensorflow model (Cannot convert a symbolic tf.Tensor to a numpy array) I have this layer class in tensorflow where i want to implement a specific equation in numpy for the return in the call function. I have this following custom layer: class PhysicalLayer(keras.layers.Layer): def __init__(self, units=32): super(PhysicalLayer, self).__init__() self.units = units def build(self, input_shape): self.w = self.add_weight( shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(self.units,), initializer="random_normal", trainable=True ) def call(self, inputs): rotationSpeedSquare = tf.math.square(rotationSpeed) maximumVibration = tf.convert_to_tensor(np.max(inputs)) stiff = rotationSpeedSquare/maximumVibration stiff.astype('float32') return tf.matmul(stiff, self.w) + self.b This layer is then implement in a model in the following way: class model(tf.keras.Model): def __init__(self, num_classes=50): super(model, self).__init__() self.dense1 = tf.keras.layers.Dense(num_classes, activation=tf.nn.relu) self.physical = PhysicalLayer() self.dense2 = tf.keras.layers.Dense(64, activation=tf.nn.relu) self.dense3 = tf.keras.layers.Dense(32, activation=tf.nn.relu) self.dense4 = tf.keras.layers.Dense(1, activation=tf.nn.relu) def call(self, inputs): x = self.dense1(inputs) x = self.physical(x) x = self.dense2(x) x = self.dense3(x) return self.dense4(x) One of my first concern is if I'm doing this model class correctly as i just learnt how to do it. By trying to fit this model with the training set (which are numpy array, dtype = float32 and size is (72367, 50)) model = model() model.compile(optimizer='adam', loss='mae', metrics=[tf.keras.metrics.RootMeanSquaredError()]) model.fit(a, b, batch_size=32, epochs=2, verbose=2) I obtain the following error: NotImplementedError: Cannot convert a symbolic tf.Tensor (model_18/dense_72/Relu:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported. Thanks A: Use tf.math.reduce_max to get the maximum of a tensor: def call(self, inputs): rotationSpeedSquare = tf.math.square(rotationSpeed) maximumVibration = tf.math.reduce_max(inputs, axis=1, keepdims=True) stiff = rotationSpeedSquare / maximumVibration return tf.matmul(stiff, self.w) + self.b
How to implement a numpy equation in the call of a tensorflow layer for a tensorflow model (Cannot convert a symbolic tf.Tensor to a numpy array)
I have this layer class in tensorflow where i want to implement a specific equation in numpy for the return in the call function. I have this following custom layer: class PhysicalLayer(keras.layers.Layer): def __init__(self, units=32): super(PhysicalLayer, self).__init__() self.units = units def build(self, input_shape): self.w = self.add_weight( shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(self.units,), initializer="random_normal", trainable=True ) def call(self, inputs): rotationSpeedSquare = tf.math.square(rotationSpeed) maximumVibration = tf.convert_to_tensor(np.max(inputs)) stiff = rotationSpeedSquare/maximumVibration stiff.astype('float32') return tf.matmul(stiff, self.w) + self.b This layer is then implement in a model in the following way: class model(tf.keras.Model): def __init__(self, num_classes=50): super(model, self).__init__() self.dense1 = tf.keras.layers.Dense(num_classes, activation=tf.nn.relu) self.physical = PhysicalLayer() self.dense2 = tf.keras.layers.Dense(64, activation=tf.nn.relu) self.dense3 = tf.keras.layers.Dense(32, activation=tf.nn.relu) self.dense4 = tf.keras.layers.Dense(1, activation=tf.nn.relu) def call(self, inputs): x = self.dense1(inputs) x = self.physical(x) x = self.dense2(x) x = self.dense3(x) return self.dense4(x) One of my first concern is if I'm doing this model class correctly as i just learnt how to do it. By trying to fit this model with the training set (which are numpy array, dtype = float32 and size is (72367, 50)) model = model() model.compile(optimizer='adam', loss='mae', metrics=[tf.keras.metrics.RootMeanSquaredError()]) model.fit(a, b, batch_size=32, epochs=2, verbose=2) I obtain the following error: NotImplementedError: Cannot convert a symbolic tf.Tensor (model_18/dense_72/Relu:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported. Thanks
[ "Use tf.math.reduce_max to get the maximum of a tensor:\n def call(self, inputs):\n rotationSpeedSquare = tf.math.square(rotationSpeed)\n maximumVibration = tf.math.reduce_max(inputs, axis=1, keepdims=True)\n\n stiff = rotationSpeedSquare / maximumVibration\n return tf.matmul(stiff, self.w) + self.b\n\n" ]
[ 0 ]
[]
[]
[ "keras", "layer", "python", "tensorflow" ]
stackoverflow_0074670055_keras_layer_python_tensorflow.txt
Q: main.dart is not found in project when archiving flutter app I'm trying to archive my flutter app in distributing it to testers first. I have made and added schemas in Xcode for different flavours of the app. I also use amplify_core plugin. First when I try to clean build it gave me an error saying "Compiling for iOS 11.0, but module 'amplify_core' has a minimum deployment target of iOS 16.0:" After a little bit of researching I've made the apmlify_core min deployment target to 11 under runner in Xcode pods. Then the build was successful. but when I try to do an archive it gives me this error "package:/main.dart: Error: No 'main' method found. Try adding a method named 'main' to your program." I will paste my main.dart and one flavour dart file for reference. anyone can help me with his. ? main.dart file class MyApp extends StatelessWidget { MyApp({Key? key}) : super(key: key); // This widget is the root of your application. final appRouter = AppRouter().router; @override Widget build(BuildContext context) { return MultiProvider( providers: [ StreamProvider<EInternetStatus>( create: (context) => ConnectionCheck().internetStatusController.stream, initialData: EInternetStatus.iLoading, ), ], child: MaterialApp.router( debugShowCheckedModeBanner: AppEnvironment.flavour == EFlavour.fDev || AppEnvironment.flavour == EFlavour.fQa ? true : false, theme: FPTheme.lightTheme, routerConfig: appRouter, ), ); } } main_dev.dart file Future<void> main() async { AppEnvironment.setupEnv(EFlavour.fDev); WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized(); await AmplifyServices().configureAmplify(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); SystemChrome.setEnabledSystemUIMode(SystemUiMode.leanBack); FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding); setUp(); runApp(MyApp()); } im not sure what I do here wrong? if anyone can help me out with this it would be amazing A: How are you running your app? i think you haven't configured build using flavours correctly in your editor try using flutter run -t lib/main_dev.dart To configure your vs code to run with flavours try changing launch.json file. "configurations": [ { "name": "Flutter", "request": "launch", "type": "dart", "program": "${workspaceFolder}/lib/main_dev.dart" }]. You can also refer This stackoverflow answer
main.dart is not found in project when archiving flutter app
I'm trying to archive my flutter app in distributing it to testers first. I have made and added schemas in Xcode for different flavours of the app. I also use amplify_core plugin. First when I try to clean build it gave me an error saying "Compiling for iOS 11.0, but module 'amplify_core' has a minimum deployment target of iOS 16.0:" After a little bit of researching I've made the apmlify_core min deployment target to 11 under runner in Xcode pods. Then the build was successful. but when I try to do an archive it gives me this error "package:/main.dart: Error: No 'main' method found. Try adding a method named 'main' to your program." I will paste my main.dart and one flavour dart file for reference. anyone can help me with his. ? main.dart file class MyApp extends StatelessWidget { MyApp({Key? key}) : super(key: key); // This widget is the root of your application. final appRouter = AppRouter().router; @override Widget build(BuildContext context) { return MultiProvider( providers: [ StreamProvider<EInternetStatus>( create: (context) => ConnectionCheck().internetStatusController.stream, initialData: EInternetStatus.iLoading, ), ], child: MaterialApp.router( debugShowCheckedModeBanner: AppEnvironment.flavour == EFlavour.fDev || AppEnvironment.flavour == EFlavour.fQa ? true : false, theme: FPTheme.lightTheme, routerConfig: appRouter, ), ); } } main_dev.dart file Future<void> main() async { AppEnvironment.setupEnv(EFlavour.fDev); WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized(); await AmplifyServices().configureAmplify(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); SystemChrome.setEnabledSystemUIMode(SystemUiMode.leanBack); FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding); setUp(); runApp(MyApp()); } im not sure what I do here wrong? if anyone can help me out with this it would be amazing
[ "How are you running your app?\ni think you haven't configured build using flavours correctly in your editor\ntry using \nflutter run -t lib/main_dev.dart\n\nTo configure your vs code to run with flavours try changing launch.json file.\n \"configurations\": [\n\n{\n \"name\": \"Flutter\",\n \"request\": \"launch\",\n \"type\": \"dart\",\n \"program\": \"${workspaceFolder}/lib/main_dev.dart\"\n}].\n\nYou can also refer This stackoverflow answer\n" ]
[ 0 ]
[]
[]
[ "archive", "dart", "flutter", "ios", "xcode" ]
stackoverflow_0074673207_archive_dart_flutter_ios_xcode.txt
Q: How to disable Eclipse IDE Language Server I am running Eclipse IDE Version 2018-12 (4.10.0) Build id: 20181214-0600 On macOS Mojave Version 10.14.1 MacBook Pro 2018 with 32GB and cpu 2.9 G i9 When I attempt to things such as open up a class file etc - I see the Initialize Language Server and I get the famous BeachBall - some times it is for a second or two and other times 30 or more seconds. Is there some configuration or something that can improve the performance of this or ability to turn it off? Search the web has turned up nothing so far. At first I thought it was the freemarker IDE extension - uninstalled that but no change. A: I uninstalled freemarker IDE and all the other JBOSS extensions since I am not currently using them. I then when into Preferences -> Language Servers and turn them all off. Now I do not have any issues with slowness of opening files or the famous mac BeachBall. A: For me the issue was with Spring, and then I went ahead and turned off all Spring language servers. I do not know what capabilities are lost due to this, but there seems to be lot of improvement that is needed here before we actually use it. What a pain in neck, killed my office work productivity for almost a month!
How to disable Eclipse IDE Language Server
I am running Eclipse IDE Version 2018-12 (4.10.0) Build id: 20181214-0600 On macOS Mojave Version 10.14.1 MacBook Pro 2018 with 32GB and cpu 2.9 G i9 When I attempt to things such as open up a class file etc - I see the Initialize Language Server and I get the famous BeachBall - some times it is for a second or two and other times 30 or more seconds. Is there some configuration or something that can improve the performance of this or ability to turn it off? Search the web has turned up nothing so far. At first I thought it was the freemarker IDE extension - uninstalled that but no change.
[ "I uninstalled freemarker IDE and all the other JBOSS extensions since I am not currently using them. \nI then when into Preferences -> Language Servers and turn them all off.\nNow I do not have any issues with slowness of opening files or the famous mac BeachBall.\n", "For me the issue was with Spring, and then I went ahead and turned off all Spring language servers. I do not know what capabilities are lost due to this, but there seems to be lot of improvement that is needed here before we actually use it.\nWhat a pain in neck, killed my office work productivity for almost a month!\n\n" ]
[ 20, 0 ]
[]
[]
[ "eclipse" ]
stackoverflow_0054354708_eclipse.txt
Q: How to compile file sass to file css in one the main file css on the vuejs project I am setup the project of the vuejs on of the my goals in the end of the project is to compile files scss which is the main file with name style.scss- from input to output in the file main file style.css to Load in the vuejs. Also all files .scss should include with @importfor examples: @import "variables";and so on in the main file style.scss. I read about it.enter link description here My project is as in the picture below. Any idea how to sole it? Thanks. A: My dear friend, if I have understood your meaning correctly, I would like to try to offer you some solutions. In order to use SCSS in a project and compile it automatically in the background, we can do the following steps: 1. Install node-sass To get the compiler, weโ€™re going to install the node-sass package. Go to your terminal, navigate to the project folder and type in the following: npm i node-sass 2. Create an SCSS folder Create a new folder called scss in your project. After doing so, copy and paste all the CSS files from your css (or stylesheets) folder to your new scss folder. Rename the extensions on all the newly pasted css files with .scss You should end up with a scss folder which looks exactly like your css folder but with the files ending with .scss. 3. Add a script in package.json In your package.json file, locate scripts and add the following piece of code inside it: "scss": "node-sass --watch scss -o css" If your css folder is named something other than css, then replace the word css with the folder name. Similarly, if your scss folder is named something other scss, then replace scss with the correct folder name. Setting context in the overall package.json file, the script will be placed like this: { โ€œnameโ€: โ€œexample-projectโ€, โ€œversionโ€: โ€œ0.4.2โ€, โ€œscriptsโ€: { โ€œstartโ€: โ€œnode ./bin/wwwโ€, โ€œscssโ€: โ€œnode-sass โ€” watch scss -o cssโ€ }, "dependencies": { "express": "~4.16.0", "express-favicon": "^2.0.1", } } 4. Run the compiler Get back into terminal and run the following commandL npm run scss Now youโ€™ll notice any changes you make in your scss files will automatically be reflected in the css files. if you have any new idea about Compile SASS to CSS you can check another steps with this link.
How to compile file sass to file css in one the main file css on the vuejs project
I am setup the project of the vuejs on of the my goals in the end of the project is to compile files scss which is the main file with name style.scss- from input to output in the file main file style.css to Load in the vuejs. Also all files .scss should include with @importfor examples: @import "variables";and so on in the main file style.scss. I read about it.enter link description here My project is as in the picture below. Any idea how to sole it? Thanks.
[ "My dear friend, if I have understood your meaning correctly, I would like to try to offer you some solutions.\nIn order to use SCSS in a project and compile it automatically in the background, we can do the following steps:\n1. Install node-sass\nTo get the compiler, weโ€™re going to install the node-sass package.\nGo to your terminal, navigate to the project folder and type in the following:\nnpm i node-sass\n\n2. Create an SCSS folder\nCreate a new folder called scss in your project. After doing so, copy and paste all the CSS files from your css (or stylesheets) folder to your new scss folder.\n\nRename the extensions on all the newly pasted css files with .scss\nYou should end up with a scss folder which looks exactly like your css folder but with the files ending with .scss.\n3. Add a script in package.json\nIn your package.json file, locate scripts and add the following piece of code inside it:\n\"scss\": \"node-sass --watch scss -o css\"\n\nIf your css folder is named something other than css, then replace the word css with the folder name.\nSimilarly, if your scss folder is named something other scss, then replace scss with the correct folder name.\nSetting context in the overall package.json file, the script will be placed like this:\n{\n โ€œnameโ€: โ€œexample-projectโ€,\n โ€œversionโ€: โ€œ0.4.2โ€,\n โ€œscriptsโ€: {\n โ€œstartโ€: โ€œnode ./bin/wwwโ€,\n โ€œscssโ€: โ€œnode-sass โ€” watch scss -o cssโ€\n},\n \"dependencies\": {\n \"express\": \"~4.16.0\",\n \"express-favicon\": \"^2.0.1\",\n }\n}\n\n4. Run the compiler\nGet back into terminal and run the following commandL\nnpm run scss\n\nNow youโ€™ll notice any changes you make in your scss files will automatically be reflected in the css files.\nif you have any new idea about Compile SASS to CSS you can check another steps with this link.\n" ]
[ 0 ]
[]
[]
[ "css", "sass", "vue.js" ]
stackoverflow_0074669582_css_sass_vue.js.txt
Q: running a test script for multiple URLs in multiple browsers (local) in selenium python I have a test script that I want to be run for multiple URLs on multiple browsers (Chrome and Firefox) locally on my machine. Every browser has to open all the URLs for the test script. I have run the test script for multiple URLs, but I'm confused about how to do it for multiple browsers. I have checked stuff online but all of them doing it remotely. my test script is below: import time from selenium import webdriver from selenium.webdriver.chrome.options import Options Driver = webdriver.Chrome() def localitems() : local_storage = Driver.execute_script( \ "var ls = window.localStorage, items = {}; " \ "for (var i = 0, k; i < ls.length; ++i) " \ " items[k = ls.key(i)] = ls.getItem(k);"\ "return items; ") return local_storage; def sessionitems() : session_storage = Driver.execute_script( \ "var ls = window.sessionStorage, items = {}; " \ "for (var i = 0, k; i < ls.length; ++i) " \ " items[k = ls.key(i)] = ls.getItem(k);"\ "return items; ") return session_storage; sites = [ "http://www.github.com", "https://tribune.com.pk" ] for index, site in enumerate(sites) print(index,site) Driver.get(site) time.sleep(5) print('localStorage', localitems()) print('sessionStorage', sessionitems()) Driver.quit() If anyone could help me with this, would be thankful. A: Create a list with the drivers and then execute your script in the for loop: drivers = [webdriver.Chrome(), webdriver.Firefox()] for Driver in drivers: def localitems(): local_storage = Driver.execute_script( \ "var ls = window.localStorage, items = {}; " \ "for (var i = 0, k; i < ls.length; ++i) " \ " items[k = ls.key(i)] = ls.getItem(k);" \ "return items; ") return local_storage; def sessionitems(): session_storage = Driver.execute_script( \ "var ls = window.sessionStorage, items = {}; " \ "for (var i = 0, k; i < ls.length; ++i) " \ " items[k = ls.key(i)] = ls.getItem(k);" \ "return items; ") return session_storage; sites = [ "http://www.github.com", "https://tribune.com.pk" ] for index, site in enumerate(sites) print(index, site) Driver.get(site) time.sleep(5) print('localStorage', localitems()) print('sessionStorage', sessionitems()) Driver.quit() Also note that there is a convention in Python (PEP-8). According to it, variable name should be lowercase. So it's better to use driver instead of Driver
running a test script for multiple URLs in multiple browsers (local) in selenium python
I have a test script that I want to be run for multiple URLs on multiple browsers (Chrome and Firefox) locally on my machine. Every browser has to open all the URLs for the test script. I have run the test script for multiple URLs, but I'm confused about how to do it for multiple browsers. I have checked stuff online but all of them doing it remotely. my test script is below: import time from selenium import webdriver from selenium.webdriver.chrome.options import Options Driver = webdriver.Chrome() def localitems() : local_storage = Driver.execute_script( \ "var ls = window.localStorage, items = {}; " \ "for (var i = 0, k; i < ls.length; ++i) " \ " items[k = ls.key(i)] = ls.getItem(k);"\ "return items; ") return local_storage; def sessionitems() : session_storage = Driver.execute_script( \ "var ls = window.sessionStorage, items = {}; " \ "for (var i = 0, k; i < ls.length; ++i) " \ " items[k = ls.key(i)] = ls.getItem(k);"\ "return items; ") return session_storage; sites = [ "http://www.github.com", "https://tribune.com.pk" ] for index, site in enumerate(sites) print(index,site) Driver.get(site) time.sleep(5) print('localStorage', localitems()) print('sessionStorage', sessionitems()) Driver.quit() If anyone could help me with this, would be thankful.
[ "Create a list with the drivers and then execute your script in the for loop:\ndrivers = [webdriver.Chrome(), webdriver.Firefox()]\n\nfor Driver in drivers:\n def localitems():\n local_storage = Driver.execute_script( \\\n \"var ls = window.localStorage, items = {}; \" \\\n \"for (var i = 0, k; i < ls.length; ++i) \" \\\n \" items[k = ls.key(i)] = ls.getItem(k);\" \\\n \"return items; \")\n return local_storage;\n\n\n def sessionitems():\n session_storage = Driver.execute_script( \\\n \"var ls = window.sessionStorage, items = {}; \" \\\n \"for (var i = 0, k; i < ls.length; ++i) \" \\\n \" items[k = ls.key(i)] = ls.getItem(k);\" \\\n \"return items; \")\n return session_storage;\n\n\n sites = [\n \"http://www.github.com\",\n \"https://tribune.com.pk\"\n ]\n\n for index, site in enumerate(sites)\n print(index, site)\n Driver.get(site)\n time.sleep(5)\n print('localStorage', localitems())\n print('sessionStorage', sessionitems())\n Driver.quit()\n\n\nAlso note that there is a convention in Python (PEP-8). According to it, variable name should be lowercase. So it's better to use driver instead of Driver\n" ]
[ 0 ]
[]
[]
[ "browser_automation", "cross_browser", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074672023_browser_automation_cross_browser_python_selenium_selenium_webdriver.txt
Q: Adding an additional key-value pair to objects in a list before passing it to a Template - Working, but I'm not sure why New to Django and I wanted to append a key:value pair to each Job object in a Queryset/list before passing it to a template. Researching on here it says you can't just append a field, but rather need to create a new dict or could possibly add attributes or something, but messing around I got it to work great, but logically it seems it shouldn't work, and I worry I may run into problems or data inconsistency somewhere. My "jobs" view gets all Jobs currently not assigned to a User, filters out Jobs based on the current signed in Users listed skillset(a custom field for my User model), and then the functionatily I'm adding is to check the current Users schedule, and add a value "conflict":True if the schedule conflicts so I can highlight it red when rendering the list of jobs to the screen. views.py (abbreviated): def jobs (request): //get all unassigned jobs, and create a list of only jobs where the user has matching skills available = Job.objects.filter(assigned_to__isnull=True).order_by('start_time').all() available = [job for job in available if request.user.is_skilled(job)] //go through each job, make it a dict, and add "conflict":True to it if scheudle confict for job in available: if not request.user.is_available(job): job = job.__dict__ job["conflict"] = True //run custom serializer() to format each field and return list of jobs return JsonResponse({'available': [job.serialize() for job in available]}) The part that doesn't make sense to me is job.__dict__ should be converting the job object to a dict, so I actually expected to get an error when I attempt to run job.serialize(). Infact, there is another view where I attempt the same thing with a single Job object(not a list or Queryset) and it gives error Dict does not contain method serialize(). And if I don't first convert to dict I get an error TypeError: 'Job' object does not support item assignment. But somehow when working with a list, the conversion doesn't occur, but my Job object now has a new field "conflict" that I can check with job.conflict in JS, templates, and in the serialize() model method: models.py (abbreviated): class Job (models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() skillsets = models.ManyToManyField(Skillset, related_name="jobs") def serialize(self): return { 'id': self.id, 'title': self.title, 'description': self.description, 'start_time': self.start_time.strftime("%b %d %Y, %I:%M %p"), 'end_time': self.end_time.strftime("%b %d %Y, %I:%M %p"), 'skillsets': [skill.title for skill in self.skillsets.all()], 'conflict': self.conflict if 'conflict' in self.__dict__ else False, } So question is, why does available contain a list of only Job objects after I should have converted some of them to Dict? I do this again on the User's object later to highlight users who are available for a particular Job, and same thing, even though I supposedly convert to Dict and add a field, the final output is a list of User objects with an added field available. I was expecting assignable to be a list of dicts, not a list of user objects: Also in views.py: def job_details (request, job_id): //get a single Job, and list of users who are specialist, then filter out users who don't have required skills job = Job.objects.get(pk=job_id) users = User.objects.filter(user_type=User.SPECIALIST) users = list(filter(lambda usr: usr.is_skilled(job), users)) //for each user, check their schedule against this job, and add "available":True/False as determined for usr in users: if (usr.is_available(job)): usr = usr.__dict__ usr["available"] = True else: usr = usr.__dict__ usr["available"] = False //return job and users to be rendered on screen, colored based on their availability return render(request, "jobs/job_details.html", { 'job': job.serialize(), 'assignable': users, 'conflict': True if request.user.user_type == User.SPECIALIST and not request.user.is_available(job) else False}) Is there a logical explaination? Is it because I'm doing it in a for loop that the conversion doesn't stick, but the field gets added to the User/Job objects, like is it converting back after it exits the for loop? A: To address your immediate question - the statement usr = usr.__dict__ done when iterating over the list simply assigns a variable usr. It does not change the element in the original list. To transform the list of model instances to dicts, you can use map function, or list comprehension. For example: users = list(map(lambda usr: {**usr.__dict__, "available": usr.is_available(job)}, users)) BTW, probably slightly better approach would be to set "available" attribute right on the model instance, and then access it in serialize method via getattr: getattr(self, "available", False). Or, you can take it a step further and add available as a python property to model class. Then you will be able to document its meaning and usage: class User(models.Model): ... @property def available(self): """Document the meaning...""" return getattr(self, "_available", False) @available.setter def available(self, value): self._available = value
Adding an additional key-value pair to objects in a list before passing it to a Template - Working, but I'm not sure why
New to Django and I wanted to append a key:value pair to each Job object in a Queryset/list before passing it to a template. Researching on here it says you can't just append a field, but rather need to create a new dict or could possibly add attributes or something, but messing around I got it to work great, but logically it seems it shouldn't work, and I worry I may run into problems or data inconsistency somewhere. My "jobs" view gets all Jobs currently not assigned to a User, filters out Jobs based on the current signed in Users listed skillset(a custom field for my User model), and then the functionatily I'm adding is to check the current Users schedule, and add a value "conflict":True if the schedule conflicts so I can highlight it red when rendering the list of jobs to the screen. views.py (abbreviated): def jobs (request): //get all unassigned jobs, and create a list of only jobs where the user has matching skills available = Job.objects.filter(assigned_to__isnull=True).order_by('start_time').all() available = [job for job in available if request.user.is_skilled(job)] //go through each job, make it a dict, and add "conflict":True to it if scheudle confict for job in available: if not request.user.is_available(job): job = job.__dict__ job["conflict"] = True //run custom serializer() to format each field and return list of jobs return JsonResponse({'available': [job.serialize() for job in available]}) The part that doesn't make sense to me is job.__dict__ should be converting the job object to a dict, so I actually expected to get an error when I attempt to run job.serialize(). Infact, there is another view where I attempt the same thing with a single Job object(not a list or Queryset) and it gives error Dict does not contain method serialize(). And if I don't first convert to dict I get an error TypeError: 'Job' object does not support item assignment. But somehow when working with a list, the conversion doesn't occur, but my Job object now has a new field "conflict" that I can check with job.conflict in JS, templates, and in the serialize() model method: models.py (abbreviated): class Job (models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) start_time = models.DateTimeField() end_time = models.DateTimeField() skillsets = models.ManyToManyField(Skillset, related_name="jobs") def serialize(self): return { 'id': self.id, 'title': self.title, 'description': self.description, 'start_time': self.start_time.strftime("%b %d %Y, %I:%M %p"), 'end_time': self.end_time.strftime("%b %d %Y, %I:%M %p"), 'skillsets': [skill.title for skill in self.skillsets.all()], 'conflict': self.conflict if 'conflict' in self.__dict__ else False, } So question is, why does available contain a list of only Job objects after I should have converted some of them to Dict? I do this again on the User's object later to highlight users who are available for a particular Job, and same thing, even though I supposedly convert to Dict and add a field, the final output is a list of User objects with an added field available. I was expecting assignable to be a list of dicts, not a list of user objects: Also in views.py: def job_details (request, job_id): //get a single Job, and list of users who are specialist, then filter out users who don't have required skills job = Job.objects.get(pk=job_id) users = User.objects.filter(user_type=User.SPECIALIST) users = list(filter(lambda usr: usr.is_skilled(job), users)) //for each user, check their schedule against this job, and add "available":True/False as determined for usr in users: if (usr.is_available(job)): usr = usr.__dict__ usr["available"] = True else: usr = usr.__dict__ usr["available"] = False //return job and users to be rendered on screen, colored based on their availability return render(request, "jobs/job_details.html", { 'job': job.serialize(), 'assignable': users, 'conflict': True if request.user.user_type == User.SPECIALIST and not request.user.is_available(job) else False}) Is there a logical explaination? Is it because I'm doing it in a for loop that the conversion doesn't stick, but the field gets added to the User/Job objects, like is it converting back after it exits the for loop?
[ "To address your immediate question - the statement usr = usr.__dict__ done when iterating over the list simply assigns a variable usr. It does not change the element in the original list. To transform the list of model instances to dicts, you can use map function, or list comprehension. For example:\nusers = list(map(lambda usr: {**usr.__dict__, \"available\": usr.is_available(job)}, users))\n\nBTW, probably slightly better approach would be to set \"available\" attribute right on the model instance, and then access it in serialize method via getattr: getattr(self, \"available\", False).\nOr, you can take it a step further and add available as a python property to model class. Then you will be able to document its meaning and usage:\nclass User(models.Model):\n ...\n @property\n def available(self):\n \"\"\"Document the meaning...\"\"\"\n return getattr(self, \"_available\", False)\n\n @available.setter\n def available(self, value):\n self._available = value\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models" ]
stackoverflow_0074673065_django_django_models.txt
Q: Jimp: getting rgb color of pixels from 24-bit bmp I have a 24-bit bmp file that I want to get the rgb values for the pixels using Jimp for node. If I open the image in GIMP and examine pixel 0,0 the rgb values are r: 45, g: 203, b: 203. However, if I use Jimp and the following code: Jimp.read(fileToRead) .then(image => { console.log(Jimp.intToRGBA(image.getPixelColor(0,0))) }) .catch(err => { console.log(err); }) I get { r: 173, g: 200, b: 150, a: 255 } By eye, r: 45, g: 203, b: 203 is the correct color. So what am I doing wrong? Do I need to use some option to tell Jimp it's 24-bit? Can Jimp read 24-bit? Internally it's using node mod bmp-js which supposedly can decode 24 bit. Am I missing some basic knowledge about bmp format? Thanks. A: I would write the actual image from which you are trying to extract the color info. Jimp has a write() method. For example: Jimp.read(...).write('/tmp/out.png'); Then open out.png and inspect by yourself
Jimp: getting rgb color of pixels from 24-bit bmp
I have a 24-bit bmp file that I want to get the rgb values for the pixels using Jimp for node. If I open the image in GIMP and examine pixel 0,0 the rgb values are r: 45, g: 203, b: 203. However, if I use Jimp and the following code: Jimp.read(fileToRead) .then(image => { console.log(Jimp.intToRGBA(image.getPixelColor(0,0))) }) .catch(err => { console.log(err); }) I get { r: 173, g: 200, b: 150, a: 255 } By eye, r: 45, g: 203, b: 203 is the correct color. So what am I doing wrong? Do I need to use some option to tell Jimp it's 24-bit? Can Jimp read 24-bit? Internally it's using node mod bmp-js which supposedly can decode 24 bit. Am I missing some basic knowledge about bmp format? Thanks.
[ "I would write the actual image from which you are trying to extract the color info. Jimp has a write() method. For example:\nJimp.read(...).write('/tmp/out.png');\nThen open out.png and inspect by yourself\n" ]
[ 0 ]
[]
[]
[ "bmp", "jimp", "node.js" ]
stackoverflow_0068270614_bmp_jimp_node.js.txt
Q: How to create a database api using STS and maven I'm a software trainee and given a task to create a database API that can perform CRUD operations using STS Spring Tool Suite . I've been created a simple maven hello world project in STS and now confused that from where i should start and what things i have to learn .. If anyone can guide me to this , i'll be very thankful to him/her plzz..if anyone. And one more question is that is Spring Boot and Spring Tool Suite are the two different things ? thank you in advance I've been tried many websites that tell me creating APIs using Spring Boot using others things but, I'm stuck between them and get confused. A: If you want to create API's for you database. Create an Spring boot project in your editor or from Spring.io site... And configure your database in your project application .properties file. And create an Class and annotate as @RestController. create an method and annotate as any mapping's like @GetMapping("Name of your API"). And Run your application.. you can hit your API in postman... You can get more clarity in this docs kindly refer this..sample project
How to create a database api using STS and maven
I'm a software trainee and given a task to create a database API that can perform CRUD operations using STS Spring Tool Suite . I've been created a simple maven hello world project in STS and now confused that from where i should start and what things i have to learn .. If anyone can guide me to this , i'll be very thankful to him/her plzz..if anyone. And one more question is that is Spring Boot and Spring Tool Suite are the two different things ? thank you in advance I've been tried many websites that tell me creating APIs using Spring Boot using others things but, I'm stuck between them and get confused.
[ "If you want to create API's for you database. Create an Spring boot project in your editor or from Spring.io site...\nAnd configure your database in your project application .properties file.\nAnd create an Class and annotate as @RestController.\ncreate an method and annotate as any mapping's like @GetMapping(\"Name of your API\").\nAnd Run your application.. you can hit your API in postman...\nYou can get more clarity in this docs kindly refer this..sample project\n" ]
[ 0 ]
[]
[]
[ "java", "maven", "spring_boot", "spring_mvc", "spring_tool_suite" ]
stackoverflow_0074673215_java_maven_spring_boot_spring_mvc_spring_tool_suite.txt
Q: List of numbers have same data but different sum I have two lists of numbers. After comparing them, they are same but there sum is different. You can get the script here: https://mega.nz/file/dHgHEQQA#9k9s86hgGH_vWrcE8J6ixYdu3GYkfwtw0V0IBvuhd4o Am I comparing wrong or what is the problem? A: Check the length of the list. e appears to be having 694 elements and r appears to be having 693 elements. so, zip aggregates only 693 elements. Hence the sum are different. print(len(e), len(r), len([x for x in zip(e, r)])) # 694 693 693
List of numbers have same data but different sum
I have two lists of numbers. After comparing them, they are same but there sum is different. You can get the script here: https://mega.nz/file/dHgHEQQA#9k9s86hgGH_vWrcE8J6ixYdu3GYkfwtw0V0IBvuhd4o Am I comparing wrong or what is the problem?
[ "Check the length of the list. e appears to be having 694 elements and r appears to be having 693 elements. so, zip aggregates only 693 elements. Hence the sum are different.\nprint(len(e), len(r), len([x for x in zip(e, r)]))\n# 694 693 693\n\n" ]
[ 0 ]
[]
[]
[ "comparison", "list", "python" ]
stackoverflow_0074673224_comparison_list_python.txt
Q: glue jupyter notebook locally instead of labs? docker run -itd -p 8888:8888 -p 4040:4040 --name glue_jupyter amazon/aws-glue-libs:glue_libs_2.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh results in i'm able to open 127.0.0.1:8888 and it redirects to jupyter labs How do i go to jupyter notebook instead? should i bash instead and then jupyter notebook from there? unsure. A: I tried the following command with glue image for 3.0, and it does takes me to the jupyter labs, with a console prompt to choose python/pyspark/etc. notebooks. docker run -it -p 8888:8888 -p 4040:4040 -e DISABLE_SSL="true" --name glue_jupyter amazon/aws-glue-libs:glue_libs_3.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh In the above command, I have removed "d", so that I can see the logs in the console as the docker runs. Choose Glue Spark Local (PySpark) under Notebook. You can start developing code in the interactive Jupyter notebook UI. A notebook with sample code showing spark versions Please refer to this AWS document (Jupyter Lab section) for reference:https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html
glue jupyter notebook locally instead of labs?
docker run -itd -p 8888:8888 -p 4040:4040 --name glue_jupyter amazon/aws-glue-libs:glue_libs_2.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh results in i'm able to open 127.0.0.1:8888 and it redirects to jupyter labs How do i go to jupyter notebook instead? should i bash instead and then jupyter notebook from there? unsure.
[ "I tried the following command with glue image for 3.0, and it does takes me to the jupyter labs, with a console prompt to choose python/pyspark/etc. notebooks.\ndocker run -it -p 8888:8888 -p 4040:4040 -e DISABLE_SSL=\"true\" --name glue_jupyter amazon/aws-glue-libs:glue_libs_3.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh\n\nIn the above command, I have removed \"d\", so that I can see the logs in the console as the docker runs.\n\nChoose Glue Spark Local (PySpark) under Notebook. You can start developing code in the interactive Jupyter notebook UI.\nA notebook with sample code showing spark versions\n\nPlease refer to this AWS document (Jupyter Lab section) for reference:https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html\n" ]
[ 0 ]
[]
[]
[ "aws_glue", "docker", "jupyter_notebook", "pyspark", "python" ]
stackoverflow_0074663072_aws_glue_docker_jupyter_notebook_pyspark_python.txt
Q: Hide Wordpress Categories from Users by Role I want to be able to hide certain Wordpress Post Categories from Users dependent on their Role. I've tried the code here: Wordpress: Hide specific categories from User Role on the Add New page I think its deprecated, and would really appreciate some help add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2); function yoursite_list_terms_exclusions( $exclusions, $args ) { global $pagenow; if (in_array($pagenow,array('post.php','post-new.php')) && !current_user_can('see_special_cats')) { $exclusions = " {$exclusions} AND t.slug NOT IN ('slug-one','slug-two')"; } return $exclusions; } With this code nothing happens. I've tried 10+ different plugins and am really getting desperate. Thanks in advance. A: add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2); function yoursite_list_terms_exclusions( $exclusions, $args ) { global $pagenow; if (in_array($pagenow,array('post.php','post-new.php')) && !current_user_can('see_special_cats')) { $exclusions = " {$exclusions} AND t.slug NOT IN ('slug-one','slug-two')"; } return $exclusions; } This code presumes that you've used a plugin like the Members plugin to create a capability called 'see_special_cats' and that you've assigned it to every role that you want to have access to the categories except of course 'Contributors'. Since you found the plugin you may not need this, but maybe it will help someone else. A: add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2); function yoursite_list_terms_exclusions( $exclusions, $args ) { $current_user = wp_get_current_user(); // Change 'see_special_cats' to capability user must have to be able see category or categories if ( $current_user->has_cap('see_special_cats') ) { $capCheck = 1; } else { $capCheck = 0; } global $pagenow; if (in_array($pagenow,array('post.php','post-new.php')) && !$capCheck) { // Change category-slug-one and two to desired categories to hide. Additional categories may be added // by separating with a comma. Delete ", 'category-slug-two'" to only hide one category $exclusions = " {$exclusions} AND t.slug NOT IN ('category-slug-one', 'category-slug-two')"; } return $exclusions; } This code works without using current_user_can(). Paste this code in your functions.php file. If you want to hide a category from everyone except for the Administrator role, as set up by the default hierarchical structure, change 'see_special_cats' to 'create_users'. Change category-slug-one and category-slug-two to the category slugs that you want hidden. There is no additional plugin required (I'm not sure where 'see_special_cats' comes from).
Hide Wordpress Categories from Users by Role
I want to be able to hide certain Wordpress Post Categories from Users dependent on their Role. I've tried the code here: Wordpress: Hide specific categories from User Role on the Add New page I think its deprecated, and would really appreciate some help add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2); function yoursite_list_terms_exclusions( $exclusions, $args ) { global $pagenow; if (in_array($pagenow,array('post.php','post-new.php')) && !current_user_can('see_special_cats')) { $exclusions = " {$exclusions} AND t.slug NOT IN ('slug-one','slug-two')"; } return $exclusions; } With this code nothing happens. I've tried 10+ different plugins and am really getting desperate. Thanks in advance.
[ "add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2);\nfunction yoursite_list_terms_exclusions( $exclusions, $args ) {\n global $pagenow;\n if (in_array($pagenow,array('post.php','post-new.php')) && \n !current_user_can('see_special_cats')) {\n $exclusions = \" {$exclusions} AND t.slug NOT IN ('slug-one','slug-two')\";\n }\n return $exclusions;\n}\n\nThis code presumes that you've used a plugin like the Members plugin to create a capability called 'see_special_cats' and that you've assigned it to every role that you want to have access to the categories except of course 'Contributors'.\nSince you found the plugin you may not need this, but maybe it will help someone else.\n", "add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2);\n\nfunction yoursite_list_terms_exclusions( $exclusions, $args ) {\n$current_user = wp_get_current_user();\n // Change 'see_special_cats' to capability user must have to be able see category or categories\n if ( $current_user->has_cap('see_special_cats') ) {\n $capCheck = 1;\n } else {\n $capCheck = 0;\n }\n global $pagenow;\n if (in_array($pagenow,array('post.php','post-new.php')) && !$capCheck) {\n // Change category-slug-one and two to desired categories to hide. Additional categories may be added\n // by separating with a comma. Delete \", 'category-slug-two'\" to only hide one category\n $exclusions = \" {$exclusions} AND t.slug NOT IN ('category-slug-one', 'category-slug-two')\";\n }\n return $exclusions;\n}\n\nThis code works without using current_user_can(). Paste this code in your functions.php file. If you want to hide a category from everyone except for the Administrator role, as set up by the default hierarchical structure, change 'see_special_cats' to 'create_users'. Change category-slug-one and category-slug-two to the category slugs that you want hidden. There is no additional plugin required (I'm not sure where 'see_special_cats' comes from).\n" ]
[ 0, 0 ]
[]
[]
[ "categories", "wordpress" ]
stackoverflow_0057656510_categories_wordpress.txt
Q: "int_list_validator" is not working in Django forms I made the following Django form. from django.core.validators import int_list_validator class RoomForm(forms. Form): room_numbers = forms.CharField(validators=[int_list_validator], required=False, max_length=4000) In this form even if I submit a string like 'hello' the form gets submitted. I mean I can get the value 'hello' in views.py. I don't understand why because "int_list_validator" should not allow it. A: Unfortunate naming: int_list_validator is not a validator but a helper function that creates one. validate_comma_separated_integer_list is a validator, created by calling int_list_validator with a more suitable message than the default _("Enter a valid value."): validate_comma_separated_integer_list = int_list_validator( message=_("Enter only digits separated by commas."), ) Usage: from django import forms from django.core.validators import int_list_validator, validate_comma_separated_integer_list # room_numbers = forms.CharField(validators=[int_list_validator], required=False, max_length=4000) room_numbers = forms.CharField(validators=[int_list_validator()], required=False, max_length=4000) # Or room_numbers = forms.CharField(validators=[validate_comma_separated_integer_list], required=False, max_length=4000)
"int_list_validator" is not working in Django forms
I made the following Django form. from django.core.validators import int_list_validator class RoomForm(forms. Form): room_numbers = forms.CharField(validators=[int_list_validator], required=False, max_length=4000) In this form even if I submit a string like 'hello' the form gets submitted. I mean I can get the value 'hello' in views.py. I don't understand why because "int_list_validator" should not allow it.
[ "Unfortunate naming: int_list_validator is not a validator but a helper function that creates one.\nvalidate_comma_separated_integer_list is a validator, created by calling int_list_validator with a more suitable message than the default _(\"Enter a valid value.\"):\n\nvalidate_comma_separated_integer_list = int_list_validator(\n message=_(\"Enter only digits separated by commas.\"),\n)\n\n\nUsage:\nfrom django import forms\nfrom django.core.validators import int_list_validator, validate_comma_separated_integer_list\n\n\n# room_numbers = forms.CharField(validators=[int_list_validator], required=False, max_length=4000)\nroom_numbers = forms.CharField(validators=[int_list_validator()], required=False, max_length=4000)\n\n# Or\nroom_numbers = forms.CharField(validators=[validate_comma_separated_integer_list], required=False, max_length=4000)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_validation" ]
stackoverflow_0074665759_django_django_forms_django_validation.txt
Q: Is it possible make tmux status bar float over the terminal content (instead of push it)? I recently changed my tmux config to toggle the status bar when I press a key map. When the status bar is displayed, it pushes the terminal content up and the flick effect is annoying. Is it possible to display the status bar over the terminal content? (tmux prompt have this 'floating behavior', so I was thinking if there is some option to also apply it to status bar) A: I found an workaround! Instead of display the status, I'm using a display-message and recreate my status line inside the message. The display-message have the wanted float behavior. Something like tmux display-message -d 3000 "#{E:status-format[0]}"
Is it possible make tmux status bar float over the terminal content (instead of push it)?
I recently changed my tmux config to toggle the status bar when I press a key map. When the status bar is displayed, it pushes the terminal content up and the flick effect is annoying. Is it possible to display the status bar over the terminal content? (tmux prompt have this 'floating behavior', so I was thinking if there is some option to also apply it to status bar)
[ "I found an workaround!\nInstead of display the status, I'm using a display-message and recreate my status line inside the message. The display-message have the wanted float behavior.\nSomething like\ntmux display-message -d 3000 \"#{E:status-format[0]}\"\n\n" ]
[ 0 ]
[]
[]
[ "tmux" ]
stackoverflow_0074626967_tmux.txt
Q: Vue 3 list does not update We are fetching data from API like: <script setup> import { onMounted, inject } from 'vue' let list = []; function init() { axios .post("/some-link/here") .then((o) => { list = o.data.bla; console.log(list); }) .catch((o) => { //TO DO }); } onMounted(() => { init(); }); </script> The console.log shows the list properly. But on the template, it does not update. <p v-for="(val, index) in list" :key="index"> {{ val.name }} </p> A: This works well <script setup> import { ref, onMounted } from "vue"; const users = ref([]); async function fetchData() { const response = await fetch("https://jsonplaceholder.typicode.com/users"); return await response.json(); } onMounted(async () => { users.value = await fetchData(); }); </script> <template> <div v-for="user in users" :key="user.id"> {{ user.id }} {{ user.name }} </div> </template> Here is a playground. A: you should use ref/reactive for reactive data let list = ref([]);
Vue 3 list does not update
We are fetching data from API like: <script setup> import { onMounted, inject } from 'vue' let list = []; function init() { axios .post("/some-link/here") .then((o) => { list = o.data.bla; console.log(list); }) .catch((o) => { //TO DO }); } onMounted(() => { init(); }); </script> The console.log shows the list properly. But on the template, it does not update. <p v-for="(val, index) in list" :key="index"> {{ val.name }} </p>
[ "This works well\n<script setup>\nimport { ref, onMounted } from \"vue\";\n\nconst users = ref([]);\n\nasync function fetchData() {\n const response = await fetch(\"https://jsonplaceholder.typicode.com/users\");\n return await response.json();\n}\n\nonMounted(async () => {\n users.value = await fetchData();\n});\n</script>\n\n<template>\n <div v-for=\"user in users\" :key=\"user.id\">\n {{ user.id }} {{ user.name }}\n </div>\n</template>\n\nHere is a playground.\n", "you should use ref/reactive for reactive data\nlet list = ref([]);\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "vue.js", "vue_component", "vuejs3" ]
stackoverflow_0074672441_javascript_vue.js_vue_component_vuejs3.txt
Q: First cell and last cell are changing simultaneously? I have a UICollectionView with 4 buttons in each cell. When I select one of the button on the FIRST cell, the same button gets selected on the LAST cell and vice versa. This problem occurs on the last and first cell ONLY. I have created a video to demonstrate the problem. And this is how my ViewController and the UICollectionView looks like (I didnt include everything, like the UI stuff and viewDidLoad): ViewController: class QuizViewController: UIViewController { private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.register(QuestionView.self, forCellWithReuseIdentifier: "questionCell") collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.delegate = self collectionView.dataSource = self return collectionView }() extension QuizViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { self.questionsIndex = indexPath.row } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return questions.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "questionCell", for: indexPath) as! QuestionView cell.configure(with: questions[indexPath.row]) cell.delegate = self return cell } } UICollectionViewCell: class QuestionView: UICollectionViewCell { private var question: Question { didSet { questionLabel.text = question.question answerButton1.setTitle(question.answers[0], for: .normal) answerButton2.setTitle(question.answers[1], for: .normal) answerButton3.setTitle(question.answers[2], for: .normal) answerButton4.setTitle(question.answers[3], for: .normal) } } private lazy var answerButton1: CustomAnswerButton = { let button = CustomAnswerButton(answerLabel: "") button.addTarget(self, action: #selector(didTapAnswerButton), for: .touchUpInside) return button }() //I have 3 more of this button but with different names, like answerButton2 public func configure(with question: Question) { self.question = question } @objc private func didTapAnswerButton(_ sender: UIButton) { answerButton1.backgroundColor = .white answerButton2.backgroundColor = .white answerButton3.backgroundColor = .white answerButton4.backgroundColor = .white if(sender.isSelected) { sender.isSelected = false delegate?.didUnselectAnswer() } else { if(answerButton1.isSelected || answerButton2.isSelected || answerButton3.isSelected || answerButton4.isSelected) { delegate?.didUnselectAnswer() } answerButton1.isSelected = false answerButton2.isSelected = false answerButton3.isSelected = false answerButton4.isSelected = false sender.isSelected = true sender.backgroundColor = UIColor(red: 162/255, green: 210/255, blue: 255/255, alpha: 1) delegate?.didSelectAnswer() } } }
First cell and last cell are changing simultaneously?
I have a UICollectionView with 4 buttons in each cell. When I select one of the button on the FIRST cell, the same button gets selected on the LAST cell and vice versa. This problem occurs on the last and first cell ONLY. I have created a video to demonstrate the problem. And this is how my ViewController and the UICollectionView looks like (I didnt include everything, like the UI stuff and viewDidLoad): ViewController: class QuizViewController: UIViewController { private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.register(QuestionView.self, forCellWithReuseIdentifier: "questionCell") collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.delegate = self collectionView.dataSource = self return collectionView }() extension QuizViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { self.questionsIndex = indexPath.row } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return questions.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "questionCell", for: indexPath) as! QuestionView cell.configure(with: questions[indexPath.row]) cell.delegate = self return cell } } UICollectionViewCell: class QuestionView: UICollectionViewCell { private var question: Question { didSet { questionLabel.text = question.question answerButton1.setTitle(question.answers[0], for: .normal) answerButton2.setTitle(question.answers[1], for: .normal) answerButton3.setTitle(question.answers[2], for: .normal) answerButton4.setTitle(question.answers[3], for: .normal) } } private lazy var answerButton1: CustomAnswerButton = { let button = CustomAnswerButton(answerLabel: "") button.addTarget(self, action: #selector(didTapAnswerButton), for: .touchUpInside) return button }() //I have 3 more of this button but with different names, like answerButton2 public func configure(with question: Question) { self.question = question } @objc private func didTapAnswerButton(_ sender: UIButton) { answerButton1.backgroundColor = .white answerButton2.backgroundColor = .white answerButton3.backgroundColor = .white answerButton4.backgroundColor = .white if(sender.isSelected) { sender.isSelected = false delegate?.didUnselectAnswer() } else { if(answerButton1.isSelected || answerButton2.isSelected || answerButton3.isSelected || answerButton4.isSelected) { delegate?.didUnselectAnswer() } answerButton1.isSelected = false answerButton2.isSelected = false answerButton3.isSelected = false answerButton4.isSelected = false sender.isSelected = true sender.backgroundColor = UIColor(red: 162/255, green: 210/255, blue: 255/255, alpha: 1) delegate?.didSelectAnswer() } } }
[]
[]
[ "Resetting the state of the UICollectionViewCell in the prepareForReuse() method might work\nclass QuestionView: UICollectionViewCell {\n\n ...\n ...\n ...\n \n override func prepareForReuse() {\n super.prepareForReuse()\n \n // Reset the state of all the buttons\n answerButton1.backgroundColor = .white\n answerButton1.isSelected = false\n \n answerButton2.backgroundColor = .white\n answerButton2.isSelected = false\n \n answerButton3.backgroundColor = .white\n answerButton3.isSelected = false\n \n answerButton4.backgroundColor = .white\n answerButton4.isSelected = false\n }\n}\n\n" ]
[ -1 ]
[ "ios", "swift", "uikit" ]
stackoverflow_0074670050_ios_swift_uikit.txt
Q: Select, insert and center a photo in the merged cell I'm a R&D baker and making a recipe template for my team, In the template there's the photo, but I need to easily allow them to click a button that will open a file selector for the photo, then center that photo in the merged cells. I'm not really good at doing this.. Sub InsertPhotoMacro() Dim photoNameAndPath As Variant Dim photo As Picture photoNameAndPath = Application.GetOpenFilename(Title:="Select Photo to Insert") If photoNameAndPath = False Then Exit Sub Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath) With photo .Left = ActiveSheet.Range("E23").Left .Top = ActiveSheet.Range("E23").Top .Width = ActiveSheet.Range("F29").Width .Height = ActiveSheet.Range("F29").Height .Placement = 1 End With End Sub A: To Select, Insert and Fill the cell, try this. Just centering it is not enough. What if the image is bigger than the merged cell? Option Explicit Sub InsertPhotoMacro() Dim photoNameAndPath As Variant Dim photo As Picture Dim ws As Worksheet Dim MrdgCell As Range '~~> This is your worksheet Set ws = ActiveSheet '~~> And this is the merged cell Set MrdgCell = ws.Range("E23") photoNameAndPath = Application.GetOpenFilename(Title:="Select Photo to Insert") If photoNameAndPath = False Then Exit Sub Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath) With photo '~~> Disable lock aspect ratio that we can freely transform .ShapeRange.LockAspectRatio = msoFalse .Left = MrdgCell.Left .Top = MrdgCell.Top '~~> This is the total merged area height and width .Height = MrdgCell.MergeArea.Height .Width = MrdgCell.MergeArea.Width End With End Sub BEFORE AFTER (SCENARIO 1) And if you do not want to Fill but just Center the image then try this Option Explicit Sub InsertPhotoMacro() Dim photoNameAndPath As Variant Dim photo As Picture Dim ws As Worksheet Dim MrdgCell As Range '~~> This is your worksheet Set ws = ActiveSheet '~~> And this is the merged cell Set MrdgCell = ws.Range("E23") photoNameAndPath = Application.GetOpenFilename(Title:="Select Photo to Insert") If photoNameAndPath = False Then Exit Sub Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath) With photo .Left = MrdgCell.Left + (MrdgCell.MergeArea.Width - .Width) / 2 .Top = MrdgCell.Top + (MrdgCell.MergeArea.Height - .Height) / 2 End With End Sub AFTER (SCENARIO 2) LOGIC Whatever option you use, understand how to arrive at the correct co-ordinates/dimensions No need to use the start and the end cell. You can refer to the complete merged cell using .MergeArea.Width and .MergeArea.Height So if you want to center, the calculation for LEFT will be MERGED CELL LEFT + (MERGED CELL WIDTH - IMAGE WIDTH) / 2 Similarly for TOP, it will be MERGED CELL TOP + (MERGED CELL HEIGHT - IMAGE HEIGHT) / 2
Select, insert and center a photo in the merged cell
I'm a R&D baker and making a recipe template for my team, In the template there's the photo, but I need to easily allow them to click a button that will open a file selector for the photo, then center that photo in the merged cells. I'm not really good at doing this.. Sub InsertPhotoMacro() Dim photoNameAndPath As Variant Dim photo As Picture photoNameAndPath = Application.GetOpenFilename(Title:="Select Photo to Insert") If photoNameAndPath = False Then Exit Sub Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath) With photo .Left = ActiveSheet.Range("E23").Left .Top = ActiveSheet.Range("E23").Top .Width = ActiveSheet.Range("F29").Width .Height = ActiveSheet.Range("F29").Height .Placement = 1 End With End Sub
[ "To Select, Insert and Fill the cell, try this. Just centering it is not enough. What if the image is bigger than the merged cell?\nOption Explicit\n\nSub InsertPhotoMacro()\n Dim photoNameAndPath As Variant\n Dim photo As Picture\n Dim ws As Worksheet\n Dim MrdgCell As Range\n \n '~~> This is your worksheet\n Set ws = ActiveSheet\n '~~> And this is the merged cell\n Set MrdgCell = ws.Range(\"E23\")\n \n photoNameAndPath = Application.GetOpenFilename(Title:=\"Select Photo to Insert\")\n \n If photoNameAndPath = False Then Exit Sub\n \n Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath)\n \n With photo\n '~~> Disable lock aspect ratio that we can freely transform\n .ShapeRange.LockAspectRatio = msoFalse\n \n .Left = MrdgCell.Left\n .Top = MrdgCell.Top\n \n '~~> This is the total merged area height and width\n .Height = MrdgCell.MergeArea.Height\n .Width = MrdgCell.MergeArea.Width\n End With\nEnd Sub\n\nBEFORE\n\nAFTER (SCENARIO 1)\n\nAnd if you do not want to Fill but just Center the image then try this\nOption Explicit\n\nSub InsertPhotoMacro()\n Dim photoNameAndPath As Variant\n Dim photo As Picture\n Dim ws As Worksheet\n Dim MrdgCell As Range\n \n '~~> This is your worksheet\n Set ws = ActiveSheet\n '~~> And this is the merged cell\n Set MrdgCell = ws.Range(\"E23\")\n \n photoNameAndPath = Application.GetOpenFilename(Title:=\"Select Photo to Insert\")\n \n If photoNameAndPath = False Then Exit Sub\n \n Set photo = ActiveSheet.Pictures.Insert(photoNameAndPath)\n \n With photo\n .Left = MrdgCell.Left + (MrdgCell.MergeArea.Width - .Width) / 2\n .Top = MrdgCell.Top + (MrdgCell.MergeArea.Height - .Height) / 2\n End With\nEnd Sub\n\nAFTER (SCENARIO 2)\n\nLOGIC\nWhatever option you use, understand how to arrive at the correct co-ordinates/dimensions\n\nNo need to use the start and the end cell. You can refer to the complete merged cell using .MergeArea.Width and .MergeArea.Height\nSo if you want to center, the calculation for LEFT will be\nMERGED CELL LEFT + (MERGED CELL WIDTH - IMAGE WIDTH) / 2\n\nSimilarly for TOP, it will be\nMERGED CELL TOP + (MERGED CELL HEIGHT - IMAGE HEIGHT) / 2\n\n" ]
[ 3 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074673136_excel_vba.txt
Q: Homebrew Error: No formulae found in taps I'm trying to install paramiko on my MacBook Pro (OSX Sierra) without going through Xcode because I'm too lazy to install Xcode honestly. When trying to run: brew install paramiko I get: Error: No available formula with the name "paramiko" ==> Searching for similarly named formulae... Error: No similarly named formulae found. ==> Searching taps... Error: No formulae found in taps. I've tried untapping home-brew via: brew untap homebrew And I get: Error: No available tap homebrew/php. Also tried: brew tap --repair brew update Nothing besides: Updated 1 tap (caskroom/cask). No changes to formulae. If I have to go through Xcode, that's fine but I feel the issue here is not the installation process but something weird with the taps... A: This worked for me. run brew doctor Warning: Some taps are not on the default git origin branch and may not receive updates. If this is a surprise to you, check out the default branch with: git -C $(brew --repo homebrew/core) checkout master then run git -C $(brew --repo homebrew/core) A: Run this command: git -C $(brew --repo homebrew/core) checkout master this will switch to master, then run brew doctor this should run without any error. If there is no error you can install anything with brew install ex: brew install wget A: I ran: brew doctor which gave me as first warning: Warning: Homebrew/homebrew-core was not tapped properly! Run: rm -rf "/opt/homebrew/Library/Taps/homebrew/homebrew-core" brew tap homebrew/core Running those 2 commands above solved the problem for me. A: I was also facing the same issue when installing Node via brew. I fixed it by running two commands: $ brew doctor This shows me this warning: Warning: Homebrew/homebrew-core was not tapped properly! Run: rm -rf "/opt/homebrew/Library/Taps/homebrew/homebrew-core" brew tap homebrew/core Then I ran these two commands to fix the warning: $ rm -rf "/opt/homebrew/Library/Taps/homebrew/homebrew-core" $ brew tap homebrew/core And then I tried installing Node: $ brew install node It worked. A: See if the following approach in the following link helps. Depending upon your pip/python/xcode version, brew may not work in installing python or python3. I installed Python3 binary .pkg for Mac from their site, installed it on Mac. Then, opened a new Terminal window and did: which python3 && python3 --version && which pip3 && pip3 --version pip3 install paramiko brew or pip - install credstash - errors - No named formulae found in taps / OSErr six-1.4.1-py2.7.egg-info operation not permitted A: sudo ln -s /usr/lib/dart/bin/pub /usr/bin/pub sudo ln -s /usr/lib/dart/bin/dart2js /usr/bin/dart2js A: git -C $(brew --repo homebrew/core) checkout master this command helps A: Apparently, I also had this issue, I'm a developer. I want to develop an OS with a command known as i686-elf-gcc, but with homebrew it doesn't work. So, use this: brew doctor And a warning will show up: Warning: Homebrew/homebrew-core was not tapped properly! Run: rm -rf "/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core" brew tap homebrew/core So run these: rm -rf "/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core" brew tap homebrew/core After that, I tried installing my package: brew install i686-elf-gcc And, it worked, it should also work for you.
Homebrew Error: No formulae found in taps
I'm trying to install paramiko on my MacBook Pro (OSX Sierra) without going through Xcode because I'm too lazy to install Xcode honestly. When trying to run: brew install paramiko I get: Error: No available formula with the name "paramiko" ==> Searching for similarly named formulae... Error: No similarly named formulae found. ==> Searching taps... Error: No formulae found in taps. I've tried untapping home-brew via: brew untap homebrew And I get: Error: No available tap homebrew/php. Also tried: brew tap --repair brew update Nothing besides: Updated 1 tap (caskroom/cask). No changes to formulae. If I have to go through Xcode, that's fine but I feel the issue here is not the installation process but something weird with the taps...
[ "This worked for me.\nrun brew doctor\n\nWarning: Some taps are not on the default git origin branch and may\nnot receive updates. If this is a surprise to you, check out the\ndefault branch with: git -C $(brew --repo homebrew/core) checkout\nmaster\n\nthen run git -C $(brew --repo homebrew/core)\n", "Run this command:\ngit -C $(brew --repo homebrew/core) checkout master\n\nthis will switch to master, then run\nbrew doctor \n\nthis should run without any error.\nIf there is no error you can install anything with brew install\nex: brew install wget\n", "I ran:\nbrew doctor\n\nwhich gave me as first warning:\n\nWarning: Homebrew/homebrew-core was not tapped properly! Run:\n\n rm -rf \"/opt/homebrew/Library/Taps/homebrew/homebrew-core\"\n brew tap homebrew/core\n\nRunning those 2 commands above solved the problem for me.\n", "I was also facing the same issue when installing Node via brew.\nI fixed it by running two commands:\n$ brew doctor\nThis shows me this warning:\nWarning: Homebrew/homebrew-core was not tapped properly! Run:\n rm -rf \"/opt/homebrew/Library/Taps/homebrew/homebrew-core\"\n brew tap homebrew/core\n\nThen I ran these two commands to fix the warning:\n$ rm -rf \"/opt/homebrew/Library/Taps/homebrew/homebrew-core\"\n$ brew tap homebrew/core\nAnd then I tried installing Node:\n$ brew install node\nIt worked.\n", "See if the following approach in the following link helps.\n\nDepending upon your pip/python/xcode version, brew may not work in installing python or python3.\nI installed Python3 binary .pkg for Mac from their site, installed it on Mac.\nThen, opened a new Terminal window and did:\n\nwhich python3 && python3 --version && which pip3 && pip3 --version\npip3 install paramiko\nbrew or pip - install credstash - errors - No named formulae found in taps / OSErr six-1.4.1-py2.7.egg-info operation not permitted\n", "sudo ln -s /usr/lib/dart/bin/pub /usr/bin/pub\nsudo ln -s /usr/lib/dart/bin/dart2js /usr/bin/dart2js\n\n", "git -C $(brew --repo homebrew/core) checkout master\nthis command helps\n", "Apparently, I also had this issue, I'm a developer.\nI want to develop an OS with a command known as i686-elf-gcc, but with homebrew it doesn't work. So, use this:\nbrew doctor\nAnd a warning will show up:\nWarning: Homebrew/homebrew-core was not tapped properly! Run:\n rm -rf \"/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core\"\n brew tap homebrew/core\n\nSo run these:\nrm -rf \"/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core\"\nbrew tap homebrew/core\nAfter that, I tried installing my package:\nbrew install i686-elf-gcc\nAnd, it worked, it should also work for you.\n" ]
[ 78, 19, 4, 4, 1, 0, 0, 0 ]
[]
[]
[ "homebrew", "macos", "paramiko", "tap", "terminal" ]
stackoverflow_0041113448_homebrew_macos_paramiko_tap_terminal.txt
Q: Data is not stored in database eventhough API successfully passed in postman I am trying to store a historical data through API from front-end(flutter). Below are the controller in laravel. When I ran my code in postman, it supposed to work, since the message "suksess add data" does appear when I sent a request and the date_checkIn, time_checkIn are all recorded as shown here https://paste.pics/f31592f51f63a5f77af77b0c0ad1e555. However, when I check in my database, the date_checkIn, time_checkIn, and location_checkIn column is NULL and only staff_id, created_at, updated_at column is recorded . As I try and repeat the request in postman but change location_checkIn, a new record appear in the attendance_record table showing the same result but now there are 2 of the same staff_id and also created_at and updated_at column is recorded. I want to store the record everytime the user clock in from front-end(flutter). How do I fix this ? public function userClockIn(Request $r) { $result = []; $result['status'] = false; $result['message'] = "something error"; $users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first(); $mytime = Carbon::now(); $time = $mytime->format('H:i:s'); $date = $mytime->format('Y-m-d'); // Retrieve current data $currentData = $users->toArray(); // Store current data in attendance record table $attendanceRecord = new AttendanceRecord(); $attendanceRecord->fill($currentData); $attendanceRecord->save(); $users->date_checkIn = $date; $users->time_checkIn = $time; $users->location_checkIn = $r->location_checkIn; $users->save(); $result['data'] = $users; $result['status'] = true; $result['message'] = "suksess add data"; return response()->json($result); } A: You still need field id when updating the user data. You may change some of your select statement by add 'id' into it : $users = User::where('staff_id', $r->staff_id)->select(['id', 'staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first(); After that, go to your AttendanceRecord model, add field id into guarded. protected $guarded = ['id']; After that, you can try it to run the endpoint again. It should be updated. But if you don't want to add guarded into your AttendanceRecord model, you should change your code when retrieve current data into: $currentData = [ "staff_id" => $users->staff_id, "date_checkIn" => $users->date_checkIn, "time_checkIn" => $users->time_checkIn, "location_checkIn" => $users->location_checkIn, ];
Data is not stored in database eventhough API successfully passed in postman
I am trying to store a historical data through API from front-end(flutter). Below are the controller in laravel. When I ran my code in postman, it supposed to work, since the message "suksess add data" does appear when I sent a request and the date_checkIn, time_checkIn are all recorded as shown here https://paste.pics/f31592f51f63a5f77af77b0c0ad1e555. However, when I check in my database, the date_checkIn, time_checkIn, and location_checkIn column is NULL and only staff_id, created_at, updated_at column is recorded . As I try and repeat the request in postman but change location_checkIn, a new record appear in the attendance_record table showing the same result but now there are 2 of the same staff_id and also created_at and updated_at column is recorded. I want to store the record everytime the user clock in from front-end(flutter). How do I fix this ? public function userClockIn(Request $r) { $result = []; $result['status'] = false; $result['message'] = "something error"; $users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first(); $mytime = Carbon::now(); $time = $mytime->format('H:i:s'); $date = $mytime->format('Y-m-d'); // Retrieve current data $currentData = $users->toArray(); // Store current data in attendance record table $attendanceRecord = new AttendanceRecord(); $attendanceRecord->fill($currentData); $attendanceRecord->save(); $users->date_checkIn = $date; $users->time_checkIn = $time; $users->location_checkIn = $r->location_checkIn; $users->save(); $result['data'] = $users; $result['status'] = true; $result['message'] = "suksess add data"; return response()->json($result); }
[ "You still need field id when updating the user data. You may change some of your select statement by add 'id' into it :\n$users = User::where('staff_id', $r->staff_id)->select(['id', 'staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first();\n\nAfter that, go to your AttendanceRecord model, add field id into guarded.\nprotected $guarded = ['id'];\n\nAfter that, you can try it to run the endpoint again. It should be updated.\nBut if you don't want to add guarded into your AttendanceRecord model, you should change your code when retrieve current data into:\n$currentData = [\n \"staff_id\" => $users->staff_id,\n \"date_checkIn\" => $users->date_checkIn,\n \"time_checkIn\" => $users->time_checkIn,\n \"location_checkIn\" => $users->location_checkIn,\n ];\n\n" ]
[ 0 ]
[]
[]
[ "api", "laravel", "laravel_api", "php" ]
stackoverflow_0074672760_api_laravel_laravel_api_php.txt
Q: verilog adder-subtractor if bug Error: Add_sub.v(32): LHS in procedural continuous assignment may not be a net: co. Error: Add_sub.v(34): LHS in procedural continuous assignment may not be a net: co. I want to write a Verilog file for a full adder-subtractor with a selection en (en == 0 is adder and en == 1 is subtractor). I am struggling on the full-adder module FA, I was trying to write an if statement to realize this. But I encountered the errors above. Below is my code: module Add_sub(x,y,co,u,en); input [3:0]x, y; input en; output [3:0]u; output co; wire [3:0]a; wire [3:1]c; xnor(a[0],x[0],en); xnor(a[1],x[1],en); xnor(a[2],x[2],en); xnor(a[3],x[3],en); reg co; FA M0(y[0],a[0],en,u[0],c[1]); FA M1(y[1],a[1],c[1],u[1],c[2]); FA M2(y[2],a[2],c[2],u[2],c[3]); FA M3(y[3],a[3],c[3],u[3],c[3]); endmodule module FA(x,y,cin,u,co,en); input x, y, cin, en; output u, co; assign u = x ^ y ^ cin; always@(en, x, y, cin) begin if (en == 0) assign co = (x & y) | (x & cin) | (y & cin); if (en == 1) assign co = (!x & y) | (!x & cin) | (y & cin); end endmodule Can someone help me with this? Or please provide me some other method of the full adder-subtractor. A: Don't use assign in an always block, and make a variable assigned in as always block a reg like this to fix the FA module. module FA(x,y,cin,u,co,en); input x, y, cin, en; output reg u, co; assign u = x ^ y ^ cin; always@(en, x, y, cin) begin if (en == 0) co = (x & y) | (x & cin) | (y & cin); if (en == 1) co = (!x & y) | (!x & cin) | (y & cin); end The design has other issues, the FA module has 6 ports, the FA instances have 5 connections. The design uses positional matching for the instance names against the port names and the position is wrong for the first instance. The en signal is in the middle of the list in the instance, and end end of the list for the module. Named association is better than positional for exactly this reason.
verilog adder-subtractor if bug
Error: Add_sub.v(32): LHS in procedural continuous assignment may not be a net: co. Error: Add_sub.v(34): LHS in procedural continuous assignment may not be a net: co. I want to write a Verilog file for a full adder-subtractor with a selection en (en == 0 is adder and en == 1 is subtractor). I am struggling on the full-adder module FA, I was trying to write an if statement to realize this. But I encountered the errors above. Below is my code: module Add_sub(x,y,co,u,en); input [3:0]x, y; input en; output [3:0]u; output co; wire [3:0]a; wire [3:1]c; xnor(a[0],x[0],en); xnor(a[1],x[1],en); xnor(a[2],x[2],en); xnor(a[3],x[3],en); reg co; FA M0(y[0],a[0],en,u[0],c[1]); FA M1(y[1],a[1],c[1],u[1],c[2]); FA M2(y[2],a[2],c[2],u[2],c[3]); FA M3(y[3],a[3],c[3],u[3],c[3]); endmodule module FA(x,y,cin,u,co,en); input x, y, cin, en; output u, co; assign u = x ^ y ^ cin; always@(en, x, y, cin) begin if (en == 0) assign co = (x & y) | (x & cin) | (y & cin); if (en == 1) assign co = (!x & y) | (!x & cin) | (y & cin); end endmodule Can someone help me with this? Or please provide me some other method of the full adder-subtractor.
[ "Don't use assign in an always block, and make a variable assigned in as always block a reg like this to fix the FA module.\nmodule FA(x,y,cin,u,co,en);\n input x, y, cin, en;\n output reg u, co;\n\n assign u = x ^ y ^ cin;\n\nalways@(en, x, y, cin) begin\n if (en == 0)\n co = (x & y) | (x & cin) | (y & cin);\n if (en == 1)\n co = (!x & y) | (!x & cin) | (y & cin);\nend \n\nThe design has other issues, the FA module has 6 ports, the FA instances have 5 connections.\nThe design uses positional matching for the instance names against the port names and the position is wrong for the first instance. The en signal is in the middle of the list in the instance, and end end of the list for the module. Named association is better than positional for exactly this reason.\n" ]
[ 0 ]
[]
[]
[ "debugging", "logic", "modelsim", "quartus", "verilog" ]
stackoverflow_0074672946_debugging_logic_modelsim_quartus_verilog.txt
Q: Create new column base upon existing column in NuShell I am new to NuShell and would like to create a quick way to locate my files by their "tags", which are in the filename. This is the method used by tagspaces. For instance, using the ls command my directory might look like this: # name type size modified 0 Documents dir 134 b a week ago 1 Fake doc1 [Fake clj client project1].txt file 15 B 2 weeks ago 2 Downloaded_doc.pdf file 150 B 4 weeks ago 3 Fake doc2 [Important :12/31/2022 client project1].txt file 365 B 1 week ago However, I would like to create a new column labeled "tags" and only include the tags (the terms inside the brackets) from the name column. I think this regex will take the bracketed information (includes brackets at this point, which I don't want: \[.+?\] I would like the end result to look like this: # name tags type size modified 0 Documents dir 134 b a week ago 1 Fake doc1 [Fake clj client project1].txt Fake clj client project1 file 15 B 2 weeks ago 2 Downloaded_doc.pdf file 150 B 4 weeks ago 3 Fake doc2 [Important :12/31/2022 client project1].txt Important :12/31/2022 client project1 file 365 B 1 week ago What would be the best way of doing this? I have read the docs but need to see more real life code before I really "get" this shell. Thank you! A: $ ls | insert tags {|item| if $item.name =~ '\[.*\]' { $item.name | str replace '.*\[(.*)\].*' '$1' } } | move tags --after name โ•ญโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ # โ”‚ name โ”‚ tags โ”‚ type โ”‚ size โ”‚ modified โ”‚ โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ 0 โ”‚ Documents โ”‚ โ”‚ dir โ”‚ 4.0 KiB โ”‚ 9 minutes ago โ”‚ โ”‚ 1 โ”‚ Downloaded_doc.pdf โ”‚ โ”‚ file โ”‚ 0 B โ”‚ 9 minutes ago โ”‚ โ”‚ 2 โ”‚ Fake doc1 [Fake clj client project1].txt โ”‚ Fake clj client project1 โ”‚ file โ”‚ 0 B โ”‚ 9 minutes ago โ”‚ โ”‚ 3 โ”‚ Fake doc2 [Important :12-31-2022 client project1].txt โ”‚ Important :12-31-2022 client project1 โ”‚ file โ”‚ 0 B โ”‚ 8 minutes ago โ”‚ โ•ฐโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ The insert built-in creates a new column It takes a closure, which runs on each item in the table. The value of $item becomes each directory entry. All we really care about here is the $item.name. First we test it to see if it has tags in the [] format. If it does, we set the tags column value to the text matching inside the []. This might be a bit tricky to parse at first, but keep in mind that the last value (in this case the only value) in the closure or block is essentially its "return value". There's no need to echo or return it, since Nushell has implicit output. For instance, if that line was simply the string "Has tags", then the tags column would include that string (rather than the actual matched tags) for each directory entry that matched the if statement. Finally, after the tags column has been inserted, we move it directly after the name column.
Create new column base upon existing column in NuShell
I am new to NuShell and would like to create a quick way to locate my files by their "tags", which are in the filename. This is the method used by tagspaces. For instance, using the ls command my directory might look like this: # name type size modified 0 Documents dir 134 b a week ago 1 Fake doc1 [Fake clj client project1].txt file 15 B 2 weeks ago 2 Downloaded_doc.pdf file 150 B 4 weeks ago 3 Fake doc2 [Important :12/31/2022 client project1].txt file 365 B 1 week ago However, I would like to create a new column labeled "tags" and only include the tags (the terms inside the brackets) from the name column. I think this regex will take the bracketed information (includes brackets at this point, which I don't want: \[.+?\] I would like the end result to look like this: # name tags type size modified 0 Documents dir 134 b a week ago 1 Fake doc1 [Fake clj client project1].txt Fake clj client project1 file 15 B 2 weeks ago 2 Downloaded_doc.pdf file 150 B 4 weeks ago 3 Fake doc2 [Important :12/31/2022 client project1].txt Important :12/31/2022 client project1 file 365 B 1 week ago What would be the best way of doing this? I have read the docs but need to see more real life code before I really "get" this shell. Thank you!
[ "$ ls | insert tags {|item|\n if $item.name =~ '\\[.*\\]' {\n $item.name | str replace '.*\\[(.*)\\].*' '$1'\n }\n } | move tags --after name\n\nโ•ญโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ\nโ”‚ # โ”‚ name โ”‚ tags โ”‚ type โ”‚ size โ”‚ modified โ”‚\nโ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค\nโ”‚ 0 โ”‚ Documents โ”‚ โ”‚ dir โ”‚ 4.0 KiB โ”‚ 9 minutes ago โ”‚\nโ”‚ 1 โ”‚ Downloaded_doc.pdf โ”‚ โ”‚ file โ”‚ 0 B โ”‚ 9 minutes ago โ”‚\nโ”‚ 2 โ”‚ Fake doc1 [Fake clj client project1].txt โ”‚ Fake clj client project1 โ”‚ file โ”‚ 0 B โ”‚ 9 minutes ago โ”‚\nโ”‚ 3 โ”‚ Fake doc2 [Important :12-31-2022 client project1].txt โ”‚ Important :12-31-2022 client project1 โ”‚ file โ”‚ 0 B โ”‚ 8 minutes ago โ”‚\nโ•ฐโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ\n\n\nThe insert built-in creates a new column\n\nIt takes a closure, which runs on each item in the table. The value of $item becomes each directory entry.\n\nAll we really care about here is the $item.name. First we test it to see if it has tags in the [] format.\n\nIf it does, we set the tags column value to the text matching inside the [].\nThis might be a bit tricky to parse at first, but keep in mind that the last value (in this case the only value) in the closure or block is essentially its \"return value\". There's no need to echo or return it, since Nushell has implicit output.\nFor instance, if that line was simply the string \"Has tags\", then the tags column would include that string (rather than the actual matched tags) for each directory entry that matched the if statement.\n\nFinally, after the tags column has been inserted, we move it directly after the name column.\n\n\n" ]
[ 1 ]
[]
[]
[ "nushell" ]
stackoverflow_0074672107_nushell.txt
Q: CSS Selector for all dd elements under a dt element Problem Is it possible to grab all dd elements under a specific dt element? Specifically, I am trying to capture the dd elements under the dt element titled 'Life Cycle' on this page: https://plants.ces.ncsu.edu/plants/abeliophyllum-distichum/ I want to capture 'Life Cycle' for other plant pages too, where they could have 1 or more dd elements under the dt for 'Life Cycle'. So I need a CSS selector that could work for the scenario of 1 or more dd elements. Here is what the HTML structure looks like: <dl> <span>Attributes:</span> <dt>Life Cycle:</dt> <dd><span>Perennial</span></dd> <dd><span>Woody</span></dd> <dt>Text:</dt> <dd><span>Text</span></dd> <dt>Text:</dt> <dd><span>Text</span></dd> <dt>Text:</dt> <dd><span>Text</span></dd> <dd><span>Text</span></dd> </dl> What I've tried dt:contains('Life Cycle:') + dd This only returns the first dd element dt:contains('Life Cycle:') ~ dd This returns all of the dd elements after the dt even dds under other dts. I wish I could use n-child like dt:contains('Life Cycle:'):nth-child(-n+2), but I can't because dd elements aren't children of dts. What I need I need something that is flexible for the scenario of having 1 or more dd elements under one dt. I am not able to modify the HTML, because I am scraping this data point from the website. This is what I am trying to capture in my CSS selector: A: Looks :contains css selecter only works in Selenium. In that case, you need something similar to :not, you can do the following: dt:contains('Life Cycle:') ~ dd { color: red; } dt:contains('Life Cycle:') ~ dt ~ dd { color: black; }
CSS Selector for all dd elements under a dt element
Problem Is it possible to grab all dd elements under a specific dt element? Specifically, I am trying to capture the dd elements under the dt element titled 'Life Cycle' on this page: https://plants.ces.ncsu.edu/plants/abeliophyllum-distichum/ I want to capture 'Life Cycle' for other plant pages too, where they could have 1 or more dd elements under the dt for 'Life Cycle'. So I need a CSS selector that could work for the scenario of 1 or more dd elements. Here is what the HTML structure looks like: <dl> <span>Attributes:</span> <dt>Life Cycle:</dt> <dd><span>Perennial</span></dd> <dd><span>Woody</span></dd> <dt>Text:</dt> <dd><span>Text</span></dd> <dt>Text:</dt> <dd><span>Text</span></dd> <dt>Text:</dt> <dd><span>Text</span></dd> <dd><span>Text</span></dd> </dl> What I've tried dt:contains('Life Cycle:') + dd This only returns the first dd element dt:contains('Life Cycle:') ~ dd This returns all of the dd elements after the dt even dds under other dts. I wish I could use n-child like dt:contains('Life Cycle:'):nth-child(-n+2), but I can't because dd elements aren't children of dts. What I need I need something that is flexible for the scenario of having 1 or more dd elements under one dt. I am not able to modify the HTML, because I am scraping this data point from the website. This is what I am trying to capture in my CSS selector:
[ "Looks :contains css selecter only works in Selenium. In that case, you need something similar to :not, you can do the following:\ndt:contains('Life Cycle:') ~ dd {\n color: red;\n}\n\ndt:contains('Life Cycle:') ~ dt ~ dd {\n color: black;\n}\n\n" ]
[ 0 ]
[]
[]
[ "css", "html", "screen_scraping", "web_scraping" ]
stackoverflow_0074672570_css_html_screen_scraping_web_scraping.txt
Q: Mat-table multiple row within a multiple row What I want is drawn out in the following image. I use Angular Material (7.x) and use the Mat-Table implementation as described here: https://material.angular.io/components/table/overview The above scenario is for the business to show multiple Sales Invoices. I used Mat Table of Angular already for using multipe rows for one row, and this works. But now I also have to make the first row (Type A) have multiple rows within the multiple row table. I have some ideas on how to be able to get this working, but I don't want to start and know beforehand if the solution is going to work or not. I started iterating over the objects in the salesInvoices: <tr mat-header-row *matHeaderRowDef="displayedPurchaseInvoiceColumns"></tr> <ng-container *ngFor="let item of invoices.salesInvoice"> <tr mat-row class="table-first-row" *matRowDef="let row; columns: displayedSalesInvoiceColumns"></tr> </ng-container> <tr mat-row class="table-second-row" *matRowDef="let row; columns: displayedPurchaseInvoiceColumns"></tr> This doesn't show anything useful. I think it doesn't even do anything as I only see the purchase Invoices displayed, not the sales invoices. I was thinking about using a mat-table for the first row? I have no idea how I am able to do so though, I am also not sure if this will work. I really want to get this working WITH Mat-Table but I am afraid I won't be able to get it working with the library of Material and have to make something custom. Any help is welcome! If I need to provide more information, please tell me. A: You can create a two-level nested Mat-table in Angular in which it can expand multiple rows at a time. On each row click from the parent grid it calls an API and loads the data for the inner grid. Component Code: ngOnInit() { this.tableService.getData().subscribe(res => { if (res.length == 0) { this.panelDataSource = new MatTableDataSource(); } else { console.log(res); this.panelDataSource = new MatTableDataSource(res); } }); } getDetails(element: any) { this.tableService.getInnerData(element.Id).subscribe(res => { if (res.length == 0) { element['innerDatasource'] = new MatTableDataSource(); } else { element['innerDatasource'] = new MatTableDataSource(res); } }); } } HTML Code: <table mat-table [dataSource]="panelDataSource" multiTemplateDataRows matSort> <ng-container [matColumnDef]="column" *ngFor="let column of columnsToDisplay"> <th mat-header-cell *matHeaderCellDef> {{column}} </th> <td mat-cell (click)="getDetails(element)" *matCellDef="let element"> {{element[column]}} </td> </ng-container> <ng-container matColumnDef="expandedDetail"> <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length"> <div class="example-element-detail" [@detailExpand]="element?.expanded" *ngIf="element?.expanded"> <div style="width: 100%;"> <table mat-table [dataSource]="element.innerDatasource" multiTemplateDataRows matSort> <ng-container matColumnDef="{{innerColumn}}" *ngFor="let innerColumn of innerDisplayedColumns"> <th mat-header-cell *matHeaderCellDef mat-sort-header> {{innerColumn}} </th> <td mat-cell *matCellDef="let address"> {{address[innerColumn]}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="innerDisplayedColumns"></tr> <tr mat-row *matRowDef="let address; columns: innerDisplayedColumns;" [class.example-element-row]="address.comments?.length" [class.example-expanded-row]="address?.expanded" (click)="address.expanded = !address?.expanded"> </tr> </table> </div> </div> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr> <tr mat-row *matRowDef="let element; columns: columnsToDisplay;" [class.example-element-row]="element.addresses?.length" [class.example-expanded-row]="element?.expanded" (click)="element.expanded = !element?.expanded"> </tr> <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr> </table> Working Stackblitz A: Use a model like: export class Model{ parent?: Parent; children?: Child[]; } Ts: public displayedColumns = ['parents', 'children']; models: Model[] = []; //Fill your models from DB and then this.dataSource = new MatTableDataSource<any>(this.models); Template: <mat-table #table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="parents"> <mat-header-cell *matHeaderCellDef> Parent</mat-header-cell> <mat-cell *matCellDef="let element"> <ng-container > {{element.parent.name}} <br /> </ng-container> </mat-cell> </ng-container> <ng-container matColumnDef="children"> <mat-header-cell *matHeaderCellDef> Children </mat-header-cell> <mat-cell *matCellDef="let element"> <ng-container *ngFor="let chl of element.children"> {{chl.name}} <br /> </ng-container> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> Stackblitz A: Combine multipleTemplateDataRows with when predicate on MatRowDef. You are looking for multipleTemplateDataRows in combination with a when predicate. The input multipleTemplateDataRows is a boolean set on the MatTable, see the documentation here: https://material.angular.io/components/table/api#MatTable Whether to allow multiple rows per data object by evaluating which rows evaluate their 'when' predicate to true. If multiTemplateDataRows is false, which is the default value, then each dataobject will render the first row that evaluates its when predicate to true, in the order defined in the table, or otherwise the default row which does not have a when predicate. The when predicate on the MatRowDef decides which template should be used for which item. See the documentation here: https://material.angular.io/components/table/api#MatRowDef Function that should return true if this row template should be used for the provided index and row data. If left undefined, this row will be considered the default row template to use when no other when functions return true for the data. For every row, there must be at least one when function that passes or an undefined to default. Note: If the when predicate on several row definitions returns true for the same item, all of those rows will be rendered. If you have multiple row definitions without a when predicate, all of those will render. In other words, you should set the multipleTemplateDataRows to true, define several row definitions and the when predicate of several of those row definitions should return true for the same item (or you don't add a when predicate at all) -> now you rendered multiple rows for your item the "material-table" way... <table mat-table [dataSource]="dataSource" multiTemplateDataRows> <!-- Your column definitions --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Name</th> <td mat-cell *matCellDef="let item">{{item.name}}</td> </ng-container> <!-- Your row definitions --> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;" when="yourFirstPredicate"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;" when="yourSecondPredicate"></tr> <!-- Add as many as you want... --> </table>
Mat-table multiple row within a multiple row
What I want is drawn out in the following image. I use Angular Material (7.x) and use the Mat-Table implementation as described here: https://material.angular.io/components/table/overview The above scenario is for the business to show multiple Sales Invoices. I used Mat Table of Angular already for using multipe rows for one row, and this works. But now I also have to make the first row (Type A) have multiple rows within the multiple row table. I have some ideas on how to be able to get this working, but I don't want to start and know beforehand if the solution is going to work or not. I started iterating over the objects in the salesInvoices: <tr mat-header-row *matHeaderRowDef="displayedPurchaseInvoiceColumns"></tr> <ng-container *ngFor="let item of invoices.salesInvoice"> <tr mat-row class="table-first-row" *matRowDef="let row; columns: displayedSalesInvoiceColumns"></tr> </ng-container> <tr mat-row class="table-second-row" *matRowDef="let row; columns: displayedPurchaseInvoiceColumns"></tr> This doesn't show anything useful. I think it doesn't even do anything as I only see the purchase Invoices displayed, not the sales invoices. I was thinking about using a mat-table for the first row? I have no idea how I am able to do so though, I am also not sure if this will work. I really want to get this working WITH Mat-Table but I am afraid I won't be able to get it working with the library of Material and have to make something custom. Any help is welcome! If I need to provide more information, please tell me.
[ "You can create a two-level nested Mat-table in Angular in which it can expand multiple rows at a time. On each row click from the parent grid it calls an API and loads the data for the inner grid.\nComponent Code:\nngOnInit() {\n this.tableService.getData().subscribe(res => {\n if (res.length == 0) {\n this.panelDataSource = new MatTableDataSource();\n } else {\n console.log(res);\n this.panelDataSource = new MatTableDataSource(res);\n }\n });\n }\n\n getDetails(element: any) {\n \n this.tableService.getInnerData(element.Id).subscribe(res => {\n if (res.length == 0) {\n element['innerDatasource'] = new MatTableDataSource();\n } else {\n \n element['innerDatasource'] = new MatTableDataSource(res);\n }\n });\n }\n}\n\nHTML Code:\n<table mat-table [dataSource]=\"panelDataSource\" multiTemplateDataRows matSort>\n <ng-container [matColumnDef]=\"column\" *ngFor=\"let column of columnsToDisplay\">\n <th mat-header-cell *matHeaderCellDef> {{column}} </th>\n <td mat-cell (click)=\"getDetails(element)\" *matCellDef=\"let element\"> {{element[column]}} </td>\n </ng-container>\n\n <ng-container matColumnDef=\"expandedDetail\">\n <td mat-cell *matCellDef=\"let element\" [attr.colspan]=\"columnsToDisplay.length\">\n <div class=\"example-element-detail\" [@detailExpand]=\"element?.expanded\" *ngIf=\"element?.expanded\">\n <div style=\"width: 100%;\">\n\n <table mat-table [dataSource]=\"element.innerDatasource\" multiTemplateDataRows matSort>\n <ng-container matColumnDef=\"{{innerColumn}}\" *ngFor=\"let innerColumn of innerDisplayedColumns\">\n <th mat-header-cell *matHeaderCellDef mat-sort-header> {{innerColumn}} </th>\n <td mat-cell *matCellDef=\"let address\"> {{address[innerColumn]}} </td>\n </ng-container>\n\n <tr mat-header-row *matHeaderRowDef=\"innerDisplayedColumns\"></tr>\n <tr mat-row *matRowDef=\"let address; columns: innerDisplayedColumns;\"\n [class.example-element-row]=\"address.comments?.length\" [class.example-expanded-row]=\"address?.expanded\"\n (click)=\"address.expanded = !address?.expanded\">\n </tr>\n </table>\n </div>\n </div>\n </td>\n </ng-container>\n\n <tr mat-header-row *matHeaderRowDef=\"columnsToDisplay\"></tr>\n <tr mat-row *matRowDef=\"let element; columns: columnsToDisplay;\"\n [class.example-element-row]=\"element.addresses?.length\" [class.example-expanded-row]=\"element?.expanded\"\n (click)=\"element.expanded = !element?.expanded\">\n </tr>\n <tr mat-row *matRowDef=\"let row; columns: ['expandedDetail']\" class=\"example-detail-row\"></tr>\n</table>\n\nWorking Stackblitz\n", "Use a model like:\nexport class Model{\nparent?: Parent;\nchildren?: Child[];\n}\n\nTs:\npublic displayedColumns = ['parents', 'children'];\n\n\nmodels: Model[] = [];\n//Fill your models from DB and then\nthis.dataSource = new MatTableDataSource<any>(this.models);\n\nTemplate:\n <mat-table #table [dataSource]=\"dataSource\" class=\"mat-elevation-z8\">\n <ng-container matColumnDef=\"parents\">\n <mat-header-cell *matHeaderCellDef> Parent</mat-header-cell>\n <mat-cell *matCellDef=\"let element\">\n <ng-container >\n {{element.parent.name}}\n <br />\n </ng-container>\n </mat-cell>\n </ng-container>\n <ng-container matColumnDef=\"children\">\n <mat-header-cell *matHeaderCellDef> Children </mat-header-cell>\n <mat-cell *matCellDef=\"let element\">\n <ng-container *ngFor=\"let chl of element.children\">\n {{chl.name}}\n <br /> \n </ng-container>\n </mat-cell>\n </ng-container>\n <mat-header-row *matHeaderRowDef=\"displayedColumns\"></mat-header-row>\n <mat-row *matRowDef=\"let row; columns: displayedColumns;\"></mat-row>\n </mat-table>\n\nStackblitz\n", "Combine multipleTemplateDataRows with when predicate on MatRowDef.\nYou are looking for multipleTemplateDataRows in combination with a when predicate.\nThe input multipleTemplateDataRows is a boolean set on the MatTable, see the documentation here: https://material.angular.io/components/table/api#MatTable\n\nWhether to allow multiple rows per data object by evaluating which rows evaluate their 'when' predicate to true. If multiTemplateDataRows is false, which is the default value, then each dataobject will render the first row that evaluates its when predicate to true, in the order defined in the table, or otherwise the default row which does not have a when predicate.\n\nThe when predicate on the MatRowDef decides which template should be used for which item. See the documentation here: https://material.angular.io/components/table/api#MatRowDef\n\nFunction that should return true if this row template should be used for the provided index and row data. If left undefined, this row will be considered the default row template to use when no other when functions return true for the data. For every row, there must be at least one when function that passes or an undefined to default.\n\nNote: If the when predicate on several row definitions returns true for the same item, all of those rows will be rendered. If you have multiple row definitions without a when predicate, all of those will render.\n\nIn other words, you should set the multipleTemplateDataRows to true, define several row definitions and the when predicate of several of those row definitions should return true for the same item (or you don't add a when predicate at all) -> now you rendered multiple rows for your item the \"material-table\" way...\n<table mat-table [dataSource]=\"dataSource\" multiTemplateDataRows>\n \n <!-- Your column definitions -->\n <ng-container matColumnDef=\"name\">\n <th mat-header-cell *matHeaderCellDef>Name</th>\n <td mat-cell *matCellDef=\"let item\">{{item.name}}</td>\n </ng-container> \n\n <!-- Your row definitions -->\n <tr mat-header-row *matHeaderRowDef=\"displayedColumns\"></tr>\n <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\" when=\"yourFirstPredicate\"></tr>\n <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\" when=\"yourSecondPredicate\"></tr>\n\n <!-- Add as many as you want... -->\n\n</table>\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "angular", "mat_table" ]
stackoverflow_0056702574_angular_mat_table.txt
Q: ElectronForge native npm module I've got a project that is using ElectronForge v6.0.3 with TypeScript and WebPack, I'm loading a native npm, module leveldb-zlib I've got it to work when running electron-forge start but when I run electron-forge make it throws the following error I'm importing leveldb-zlib like so import { LevelDB } from "leveldb-zlib"; I'm not importing the module from the renderer. Here are the webpack configs webpack.rules.ts import type { ModuleOptions } from 'webpack'; export const rules: Required<ModuleOptions>['rules'] = [ // Add support for native node modules { // We're specifying native_modules in the test because the asset relocator loader generates a // "fake" .node file which is really a cjs file. test: /native_modules[/\\].+\.node$/, use: 'node-loader', }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@vercel/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', }, }, }, { test: /\.tsx?$/, exclude: /(node_modules|\.webpack)/, use: { loader: 'ts-loader', options: { transpileOnly: true, }, }, }, { test: /\.(woff|woff2|ttf|eot|png|jpg|svg|gif)$/i, use: ['file-loader'] } ]; webpack.main.config.ts import type { Configuration } from 'webpack'; import { rules } from './webpack.rules'; export const mainConfig: Configuration = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/index.ts', // Put your normal webpack config below here module: { rules, }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx', '.css', '.json'], }, externals: { "leveldb-zlib": "leveldb-zlib" } }; !!! EDIT I managed to get it to compile by adding the following hooks to the forge.config.ts, HOWEVER this makes it take forever to compile.. (I did not come up with this solution, I just modified it for typescript) import type { ForgeConfig } from '@electron-forge/shared-types'; import { MakerSquirrel } from '@electron-forge/maker-squirrel'; import { MakerZIP } from '@electron-forge/maker-zip'; import { MakerDeb } from '@electron-forge/maker-deb'; import { MakerRpm } from '@electron-forge/maker-rpm'; import { WebpackPlugin } from '@electron-forge/plugin-webpack'; import { mainConfig } from './webpack.main.config'; import { rendererConfig } from './webpack.renderer.config'; import * as path from "path"; import * as fs from "fs"; import { spawn } from "child_process"; const textDecoder = new TextDecoder(); const config: ForgeConfig = { packagerConfig: {}, rebuildConfig: {}, makers: [new MakerSquirrel({}), new MakerZIP({}, ['darwin']), new MakerRpm({}), new MakerDeb({})], plugins: [ new WebpackPlugin({ mainConfig, renderer: { config: rendererConfig, entryPoints: [ { html: './src/index.html', js: './src/renderer.ts', name: 'main_window', preload: { js: './src/preload.ts', }, }, ], }, }), ], hooks: { readPackageJson: async (_forgeConfig, packageJson) => { // only copy deps if there isn't any if (Object.keys(packageJson.dependencies).length === 0) { const buffer = fs.readFileSync(path.resolve(__dirname, 'package.json')); const originalPackageJson = JSON.parse(textDecoder.decode(buffer)); Object.keys(mainConfig.externals as Record<string, unknown>).forEach(key => { packageJson.dependencies[key] = originalPackageJson.dependencies[key]; }); } return packageJson; }, packageAfterPrune: async (_forgeConfig, buildPath) => { return new Promise((resolve, reject) => { const npmInstall = spawn('npm', ['install'], { cwd: buildPath, stdio: 'inherit', shell: true }); npmInstall.on('close', (code) => { if (code === 0) { resolve(); } else { reject(new Error('process finished with error code ' + code)); } }); npmInstall.on('error', (error) => { reject(error); }); }); } } }; export default config; A: the edit fixed it, also added --production to the npm install command.
ElectronForge native npm module
I've got a project that is using ElectronForge v6.0.3 with TypeScript and WebPack, I'm loading a native npm, module leveldb-zlib I've got it to work when running electron-forge start but when I run electron-forge make it throws the following error I'm importing leveldb-zlib like so import { LevelDB } from "leveldb-zlib"; I'm not importing the module from the renderer. Here are the webpack configs webpack.rules.ts import type { ModuleOptions } from 'webpack'; export const rules: Required<ModuleOptions>['rules'] = [ // Add support for native node modules { // We're specifying native_modules in the test because the asset relocator loader generates a // "fake" .node file which is really a cjs file. test: /native_modules[/\\].+\.node$/, use: 'node-loader', }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@vercel/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', }, }, }, { test: /\.tsx?$/, exclude: /(node_modules|\.webpack)/, use: { loader: 'ts-loader', options: { transpileOnly: true, }, }, }, { test: /\.(woff|woff2|ttf|eot|png|jpg|svg|gif)$/i, use: ['file-loader'] } ]; webpack.main.config.ts import type { Configuration } from 'webpack'; import { rules } from './webpack.rules'; export const mainConfig: Configuration = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/index.ts', // Put your normal webpack config below here module: { rules, }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx', '.css', '.json'], }, externals: { "leveldb-zlib": "leveldb-zlib" } }; !!! EDIT I managed to get it to compile by adding the following hooks to the forge.config.ts, HOWEVER this makes it take forever to compile.. (I did not come up with this solution, I just modified it for typescript) import type { ForgeConfig } from '@electron-forge/shared-types'; import { MakerSquirrel } from '@electron-forge/maker-squirrel'; import { MakerZIP } from '@electron-forge/maker-zip'; import { MakerDeb } from '@electron-forge/maker-deb'; import { MakerRpm } from '@electron-forge/maker-rpm'; import { WebpackPlugin } from '@electron-forge/plugin-webpack'; import { mainConfig } from './webpack.main.config'; import { rendererConfig } from './webpack.renderer.config'; import * as path from "path"; import * as fs from "fs"; import { spawn } from "child_process"; const textDecoder = new TextDecoder(); const config: ForgeConfig = { packagerConfig: {}, rebuildConfig: {}, makers: [new MakerSquirrel({}), new MakerZIP({}, ['darwin']), new MakerRpm({}), new MakerDeb({})], plugins: [ new WebpackPlugin({ mainConfig, renderer: { config: rendererConfig, entryPoints: [ { html: './src/index.html', js: './src/renderer.ts', name: 'main_window', preload: { js: './src/preload.ts', }, }, ], }, }), ], hooks: { readPackageJson: async (_forgeConfig, packageJson) => { // only copy deps if there isn't any if (Object.keys(packageJson.dependencies).length === 0) { const buffer = fs.readFileSync(path.resolve(__dirname, 'package.json')); const originalPackageJson = JSON.parse(textDecoder.decode(buffer)); Object.keys(mainConfig.externals as Record<string, unknown>).forEach(key => { packageJson.dependencies[key] = originalPackageJson.dependencies[key]; }); } return packageJson; }, packageAfterPrune: async (_forgeConfig, buildPath) => { return new Promise((resolve, reject) => { const npmInstall = spawn('npm', ['install'], { cwd: buildPath, stdio: 'inherit', shell: true }); npmInstall.on('close', (code) => { if (code === 0) { resolve(); } else { reject(new Error('process finished with error code ' + code)); } }); npmInstall.on('error', (error) => { reject(error); }); }); } } }; export default config;
[ "the edit fixed it, also added --production to the npm install command.\n" ]
[ 0 ]
[]
[]
[ "electron", "electron_forge", "native_module", "typescript", "webpack" ]
stackoverflow_0074610997_electron_electron_forge_native_module_typescript_webpack.txt
Q: How can I use a new created column in GROUP BY In my SQL query, I want to check if a column has the string 'test' and safe the value in a new column When I use the new column in GROUP BY, I get error saying it can't find the new column: SELECT CAST([EvtTime] as date) AS myDay, CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult, COUNT_BIG(*) AS myCount, [name] FROM [mytable] GROUP BY myDay, testResult I am using SQL Server. A: CROSS APPLY is a clean way to solve this issue. SELECT CAST([EvtTime] as date) AS myDay, X.testResult, COUNT_BIG(*) AS myCount, [name] FROM myTable CROSS APPLY (VALUES (CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END)) AS X(testResult) GROUP BY myDay, testResult A: You can use inline view: SELECT *, COUNT_BIG(*) AS myCount FROM ( SELECT CAST([EvtTime] as date) AS myDay, CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult, [name] FROM [MyTable] ) MyInlineView GROUP BY myDay, testResult
How can I use a new created column in GROUP BY
In my SQL query, I want to check if a column has the string 'test' and safe the value in a new column When I use the new column in GROUP BY, I get error saying it can't find the new column: SELECT CAST([EvtTime] as date) AS myDay, CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult, COUNT_BIG(*) AS myCount, [name] FROM [mytable] GROUP BY myDay, testResult I am using SQL Server.
[ "CROSS APPLY is a clean way to solve this issue.\nSELECT\n CAST([EvtTime] as date) AS myDay,\n X.testResult,\n COUNT_BIG(*) AS myCount,\n [name]\nFROM myTable\nCROSS APPLY (VALUES (CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END)) AS X(testResult)\nGROUP BY myDay, testResult\n\n", "You can use inline view:\nSELECT *,\n COUNT_BIG(*) AS myCount\nFROM (\n SELECT\n CAST([EvtTime] as date) AS myDay,\n CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult,\n [name]\n FROM [MyTable]\n) MyInlineView\nGROUP BY myDay, testResult\n\n" ]
[ 4, 0 ]
[]
[]
[ "sql", "sql_server" ]
stackoverflow_0074673241_sql_sql_server.txt