text
stringlengths
15
59.8k
meta
dict
Q: Converting data to panel format using forloops vba-excel My data set looks like: AUS, UK, USA, GERMANY, FRANCE, MEXICO, DATE R1, R1, R1, R1 , R1 , R1 , 1 R2, R2, R2, R2 , R2 , R2 , 2 ... And so on. I want to convert it so that it looks like COUNTRY, RETURNS, DATE, AUS, R1, 1 AUS, R2, 2 ..., ..., ..., UK, R1, 1, UK, R2, 2, ... ... ..., MEXICO, R1, 1, MEXICO, R2, 2, ... ... ... I feel like this should be possible with a simple nested forloop. I tried: sub panel() 'dim variables Dim i As Integer Dim j As Integer Dim reps As Integer Dim country As String Dim strfind As String Dim obs As Integer 'count the number of countries reps = Range("D1:AL1").Columns.Count 'count the number of observations per country obs = Range("C4:C5493").Rows.Count 'copy and paste country into panel format For i = 1 To reps 'set country name country =Range("D1").Cells(1, i) For j = 1 To obs 'copy and paste country values Range("AS2").Cells(j, 1) = country Next j Next i but after the j loops finishes, and the new country name is set, the new values replace the old values in the first batch of cells. A: Consider an SQL solution using UNION queries to select each column for long format. If using Excel for PC, Excel can connect to the Jet/ACE SQL Engine (Windows .dll files) via ADO and run SQL queries on worksheets of current workbook. With this approach, you avoid any for looping, nested if/then logic, and other data manipulation needs for desired output. Below example assumes data resides in tab called DATA and an empty tab called RESULTS. Sub RunSQL() Dim conn As Object, rst As Object Dim strConnection As String, strSQL As String Dim i As Integer Set conn = CreateObject("ADODB.Connection") Set rst = CreateObject("ADODB.Recordset") ' CONNECTION STRINGS (TWO VERSIONS) ' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _ ' & "DBQ=C:\Path\To\Workbook.xlsm;" strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _ & "Data Source='C:\Path\To\Workbook.xlsm';" _ & "Extended Properties=""Excel 8.0;HDR=YES;"";" strSQL = " SELECT 'AUS' AS COUNTRY, AUS AS RETURNS, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'UK', UK AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'USA', USA AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'GERMANY', GERMANY AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'FRANCE', FRANCE AS Country, [DATE] FROM [DATA$]" _ & " UNION ALL SELECT 'MEXICO', MEXICO AS Country, [DATE] FROM [DATA$];" ' OPEN CONNECTION & RECORDSET conn.Open strConnection rst.Open strSQL, conn ' COLUMN HEADERS For i = 1 To rst.Fields.Count Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name Next i ' DATA ROWS Worksheets("RESULTS").Range("A2").CopyFromRecordset rst rst.Close: conn.Close Set rst = Nothing: Set conn = Nothing End Sub Output COUNTRY RETURNS DATE AUS R1 1 AUS R2 2 UK R1 1 UK R2 2 USA R1 1 USA R2 2 GERMANY R1 1 GERMANY R2 2 FRANCE R1 1 FRANCE R2 2 MEXICO R1 1 MEXICO R2 2 A: Okay, I fixed it. Probably not the best code, but it works :). Sub replicate_dates() 'declare variables Dim i As Double Dim j As Double Dim reps As Integer Dim country As String Dim strfind As String Dim obs As Integer 'set strfind value strfind = "-DS Market" 'count the number of countries reps = Range("D1:AL1").Columns.Count 'count the number of observations per country obs = Range("C4:C5493").Rows.Count i = 0 'copy and paste country into panel format For k = 1 To reps 'set country name and clean string country = Replace(Range("D1").Cells(1, k), strfind, "") For j = i + 1 To obs + i 'copy and paste country values Range("AS5").Cells(i, 1) = country i = 1 + i Next j Next k End Sub Edit: Nvm, this fails to work outside a very specific case.
{ "language": "en", "url": "https://stackoverflow.com/questions/37478043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass parameter to calling form? Here is the code with Form with Singleton pattern. private Form1(int number = -1) { test_number = number; InitializeComponent(); } private static Form1 _Instance; public static Form1 Instance { get { if (_Instance == null) _Instance = new Form1(); return _Instance; } } I set int number = -1 in constructor because without it it doens't work here : if (_Instance == null) _Instance = new Form1(); But when I want to call this form in other form: Form1 f = new Form1(n); But here's the error: Error 2 'KR.Form1' does not contain a constructor that takes 1 arguments How to pass parameter with Singleton pattern? A: It seems you want your Singleton to store a variable. Make a function that sets the variable and leave the constructor empty. A: Don't use a default value in the constructor. For your singleton, just pass the default value of zero if you don't want to use it. Or, define two constructors, one without your argument, and one with it. Also, if you want to use the constructor from another Form (or any other class), it cannot be defined as private. Define it as public instead. public Form1(int number) : this() //call the default constructor so that InitializeComponents() is still called { test_number = number; } public Form1() { InitializeComponent(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/23684496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to modify Webform field type in Drupal 7 We are working on Drupal 7 and we need to modify the "webform field type" of an existing webform. But we are unable to do that. We have also tried by deleting the existing field "form key" and tried creating a new field with the same "form key" but the data of the existing column gets deleted. A: @Ravi, you can use the following module to migrate data from the old field to the new field, you just need to map the fields. The module contains an example: https://www.drupal.org/project/migrate_d2d If the previous option is too complicated, you can do the following trick: export the old field table as INSERT format from the database, the table name will looks like this: field_data_field_name Then, just replace the name table from the old field to the new field table. Finally, just execute those insert into your database. This is an example, how an insert statement looks from a drupal field INSERT INTO field_data_field_name(entity_type,bundle,deleted,entity_id,revision_id,`language`,delta,field_address_type_value,field_address_type_format) VALUES ('entityform','solicitud_facturacion',0,656,656,'und',0,'AVENIDA',NULL); I hope you understand this!
{ "language": "en", "url": "https://stackoverflow.com/questions/51177228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issues Overloading CTOR's in Scala Im having an issue over loading the constructors in Scala. Each time I try to pass a value for the over loaded CTOR I get the error Example: var client : Client = Client(*variable type List[String]()*); Unspecified value parameter clientList. My goal is to have an object created using 2 different data types. One a NodeSeq and the Other a List. Never Both. Am I over loading the CTOR correctly or is there a more efficient way to achieve my goal? package api import xml._ case class Client(clientNode: NodeSeq, clientList: List[String]) { def this(clientNode: NodeSeq) = this(clientNode, null) def this(clientList: List[String]) = this(null, clientList) var firstName: String var lastName: String var phone: String var street: String var city: String var state: String var zip: String var products = List[String]() var serviceOrders = List[String]() if (clientList == null) { firstName = (clientNode \\ "firstname").text lastName = (clientNode \\ "lastname").text phone = (clientNode \\ "phone").text street = (clientNode \\ "street").text city = (clientNode \\ "city").text state = (clientNode \\ "state").text zip = (clientNode \\ "zip").text (clientNode \\ "products").foreach(i => products = i.text :: products) (clientNode \\ "serviceOrders").foreach(i => serviceOrders = i.text :: serviceOrders) } else { firstName = clientList(0) lastName = clientList(1) phone = clientList(2) street = clientList(3) city = clientList(4) state = clientList(5) zip = clientList(6) } override def toString(): String = { return "Name : " + firstName + " " + lastName + "\nAddress : " + "\n\t" + street + "\n\t" + city + ", " + state + " " + zip } } A: You didn't post working code; you can't have undefined vars. Anyway, the problem is that even though you have overridden the constructors, you have not overridden the builders in the companion object. Add this and it will work the way you want: object Client { def apply(clientNode: NodeSeq) = new Client(clientNode) def apply(clientList: List[String]) = new Client(clientList) } (if you're using the REPL, be sure to use :paste to enter this along with the case class so you add to the default companion object instead of replacing it). But a deeper problem is that this is not the way you should be solving the problem. You should define a trait that contains the data you want: trait ClientData { def firstName: String def lastName: String /* ... */ } and inherit from it twice, once for each way to parse it: class ClientFromList(cl: List[String]) extends ClientData { val firstName = cl.head . . . } or you could turn the NodeSeq into a list and parse it there, or various other things. This way you avoid exposing a bunch of vars which are probably not meant to be changed later. A: Auxiliary constructors are for simple one-liners and aren't suitable in this case. More idiomatic way would be to define factory methods in a companion object: case class Client(firstName: String, lastName: String, products: List[String] = Nil) object Client { import scala.xml.NodeSeq def fromList(list: List[String]): Option[Client] = list match { case List(firstName, lastName) => Some(Client(firstName, lastName)) case _ => None } def fromXml(nodeSeq: NodeSeq): Option[Client] = { def option(label: String) = (nodeSeq \\ label).headOption.map(_.text) def listOption(label: String) = (nodeSeq \\ label).headOption.map { _.map(_.text).toList } for { firstName <- option("firstname") lastName <- option("lastname") products <- listOption("products") } yield Client(firstName, lastName, products) } } I also took the liberty of improving your code by eliminating mutability and making it generally more runtime safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/9999911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want an extensive table (left->right) but with the first column fixed I am creating a "gant chart" style table, so it means that it has to have the first column fixed, and it can be a very long table , from left to right. I have tried to : 1. use simple HTML; 2. use DIVs and CSS; 3. use TH and CSS; no good results so far The div was the closest one, but the first column is overflown and the table is not aligned anymore. <table > <tr> <th > &nbsp;</th> <td colspan='14'>2019</td> </tr> <tr><th>&nbsp </th> <td colspan='14'>9</td> </tr> <tr><th> Department - Team</th> <td style='width:30px;'>4</td> <td style='width:30px;'>5</td> <td style='width:30px;'>6</td> <td style='width:30px;'>7</td> <td style='width:30px;'>8</td> <td style='width:30px;'>9</td> <td style='width:30px;'>10</td> <td style='width:30px;'>11</td> <td style='width:30px;'>12</td> <td style='width:30px;'>13</td> <td style='width:30px;'>14</td> <td style='width:30px;'>15</td> <td style='width:30px;'>16</td> <td style='width:30px;'>17</td></tr> <tr> <th >Corporate Development - Fundraisin </th> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td> <td style='width:30px;background-color:#FFAAAA;'>7.67</td></tr> <tr> <th >Corporate Development - Marketing </th> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td> <td style='width:30px;background-color:#AAAAFF;'>1.25</td></tr> <tr> <th >FAS - Team A </th> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAAAA;'>10.00</td> <td style='width:30px;background-color:#FFAA14;'>5.00</td> <td style='width:30px;background-color:#FFAA14;'>5.00</td> <td style='width:30px;background-color:#FFAA14;'>5.00</td></tr> <tr> <th >BF Server - Server . </th> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#FFAA14;'>4.75</td> <td style='width:30px;background-color:#AAAAFF;'>1.75</td> <td style='width:30px;background-color:#AAAAFF;'>1.75</td> <td style='width:30px;background-color:#AAAAFF;'>1.75</td> </tr> I expect to see a simple table, but I cannot fit these three outcomes at once: * very long from left to right; * the first column is always visible; * no text overflow (in case of using divs) A: Some kind of solution, but I am disappointed to not be able to make the header selectable. The core of my proposal is using a non visible copy of your headlines to make room for the fixed header and then use z-index property to hide the non usable horizontal scrollbar of the .header-container. .chart { position: relative; /* simulate horizontal scrolling, to remove */ width: 700px; } .chart-wrapper { display: flex; overflow-x: scroll; } .header-container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; overflow-x: scroll; z-index: -1; } .data-container { display: flex; pointer-events: none; } .header, .header-spacing { flex-shrink: 0; display: flex; flex-direction: column; font-weight: bold; text-align: center; } .header { position: absolute; top: 0; bottom: 0; z-index: 1; background: white; } .header-spacing { visibility: hidden; } .data { z-index: -2; } .row { display: flex; width: 100% } .row > div, .header > div { flex-grow: 1; min-width: 50px; margin: 1px; } <div class="chart"> <div class="chart-wrapper"> <div class="header-container"> <div class="header"> <div> Department - Team</div> <div>Corporate Development - Fundraisin </div> <div>Corporate Development - Marketing </div> <div>FAS - Team A </div> <div>BF Server - Server . </div> </div> </div> <div class="data-container"> <div class="header-spacing"> <div> Department - Team</div> <div>Corporate Development - Fundraisin </div> <div>Corporate Development - Marketing </div> <div>FAS - Team A </div> <div>BF Server - Server . </div> </div> <div class="data"> <div class="row"> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>16</div> <div>17</div> </div> <div class="row"> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> <div style="background-color:#FFAAAA;">7.67</div> </div> <div class="row"> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> <div style="background-color:#AAAAFF;">1.25</div> </div> <div class="row"> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAAAA;">10.00</div> <div style="background-color:#FFAA14;">5.00</div> <div style="background-color:#FFAA14;">5.00</div> <div style="background-color:#FFAA14;">5.00</div> </div> <div class="row"> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#FFAA14;">4.75</div> <div style="background-color:#AAAAFF;">1.75</div> <div style="background-color:#AAAAFF;">1.75</div> <div style="background-color:#AAAAFF;">1.75</div> </div> </div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/58247898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: snimpy.snmp.SNMPNoSuchObject: No such object was found I'm having an exception raised, but I don't get why snimpy.snmp.SNMPNoSuchObject: No such object was found Code from snimpy import manager as snimpy def snmp(hostname, oids, mibs): logger.debug(hostname) logger.debug(oids) logger.debug(mibs) for mib in mibs: snimpy.load(mib) session = snimpy.snmp.Session(hostname, "public", 1) details = session.get(*oids) return [{ 'oid': '.' + '.'.join(repr(node) for node in oid[0]), 'value': oid[1] } for oid in details] oids = ['.1.3.6.1.2.1.25.3.2.1.3.1', '.1.3.6.1.2.1.43.10.2.1.4.1.1.1.3.6.1.2.1.1.4.0', '.1.3.6.1.2.1.1.1.0', '.1.3.6.1.2.1.1.5.0', '.1.3.6.1.2.1.1.3.0'] hostname = '192.168.2.250' mibs = ['DISMAN-EVENT-MIB', 'HOST-RESOURCES-MIB', 'SNMPv2-MIB', 'SNMPv2-SMI'] snmp(hostname, oids, mibs) Error >>> scanner.get_device_infos('192.168.2.250') Traceback (most recent call last): File "<input>", line 1, in <module> File "~/project/daemon/api/scanner.py", line 62, in get_device_infos infos = self.network_tools.snmp(hostname, oids, mibs) File "~/project/daemon/api/network_tools.py", line 26, in snmp logger.debug(type(oids)) File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 286, in get return self._op(self._cmdgen.getCmd, *oids) File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 278, in _op return tuple([(oid, self._convert(val)) for oid, val in results]) File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 278, in <listcomp> return tuple([(oid, self._convert(val)) for oid, val in results]) File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 249, in _convert self._check_exception(value) File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 217, in _check_exception raise SNMPNoSuchObject("No such object was found") # nopep8 snimpy.snmp.SNMPNoSuchObject: No such object was found Doing it in bash works Reaching the equipment using bash and snmpget command works fine: declare -a oids=( '.1.3.6.1.2.1.25.3.2.1.3.1' # HOST-RESOURCES-MIB::hrDeviceDescr.1 '.1.3.6.1.2.1.43.10.2.1.4.1.1' # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count '.1.3.6.1.2.1.1.4.0' # SNMPv2-MIB::sysContact.0 '.1.3.6.1.2.1.1.1.0' # SNMPv2-MIB::sysDescr.0 '.1.3.6.1.2.1.1.5.0' # SNMPv2-MIB::sysName.0 '.1.3.6.1.2.1.1.3.0' # DISMAN-EVENT-MIB::sysUpTimeInstance ) for oid in ${oids[@]}; do echo "$oid" snmpget -v 1 -t .3 -r 2 -c public 192.168.2.250 -m +SNMPv2-MIB "$oid" echo done output: .1.3.6.1.2.1.25.3.2.1.3.1 HOST-RESOURCES-MIB::hrDeviceDescr.1 = STRING: Brother HL-5250DN series .1.3.6.1.2.1.43.10.2.1.4.1.1 SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 = Counter32: 22629 .1.3.6.1.2.1.1.4.0 SNMPv2-MIB::sysContact.0 = STRING: .1.3.6.1.2.1.1.1.0 SNMPv2-MIB::sysDescr.0 = STRING: Brother NC-6400h, Firmware Ver.1.01 (05.08.31),MID 84UZ92 .1.3.6.1.2.1.1.5.0 SNMPv2-MIB::sysName.0 = STRING: BRN_7D3B43 .1.3.6.1.2.1.1.3.0 DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (168019770) 19 days, 10:43:17.70 Question What's the matter here? A: One of the oid seem to trigger the error (cf. '.1.3.6.1.2.1.43.10.2.1.4.1.1' # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count), moving it to last fix the error. But this is a dubious solution. oids = [ '.1.3.6.1.2.1.25.3.2.1.3.1', # HOST-RESOURCES-MIB::hrDeviceDescr.1 '.1.3.6.1.2.1.1.4.0', # SNMPv2-MIB::sysContact.0 '.1.3.6.1.2.1.1.1.0', # SNMPv2-MIB::sysDescr.0 '.1.3.6.1.2.1.1.5.0', # SNMPv2-MIB::sysName.0 '.1.3.6.1.2.1.1.3.0', # DISMAN-EVENT-MIB::sysUpTimeInstance # ugly duckling '.1.3.6.1.2.1.43.10.2.1.4.1.1' # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count ]
{ "language": "en", "url": "https://stackoverflow.com/questions/39831446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force docker compose to pull latest image for a container I've a system running on docker, my system has an specific test environment which might need to update the image version several times on a day... So every time a new version need to be placed, i need to open the compose.yml file, look the container and edit the image version, then re-run docker compose up -d So to skip this boring process of edit the compose.yml file, I had one idea: in the pipeline which builds and publishes the docker image, i create a new tag $image_name:latest-test and a new step which publishes the image to this tag so on any image update in my pipeline two tags are created, one with the version number and other with the latest-test... both are published to dockerhub and this process works like a charm but even when a new image is published to dockerhub and i run docker compose up -d no matter if the container is running or not, docker doesn't check if the image we have cached is really the one on dockerhub... it assumes the cache is the latest one and dont update THE QUESTION IS: 1 - is there any way to force docker to check if the cached image has been updated on dockerhub? 2 - is there any other workaround i can do to keep a specific tag on my compose.yml file and update the image when needed without needing to edit the file 1000 times a day? thanks A: is there any way to force docker to check if the cached image has been updated on dockerhub? No. is there any other workaround i can do to keep a specific tag on my compose.yml file and update the image when needed without needing to edit the file 1000 times a day? Just use latest and use docker-compose pull to pull the images.
{ "language": "en", "url": "https://stackoverflow.com/questions/73429215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any way to save variable and its values during debugging in intellij? I am struggling with an error. I cannot find it. Is there a way to compare the debugging results before and after a change in intellij. Other solutions will be also welcomed. I am explaining my scenario here. I am debugging a class and at a break point, there are three variables. I named it variableA, variableB and variableC. For example, the debugger stops when the variableA gets its values. At that time, I would like to save the content of variableA. In this way, I can compare the content of variableA before and after the change. A: I think the only thing, you can do in your case, open all the values of a variable and select all and copy-paste like the Mark pointed out in his comment. A: Would a print statement work? you could use a global counter to keep track of which pass you are at and then compare the values in the consoles.
{ "language": "en", "url": "https://stackoverflow.com/questions/35272024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: C | Pointer | Segmentation fault I have this code: My problem is that, whenever I call this function ma_init(); I get a segmentation fault on footer->status = FREE; I would appreciate it if somebody points me into the right direction here cause after some googling for some hours, I can't seem to figure this out. Edit: header file: A: typedef unsigned char byte; This is unreadable. Consider including <stdint.h> and using uint8_t. My problem is that, whenever I call this function ma_init(); I get a segmentation fault on footer->status = FREE; Please learn to compile with all warnings & debug info (e.g. gcc -Wall -Wextra -g with GCC...) then use the debugger (gdb) ... You are initializing header to the address of mem_pool. Then you do some questionable (that is wrong) pointer arithmetic mem_chunk_header * footer = header + header->size + sizeof(mem_chunk_header); // the + above are likely to be wrong You are adding to a pointer header so the + is in terms of pointed element size (not bytes), that is in units of sizeof(mem_chunk_header) which certainly is at least 2 and probably more (on my Linux/x86-64 desktop it is 8). Your footer is far away. With a debugger, you would have noticed that (by querying the values of header, footer, mem_pool). Consider also using valgrind BTW, if you are coding a memory allocator à la malloc you'll better base it on operating system specific primitives (generally system calls) modifying your virtual address space. On Linux you would use mmap(2) and friends. points me into the right direction here cause after some googling for some hours You need to spend weeks reading some good C programming book. Hours of work are not enough in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/45151144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Firebase Realtime Database data is loaded too late I get my data in the table on Firebase Realtime Database. However, when there is a lot of data, it takes minutes to load. Like 5-6 minutes for 500 data. How can I solve this? Thanks, best regards. private void initCustomAdapter() { mPeriodsReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { mPeriodsReference.keepSynced(true); OnlinePeriod period = dataSnapshot.getValue(OnlinePeriod.class); dataList.add(period); pageNum = 1; Collections.reverse(dataList); resfreshListView(); Log.d("TAG","list coming" + dataList); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { throw error.toException(); } }); mPeriodsRecycler.setLayoutManager(new GridLayoutManager(mContext, 1));// mPeriodsRecycler.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDPToPixel(mContext, 3))); mTrackAdapter = new TrackListAdapter(mContext, filterDataList);//new ArrayList<CategoryModel>() mPeriodsRecycler.setAdapter(mTrackAdapter); } A: From what I can deduce by looking at the code given, first you are loading the data into the list dataList and then you are reversing the entire list using Collections.reverse(dataList); which is an expensive operation. So, a way around is make your own reversing function to reverse the arraylist because the default .reverse() provided by the Collections class is not very efficient. You can try the below code to reverse the list in-place (same ArrayList is used ,hence making it efficient): public ArrayList<Integer> revArrayList(ArrayList<Integer> list) { for (int i = 0; i < list.size() / 2; i++) { Integer temp = list.get(i); list.set(i, list.get(list.size() - i - 1)); list.set(list.size() - i - 1, temp); } return list; }
{ "language": "en", "url": "https://stackoverflow.com/questions/66187572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you permanently add to an array in Javascript? Forgive me, I'm very new to programming in general, especially Javascript. I've basically got an array as shown simplified below. var recipes = [ { "recipeName":"Recipe1" , "ingredient1":"Recipe1Ingredient1" , "ingredient2":"Recipe1Ingredient2" , "ingredient3":"Recipe1Ingredient3"}, { "recipeName":"Recipe2" , "ingredient1":"Recipe2Ingredient1" , "ingredient2":"Recipe2Ingredient2" , "ingredient3":"Recipe2Ingredient3"}, ]; On one page, users can search for recipes. On another, they can add recipes to the array via an HTML form. I have the following which pushes the new data to the array. recipes.push({"recipeName":newRecipeName , "ingredient1":newIngredient1 , "ingredient2":newIngredient2 , "ingredient3":newIngredient3}); This works fine initially, but if I refresh the page or go back to the find page, the new recipe is removed from the array. I want the new recipe to be added permanently to the array. I'm guessing the solution for this isn't so simple, but I've been looking into this for a while and done a lot of searching to no avail. Can anybody point me in the right direction? Again apologies for my inexperience, I'm very new to programming. A: The main thing you need to keep in mind here is that each time the page is refreshed it has no knowledge of the data that was on the previous page. As was mentioned in a previous comment, persistent storage is what you're looking for. This might come in the form of a full-on (NoSQL/RDBMS) database or in some other semi-permanent form stored only within the browser. You can either start using a full-on database or if you want something more light weight, you can use local storage or cookies. One thing to note is that, unless you implement something server side, eg: a database, the changes will be persistent only to the user and only so long as they don't clear the cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/21144565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Importing multiple files named sequentially in Python I have about 50 Python files in a directory, all named in a sequential order, for example: myfile1, myfile2.....myfile50. Now, I want to import the contents of these files inside another Python file. This is what I tried: i = 0 while i < 51: file_name = 'myfile' + i import file_name i += 1 However, I get the following error: ImportError: No module named file_name How may I import all these sequentially named files inside another Python file, without having to write import for each file individually? A: You can't use import to import modules from a string containing their name. You could, however, use importlib: import importlib i = 0 while i < 51: file_name = 'myfile' + str(i) importlib.import_module(file_name) i += 1 Also, note that the "pythonic" way of iterating a set number of times would be to use a for loop: for i in range(0, 51): file_name = 'myfile' + str(i) importlib.import_module(file_name) A: The other answer by @Mureinik is good, but simply doing - importlib.import_module(file_name) is not enough. As given in the documentation of importlib - importlib.import_module(name, package=None) Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). The specified module will be inserted into sys.modules and returned. importlib.import_module simply returns the module object, it does not insert it into the globals namespace, so even if you import the module this way, you cannot later on use that module directly as filename1.<something> (or so). Example - >>> import importlib >>> importlib.import_module('a') <module 'a' from '/path/to/a.py'> >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined To be able to use it by specifying the name, you would need to add the returned module into the globals() dictionary (which is the dictionary for the global namespace). Example - gbl = globals() for i in range(0, 51): file_name = 'myfile{}'.format(i) try: gbl[file_name] = importlib.import_module(file_name) except ImportError: pass #Or handle the error when `file_name` module does not exist. It might be also be better to except ImportError incase file_name modules don't exist, you can handle them anyway you want. A: @Murenik and @Anand S Kumar already gave a right answers, but I just want to help a little bit too :) If you want to import all files from some folder, it's better to use glob function instead hardcoded for cycle. It's pythonic way to iterate across files. # It's code from Anand S Kumar's solution gbl = globals() def force_import(module_name): try: gbl[module_name] = importlib.import_module(module_name) except ImportError: pass #Or handle the error when `module_name` module does not exist. # Pythonic way to iterate files import glob for module_name in glob.glob("myfile*"): force_import( module_name.replace(".py", "") )
{ "language": "en", "url": "https://stackoverflow.com/questions/33062168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get log by using logog in DLL API's in C++ How to write log inside DLL API? In my program I am using two threads with one main thread. I am initializing: LOGOG_INITIALIZE(); logog::LogFile errFile("log.txt"); Into my main thread and using INFO, ERR in main thread other two threads. My main thread is using C++ DLL API's. I am perfectly getting log from main thread and two other running thread but my problem is I am not able to get log from DLL API's flow. How to get log by using logog in DLL API's. I would like to clear here if I am using INFO in DLL API. it is crashing but if I do LOGOG_INITIALIZE(); inside DLL API, INFO executes but does not log anything. A: If i get it correct, your situation is as follows: You have, for example, one application (EXE) which uses a shared library (DLL). From both, the EXE and the DLL, you want to be able to log. Last time i checked out the logog library i run in problems with the situation described above. Maybe now it is corrected? Under windows (only!), the logog library doesn't export any symbols - it is simply not ready to be used as DLL. This forces you to build and use logog as static library - which leads to problems with static variables inside the logog library which should exist only once, but in reality are existing as many times as the static library was linked to a module (EXE or DLL). The solution would be to build and use the logog library as DLL. Maybe this covers your problem and you may take the effort to export the symbols of the logog library. Or you could get in contact with the library writer.
{ "language": "en", "url": "https://stackoverflow.com/questions/12275437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: knitr hook to separate 000's, but not for years I define a hook at the top of my rnw to separate '000s with commas: knit_hooks$set(inline = function(x) { prettyNum(x, big.mark=",") }) However, there are some numbers that I don't want to format like this, such as years. Is there a better way to write the hook, or a way to override the hook when I print \Sexpr{nocomma} in the example below? \documentclass{article} \begin{document} <<setup>>= library(knitr) options(scipen=999) # turn off scientific notation for numbers opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) knit_hooks$set(inline = function(x) { prettyNum(x, big.mark=",") }) wantcomma <- 1234*5 nocomma <- "September 1, 2014" @ The hook will separate \Sexpr{wantcomma} and \Sexpr{nocomma}, but I don't want to separate years. \end{document} Output: The hook will separate 6,170 and September 1, 2,014, but I don’t want to separate years. A: If the only things your don't want comma-separated are strings that have years in, use: knit_hooks$set(inline = function(x) { if(is.numeric(x)){ return(prettyNum(x, big.mark=",")) }else{ return(x) } }) That works for your calendar string. But suppose you want to just print a year number on its own? Well, how about using the above hook and converting to character: What about \Sexpr{2014}? % gets commad What about \Sexpr{as.character(2014)}? % not commad or possibly (untested): What about \Sexpr{paste(2014)}? % not commad which converts the scalar to character and saves a bit of typing. We're not playing code golf here though... Alternatively a class-based method: comma <- function(x){structure(x,class="comma")} nocomma <- function(x){structure(x,class="nocomma")} options(scipen=999) # turn off scientific notation for numbers opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) knit_hooks$set(inline = function(x) { if(inherits(x,"comma")) return(prettyNum(x, big.mark=",")) if(inherits(x,"nocomma")) return(x) return(x) # default }) wantcomma <- 1234*5 nocomma1 <- "September 1, 2014" # note name change here to not clash with function Then just wrap your Sexpr in either comma or nocomma like: The hook will separate \Sexpr{comma(wantcomma)} and \Sexpr{nocomma(nocomma1)}, but I don't want to separate years. If you want the default to commaify then change the line commented "# default" to use prettyNum. Although I'm thinking I've overcomplicated this and the comma and nocomma functions could just compute the string format themselves and then you wouldn't need a hook at all. Without knowing exactly your cases I don't think we can write a function that infers the comma-sep scheme - for example it would have to know that "1342 cases in 2013" needs its first number commad and not its second...
{ "language": "en", "url": "https://stackoverflow.com/questions/26382512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Sprites don't stop dragging on MOUSE_UP I have Sprites that I want to have move around when I click and hold them and stop when I release them. I have methods that add Event listeners to the Sprites: public function layOutEventListeners():void { var addSpriteEventListener:Function = function(spr:Dictionary, index:int, vector:Vector.<Dictionary>) { spr["sprite"].addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); spr["sprite"].addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } gridVec.forEach(addSpriteEventListener); }` and methods to handle the events: public function mouseDownHandler(me:MouseEvent):void { trace(me.target.toString()); trace(me.currentTarget.toString()); this.drawSprite(me.target); this.growByTwo(me.target); me.stopImmediatePropagation(); me.currentTarget.startDrag(me); } public function mouseUpHandler(me:MouseEvent):void { trace(me.target.toString()); trace(me.currentTarget.toString()); me.stopImmediatePropagation(); this.originalSize(me.target); me.currentTarget.stopDrag(); }` My problem is: when I click on the Sprites, as soon as I move the cursor, the Sprite's registration point snaps to the cursor, and when I release the mouse the Sprite doesn't stop following the cursor. I initially thought it was a problem with pixel collision. I thought the cursor wasn't touching anything on MOUSE_UP, but that proved to be false after I experimented. I even replicated the exact same Event adding and handling methods by starting another project and found that I wasn't having this problem. The test Sprite was simply dragging and dropping like usual, not snapping to the registration point, and being dragged by the point I clicked. The only difference I can see, and also my only suspicion, is that the Sprites in my original code are being added to a Sprite, which is then being added to the stage, whereas the Sprite in the test project is being added to the root DisplayObject. I'm thinking that somehow the Event propagating down to the container Sprite and dragging and dropping that without dropping the other Sprite. The weird snapping I'm seeing might be the cursor snapping to the object behind the other sprite. Another important thing: when I drop a Sprite on top of another Sprite, that Sprite stops moving like I want it to, but still trails the registration point. Regardless, I'm really stumped and I really don't know that I'm running over. Any ideas? A: This is usually because sometimes the mouse is not over the clip when MOUSE_UP occurs, either because of other clips getting in the way or maybe the player is not refreshing the stage fast enough, etc... I'm not sure this is your case, but either way it is often recommended to assign the MOUSE_UP event to the stage, so you can safely assure it is always triggered. Make sure to remove the listener on the mouseUp handler though ;) spr["sprite"].addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); public function mouseDownHandler(me:MouseEvent):void { stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } public function mouseUpHandler(me:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } The down side is that you lose your clip reference on mouseUp, but you can create a reference by hand on mouseDown, or do the whole thing internally (within the sprite's code).
{ "language": "en", "url": "https://stackoverflow.com/questions/5148872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: generated structure and memory links in python I'm generating data structure with function. And when I try fill it with few nested loops I have problem with memory link: result last loop set all previous. If I use hand-writed structure which absolutely similar to function-generated it work good. def data_fill(data, label): for item_index, item in enumerate(data): for subitem_index, subitem in enumerate(item['subitems']): value = 'item-%s-subitem-%s' % (item_index, subitem_index) data[item_index]['subitems'][subitem_index]['prop'] = value print('%s filled: ' % label, data) def gen_data(): subitems = [] for subitem in range(2): subitems.append({ 'title': subitem, 'prop': None, }) data = [] for item in range(3): data.append({ 'title': item, 'subitems': subitems, }) return data DATA = [ { 'title': 0, 'subitems': [ { 'title': 0, 'prop': None }, { 'title': 1, 'prop': None } ] }, { 'title': 1, 'subitems': [ { 'title': 0, 'prop': None }, { 'title': 1, 'prop': None } ] }, { 'title': 2, 'subitems': [ { 'title': 0, 'prop': None }, { 'title': 1, 'prop': None } ] } ] DATA_GEN = gen_data() data_fill(DATA, 'DATA') data_fill(DATA_GEN, 'DATA_GEN') Results: DATA filled (right): [ { 'title': 0, 'subitems': [ { 'title': 0, 'prop': 'item-0-subitem-0' }, { 'title': 1, 'prop': 'item-0-subitem-1' } ] }, { 'title': 1, 'subitems': [ { 'title': 0, 'prop': 'item-1-subitem-0' }, { 'title': 1, 'prop': 'item-1-subitem-1' } ] }, { 'title': 2, 'subitems': [ { 'title': 0, 'prop': 'item-2-subitem-0' }, { 'title': 1, 'prop': 'item-2-subitem-1' } ] } ] DATA_GEN filled (wrong): [ { 'title': 0, 'subitems': [ { 'title': 0, 'prop': 'item-2-subitem-0' }, { 'title': 1, 'prop': 'item-2-subitem-1' } ] }, { 'title': 1, 'subitems': [ { 'title': 0, 'prop': 'item-2-subitem-0' }, { 'title': 1, 'prop': 'item-2-subitem-1' } ] }, { 'title': 2, 'subitems': [ { 'title': 0, 'prop': 'item-2-subitem-0' }, { 'title': 1, 'prop': 'item-2-subitem-1' } ] } ] I think this happens because prop in DATA_GEN is link to one memory place. And I have some questions: * *How make my function-generated structure work right? *Where read more about this behavior? A: def gen_data(): subitems = [] for subitem in range(2): subitems.append({ 'title': subitem, 'prop': None, }) data = [] for item in range(3): data.append({ 'title': item, 'subitems': subitems, }) return data You are inserting the same subitems array into the data every time, so when you write one of its values: data[item_index]['subitems'][subitem_index]['prop'] = value You are updating that same subitem. Solution - put the sub-item generation code inside the data generation loop, to create an independent subitems array for each data item: def gen_data(): data = [] for item in range(3): subitems = [] for subitem in range(2): subitems.append({ 'title': subitem, 'prop': None, }) data.append({ 'title': item, 'subitems': subitems, }) return data The outputs now match as expected. As a side note, since you are already iterating over the elements of the subitems arrays, the write statement can simply become: subitem['prop'] = value A: The problem is here: def gen_data(): subitems = [] for subitem in range(2): subitems.append({ 'title': subitem, 'prop': None, }) data = [] for item in range(3): data.append({ 'title': item, 'subitems': subitems, # here }) return data Within this function, you only made one subitems list, and you're referring to it in multiple places. If you want different copies, create that list within the loop: def gen_data(): data = [] for item in range(3): subitems = [] for subitem in range(2): subitems.append({ 'title': subitem, 'prop': None, }) data.append({ 'title': item, 'subitems': subitems, # here }) return data
{ "language": "en", "url": "https://stackoverflow.com/questions/54143629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing a log file to count how many error and info entries a particular user has utilizing Python 3 I have the task of taking/parsing a log entry and having to first check if a regex pattern matches the INFO or ERROR message formats. Upon a successful match, add one to the corresponding value in the per_user dictionary such that if Bob had 3 entries in the log file and 2 were Errors it would generate Bob 2 Errors 1 Info in the dictionary. If you get an ERROR message, add one to the corresponding entry in the error dictionary by using proper data structure. The logfiles are of the following layout: Jan 31 00:21:30 ubuntu.local ticky: ERROR: The ticket was modified while updating (breee) I've been trying out whether to use Collections module or not and whether it would be best to use findall or .search. Here is what I've got so far. #!/usr/bin/env python3 import csv import operator import re from collections import defaultdict errors = defaultdict(int) per_user = defaultdict(list) file = open("syslog.log") error_count = 0 for line in file: #Set regular expression to find lines containing INFO or Error followed by colon the log message as an option and the username in parentheses at the end of the line... Contains 3 groups) info = re.findall(r"ticky: (?P<logtype>INFO|ERROR): (?P<logmessage>[\w].*)? \((?P<username>[\w]*)\)$", line, re.MULTILINE) for logtype, logmessage, username in info: per_user[username].append(logtype) file.close() print(per_user) This returns the info as {username: [logtype(s)]} and I'm not sure if I can take that information and run a count on it OR if it would be better to scrap the current code and do a .search() or . match() with an if statement and counter. These dictionaries will be written to CSV files if that makes a difference. A: I don't have 50 reputation to comment in your post. So, here is a "attempt" to answer your question. Feel free to comment and mark if this solves your question. Take a look at the code: import csv import re per_user = {} file = open("syslog.log") for line in file: #Set regular expression to find lines containing INFO or Error followed by colon the log message as an option and the username in parentheses at the end of the line... Contains 3 groups) info = re.findall(r"ticky: (?P<logtype>INFO|ERROR): (?P<logmessage>[\w].*)? \((?P<username>[\w]*)\)$", line, re.MULTILINE) for logtype, logmessage, username in info: if username not in per_user: per_user[username] = { "username": username, "INFO": 0, "ERROR": 0 } # Creates a new dict for that user per_user[username][logtype] += 1 # Sum one to INFO or ERROR counters file.close() for user_data in per_user.values(): print(user_data) # TODO: This is only for debugging Notes: * *if username does not exist in the current dictionary, it instance a new dictionary for that user and also initializes it with 3 keys: username, INFO, ERROR (last 2 are the counters) *then tries to sum up 1 to the current logtype *per_user.values() search for the values of each user (which are dictionaries) I've made a log file with 3 entries, with the same format as your question posts: Jan 31 00:21:30 ubuntu.local ticky: ERROR: The ticket was modified while updating (breee) Jan 31 00:21:30 ubuntu.local ticky: ERROR: The ticket was modified while updating (sam) Jan 31 00:21:30 ubuntu.local ticky: INFO: The ticket was successful (breee) And the output of the script is: {'username': 'breee', 'INFO': 1, 'ERROR': 1} {'username': 'sam', 'INFO': 0, 'ERROR': 1} This will become handy when using DictWriter of the csv module. Note aside. You can use the context manager called "with" to open the log file. ... with open("syslog.log", 'r') as file: for line in file: #Set... info = re.findall(... ... With this, you can safely omit closing the file. CSV Module: https://docs.python.org/3/library/csv.html DictWriter Method: https://docs.python.org/3/library/csv.html#csv.DictWriter See the example code of the python documentation: import csv with open('names.csv', 'w', newline='') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'}) For your case: with open('output.csv', 'w') as csvfile: fieldnames = ['username', 'INFO', 'ERROR'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() # Writes the field names for user_data in per_user.values(): writer.writerow(user_data) Output in the file 'output.csv': username,INFO,ERROR breee,1,1 sam,0,1 You can adapt this code to your needs. Best regards, Goran A: You could use nested dictionary to create structure { "bob": {"error": ..., "info": ...}, "breee": {"error": ..., "info": ...}, } And you can do it with nested defaultdict def errors(): return defaultdict(int) per_user = defaultdict(errors) or using lambda per_user = defaultdict(lambda:defaultdict(int)) (defaultdict needs function's name (without ()) so it can't be defaultdict(defaultdict(int))) And now you can count it for logtype, logmessage, username in info: per_user[username][logtype] += 1 After counting you can display it. Because some users may not have some messages in log (and in per_user) so you have to use logtype.get('ERROR', 0) instead of logtype['ERROR'] for user, logtype in per_user.items(): error = logtype.get('ERROR', 0) info = logtype.get('INFO', 0) print(user, error, 'errors', info, 'infos') And the same way you can save in CSV with open('output.csv', 'w') as f: csvwriter = csv.writer(f) # write header csvwriter.writerow(['name', 'error', 'info']) # write rows for user, logtype in per_user.items(): error = logtype.get('ERROR', 0) info = logtype.get('INFO', 0) print(user, error, 'errors', info, 'infos') csvwriter.writerow([user, error, info]) Minimal working example. I used list file instead of real data from file so everyone can run it without problems. But you can use open(), close() import csv import re from collections import defaultdict per_user = defaultdict(lambda:defaultdict(int)) #file = open("syslog.log") file = [ 'Jan 31 00:21:30 ubuntu.local ticky: ERROR: The ticket was modified while updating (breee)', 'Jan 31 00:21:30 ubuntu.local ticky: INFO: hello world (bob)', ] for line in file: #Set regular expression to find lines containing INFO or Error followed by colon the log message as an option and the username in parentheses at the end of the line... Contains 3 groups) info = re.findall(r"ticky: (?P<logtype>INFO|ERROR): (?P<logmessage>[\w].*)? \((?P<username>[\w]*)\)$", line, re.MULTILINE) for logtype, logmessage, username in info: per_user[username][logtype] += 1 #file.close() print(per_user) with open('output.csv', 'w') as f: csvwriter = csv.writer(f) # write header csvwriter.writerow(['name', 'error', 'info']) # write rows for user, logtype in per_user.items(): error = logtype.get('ERROR', 0) info = logtype.get('INFO', 0) print(user, error, 'errors', info, 'infos') csvwriter.writerow([user, error, info])
{ "language": "en", "url": "https://stackoverflow.com/questions/62579890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I change a const value when a button is clicked? Can somebody help me replace the console.log lines with something that will help me change the player.choice value based on which button is clicked? const player = { currentChoice: null } const computer = { currentChoice: null } const choices = ["Lapis", "Papyrus", "Scalpellus"]; document.querySelector('#Lapis').onclick = setLapis document.querySelector('#Papyrus').onclick = setPapyrus document.querySelector('#Scalpellus').onclick = setScalpellus; function setLapis(){ console.log("Lapis"); } function setPapyrus(){ console.log("Papyrus"); } function setScalpellus(){ console.log("Scalpellus"); } player.currentChoice = choices[0]; <button id="Lapis">Lapis</button> <button id="Papyrus">Papyrus</button> <button id="Scalpellus">Scalpellus</button> A: const player = { currentChoice: null } const computer = { currentChoice: null } const choices = ["Lapis", "Papyrus", "Scalpellus"]; document.querySelector('#Lapis').onclick = setLapis document.querySelector('#Papyrus').onclick = setPapyrus document.querySelector('#Scalpellus').onclick = setScalpellus; function setLapis(){ player.currentChoice = choices[0]; console.log(player.currentChoice); } function setPapyrus(){ player.currentChoice = choices[1]; console.log(player.currentChoice); } function setScalpellus(){ player.currentChoice = choices[2]; console.log(player.currentChoice); } <button id="Lapis">Lapis</button> <button id="Papyrus">Papyrus</button> <button id="Scalpellus">Scalpellus</button>
{ "language": "en", "url": "https://stackoverflow.com/questions/63910299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Html To Doc(Word) Or RTF Format What would the best possible way to convert a html page (with css, tables, images etc.) to be converted to word or rtf format. I already know about adding the content-type = application/word header and that's not an option because we need the images embedded in the document so that it can be viewed without an active internet connection. I need either a free (preferably) or commercial .NET library or a command line utility as I need to do this on a hosted ASP.NET application on a shared server :|. A: If you are using Word 2003 or 2007 you can convert xhtml documents to Word Xml documents using xslt. If you google for html to docx xsl you will find many examples of the opposite (converting docx to html) so you might one of those examples as a basis for a conversion. The only challenge would be downloading and embedding the images in the document, but that is also possible. A: There are several possibilities for converting HTML to RTF. These links should get you started: * *DocFrac, conversion between HTML, RTF and text. Free, runs on Windows. *XHTML2RTF: An HTML to RTF conversion tool based on XSL *Writing an RTF to HTML converter Converting to MS Word .doc is much harder and probably not worthwhile for you. For the reasons this is such a pain, read Joel's interesting article on .doc. If you have to write .doc for some reason, COM interop with MSOffice is probably your best bet.
{ "language": "en", "url": "https://stackoverflow.com/questions/1026281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: understanding WinDbg output I have a Winform application (C#) which imports some functions from dll. Sometimes when running the application i get the following exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. I catch it in AppDomain.CurrentDomain.UnhandledException. So i tried to debug it with WinDbg. I was able to catch the exception and get the following output: !analyze -v FAULTING_IP: KERNEL32!SetErrorMode+14b 77e6c427 8a08 mov cl,byte ptr [eax] EXCEPTION_RECORD: ffffffff -- (.exr 0xffffffffffffffff) ExceptionAddress: 77e6c427 (KERNEL32!SetErrorMode+0x0000014b) ExceptionCode: c0000005 (Access violation) ExceptionFlags: 00000000 NumberParameters: 2 Parameter[0]: 00000000 Parameter[1]: 087deadc Attempt to read from address 087deadc FAULTING_THREAD: 00000b1c PROCESS_NAME: App.exe ERROR_CODE: (NTSTATUS) 0xc0000005 - The instruction at "0x%08lx" referenced memory at "0x%08lx". The memory could not be "%s". EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at "0x%08lx" referenced memory at "0x%08lx". The memory could not be "%s". EXCEPTION_PARAMETER1: 00000000 EXCEPTION_PARAMETER2: 087deadc READ_ADDRESS: 087deadc FOLLOWUP_IP: KERNEL32!SetErrorMode+14b 77e6c427 8a08 mov cl,byte ptr [eax] NTGLOBALFLAG: 0 APPLICATION_VERIFIER_FLAGS: 0 MANAGED_STACK: !dumpstack -EE OS Thread Id: 0xb1c (34) Current frame: ChildEBP RetAddr Caller,Callee ADDITIONAL_DEBUG_TEXT: Followup set based on attribute [UnloadedModule_Arch_AX] from Frame:[0] on thread:[b1c] ; Enable Pageheap/AutoVerifer DEFAULT_BUCKET_ID: HEAP_CORRUPTION PRIMARY_PROBLEM_CLASS: HEAP_CORRUPTION BUGCHECK_STR: APPLICATION_FAULT_HEAP_CORRUPTION_INVALID_POINTER_READ LAST_CONTROL_TRANSFER: from 7a0aa797 to 77e6c427 STACK_TEXT: WARNING: Stack unwind information not available. Following frames may be wrong. 08bddc6c 7a0aa797 00000000 00000001 087deadc KERNEL32!SetErrorMode+0x14b 08bddd68 7c82a124 056306e8 08bddf9c 7c82a0b8 mscorwks!CorLaunchApplication+0x281f8 08bddd74 7c82a0b8 7c82a0fc 00000001 00000004 ntdll!RtlpAllocateFromHeapLookaside+0x13 08bddf9c 00000000 00000000 00000000 00000000 ntdll!RtlAllocateHeap+0x1dd STACK_COMMAND: .ecxr ; ~~[b1c] ; .frame 0 ; ~34s ; kb SYMBOL_NAME: ure.dll!Unloaded FOLLOWUP_NAME: MachineOwner MODULE_NAME: ure.dll IMAGE_NAME: ure.dll DEBUG_FLR_IMAGE_TIMESTAMP: 750063 FAILURE_BUCKET_ID: HEAP_CORRUPTION_c0000005_ure.dll!Unloaded BUCKET_ID: APPLICATION_FAULT_HEAP_CORRUPTION_INVALID_POINTER_READ_ure.dll!Unloaded WATSON_STAGEONE_URL: http://watson.microsoft.com/StageOne/App_exe/1_2009_403_12/49e707a9/KERNEL32_dll/5_2_3790_4062/46264680/c0000005/0002c427.htm?Retriage=1 Followup: MachineOwner What does that mean? and what should i do with it? Thanks in advance for any tips!! A: It looks like ure.dll has been unloaded, and a call to NlsAnsiToUnicodeMultiByteToWideChar() referring to it is failing. You could run .symfix before !analyze -v to confirm that. Is that the DLL you're importing? If not, you have memory corruption. Otherwise, the bug is probably in that DLL. Are you using P/Invoke to import it? Yup, the unloaded DLL information has been corrupted. As you might guess, it's .NET's culture.dll, and Windbg is reading the 'cult' part of that as the timestamp and checksum. Try restarting and doing the following: .symfix sxe ud g and when the breakpoint hits: kb (That's telling Windbg to run until the DLL is unloaded, and then dump the stack) Run for a bit to let the module unload, and execute the following command. Then let Windbg run until you get the exception, and do this command again to compare: db ntdll!RtlpUnloadEventTrace (That's the beginning of the unloaded module table, which is getting corrupted.)
{ "language": "en", "url": "https://stackoverflow.com/questions/759365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nodejs - getting client socket to try again after 5 sec time out Just starting out in node.js programming and writing a tcp socket client. I want the client to connect to a server. If the server is not available (i.e. server does not exist at a agreed port), i want the client to timeout and reconnect after the timeout. I have this code but it hangs at the second client.connect. What's wrong? var net = require('net'); var HOST = '127.0.0.1'; var PORT = 9000; var client = new net.Socket(); client.connect(PORT, HOST, function(){ console.log('CONNECTED TO: ' + HOST + ':' + PORT); client.write('I am Superman!'); }); client.on('error', function(e) { while (e.code == 'ECONNREFUSED') { console.log('Is the server running at ' + PORT + '?');` socket.setTimeout(1000, function() { console.log('Timeout for 5 seconds before trying port:' + PORT + ' again'); } client.connect(PORT, HOST, function(){ console.log('CONNECTED TO: ' + HOST + ':' + PORT); client.write('I am the inner superman'); }); }); }); Updated code: var net = require('net'); var HOST = '127.0.0.1'; var PORT = 9000; var client = new net.Socket(); client.connect(PORT, HOST, function(){ console.log('CONNECTED TO: ' + HOST + ':' + PORT); client.write('I am Superman'); }); client.on('error', function(e) { while (e.code == 'ECONNREFUSED') { console.log('Is the server running at ' + PORT + '?'); client.setTimeout(4000, function() { client.connect(PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT); client.write('I am inner Superman'); }); console.log('Timeout for 5 seconds before trying port:' + PORT + ' again'); }); } }); client.on('data', function(data) { console.log('DATA: ' + data); client.destroy(); }); client.on('close', function() { console.log('Connection closed'); }); With the updated code, the timeout does not appear to take effect. When i start this client with no corresponding server, the result shows below with no 4 second wait. Is the server running at 9000? Is the server running at 9000? Is the server running at 9000? Is the server running at 9000? … Update (Barking up the wrong tree?) I went back to look at the socket.on('error') event and saw that the close event is called immediately after the error. So the code will close out the tcpclient without waiting for 4 seconds. Any better ideas? A: You're timeout is reversed. Should look like: var net = require('net'); var HOST = '127.0.0.1'; var PORT = 9000; var client = new net.Socket(); client.connect(PORT, HOST, function(){ console.log('CONNECTED TO: ' + HOST + ':' + PORT); client.write('I am Superman!'); }); client.on('error', function(e) { if(e.code == 'ECONNREFUSED') { console.log('Is the server running at ' + PORT + '?'); client.setTimeout(4000, function() { client.connect(PORT, HOST, function(){ console.log('CONNECTED TO: ' + HOST + ':' + PORT); client.write('I am the inner superman'); }); }); console.log('Timeout for 5 seconds before trying port:' + PORT + ' again'); } }); client.on('data', function(data) { console.log('DATA: ' + data); client.destroy(); }); client.on('close', function() { console.log('Connection closed'); }); The function you want to run after the timeout is the callback. That's the one that waits for execution. Also, change your while to an if, that condition won't change during a single error event. And your parens and brackets are mismatched. A: per my comment on accepted answer I discovered an issue using the .connect callback vs the 'connect' listener. Each time you call .connect it cues the callback (adds a listener) even though the connection fails. So when it finally does connect all those callbacks get called. So if you use .once('connect'.. instead that won't happen. Below are logging statements from my project's client code that led me to this observation. ENOENT timeout ENOENT timeout ENOENT timeout ENOENT timeout ENOENT timeout ENOENT timeout ENOENT timeout ENOENT timeout ENOENT timeout (node:21061) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connect listeners added. Use emitter.setMaxListeners() to increase limit ^=== if you timeout and try .connect again eventually you hit this limit ENOENT timeout <==== here is where the connection finally happens connecting <==== now all those listener callbacks fire. connecting connecting connecting connecting connecting connecting connecting connecting connecting connecting so try this version below instead const net = require('net') const HOST = '127.0.0.1' const PORT = 9000 const client = new net.Socket() const connect = () => {client.connect(PORT, HOST)} client.once('connect', function(){ console.log('CONNECTED TO: ' + HOST + ':' + PORT) client.write('I am Superman!') }) client.on('error', function(e) { if(e.code == 'ECONNREFUSED') { console.log('Is the server running at ' + PORT + '?') console.log('Waiting for 5 seconds before trying port:' + PORT + ' again') setTimeout(connect,5000) } }) connect() client.on('data', function(data) { console.log('DATA: ' + data) client.destroy() }) client.on('close', function() { console.log('Connection closed') })
{ "language": "en", "url": "https://stackoverflow.com/questions/19981040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Modal is working in Firefox but not in Chrome Modal is working in Firefox but not in Chrome, I added the code below. * *The following is my app.js : $('.test').on('click', function (event) { event.preventDefault(); $('#join-req').modal(); }); *HTML : <a href="#" class="test">Join to my Group</a> *The modal : <div class="modal fade" tabindex="-1" role="dialog" id="join-req"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Join Request</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="post-body">Join request to expert</label> <textarea class="form-control" name="join-body" id="join-body" rows="5"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="modal-save">Submit request</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> The following are the Bootstrap and jquery links : <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link rel="stylesheet" href="{{ URL::to('src/css/main.css') }}"> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> </head> <body> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script src="{{ URL::to('src/js/app.js') }}"></script> Thanks in advance A: I can think of 3 possible causes of your problems, given that no errors are shown in your console. * *JQuery could have been loaded twice. * *check for inclusions of files which may already have been included in the others. *The .js files which you are referencing might not be in the right order, * *make sure JQuery is loaded and only then Bootstrap . *Your JQuery doesn't work well with your current Bootstrap version. Try upgrading either of the 2 or both.
{ "language": "en", "url": "https://stackoverflow.com/questions/57000362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change values of a timedelta column based on the previous row Let it be the following Python Panda Dataframe: code visit_time flag other counter 0 NaT True X 3 0 1 days 03:00:12 False Y 1 0 NaT False X 3 0 0 days 05:00:00 True X 2 1 NaT False Z 3 1 NaT True X 3 1 1 days 03:00:12 False Y 1 2 NaT True X 3 2 5 days 10:01:12 True Y 0 To solve the problem, only the columns: code, visit_time and flag are needed. Each row with a value of visit_time, has a previous row with value NaT. Knowing this, I want to do next modification in the dataframe: * *Sets the flag of the row with non-null value of visit_time to the same value as its previous row. Example: code visit_time flag other counter 0 NaT True X 3 0 1 days 03:00:12 True Y 1 0 NaT False X 3 0 0 days 05:00:00 False X 2 1 NaT False Z 3 1 NaT True X 3 1 1 days 03:00:12 True Y 1 2 NaT True X 3 2 5 days 10:01:12 True Y 0 I am grateful for the help offered in advance. A: You can use .mask to set the 'flag' values to the .shifted version of itself where 'visit_time' values are notnull. out = df.assign( flag=df['flag'].mask(df['visit_time'].notnull(), df['flag'].shift()) ) print(out) code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 True Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 False X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 True Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0 * *.mask(condition, other) replaces values where condition is True with the values of other in this case other is the value from the previous row. *.assign(…) is a way to update a column while returning a new DataFrame this can be replaced with column assignment df['flag'] = df['flag'].where(…) to modify the DataFrame in place. Creating a column from a string variable. df[name] = df[name].mask(df['visit_time'].notnull(), df[name].shift())) A: You can simply have a shifted dataframe as in: df_previous = df.copy() df_previous.index+=1 Looking like: code visit_time flag other counter 1 0 NaT True X 3 2 0 1 days 03:00:12 False Y 1 3 0 NaT False X 3 4 0 0 days 05:00:00 True X 2 5 1 NaT False Z 3 6 1 NaT True X 3 7 1 1 days 03:00:12 False Y 1 8 2 NaT True X 3 9 2 5 days 10:01:12 True Y 0 Now you can have it merge with original dataframe and assign values with simple vector comparisons: df = df.merge(df_previous[['visit_time', 'flag']], right_index=True, left_index=True, how='left', suffixes=["",'_previous']) df.loc[df.visit_time.notna(), 'flag'] = df.loc[df.visit_time.notna(), 'flag_previous'] Now your dataframe looks like: code visit_time flag other counter visit_time_previous flag_previous 0 0 NaT True X 3 nan nan 1 0 1 days 03:00:12 True Y 1 NaT 1 2 0 NaT False X 3 1 days 03:00:12 0 3 0 0 days 05:00:00 False X 2 NaT 0 4 1 NaT False Z 3 0 days 05:00:00 1 5 1 NaT True X 3 NaT 0 6 1 1 days 03:00:12 True Y 1 NaT 1 7 2 NaT True X 3 1 days 03:00:12 0 8 2 5 days 10:01:12 True Y 0 NaT 1 You can also remove previous columns if you like with: df.drop(list(df.filter(regex = '_previous')), axis = 1) Which will leave you with: code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 True Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 False X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 True Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0 A: for row in df.iterrows(): if row[0] < df.shape[0] - 1: # stop comparing when getting to last row if df.at[row[0], 'visit_time'] == 'NaT' and df.at[row[0] + 1, 'visit_time'] != 'NaT': df.at[row[0] + 1, 'flag'] = df.at[row[0], 'flag'] Before: code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 False Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 True X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 False Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0 After: code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 True Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 False X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 True Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0
{ "language": "en", "url": "https://stackoverflow.com/questions/72403450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Link to local file How can I link to a local file in PHP? I've tried all of these, but nothing works to prompt a file-download. According to: http://php.net/manual/en/wrappers.file.php I can add: file:/// But my editor doesn't like that when I also add the \ to designate the folder-structure, and the page then fails to load. $path = "file:\\\E:\machine\files\months\"; $path = "file:\\\E:\\machine\\files\\months\\"; $path = "file:\\\E:/\machine/\files/\months/\"; $path = "file:\\\E:/machine/files/months/"; None of those work -- either the page fails to load, or the slashes aren't going the correct direction for local paths. How can I link to a file on a local machine? (yes I know it will only work if the path structure is exactly the same) Thanks EDIT -- The issue isn't the filename. I add that later and that works fine. The issue is my syntax with path AND/OR file:/// My editor complains about file:/// http://imgur.com/uEaxgnM
{ "language": "en", "url": "https://stackoverflow.com/questions/36492373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery save clicked state after refresh I created function that change a view. Add some new classes if option was clicked. But I want to save state of clicked option and after refresh of page It should display option clicked before refresh. I implemented jQuery option $.cookie but it looks like it doesn't work. I only have an error "$.cookie is not a function" var gridOfThree = $('.mh-1on3--grid').on('click', function () { $('.mh-1on3--grid').addClass('mh-filters__right__button--active'); $('.mh-1on2--grid').removeClass('mh-filters__right__button--active'); $('.mh-1on1--grid').removeClass('mh-filters__right__button--active'); $('.mh-margin-bottom-small').removeClass('mh-grid__1of2'); $('.mh-margin-bottom-small').removeClass('mh-grid__1of1'); $('.mh-margin-bottom-small').addClass('mh-grid__1of3'); if (!$('#post-113').hasClass('mh-estate-vertical')) { $('#post-113').addClass('mh-estate-vertical'); } $('#post-113').removeClass('mh-estate-horizontal'); $('.wrap-div-to-change-look').removeClass('mh-estate-horizontal__inner'); $('.vertical-to-horizontal-dynamic').removeClass('mh-estate-horizontal__right'); $('.vertical-to-horizontal-dynamic').addClass('mh-estate-vertical__content'); $('.vertical-to-horizontal-dynamic').css('height','275px'); $('.mh-estate-vertical__date').css('left', ''); if ($('div.mh-estate-horizontal__left').hasClass('mh-estate-horizontal__left')) { $('.mh-thumbnail').unwrap('<div class="mh-estate-horizontal__left"></div>'); } $.cookie('gridOfThree', true); $.cookie('gridOfTwo', false); $.cookie('gridOfOne', false); }); var gridOfTwo = $('.mh-1on2--grid').on('click', function () { $('.mh-1on2--grid').addClass('mh-filters__right__button--active'); $('.mh-1on3--grid').removeClass('mh-filters__right__button--active'); $('.mh-1on1--grid').removeClass('mh-filters__right__button--active'); $('.mh-margin-bottom-small').removeClass('mh-grid__1of1'); $('.mh-margin-bottom-small').removeClass('mh-grid__1of3'); $('.mh-margin-bottom-small').addClass('mh-grid__1of2'); if (!$('#post-113').hasClass('mh-estate-vertical')) { $('#post-113').addClass('mh-estate-vertical'); } $('#post-113').removeClass('mh-estate-horizontal'); $('.wrap-div-to-change-look').removeClass('mh-estate-horizontal__inner'); $('.vertical-to-horizontal-dynamic').removeClass('mh-estate-horizontal__right'); $('.vertical-to-horizontal-dynamic').addClass('mh-estate-vertical__content'); $('.vertical-to-horizontal-dynamic').css('height','146px'); $('.mh-estate-vertical__date').css('left', ''); if ($('div.mh-estate-horizontal__left').hasClass('mh-estate-horizontal__left')) { $('.mh-thumbnail').unwrap('<div class="mh-estate-horizontal__left"></div>'); } $.cookie('gridOfTwo', true); $.cookie('gridOfThree', false); $.cookie('gridOfOne', false); }); var gridOfOne = $('.mh-1on1--grid').on('click', function () { $('.mh-1on1--grid').addClass('mh-filters__right__button--active'); $('.mh-1on3--grid').removeClass('mh-filters__right__button--active'); $('.mh-1on2--grid').removeClass('mh-filters__right__button--active'); $('.mh-margin-bottom-small').removeClass('mh-grid__1of2'); $('.mh-margin-bottom-small').removeClass('mh-grid__1of3'); $('.mh-margin-bottom-small').addClass('mh-grid__1of1'); $('#post-113').removeClass('mh-estate-vertical'); $('#post-113').addClass('mh-estate-horizontal'); $('.wrap-div-to-change-look').addClass('mh-estate-horizontal__inner'); $('.vertical-to-horizontal-dynamic').addClass('mh-estate-horizontal__right'); $('.vertical-to-horizontal-dynamic').removeClass('mh-estate-vertical__content'); $('.vertical-to-horizontal-dynamic').css('height','146px'); $('.mh-estate-vertical__date').css('left', '475px'); if (!$('div.mh-estate-horizontal__left').hasClass('mh-estate-horizontal__left')) { $('.mh-thumbnail').wrap('<div class="mh-estate-horizontal__left"></div>'); } $.cookie('gridOfOne', true); $.cookie('gridOfTwo', false); $.cookie('gridOfThree', false); }); if ($.cookie('gridOfOne') == 'true') { $('.mh-1on1--grid').click(); } else if ($.cookie('gridOfTwo') == 'true') { $('.mh-1on2--grid').click(); } else if ($.cookie('gridOfThree') == 'true') { $('.mh-1on3--grid').click(); } A: Create a localstorage as localStorage.setItem('key',value); And get result from localStorage.getItem('key');
{ "language": "en", "url": "https://stackoverflow.com/questions/45751572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't LinkedHashSet have addFirst method? As the documentation of LinkedHashSet states, it is Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. So it's essentially a HashSet with FIFO queue of keys implemented by a linked list. Considering that LinkedList is Deque and permits, in particular, insertion at the beginning, I wonder why doesn't LinkedHashSet have the addFirst(E e) method in addition to the methods present in the Set interface. It seems not hard to implement this. A: As Eliott Frisch said, the answer is in the next sentence of the paragraph you quoted: … This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). … An addFirst method would break the insertion order and thereby the design idea of LinkedHashSet. If I may add a bit of guesswork too, other possible reasons might include: * *It’s not so simple to implement as it appears since a LinkedHashSet is really implemented as a LinkedHasMap where the values mapped to are not used. At least you would have to change that class too (which in turn would also break its insertion order and thereby its design idea). *As that other guy may have intended in a comment, they didn’t find it useful. That said, you are asking the question the wrong way around. They designed a class with a functionality for which they saw a need. They moved on to implement it using a hash table and a linked list. You are starting out from the implementation and using it as a basis for a design discussion. While that may occasionally add something useful, generally it’s not the way to good designs. While I can in theory follow your point that there might be a situation where you want a double-ended queue with set property (duplicates are ignored/eliminated), I have a hard time imagining when a Deque would not fulfil your needs in this case (Eliott Frisch mentioned the under-used ArrayDeque). You need pretty large amounts of data and/or pretty strict performance requirements before the linear complexity of contains and remove would be prohibitive. And in that case you may already be better off custom designing your own data structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/53877927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I fix this Apache server situation? I've been working on a huge upgrade of several websites for several months. It includes upgrading to PDO database connections and modifying Apache so that people who arrive on links pointing to mysite/World/New_York will be redirected to mysite/world/new-york. Unfortunately, publishing it has been an endless series of disasters. All my websites are crashed, and pages load extremely slowly. It takes forever to publish files online, and sometimes I can't put anything online at all. So I was happy to get this notice from my webhost; at least I have some clue about what's going on. Can anyone explain to me what it means and what I have to do to fix it? If there's no solution, do you think I might fix it by simply deleting all my websites (about two dozen of them) entirely, then just publishing them back online slowly, one at a time? IT appears your own server IP is making GET requests to Apache, causing excessive loading and causing service failures. On today's date, your IP made almost 6,000 connections to Apache:<br><br> [root@host ~]# grep 64.91.229.106 /usr/local/apache/domlogs/mysite.org | wc -l 5924 [root@host ~]#<br><br> These were all the same request:<br><br> 64.91.229.106 - - [12/Apr/2014:08:10:10 -0400] "GET /404.php HTTP/1.0" 200 14294 "-" "-"<br><br> And that made up the total of requests:<br><br> [root@host ~]# grep 64.91.229.106 /usr/local/apache/domlogs/mysite.org | grep "GET /404.php HTTP/1.0" | wc -l 5924 [root@host ~]#<br><br> I'd suggest seeking out the assistance of a developer to see where the source of these requests lie, as they are what have been loading down your server today. Let us know if you have any questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/23039221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing the CSS class of a child element on parent hover My Html: <div class="parent"> <span class= "child"></span> </div> I want to change the CSS of the child span tag when I hover over the parent element and revert the child's CSS on mouseout over parent. How can I do this with CSS & HTML? A: .parent:hover .child{ some props } A: try this: using the normal pseudo element in css :hover, adding the child element .child to add his style .parent:hover .child{ background-color:red; }
{ "language": "en", "url": "https://stackoverflow.com/questions/20920677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error while running statsmodels in colab "estimate_tweedie_power() missing 1 required positional argument: 'mu'" Modeling Tweedie distribution in statsmodels in Google Colab, but I'm getting an error while trying to use estimate_tweedie_power function. Here is the code from my notebook. #Training model tweedie_model = sm.GLM(y_train, X_train, exposure = df_train.exposure, family=sm.families.Tweedie(link=None,var_power=1.5,eql=True)) tweedie_result = tweedie_model.fit() #Using the initial model output to decide the optimum index parameter "p" GLM.estimate_tweedie_power(training_result, method='brentq', low=1.01, high=5.0) Here is my error while running estimate_tweedie_power function. estimate_tweedie_power() missing 1 required positional argument: 'mu' A: You might want to use something like: tweedie_model.estimate_tweedie_power(tweedie_result.mu, method='brentq', low=1.01, high=5.0) Reference: https://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.estimate_tweedie_power
{ "language": "en", "url": "https://stackoverflow.com/questions/61276846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrapinghub Deploy Failed I am trying to deploy a project to scrapinghub and here's the error I am getting slackclient 1.3.2 has requirement websocket-client<0.55.0,>=0.35, but you have websocket-client 0.57.0. Warning: Pip checks failed, please fix the conflicts. WARNING: There're some errors when doing pip-check: WARNING: The scripts pip, pip3 and pip3.8 are installed in '/app/python/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. {"message": "Dependencies check exit code: 1", "details": "Pip checks failed, please fix the conflicts", "error": "requirements_error"} {"status": "error", "message": "Requirements error"} Deploy log location: /var/folders/p7/nwmq6_4138n6t3w2spdnpzfm0000gn/T/shub_deploy_5l9k3_nm.log Error: Deploy failed: b'{"status": "error", "message": "Requirements error"}' I can't figure out how to find the log file its saying? A: I had this issue recently and the cause was that the stack I was using on the dash required specific, older versions of packages that were dependencies of ones in my requirements. A good first step is to try installing the older version of websocket-client. If slackclient 1.3.2 works on the older version you;re good, otherwise you might need to try rolling back slackclient too.
{ "language": "en", "url": "https://stackoverflow.com/questions/61822730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Laravel Generate Basic Auth I am using Basic Auth ( Auth::onceBasic() ) in Laravel. How can I generate the Token shown after 'BASIC' which is sent in the header which is automatically generated by PostMan. I believe I need to send that token back to the user so he can login next time with that token in the header? I wonder how can I return it back to the user from the code? In the screenshot below PostMan generates it by itself. I hope I have understood basic auth correctly. I know how to do it using Passport.
{ "language": "en", "url": "https://stackoverflow.com/questions/58291728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ActionBar tab background with xml Is it possibile to create a Holo-like ActionBar tab background only with xml drawables? If yes, how? If no, what's the limitation? Browsing the Android source code I found that the tab background is defined with a selector drawable in tab_indicator_holo.xml: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Non focused states --> <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_unselected_holo" /> <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_selected_holo" /> <!-- Focused states --> <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_unselected_focused_holo" /> <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_selected_focused_holo" /> <!-- Pressed --> <!-- Non focused states --> <item android:state_focused="false" android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/tab_unselected_pressed_holo" /> <item android:state_focused="false" android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/tab_selected_pressed_holo" /> <!-- Focused states --> <item android:state_focused="true" android:state_selected="false" android:state_pressed="true" android:drawable="@drawable/tab_unselected_pressed_holo" /> <item android:state_focused="true" android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/tab_selected_pressed_holo" /> </selector> And then using 9 patch drawables for each state, such as tab_selected_holo.9.png. I was wondering if those 9 patch drawables could be replaced with layer list drawables, shape drawables or a combination, thus saving the need to create various PNG files (6 per density by my count). I noticed that ActionBarSherlock also uses 9 patch drawables, so it's highly likely this is the only way to do it. A: To completely customize your ActionBar tabs, try something like the following, for a fictional tab called "Home". This layout contains an image and label. (1) create the tab as normal, but specify a custom layout via ActionBar.Tab.setCustomView() // Home tab LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); HomeFragment homeFragment = new HomeFragment(); RelativeLayout layoutView = (RelativeLayout)inflater.inflate(R.layout.layout_tab_home, null); TextView title = (TextView)layoutView.findViewById(R.id.title); ImageView img = (ImageView)layoutView.findViewById(R.id.icon); ActionBar.Tab tabHome = mActionBar.newTab(); tabHome.setTabListener(homeFragment); title.setText(this.getString(R.string.tabTitleHome)); img.setImageResource(R.drawable.tab_home); tabHome.setCustomView(layoutView); mActionBar.addTab(tabHome); (2) create a layout for your tab (layout_tab_home.xml) <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="56dip" android:layout_weight="0" android:layout_marginLeft="0dip" android:layout_marginRight="0dip"> <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:paddingBottom="2dip" /> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/icon" android:paddingLeft="0dip" android:paddingRight="0dip" style="@style/tabText" /> </RelativeLayout> (3) set a drawable for your image <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@drawable/home_sel" /> <item android:state_selected="false" android:drawable="@drawable/home_unsel" /> </selector> in this example, I just have a PNG graphic with diff't colors for selected vs. unselected states You seem to be most interested in the BACKGROUND drawable, so the same thing would apply, but set a background drawable on your RelativeLayout, and use a selector similar to the above. A: You can use inset drawables to create the line strip at the bottom. This xml will create a white rectangle with a blue line at the bottom like the one you posted. Then you can use state list drawables for its state. <?xml version="1.0" encoding="utf-8"?> <inset xmlns:android="http://schemas.android.com/apk/res/android" android:insetBottom="0dp" android:insetLeft="-5dp" android:insetRight="-5dp" android:insetTop="-5dp" > <shape> <solid android:color="#FFF" /> <stroke android:width="3dp" android:color="#00F" /> </shape> </inset> For more info you can have a look at this post: http://blog.stylingandroid.com/archives/1329
{ "language": "en", "url": "https://stackoverflow.com/questions/11653642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Time Complexity of Straight Forward Dijkstra's Algorithm I am having a hard time seeing the O(mn) bound for the straightforward implementation Dijkstra's algorithm (without a heap). In my implementation and others I have found the main loop iterates n-1 times (for each vertex that is not source, n-1), then in each iteration finding the minimum vertex is O(n) (examining each vertex in the queue and finding min distance to source) and then each discovered minimum vertex would have at most n-1 neighbors, so updating all neighbors is O(n). This would seem to me to lead to a bound of O(n^2). My implementation is provided below public int[] dijkstra(int s) { int[] dist = new int[vNum]; LinkedList queue = new LinkedList<Integer>(); for (int i = 0; i < vNum; i++) { queue.add(i); // add all vertices to the queue dist[i] = Integer.MAX_VALUE; // set all initial shortest paths to max INT value } dist[s] = 0; // the source is 0 away from itself while (!queue.isEmpty()) { // iterates over n - 1 vertices, O(n) int minV = getMinDist(queue, dist); // get vertex with minimum distance from source, O(n) queue.remove(Integer.valueOf(minV)); // remove Integer object, not position at integer for (int neighbor : adjList[minV]) { // O(n), max n edges int shortestPath = dist[minV] + edgeLenghts[minV][neighbor]; if (shortestPath < dist[neighbor]) { dist[neighbor] = shortestPath; // a new shortest path have been found } } } return dist; } I don't think this is correct, but I am having trouble see where m factors in. A: Your implementation indeed removes the M factor, at least if we consider only simple graphs (no multiple edges between two vertices). It is O(N^2)! The complexity would be O(N*M) if you would iterate through all the possible edges instead of vertices. EDIT: Well, it is actually O(M + N^2) to be more specific. Changing value in some vertex takes O(1) time in your algorithm and it might happen each time you consider an edge, in other words, M times. That's why there is M in the complexity. Unfortunately, if you want to use simple heap, the complexity is going to be O(M* log M) (or M log N). Why? You are not able to quickly change values in heap. So if dist[v] suddenly decreases, because you've found a new, better path to v, you can't just change it in the heap, because you don't really know it's location. You may put a duplicate of v in your heap, but the size of the heap would be then O(M). Even if you store the location and update it cleverly, you might have O(N) items in the heap, but you still have to update the heap after each change, which takes O(size of heap). You may change the value up to O(M) times, what gives you O(M* log M (or N)) complexity
{ "language": "en", "url": "https://stackoverflow.com/questions/59462121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL/PHP mass update multiple records with one query using CROSS JOIN on same table I have a PHP script that runs ever 60 seconds. It queries an external database to check if any records have been updated. It's basically a booking system that requires manual approval or rejection of booking requests. The system is being modified to allow customers to request changes to already accepted bookings. I'm looking for the quickest way to update the local database in one transaction (so customers can access a web portal to view the status of each booking etc). I thought I found it but I'm experiencing unpredictable results (not all of the records are being updated all of the time) but I'm not sure if it's because of the query I'm using or other factors. This is my method of updating the records: UPDATE bookings CROSS JOIN (SELECT * FROM bookings WHERE parent_id IN (1, 2, 3, 4, 5) AND processed = 0) AS Child SET bookings.date = Child.date, bookings.time = Child.time, bookings.name = Child.name, bookings.email = Child.email, bookings.telephone = Child.telephone WHERE bookings.id = Child.parent_id I'm calling the edited booking record the 'child' and the main booking that has had the requested change on it the 'parent'. If the change request is accepted then most of the parent record (fields I choose) should be updated with the data from the child record. A child record is considered a child if it has a value in the parent_id field. The above example would be created dynamical in PHP but for simplicity, 1, 2 , 3, 4 and 5 would be the IDs of the master/parent bookings that have had accepted change requests, thus requiring an update. The inner query is getting the necessary child records. I guess my real question is: should my query work, does it look correct and logical? Should it work even if a field in the original booking was empty and now has a value and visa versa if it's requested that a field now have a blank or null value? Maybe I'm using the wrong method entirely! Many thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/40248319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Web App after restoring iPhone 4 backup on iPhone SE has the iPhone 4 size I am moving from iPhone 4 to iPhone SE. I have a web app on my iPhone 4 that was added to the home screen. After restoring iPhone 4 backup on the iPhone SE I see this Web App but its size is constrained to the size of the iPhone 4 screen while displayed on the bigger iPhone SE screen. Is there any way to "recalculate" the size of the Web App without removing/installing it again? I am using LocalStorage a lot in this web app and if I remove it from the home screen I will loose it all. A: Do you have a startup image for your web app? The last time i worked on a web app (some years ago) I discovered that the startup image resolution decides the resolution for the rest of the app(!). See this SO question for startup image HTML syntax for multiple devices. I hope this helps. A: So apparently when you add a Homescreen bookmark - you get a simple iOS app (with a single WebView probably) which is not converted when you restore if from backup on a device with bigger screen. In my case I had to reinstall it on my new device in order to have a full screen app version.
{ "language": "en", "url": "https://stackoverflow.com/questions/37933848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php for loop and keep history generating a new array with all the values inside $Xn = count($where = array(1, 2, 3, 4, 5, ... , $n))/3; where $n is multiple of 3 objects!!! for($i = 1; $i <= ($Xn); $i++) { $field[$Xn-$i] = $where[(3*$i)-3]; $operator[$Xn-$i] = $where[(3*$i)-2]; $value[$Xn-$i] = $where[(3*$i)-1]; } all i want is to create a big array with all values inside! like this: array($field[0], $operator[0], $value[0], $field[1], $operator[1], $value[1], $field[2], $operator[2], $value[2]...) or 3 small arrays like this: $field_$n = array($field[0], $field[1], $field[2]...) etc.. how can this be done? thanks in advance!!! A: sorry guys for bad language and meaning in the question!!, what i had in mind was this!! public function action_X_single($action, $table, $where = array()) { $Xn = count($where)/3; $operators = array('=', '>', '<', '>=', '<='); for($i=1; $i<=$Xn; $i++){ $field[] = array( 'field' => $where[(3*$i)-3] ); $operator[] = array( 'operator' => $where[(3*$i)-2] ); $value[] = array( 'value' => $where[(3*$i)-1] ); } $sql .= "{$action} FROM {$table} WHERE " ; for($i=0;$i<$Xn;$i++) { if(($i)==0) { $sql .= implode(' ', $field[0]) . " " . implode(' ', $operator[0])." ?"; } else { $sql .= " AND ".implode(' ', $field[$i]) . " " . implode(' ', $operator[$i])." ?"; } } for($i=0;$i<$Xn;$i++) { if($i==0) { $values .= implode(' ', $value[0]); }else { $values .= " ".implode(' ', $value[$i]); } } if(!$this->query($sql, explode(' ', $values))->error()) { return $this; } return false; } and so to get the values from my table i used this: public function get_X_single($table, $where) { return $this->action_X_single('SELECT *', $table, $where); }
{ "language": "en", "url": "https://stackoverflow.com/questions/36723957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to improve my delete statement in oracle? If I have a 3(inst, acct and recordno) columns as part of primary key and I knew only values of first 2,and my table has multiple indexes and every index has first 2 columns (inst and acct) and third one is something different. Now questions. * *if I have the delete query like this Delete from TABL where inst=XXX and acct=123456789 which key it will pick up? *Is it fine if I add an extra where condition like recordno > 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/53817382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Webhook Subscription for AzureAd groups and Users not working I have created a webhook subscription for Users and Groups by making a POST call to https://graph.microsoft.com/v1.0/subscriptions with the following as payload: { "changeType": "updated,deleted", "notificationUrl": "https://a0317384.ngrok.io", "resource": "groups", "expirationDateTime": "2019-06-25T19:23:45.9356913Z", "clientState": "<redacted>" } A Subscription is successfully getting created and I am returning verification token from my endpoint. I can also see it in the list of Subscriptions by making GET call on above URL. When I am making some changes in Groups, like changing displayName or adding Members to the Group, I am not seeing notifications in real-time. Sometimes I am getting notifications in a bulk and other times the notifications do not arrive at all. I have tried multiple times to delete and re-create the Subscription, but I still see the same behavior. Can anyone tell why is it happening? A: Notifications can be batched for performance optimizations and the delay to deliver notifications can vary based on service load and other factors. While debugging you should also make sure there's no blocking conditions set by the IDE (like a break point for instance) that might block other incoming requests. Lastly, it's pretty rare, but service outages can happen, in that case the best thing to do it to contact support.
{ "language": "en", "url": "https://stackoverflow.com/questions/56736435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Launch and write to terminal in Qt I am coding in linux using Qt. I understand that with popen or QProcess I can launch terminal from my program, but how do I write into to it? I google around people are suggesting fork() and pipe(). My purpose is to do an ICMP ping with the terminal, and stop when ping successfully. I made it with popen, but I couldn't stop the ping process thus my program won't run. A: You don't write anything to terminal because there's no terminal. You pass name of a program to run and its arguments as arguments of the QProcess::start method. If you only need to know if ping was successful or not it's enough to check the exit code of the process which you started earlier using QProcess::start; you don't have to read its output. from ping(8) - Linux man page If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not. By default ping under Linux runs until you stop it. You can however use -c X option to send only X packets and -w X option to set timeout of the whole process to X seconds. This way you can limit the time ping will take to run. Below is a working example of using QProcess to run ping program on Windows. For Linux you have to change ping options accordingly (for example -n to -c). In the example, ping is run up to X times, where X is the option you give to Ping class constructor. As soon as any of these executions returns with exit code 0 (meaning success) the result signal is emitted with value true. If no execution is successful the result signal is emitted with value false. #include <QCoreApplication> #include <QObject> #include <QProcess> #include <QTimer> #include <QDebug> class Ping : public QObject { Q_OBJECT public: Ping(int count) : QObject(), count_(count) { arguments_ << "-n" << "1" << "example.com"; QObject::connect(&process_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(handlePingOutput(int, QProcess::ExitStatus))); }; public slots: void handlePingOutput(int exitCode, QProcess::ExitStatus exitStatus) { qDebug() << exitCode; qDebug() << exitStatus; qDebug() << static_cast<QIODevice*>(QObject::sender())->readAll(); if (!exitCode) { emit result(true); } else { if (--count_) { QTimer::singleShot(1000, this, SLOT(ping())); } else { emit result(false); } } } void ping() { process_.start("ping", arguments_); } signals: void result(bool res); private: QProcess process_; QStringList arguments_; int count_; }; class Test : public QObject { Q_OBJECT public: Test() : QObject() {}; public slots: void handle(bool result) { if (result) qDebug() << "Ping suceeded"; else qDebug() << "Ping failed"; } }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); Test test; Ping ping(3); QObject::connect(&ping, SIGNAL(result(bool)), &test, SLOT(handle(bool))); ping.ping(); app.exec(); } #include "main.moc"
{ "language": "en", "url": "https://stackoverflow.com/questions/4629185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Calendar Application I need some help with jQuery Calendar application. The specific calendar I'm looking for can be found at the following addresses.. I will be glad if anyone knows and would be kind to provide me the name of the calendar that was used in the links below. Calendar Example 1 Calendar Example 2 A: On chrome right click on the page , select inspect element then go to the resources panel and check the scripts folder. A: Inside your links it's a custom-made server-side calendar. It has nothing to do with jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/12232473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: slick plugin is not working for dynamically created content but works well for static content <div id="id1" class="scroll-footer"> <dynamically created div1></div> <dynamically created div2></div> <dynamically created div3></div> <dynamically created div4></div> </div> $(document).ready(function(){ $('.scroll-footer').slick({ slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000, arrows: true }) }); we have added slick class to id1 div dynamically but it doesn't work? How can I add slick class after loading the dynamically created div1, div 2etc?? A: I also have the same question, and here's how I solve it. You need to .slick("unslick") it first $('.portfolio-thumb-slider').slick("unslick"); $('.portfolio-item-slider').slick({ slidesToShow: 1, adaptiveHeight: false, // put whatever you need }); Hope that help. A: There is a method for these kind of things. As documentation states: slickAdd html or DOM object, index, addBefore Add a slide. If an index is provided, will add at that index, or before if addBefore is set. If no index is provided, add to the end or to the beginning if addBefore is set. Accepts HTML String || Object I would do it like this: $('#id1').slick(); $.ajax({ url: someurl, data: somedata, success: function(content){ var cont=$.parseHTML(content); //depending on your server result $(cont).find('.dynamically.created.div').each(function(){ $('#id1').slick('slickAdd', $(this)); }) } }) A: You need the initialise the function again while adding the dynamic element Suggest you to do this function sliderInit(){ $('.scroll-footer').slick({ slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000, arrows: true }); }; sliderInit(); Call the function here for default load of function and call the same function sliderInit() where you are adding dynamic element. NOTE : Remember to write this function after adding the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/38843771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: File system access from Safari (IOS) For Windows/Linux based browsers I can use Java plugin to access filesystem. As IOS does not support Java, is there any alternative way to get it done? A: No, you can't. File cannot be uploaded or even downloaded in iOS safari. In iCab you can upload by <input type = 'file'> but you can't access filesystem. Acessing entire filesystem from browser will be a security disaster. And also java plugin can't acess entire filesystem. A: It depends what do you want to do. If you just want allow user to navigate to interesting file(s) and then upload it to server for processing you can use <input type='file'> in your HTML. If you need more functionality you have to implement native plug-in to browser or use Flash.
{ "language": "en", "url": "https://stackoverflow.com/questions/12284108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: System.NotSupportedException: 'The entity or complex type 'Model' cannot be constructed in a LINQ to Entities query.' I want to release data to crystal report through code below. I get an error as image. ReportDocument rd = new ReportDocument(); rd.Load(Path.Combine(Server.MapPath("~/Reports"), "visitorlist.rpt")); rd.SetDataSource(db.Visitor.Select(c => new Visitor() { name = c.name == null ? "" : c.name, surname = c.surname == null ? "" : c.surname, organization = c.organization == null ? "" : c.organization, input_time = !c.input_time.HasValue ? (DateTime?)System.Data.SqlTypes.SqlDateTime.MinValue : (c.input_time).Value, output_time = !c.output_time.HasValue ? (DateTime?)System.Data.SqlTypes.SqlDateTime.MinValue : (c.output_time).Value }).ToList()); A: You can add a ToList before the Select to execute the query before transforming the result. rd.SetDataSource(db.Visitor.ToList().Select(c => new Visitor() { // ... }));
{ "language": "en", "url": "https://stackoverflow.com/questions/65077249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to transition just for transform rotate I have an HTML element that must rotate in a hover event. look at the code. I don't want transition for translateX. I just want transition for rotate. what should I do?? .cog { margin-top: 250px; cursor: pointer; transition: transform 0.5s ease-in-out; position: relative; left: 50%; transform: translateX(-50%); } .cog:hover { transform: rotate(-.4turn); } A: Try this: Remove the transform property from cog class. Then it will only rotate. CSS .cog { margin-top: 250px; cursor: pointer; transition: transform 0.5s ease-in-out; position: relative; left: 50%; } .cog:hover { transform: rotate(-.4turn); } A: You need to include the translation on hover too: .cog { cursor: pointer; transition: transform 0.5s ease-in-out; position: relative; left: 50%; transform: translateX(-50%); width:50px; height:50px; background:red; } .cog:hover { transform: translateX(-50%) rotate(-.4turn); } <div class="cog"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/56928329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Easy XML serialization with custom conversion of node values? How can i deserialize and cast the following xml file? I want Valid element be casted to bool property and Time object be casted in DateTime property <Foo> <Valid>True</Valid> <Time>19/02/2012 00:25:50</Time> </Foo> And not with reflection please A: Xml deserialization. Create your class with attributes: class Foo { [XmlAttribute] public bool valid; [XmlAttribute] public DateTime time; } Remember - fields must be public. And then: FileStream fs = new FileStream(filename, FileMode.Open); XmlReader reader = XmlReader.Create(fs); XmlSerializer xs = new XmlSerializer(typeof(Foo)); Foo foo = (Foo)xs.Deserialize(reader); fs.Close(); A: .net has a xmlserializer object that lets you serialize and deserialize an object into and from a xml stream but it creates its tags in a different way than your xml file. Maybe you can create a custom serializer that will act according to you rules. Here you can find an example.(it uses a xsd file to set the rules of serialization)
{ "language": "en", "url": "https://stackoverflow.com/questions/9344444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to copy assets with vue-cli-service build command? Below is the content of my app src directory. How can I copy files located in src/assets/others to dist/others folder with vue-cli-service build command? Btw. my project was created with vue create command. src/ ├── App.vue ├── assets |    ├── others |       └── metadata.xlsx dist/ ├── css │   ├── app.4d032e62.css │   └── chunk-vendors.f6f30965.css ├── favicon.ico ├── img │   └── upload.a0fd70ac.svg ├── index.html └── js ├── app.11cd5b00.js ├── app.11cd5b00.js.map ├── chunk-vendors.58c6929b.js └── chunk-vendors.58c6929b.js.map A: In a Vue CLI project, the src/assets directory normally contains files that are processed by Webpack (for minification, etc.), and static assets are stored in the public directory. So, you could move your src/assets/others to public/others, where they'll automatically be copied to dist during the build. On the other hand, if you'd rather the src/assets directory also contain static assets for some reason, you could configure the WebpackCopyPlugin (already included in Vue CLI) to copy src/assets/others to dist/others at build time: // vue.config.js const path = require('path') module.exports = { chainWebpack: config => { config.plugin('copy') .tap(args => { args[0].push({ from: path.resolve(__dirname, 'src/assets/others'), to: path.resolve(__dirname, 'dist/others'), toType: 'dir', ignore: ['.DS_Store'] }) return args }) } } A: With webpack 5 and vue-cli 5 this changed to: // vue.config.js const path = require('path') module.exports = { chainWebpack: (config) => { config.plugin('copy').tap((entries) => { entries[0].patterns.push({ from: path.resolve(__dirname, 'src/assets/others'), to: path.resolve(__dirname, 'dist/others'), toType: 'dir', noErrorOnMissing: true, globOptions: { ignore: ['.DS_Store'] }, }) return entries }) }, }
{ "language": "en", "url": "https://stackoverflow.com/questions/60304092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: .load and .unload external page inside a div I'm using this jQuery function to load an external page inside a div on click. $(document).on("click", ".more", function() { $("#wait").load("www.google.com") }), $(document).on("click",".more",function(){ $("#wait").empty() }) #wait{ width:80vw; height:80vh; position:fixed; top:30px; left:30px; background:red; } #more{cursor:pointer} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="more">CLICK</div> <div id="wait"></div> It works but if I click to show that div again it will be empty. What the alternative to .empty()? Thanks. A: From your post it seems you want to load it once and then just toggle. $(document).on("click", ".more", function() { var $wait = $("#wait"); if ($wait.html().length==0) $wait.load("about.html"); $wait.show(); $(this).toggleClass("more less"); }); $(document).on("click",".less",function(){ $("#wait").hide(); $(this).toggleClass("less more"); }); To add and delete each time you click the SAME button try this which seems to be very much what you already tried $(document).on("click", ".more", function() { $("#wait").load("about.html"); $(this).toggleClass("more less"); }); $(document).on("click",".less",function(){ $("#wait").empty(); $(this).toggleClass("less more"); }); One event handler: $(document).on("click", ".moreorless", function() { if ($(this)hasClass("more")) { $("#wait").load("about.html"); $(this).toggleClass("more less"); } else { $("#wait").empty(); $(this).toggleClass("less more"); } }); A: Why not just load the data on page load and then toggle() the display when button is clicked? $(function(){ // add the content right when page loads $("#wait").load("about.html"); $('#more').click(function(){ // toggle display $("#wait").toggle(); // toggle class $(this).toggleClass("less more"); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/40564923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: insert responsive gmail html signature My html signature in browser is quite good with following design: [ ] name [img] company [ ] email but when I copy to gmail signature, it seems to be broken! the image stands in wrong position! [ ] [img] [ ] name company email please help me to resolve this problem! ps: I have not enough reputations to post image. <div class = "col-lg-12 col-md-12" style ="display:inline"> <div class = "col-xs-1 col-sm-1" style = "padding:0 0 0 0;display:inline"> <img src="http://i.imgur.com/8wclWry.png" width="65px" height="65px" id="sigPhoto"> </div> <div class = "col-lg-11 col-md-10" style = "padding:0 0 0 0; display:inline"> <p class = "col-lg-11 col-md-10" style = "padding:0 0 0 0"> <span id = "name"> Ta Quynh Giang <!-- Name here--> </span> </p> <p class = "col-lg-11 col-md-10" style = "padding:0 0 0 0; display:inline"> <span> Marketing Manager - ABIVIN Vietnam, JSC. </span> </p> <div class = "col-lg-11 col-md-10" style = "padding:0 0 0 0; margin-top: 5px; display:inline"> <div class = "col-md-2 col-sm-4 info" style = "padding:0 0 0 0 ;display:inline"> <span id = "head-info"> M </span>&nbsp;&nbsp;+84 168 992 1733 </div> <div class = "col-md-2 col-sm-4 info" style = "padding:0 0 0 0; display:inline"> <span id = "head-info"> W </span>&nbsp;&nbsp;<a href = "abivin.com">http://abivin.com</a> </div> </div> <div class = "col-lg-11 col-md-10" style = "padding:0 0 0 0; margin-top: 5px; display:inline"> <div class = "col-md-2 col-sm-4 info" style = "padding:0 0 0 0; display:inline"> <span id = "head-info"> E </span>&nbsp;&nbsp;[email protected] </div> <div class = "col-md-3 col-sm-5 info" style = "padding:0 0 0 0; display:inline"> <span id = "head-info"> A </span>&nbsp;&nbsp;&nbsp;R503, 35 Lang Ha, Hanoi, Vietnam </div> </div> </div> A: I think you were missing a closing div tag to the whole code block ( certainly in the code posted above anyway ) which would throw the html alignment out in some instances. I have corrected that in the following - though I cannot test under the circumstances that you are using the code. <div class='col-lg-12 col-md-12' style='display:block'> <div class='col-xs-1 col-sm-1' style='padding:0;display:inline'> <img src='http://i.imgur.com/8wclWry.png' width='65px' height='65px' id='sigPhoto'> </div> <div class='col-lg-11 col-md-10' style='padding:0; display:inline'> <p class='col-lg-11 col-md-10' style='padding:0'> <span id='name'> Ta Quynh Giang <!-- Name here--> </span> </p> <p class='col-lg-11 col-md-10' style='padding:0; display:inline'> <span> Marketing Manager - ABIVIN Vietnam, JSC. </span> </p> <div class='col-lg-11 col-md-10' style='padding:0; margin-top: 5px; display:inline'> <div class='col-md-2 col-sm-4 info' style='padding:0 ;display:inline'> <span id='head-info'> M </span>&nbsp;&nbsp;+84 168 992 1733 </div> <div class='col-md-2 col-sm-4 info' style='padding:0; display:inline'> <span id='head-info'> W </span>&nbsp;&nbsp;<a href='http://abivin.com' target='_blank'>http://abivin.com</a> </div> </div> <div class='col-lg-11 col-md-10' style='padding:0; margin-top: 5px; display:inline'> <div class='col-md-2 col-sm-4 info' style='padding:0; display:inline'> <span id='head-info'> E </span>&nbsp;&nbsp;[email protected] </div> <div class='col-md-3 col-sm-5 info' style='padding:0; display:inline'> <span id='head-info'> A </span>&nbsp;&nbsp;&nbsp;R503, 35 Lang Ha, Hanoi, Vietnam </div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/30817313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: retrieving information from related tables with Zend Framework and Doctrine 1.2 After working hard in my ZF/Doctrine integration I'm having a problem "translating" my previous Zend_Db work into Doctrine. I used generate-models-db to create the models and I did got to access some properties form the view but only those concerning the table whose model I created like this: $usuarios = new Model_Users(); $usr = $usuarios->getTable()->findAll(); $this->view->show = $usr; Model_Users is related to two tables with this method: public function setUp() { parent::setUp(); $this->hasMany('Model_PlanillaUsers as PlanillaUsers', array( 'local' => 'id', 'foreign' => 'users_id')); $this->hasMany('Model_UsersHasPais as UsersHasPais', array( 'local' => 'id', 'foreign' => 'users_id')); } Right now I'm concerned about UsersHasPais...which tells me what pais.pais fields and which users.id entries match. This is the Model_Pais: abstract class Model_Base_Pais extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('pais'); $this->hasColumn('id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'primary' => true, 'autoincrement' => true, )); $this->hasColumn('pais', 'string', 20, array( 'type' => 'string', 'length' => 20, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, )); } public function setUp() { parent::setUp(); $this->hasMany('Model_UsersHasPais as UsersHasPais', array( 'local' => 'id', 'foreign' => 'pais_id')); } } And this is the join table: abstract class Model_Base_UsersHasPais extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('users_has_pais'); $this->hasColumn('id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'primary' => true, 'autoincrement' => true, )); $this->hasColumn('users_id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, )); $this->hasColumn('pais_id', 'integer', 4, array( 'type' => 'integer', 'length' => 4, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, )); } public function setUp() { parent::setUp(); $this->hasOne('Model_Users as Users', array( 'local' => 'users_id', 'foreign' => 'id')); $this->hasOne('Model_Pais as Pais', array( 'local' => 'pais_id', 'foreign' => 'id')); } } Now what I want to be able to retrieve,...if not clear enough is the fields called pais from the pais table that match with my current user id. How do I do this with Doctrine? EDIT: //Added to Model_Users class public function saveUser($user) { $this->email = $user['email']; $this->password = crypt($user['password'], $this->_salt); $this->url = $user['url']; $this->responsable = $user['responsable']; $this->role = $user['role']; $this->fecha = Zend_Date::now()->toString('yyyyMMddHHmmss'); $id = $this->save(); } //Users table schema Users: connection: 0 tableName: users columns: id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: true email: type: string(50) fixed: false unsigned: false primary: false notnull: false autoincrement: false password: type: string(250) fixed: false unsigned: false primary: false notnull: false autoincrement: false url: type: string(50) fixed: false unsigned: false primary: false notnull: false autoincrement: false responsable: type: string(50) fixed: false unsigned: false primary: false notnull: false autoincrement: false role: type: string(25) fixed: false unsigned: false primary: false notnull: false autoincrement: false fecha: type: timestamp(25) fixed: false unsigned: false primary: false notnull: true autoincrement: false relations: PlanillaUsers: local: id foreign: users_id type: many UsersHasPais: local: id foreign: users_id type: many A: In your controller write a query something like $cu = current_user_id // you'll have to set this your self from a session variable etc $q = Doctrine_Query::create() ->select('p.pais') ->from('Model_Pais p') ->leftJoin('p.Model_UsersHasPais s') ->leftJoin('s.Model_Users u') ->where('u.id = ?',$cu); $result = $q->fetchArray();
{ "language": "en", "url": "https://stackoverflow.com/questions/6216504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python get/set value of dict of dicts by key in variable I have dict of dicts in Python, it can be deep, not just 2 levels. data = { 0: { 1: { 2: "Yes" }, 3: { 4: "No" } }, } I need to get and set the data, but the key is dynamic and is stored in list key_to_get = [0,1,2] print(data.get(key_to_get)) Should print Yes Ideas? A: Here is a simple recursive function which solves the problem def getValue(dict, keys): if len(keys) == 1: return dict.get(keys[0]) return getValue(dict.get(keys[0]), keys[1:]) And an iterative approach if you're boring temp = data for key in key_to_get: temp = temp.get(key) print(temp)
{ "language": "en", "url": "https://stackoverflow.com/questions/52347116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: percentage count for pandas df grouped by multiple columns I have two pandas df. The data is grouped by month, category, product. It also has a spend column. I need to calculate the percentage of spend column. Below is the sample of df_raw: spend_sum category month product_list Home 1 A 10 B 20 C 30 Home 2 A 40 B 50 C 60 Below is the sample of df_new: spend_sum category month product_list Home 1 A 1 B 2 C 3 Home 2 A 20 B 10 C 5 My code is: df_raw = df.explode('product_list').groupby(['category', 'month', 'product_list']).count() I need to divide df_new['spend_sum'] / df_raw['spend_sum'] Desired output is: percentage category month product_list Home 1 A 0.1 B 0.1 C 0.1 Home 2 A 0.5 B 0.2 C 0.008 A: Just this will do: df_new['pct'] = df_new['spend_sum']/df_raw['spend_sum'] spend_sum pct category month product_list Home 1 A 1 0.100000 B 2 0.100000 C 3 0.100000 2 A 20 0.500000 B 10 0.200000 C 5 0.083333
{ "language": "en", "url": "https://stackoverflow.com/questions/63581624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does each IntentService get its own background thread? Apparently, all AsyncTasks share one thread: Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. An IntentService gets one thread and handles each Intent in turn: All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time. But if I have multiple IntentServices, does each get its own thread? Or does Android just use one thread that all IntentServices share? A: Apparently, all AsyncTasks share one thread: By default, yes. Use executeOnExecutor() to opt into a thread pool. In the documentation, the next paragraph after your quoted one is: If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.   But if I have multiple IntentServices, does each get its own thread? Yes. The source code to IntentService shows that it creates its own HandlerThread in onCreate().
{ "language": "en", "url": "https://stackoverflow.com/questions/23701156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create deep copy of List I read a lot of articles where people describes how to create a deep copy of list. But it requires a lot of code or work with memory streams. Is there any other easier way to create independent copy of List of class objects?
{ "language": "en", "url": "https://stackoverflow.com/questions/20095209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making subject for a matrix formula in Sympy I am new to sympy. I am working with sympy matrices. Is anybody knows about making a matrix as subject from a matrix equation? for examble if the equation is like following A+2B=C, here A,B and C are matrices. I want to make subject as B. So that the final answer must be looks like B=(C-A)/2. Is there any straight way in sympy to do this? A: The approach offered by asmeurer seems to be applicable: see How to solve matrix equation with sympy?. First, declare A, B and C to be non-commutative variables and obtain a solution to the equation. Second, re-define C and A as the desired arrays and then apply the formula to these arrays. >>> from sympy import * >>> A,B,C = symbols('A B C', commutative=False) >>> solve(A+2*B-C,B) [(-A + C)/2] >>> A = Matrix([2,2,1,5]) >>> C = Matrix([1,1,1,1]) >>> A = A.reshape(2,2) >>> C = C.reshape(2,2) >>> (-A + C)/2 Matrix([ [-1/2, -1/2], [ 0, -2]]) To answer the question in the comments: Define matrix C to be the zero matrix on the right of the equation and proceed as above. >>> A,B,C = symbols('A B C', commutative=False) >>> solve(2*A+B-C,A) [(-B + C)/2] >>> B = Matrix([1,4,3,5]) >>> B = B.reshape(2,2) >>> C = Matrix([0,0,0,0]) >>> C = C.reshape(2,2) >>> (-B + C)/2 Matrix([ [-1/2, -2], [-3/2, -5/2]])
{ "language": "en", "url": "https://stackoverflow.com/questions/41078758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dict Update method only adds last value I have the following code (link here) I have looked at similar posts and examples online but have not been able to understand / resolve the issue on why .update only adds the last value to the dictionary import json def main(): jsonData = {'CompanyId': '320193', 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2020-09-26'}, 'value': '39789000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2019-09-28'}, 'value': '50224000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2018-09-29'}, 'value': '25913000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2021-09-25'}, 'value': '35929000000'}], 'NetIncomeLoss': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'value': '94680000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'value': '57411000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'value': '55256000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '94680000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '57411000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '55256000000'}]} jsonDump = json.dumps(jsonData) actualJson = json.loads(jsonDump) finalJson = fixData(actualJson) print(finalJson) def fixData(jsonData): jsonDump = json.dumps(jsonData) actualJson = json.loads(jsonDump) finalObject = {} finalObject['CompanyId'] = actualJson.get("CompanyId") CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = actualJson.get( "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents") one = dataRepeat(CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents,"CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents") finalObject.update(one) NetIncomeLoss = actualJson.get("NetIncomeLoss") two = dataRepeat(NetIncomeLoss, "NetIncomeLoss") finalObject.update(two) return finalObject def dataRepeat(item, property): final = {} test = {} mList = [] super_dict = {} for i in item: decimals = i.get("decimals") unitRef = i.get("unitRef") if (i.get("period").get("startDate")): startDate = i.get("period").get("startDate") else: startDate = None if (i.get("period").get("endDate")): endDate = i.get("period").get("endDate") else: endDate = None if (i.get("period").get("instant")): instant = i.get("period").get("instant") else: instant = None propertyValue = i.get("value") final['Decimals'] = decimals final['UnitRef'] = unitRef final['StartDate'] = startDate final['EndDate'] = endDate final['Instant'] = instant final[f"{property}"] = propertyValue mList.append({"Decimals": final['Decimals']}), mList.append({"UnitRef": final['UnitRef']}), mList.append({"StartDate": final['StartDate']}), mList.append({"EndDate": final['EndDate']}), mList.append({"Instant": final['Instant']}), mList.append({f"{property}": final[f"{property}"]}) # ou = {} # for d in mList: # for key, value in d.items(): # ou.setdefault(key, []).append(value) # return ou ou = {} for d in mList: ou.update(d) return ou main() What I get : {'CompanyId': '320193', 'Decimals': '-6', 'UnitRef': 'usd', 'StartDate': '2018-09-30', 'EndDate': '2019-09-28', 'Instant': None, 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '35929000000', 'NetIncomeLoss': '55256000000'} vs Entire Data: {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': None} {'EndDate': None} {'Instant': '2020-09-26'} {'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '39789000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': None} {'EndDate': None} {'Instant': '2019-09-28'} {'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '50224000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': None} {'EndDate': None} {'Instant': '2018-09-29'} {'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '25913000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': None} {'EndDate': None} {'Instant': '2021-09-25'} {'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '35929000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': '2020-09-27'} {'EndDate': '2021-09-25'} {'Instant': None} {'NetIncomeLoss': '94680000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': '2019-09-29'} {'EndDate': '2020-09-26'} {'Instant': None} {'NetIncomeLoss': '57411000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': '2018-09-30'} {'EndDate': '2019-09-28'} {'Instant': None} {'NetIncomeLoss': '55256000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': '2020-09-27'} {'EndDate': '2021-09-25'} {'Instant': None} {'NetIncomeLoss': '94680000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': '2019-09-29'} {'EndDate': '2020-09-26'} {'Instant': None} {'NetIncomeLoss': '57411000000'} {'Decimals': '-6'} {'UnitRef': 'usd'} {'StartDate': '2018-09-30'} {'EndDate': '2019-09-28'} {'Instant': None} {'NetIncomeLoss': '55256000000'} Expected output would be where the finalJson contains all the data A: You have the lot of inefficiences in code that is detracting from an issue at hand. Ex: jsonDump = json.dumps(jsonData) actualJson = json.loads(jsonDump) What is the point? To equal just as: actualJson = jsonData Or even: actualJson = jsonData.copy() Next: finalObject = {} finalObject['CompanyId'] = actualJson.get("CompanyId") This can be to: finalObject = {'CompanyId' : actualJson.get("CompanyId") } Then: if (i.get("period").get("instant")): But i.get if not there, is None, so I think for in case your error, then don't handle as such: if (i["period"].get("instant")): And then also: f"{property}" Specifically, here: mList.append({f"{property}": final[f"{property}"]}) But what is property? I think it's just a string: property So: mList.append({property: final[property]}) A: What I see from your data: We know that a dictionary does not have duplicate keys: I want to show with an example: d={} list_of_dict=[{1:'a',2:'b'},{1:'c'}] Now, when you apply update: for x in list_of_dict: d.update(x) Now, you will get: #{1: 'c', 2: 'b'} You see update() will override the the value of key 1 from 'a' to 'c'. This is what exactly happening in your code
{ "language": "en", "url": "https://stackoverflow.com/questions/75175999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: C++ Segmentation Fault Confusing {CLOSED} I know that Seg Sault is caused by accessing data that isn't yours, but I don't see why this small bit of code to assign values to and print a 9X9 2d array returns Seg Fault. Please help! The code looks like this: using namespace std; #include <iostream>; #include <string>; string output = "|"; string topBoard[9][9]; int main() { for (int i = 0; i < 9; i++) { for (int ii = 0; ii < 9; ii++) { topBoard[i][ii] = "empty"; } } for (int ii = 0; ii < 9; ii++) { cout << "-----------------------------------------------------------------"; output = "|"; for (int i = 0; i < 9; i++) { output = output + topBoard[ii][i] + "|"; } cout << output; } return(0); }; Output: Segmentation Fault Process exited with code 139 Anyone have any idea why this might happen? EDIT: I use cloud9 if anyone wants to check it out, works great for working on your stuff just about anywhere. Further Editing: here is the code with all your edits: using namespace std; #include <iostream> #include <string> const int Height = 9; const int Width = 9; string output = "|"; string topBoard[Height][Width]; int main() { for (int i = 0; i < Height; i++) { for (int ii = 0; ii < Width; ii++) { topBoard[i][ii] = "empty"; } } for (int ii = 0; ii < Height; ii++) { cout << "-----------------------------------------------------------------"; output = "|"; for (int i = 0; i < Width; i++) { output = output + topBoard[ii][i] + "|"; } cout << output; } return(0); } A: This code runs perfectly fine in Visual Studio 2013. Only change is that the last semicolon needs to come after the return statement not after }. Here is the output: -----------------------------------------------------------------|empty|empty|em pty|empty|empty|empty|empty|empty|empty|empty|---------------------------------- -------------------------------|empty|empty|empty|empty|empty|empty|empty|empty| empty|empty|-----------------------------------------------------------------|em pty|empty|empty|empty|empty|empty|empty|empty|empty|empty|---------------------- -------------------------------------------|empty|empty|empty|empty|empty|empty| empty|empty|empty|empty|-------------------------------------------------------- ---------|empty|empty|empty|empty|empty|empty|empty|empty|empty|empty|---------- -------------------------------------------------------|empty|empty|empty|empty| empty|empty|empty|empty|empty|empty|-------------------------------------------- ---------------------|empty|empty|empty|empty|empty|empty|empty|empty|empty|empt y|-----------------------------------------------------------------|empty|empty| empty|empty|empty|empty|empty|empty|empty|empty|-------------------------------- ---------------------------------|empty|empty|empty|empty|empty|empty|empty|empt y|empty||empty|empty|empty|empty|empty|empty|empty|empty|empty||---------------- -------------------------------------------------|||empty|empty|empty|empty|empt y|empty|empty|empty|empty|
{ "language": "en", "url": "https://stackoverflow.com/questions/34349582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-7" }
Q: Vulkan Dynamic Buffer With Different Texture Per Object I am currently using a dynamic buffer to store the uniforms of multiple objects and update them individually without changing the shader. The problem is that when i am adding a VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER to my descriptor the render is this (I can't post images due to low reputation)! Just the color of the background of the texture. This is my initialization of the descriptor(). descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[0].dstSet = descriptorSet; descriptorWrites[0].pNext = NULL; descriptorWrites[0].dstBinding = 0; descriptorWrites[0].dstArrayElement = 0; descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; descriptorWrites[0].descriptorCount = 1; descriptorWrites[0].pBufferInfo = &bufferInfo; descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[1].dstSet = descriptorSet; descriptorWrites[1].pNext = NULL; descriptorWrites[1].dstBinding = 1; descriptorWrites[1].dstArrayElement = 0; descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrites[1].descriptorCount = 1; descriptorWrites[1].pImageInfo = &imageInfo; And this is my fragment shader: #version 450 #extension GL_ARB_separate_shader_objects : enable layout(set=0, binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 1) in vec2 fragTexCoord; layout(location = 0) out vec4 outColor; void main() { outColor = texture(texSampler, fragTexCoord*2); } What could be the reason of this? I have updated descriptor layout, and the validation layer don't throw any errors and the dynamic buffer was working perfectly even for multiple objects. Is the binding corrupted or something like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/50205777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: overflow-y scroll and overflow hidden issue in pop-up window I have a problem, and I cant find solution for that.. I have pop-up window, positioning fixed and 100% height and width. I want to set overflow-y: scroll to block .item-details, if there be much content - user can scroll, but only that block .item-details. I have already set that .item-details { border-top: 1px solid #e7e7e7; padding-top: 38px; overflow-y: scroll; } but it dont work.. Here is JsFiddle DEMO, thanks for any help. A: You are missing a height attribute on .item-details Is this what you're after? DEMO
{ "language": "en", "url": "https://stackoverflow.com/questions/25002123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adjusting height and width of div and its contents I am trying to adjust the height and width of an HTML parent Div without changing the child div styles. Is there any option to adjust the div dimensions? Example Scenario: I have a tree that I am planning to use as a common code to create multiple trees. One small one big etc. So without changing the tree leaves and stem styles(child divs inside parent div), do we have an option to change parent div dimensions so that child divs will be automatically adjusted accordingly? My fiddle is here <div class="tree" style="position:absolute;left:20px;right:20px; height:200px;width:200px; "> <div id="leaf1" style="height:90px;width:90px;background-color:green;border-radius:60px;position:absolute;left:40px;top:80px;"></div> <div id="leaf2" style="height:90px;width:90px;background-color:green;border-radius:60px;position:absolute;left:100px;top:85px;"></div> <div id="leaf3" style="height:90px;width:90px;background-color:green;border-radius:60px;position:absolute;left:80px;top:40px;"></div> <div id="stem" style="height: 150px;width: 30px;background-color: brown;position: absolute;left: 100px;top: 100px; z-index:-1;"></div> </div> A: build this using only background instead of inner divs and rely on percentage values: .tree { border:1px solid; width:100px; display:inline-block; background: radial-gradient(circle at 36% 51%,green 22%,transparent 23%), radial-gradient(circle at 52% 37%,green 22%,transparent 23%), radial-gradient(circle at 64% 52%,green 22%,transparent 23%), linear-gradient(brown,brown) bottom/15% 50%; background-repeat:no-repeat; } .tree:before { content:""; display:block; padding-top:150%; } <div class="tree"></div> <div class="tree" style="width:200px;"></div> <div class="tree" style="width:250px;"></div> <div class="tree" style="width:50px;"></div> A: I am not sure why you cannot do it: Also keep the css code separate it is easy to manage, I have modified for you. <style> .tree { border: 1px solid black; position: relative; left: 20px; right: 20px; height: 300px; /* you can do it here */ width: 300px; /* you can do it here */ } #leaf1 { height: 90px; width: 90px; background-color: green; border-radius: 60px; position: absolute; left: 40px; top: 80px; } #leaf2 { height: 90px; width: 90px; background-color: green; border-radius: 60px; position: absolute; left: 100px; top: 85px; } #leaf3 { height: 90px; width: 90px; background-color: green; border-radius: 60px; position: absolute; left: 80px; top: 40px; } #stem { height: 150px; width: 30px; background-color: brown; position: absolute; left: 100px; top: 100px; z-index: -1; } </style> <div class="tree">Parent Div <div id="leaf1"></div> <div id="leaf2"></div> <div id="leaf3"></div> <div id="stem"></div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/60910728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Git pull the last push that was done I have made many changes to my source files and would just like to pull the last push that was done. I would like it to delete any new files, and revert modified files to the last version. I basically want to just revert to how the origin master last was. Is there a way to do this without deleting the directory, re-initializing git, and then cloning the repo? A: git reset --hard will bring you back to the last commit, and git reset --hard origin/master will bring you back to origin/master. A: You can revert the change Read more: http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html A: Another option is just to discard all your changes git checkout . And then git pull
{ "language": "en", "url": "https://stackoverflow.com/questions/10057000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the UITextField placeholder text decreasing in size? I have a peculiar problem in Interface Builder with placeholder text. Some of the placeholder text is smaller than the rest and I can't find a reason why. When I duplicate a UITextfield with full-sized placeholder text it changes instantly to a smaller font. Xcode 6.1.1 on Mac OS X 10.10.2 A: This is just a visual bug in Xcode 6. Whenever you copy an element with text, that text's font-size seems to visually be altered. However, when you build and run the app, it should show up normal on your device or simulator. You can fix the visual bug by clicking on the copied element, going to the attributes inspector, and then changing the font-size down one and then back up one.
{ "language": "en", "url": "https://stackoverflow.com/questions/28290564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: pattern matching, tuples and multiplication in Python What is be best way to reduce this series of tuples ('x', 0.29, 'a') ('x', 0.04, 'a') ('x', 0.03, 'b') ('x', 0.02, 'b') ('x', 0.01, 'b') ('x', 0.20, 'c') ('x', 0.20, 'c') ('x', 0.10, 'c') into: ('x', 0.29 * 0.04 , 'a') ('x', 0.03 * 0.02 * 0.01, 'b') ('x', 0.20 * 0.20 * 0.10, 'c') EDIT: X is a constant, it is known in advance and can be safely ignored And the data can be treated as pre-sorted on the third element as it appears above. I am trying to do it at the moment using operator.mul, and a lot of pattern matching, and the odd lambda function... but I'm sure there must be an easier way! Can I just say thank you for ALL of the answers. Each one of them was fantastic, and more than I could have hoped for. All I can do is give them all an upvote and say thanks! A: Here's a functional programming approach: from itertools import imap, groupby from operator import itemgetter, mul def combine(a): for (first, last), it in groupby(a, itemgetter(0, 2)): yield first, reduce(mul, imap(itemgetter(1), it), 1.0), last A: Here's a more stateful approach. (I like @Sven's better.) def combine(a) grouped = defaultdict(lambda: 1) for _, value, key in a: grouped[key] *= value for key, value in grouped.items(): yield ('x', value, key) This is less efficient if the data are already sorted, since it keeps more in memory than it needs to. Then again, that probably won't matter, because it's not stupidly inefficient either. A: Given that you are ultimately going to multiply together all of the found values, instead of accumulating a list of the values and multiplying them at the end, change your defaultdict to take an initializer method that sets new keys to 1, and then multiply as you go: data = [('x', 0.29, 'a'), ('x', 0.04, 'a'), ('x', 0.03, 'b'), ('x', 0.02, 'b'), ('x', 0.01, 'b'), ('x', 0.20, 'c'), ('x', 0.20, 'c'), ('x', 0.10, 'c'),] from collections import defaultdict def reduce_by_key(datalist): proddict = defaultdict(lambda : 1) for _,factor,key in datalist: proddict[key] *= factor return [('x', val, key) for key,val in sorted(proddict.items())] print reduce_by_key(data) Gives: [('x', 0.011599999999999999, 'a'), ('x', 5.9999999999999993e-06, 'b'), ('x', 0.004000000000000001, 'c')]
{ "language": "en", "url": "https://stackoverflow.com/questions/11004838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python: Add values to dictionary Let say we have an array of positive integers and some integer x/ Each element in the array represents a missions and it's difficulty level and we want to find the minimum number of days to complete all the missions. The difference between the difficult level of any two mission performed on the same day should not be greater than an integer x. For example: Arr = [5,8,2,7] x = 3 5 and 8 can be performed in the first day 2 on the second day and 7 in the last day I would like to get the following result: dict = {key1:[5,8],key2:[2],key3:[3]} A: your question is a little vague as to what the answer could be, did you want a value to return true if this is the case? did you want to gauruntee a way to fill the dictionary in a way where your condition is true? if you want to check that your condition is true, try: bool_dict = {} for key, val in dict.items(): if max(val)-min(val)>x: bool_list[key]=False else: bool_dict[key]=True print(bool_dict) A: Here's my implementation: def missions_to_dict(arr, x): curr_key = 1 last_mission = arr[0] dict = {"key1": [last_mission]} # Loop through all missions for curr_mission in arr[1:]: # Check to see if current mission is x away from last mission if abs(curr_mission - last_mission) <= x: # Add it to same key as last mission dict[f"key{curr_key}"].append(curr_mission) # Otherwise, need to create new key else: curr_key += 1 dict[f"key{curr_key}"] = [curr_mission] # Set current mission to last mission last_mission = curr_mission return dict
{ "language": "en", "url": "https://stackoverflow.com/questions/73227081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How can I natively launch an external app from within Xamarin.Forms? As the question title suggests, I'm looking for a way to launch an external app from within a Xamarin.Forms app. For example, my app has a list of addresses, and when the user taps on one of them, the built-in map app for the current platform would open (Google Maps for Android, Apple Maps for iOS). In case it matters, I am only targeting Android and iOS. I could use a dependency service and write the app-launching code on a per-platform basis, of course, but I'd prefer if I only had to write it once. Is there a native way to do this in Xamarin.Forms? I was unable to find anything that officially documented this on the Xamarin site or forums. A: Use Device.OpenUri and pass it the appropriate URI, combined with Device.OnPlatform to format the URI per platform string url; Device.OnPlatform(iOS: () => { url = String.Format("http://maps.apple.com/maps?q={0}", address); }, Android: () => { url = String.Format("http://maps.google.com/maps?q={0}", address); }); Device.OpenUri(url); A: As of Xamarin.Forms v4.3.0.908675 (probably v4.3.0) Device.OpenUri is deprecated and you should use Launcher.TryOpenAsync from Xamarin.Essentials instead. Although you will find it troublesome, or at least I did. A: Use Below code, and add namespaces Xamarin.Essentials and Xamarin.Forms if (Device.RuntimePlatform == Device.iOS) { // https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html await Launcher.OpenAsync("http://maps.apple.com/?daddr=San+Francisco,+CA&saddr=cupertino"); } else if (Device.RuntimePlatform == Device.Android) { // opens the 'task chooser' so the user can pick Maps, Chrome or other mapping app await Launcher.OpenAsync("http://maps.google.com/?daddr=San+Francisco,+CA&saddr=Mountain+View"); } else if (Device.RuntimePlatform == Device.UWP) { await Launcher.OpenAsync("bingmaps:?rtp=adr.394 Pacific Ave San Francisco CA~adr.One Microsoft Way Redmond WA 98052"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/34643604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use the new AndroidX Media2? I am using Media App Architecture as a guide for building a music player app. But it uses the classes from support media-compat / Androidx Media. But now AndroidX Media2 is available in stable channels and I don't see any word of it. What is it? * *is AndroidX Media2 supposed to deprecate AndroidX Media? *is there a developer guide or other sources of documentation for AndroidX Media2? Please, no links to JavaDoc, thanks. A: Jetpack Media3 has launched! https://developer.android.com/jetpack/androidx/releases/media3 This blog post gives a great explanation about how the media libraries evolved. I strongly recommend integrating with androidx.media3. If for whatever reason you cannot use androidx.media3, my recommendation is to stick with androidx.media instead of androidx.media2 due to the latter not being supported by other media integrations, such as Cast Connect. Integrating Media2 with ExoPlayer is also quite a bit more complex. From my perspective, the key benefit of switching from Media1 to Media2 is the ability to provide more fine-grained permission controls. See Jaewan Kim's blog post that goes in depth about the more complex SessionPlayerConnector API and permissions to accept or reject connections from a controller in media2. If you have an existing Media1 implementation using MediaSession (preferably using ExoPlayer with MediaSessionConnector), and have no need for the permission controls in Media2, you can either stick with Media1 or upgrade to Media3. The “What's next for AndroidX Media and ExoPlayer” talk from Android Dev Summit 2021 goes much more in depth on Media3. A: All the documentation I was able to find was useless and outdated. androidx.media and the appcompat media libraries are both superseded by androidx.media2 (but not deprecated for some reason). The most high-level API for media apps appears to be MediaLibraryService for the service and MediaBrowser for the frontend. Just make absolutely sure you declare the right intent filters on the service (which are in the javadoc :P) A: Here is my working solution using Media2 libs (AndroidX): * *Add 3 dependencies in Build.gradle implementation "androidx.media2:media2-session:1.2.0" implementation "androidx.media2:media2-widget:1.2.0" implementation "androidx.media2:media2-player:1.2.0" *Create layout activity_video_player.xml and put this code into it: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/accompany_agent_details" style="@style/Layout.Default"> <LinearLayout android:id="@+id/videoLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:orientation="vertical"> <android.widget.VideoView android:id="@+id/simpleVideoView" android:layout_width="match_parent" android:layout_height="300dp" /> </LinearLayout> </RelativeLayout> <style name="Layout.Default"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">match_parent</item> </style> *Create activity class SimpleVideoActivity: public class VideoPlayerActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_player_android_x); VideoView simpleVideoView = findViewById(R.id.simpleVideoView); MediaMetadata mediaMetaData = new MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_TITLE, "Put your video text here").build(); UriMediaItem item = new UriMediaItem.Builder(Uri.parse("Put your video URL here")).setMetadata(mediaMetaData).build(); MediaPlayer mediaPlayer = new MediaPlayer(this); simpleVideoView.setPlayer(mediaPlayer); mediaPlayer.setMediaItem(item); mediaPlayer.prepare(); mediaPlayer.play(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65224178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Toggle class with expand/collapse all multiple accordions I am having trouble with a jquery script I am trying to write. It looks right to me but not quite there yet. Can someone please help me understand why this isn't working? jQuery('.expand').click(function(){ jQuery('.expandnav').find('div.menu-body').show('slow'); if( ('.menu-body').is(':visible') ){ (this).addClass('collapse-active'); }else{ (this).removeClass('collapse-active'); } }); When .expand is clicked .menu-body does show but the conditional doesn't seem to run. I have tested with alerts and no response... i am using toggleClass on each individual accordion as there are many to the page but I need the addClass/removeClass to swap the +,- images. Hope that makes sense. Bottom line is the conditional is not responding. Any help is greatly appreciated A: You'll want to use the callback method of $.fn.show, read more at http://api.jquery.com/show/ Here's a fiddle showing the proposed change: http://jsfiddle.net/pewt8/
{ "language": "en", "url": "https://stackoverflow.com/questions/12434805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using profile and boot method within confint option, with glmer model I am using glmer with a logit link for a gaussian error model. When I try obtaining the confidence intervals, using either profile or the boot method with the confint option, I obtain an error for use of profile likelihood, and with bootstrapping: > Profile: Computing profile confidence intervals ... Error in > names(opt) <- profnames(fm, signames) : 'names' attribute [2] must > be the same length as the vector [1] > > Boot: Error in if (const(t, min(1e-08, mean(t, na.rm = TRUE)/1e+06))) > { : missing value where TRUE/FALSE needed In addition: Warning > message: In bootMer(object, FUN = FUN, nsim = nsim, ...) : some > bootstrap runs failed (9999/10000) I have looked at online suggestions on how to overcome the profile issue, by installing the lme4 development tool and I have also eliminated all NAs from the dataset. However, in both instances, I still receive the same two error messages. Is anybody able to offer any help as to whether this is a lme4 issue, or whether it's more fundamental. Here is code to produce the first 20 observations and the model format: df2 <- data.frame( prop1 = c(0.46, 0.471, 0.458, 0.764, 0.742, 0.746, 0.569, 0.45, 0.491, 0.467, 0.464, 0.556, 0.584, 0.478, 0.456, 0.46, 0.493, 0.704, 0.693, 0.651), prop2 = c(0.458, 0.438, 0.453, 0.731, 0.738, 0.722, 0.613, 0.498, 0.452, 0.451, 0.447, 0.48, 0.576, 0.484, 0.473, 0.467, 0.467, 0.722, 0.707, 0.709), site = c(1,1,2,3,3,3,4,4,4,4,4,5,5,5,6,6,7,8,8,8) ) df2$site <- factor(df2$site) model <- glmer(prop2 ~ prop1 + (1|site), data=df2, family=gaussian(link="logit")) summary(model) The response is a proportion (0,1), as is the covariate. I have used the logit link to keep the expected values of the response bound between (0,1), rather than being unbound with the normal, though this data fits a LMM reasonably well. I will also analyse the difference between the two proportions, for which I expect some differences (and fitted values) to violate the (0,1) boundary - so I will model this with either an identity link with gaussian error, or logit link on the scaled difference (coercing this to be (0,1)). Also, given that there may only be 1-5 records per site, I will naturally consider running linear regression or GLM (proportions), and treat site as a fixed effect in the modelling process, if the estimate of the random effects variance is zero (or very small). A: For your example it works with bootstrap: confint(model, method = "boot") # 2.5 % 97.5 % # .sig01 12.02914066 44.71708844 # .sigma 0.03356588 0.07344978 # (Intercept) -5.26207985 1.28669024 # prop1 1.01574201 6.99804555 Take into consideration that under your proposed model, although your estimation will be always between 0 and 1, it is expected to observe values lower than 0 and greater than 1. A: You've identified a bug with the current version of lme4, partially fixed on Github now (it works with method="boot"). (devtools::install_github("lme4/lme4") should work to install it, if you have development tools installed.) library(lme4) fit_glmer <- glmer(prop2 ~ prop1 + (1|site), data=df2, family=gaussian(link="logit")) Profiling/profile confidence intervals still don't work, but with a more meaningful error: try(profile(fit_glmer)) ## Error in profile.merMod(fit_glmer) : ## can't (yet) profile GLMMs with non-fixed scale parameters Bootstrapping does work. There are lot of warnings, and a lot of refitting attempts failed, but I'm hoping that's because of the small size of the data set provided. bci <- suppressWarnings(confint(fit_glmer,method="boot",nsim=200)) I want to suggest a couple of other options. You can use glmmADMB or glmmTMB, and these platforms also allow you to use a Beta distribution to model proportions. I would consider modeling the difference between proportion types by "melting" the data (so that there is a prop column and a prop_type column) and including prop_type as a predictor (possibly with an individual-level random effect identifying which proportions were measured on the same individual) ... library(glmmADMB) fit_ADMB <- glmmadmb(prop2 ~ prop1 + (1|site), data=df2, family="gaussian",link="logit") ## warning message about 'sd.est' not defined -- only a problem ## for computing standard errors of predictions, I think? library(glmmTMB) fit_TMB <- glmmTMB(prop2 ~ prop1 + (1|site), data=df2, family=list(family="gaussian",link="logit")) It sounds like your data might be more appropriate for a Beta model? fit_ADMB_beta <- glmmadmb(prop2 ~ prop1 + (1|site), data=df2, family="beta",link="logit") fit_TMB_beta <- glmmTMB(prop2 ~ prop1 + (1|site), data=df2, family=list(family="beta",link="logit")) Compare results (fancier than it needs to be) library(broom) library(plyr) library(dplyr) library(dwplot) tab <- ldply(lme4:::namedList(fit_TMB_beta, fit_ADMB_beta, fit_ADMB, fit_TMB, fit_glmer), tidy,.id="model") %>% filter(term != "(Intercept)") dwplot(tab) + facet_wrap(~term,scale="free", ncol=1)+theme_set(theme_bw())
{ "language": "en", "url": "https://stackoverflow.com/questions/37466771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to offer a chooser to get content for multiple mime types? I want to have one button in my app that lets the user pick images or any other files from the apps on the device. Here's the code in my activity for letting the user pick files from apps such as Dropbox and Drive: private static int RESULT_GET_CONTENT = 1; public void getFileContent() { Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT); fileIntent.setType("file/*"); startActivityForResult(fileIntent, RESULT_GET_CONTENT); } That brings up a list of the available apps. When the user chooses one that app lets him browse the files. To pick images from the Gallery I can change the intent's type to "image/*". How do I change this to bring up a list of apps that includes files apps (Dropbox & Drive) and image apps (Gallery)? A: It turns out that the solution is very simple. I just needed to use "*/*" as the type and then add the openable category which filters out things like contacts that I don't want. public void getFileContent() { Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT); fileIntent.setType("*/*"); fileIntent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(fileIntent, RESULT_GET_CONTENT); }
{ "language": "en", "url": "https://stackoverflow.com/questions/19017172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Running batch jobs in Pivotal Cloud foundary We have a requirement to migrate mainframe batch jobs to PCF cloud but as 3R's of security Rotate, Repave and Repair it might be possible that in the instance where batch job is running as spring batch that instance can be repaved/repair and our running jobs got terminated. In that scenario how to ensure that during repavement/repair of an PCF instance our jobs will not get impacted. We are looking for best way to migrate jobs in PCF cloud, any help/suggestion will be really helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/73137226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use flavors to set different endpoints to my app? I've an app and I want to have an English version too (It's only in Spanish now). I've already created all the strings and resources, and I want to use them and set different endpoints to my app whether it's the english version or the spanish one. How can I do that? I know I could use flavors but I've never read about setting different endpoints with flavors, is it possible to use flavors or do I have to use something else? P.S.: By "endpoints" I mean servers that answer http REST requests Thanks! A: So you would have 2 different folders values and values-es. The best way for you is to create config.xml file in both folders with different url e.g.: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="endpoint">http://endpoint.com/en/index.html</string> </resources> To get the value for particular language you would get it like ordinary string: context.getString(R.string.endpoint); A: Flavours is not what you want to use because then you will build different APK file. You probably want to have a unique app with different languages capability. The Android doc has a great explanation about how to do this : http://developer.android.com/training/basics/supporting-devices/languages.html
{ "language": "en", "url": "https://stackoverflow.com/questions/37059346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setf variable to computing time? I want to set variable to computing time like this (setf a (time (+ 1 1))) but instead of time I get this Break 1 [7]> a 2 How can I set a to computing time? A: Use GET-INTERNAL-RUN-TIME (or GET-INTERNAL-REAL-TIME): (setf a (let ((start (get-internal-run-time))) (+ 1 1) ;This is the computation you want to time. (- (get-internal-run-time) start))) Divide by INTERNAL-TIME-UNITS-PER-SECOND if you want the result in seconds. You would probably want to make a function or macro if you do this a lot. A: See the answer of Lars. TIME writes implementation dependent information to the trace output. If you want its output as a string: (with-output-to-string (*trace-output*) (time (+ 1 1)))
{ "language": "en", "url": "https://stackoverflow.com/questions/19112016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query parameters for root component in Angular IO I have a very simple Angular 4+ application that fetches data from API and displays the data. I believe this should be possible by using just the root component:{path: 'main', component: MainComponent} and QueryParams like ?id=1. I am able to fetch the query param, but for some reason my router repeats the route+params part of the URL after the already existing route+params part. For example my local address malforms from localhost:4200/main?id=1 into localhost:4200/main?id=1/main?id=1. The ActivatedRoute does pick the correct query parameter from the URL but I would like to keep the URL as sanitized as possible. How do I prevent this duplication from happening? I have set <base href='/'> as per routing requirements in my index.html. Module: @NgModule({ imports: [ BrowserModule, RouterModule, RouterModule.forRoot( [ { path: 'main', component: MainComponent}, ]), CommonModule, HttpModule, FormsModule, NgbModule.forRoot() ], declarations: [MainComponent], providers: [ {provide: APP_BASE_HREF, useValue: window.document.location.href}, DataService, WindowService, HttpUtil ], bootstrap: [MainComponent] }) export class MainModule{} Component: @Component({ selector: 'main-component', templateUrl: './main.component.html', styleUrls: ['./main.component.css'] }) export class MainComponent implements OnInit { constructor(private dataService: DataService, private activatedRoute: ActivatedRoute) { } ngOnInit() { this.activatedRoute.queryParams.subscribe((params: Params) => { if (!(Object.keys(params).length === 0 && params.constructor === Object)) { console.log(params); } }); } } A: This is caused by your APP_BASE_HREF {provide: APP_BASE_HREF, useValue: window.document.location.href} You are telling the app to use window.document.location.href main?id=1 as your basehref. Angular then appends its own routes to the end of the basehref. This is why you are getting the duplication localhost:4200/main?id=1(< APP_BASE_HREF)/main?id=1(< ROUTE) Here are the docs on the functionality of APP_BASE_HREF (https://angular.io/api/common/PathLocationStrategy#description)
{ "language": "en", "url": "https://stackoverflow.com/questions/47265602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make Discord-Bot to reply same message for any command I want my bot to reply the same message for no matter whatever command it receives. I know how to reply to commands when they are knows but here I want to reply a particular string irrespective of the command. I tried: [Command("")] public async Task gg() { await ReplyAsync("gg"); await Context.Channel.SendMessageAsync("hi there"); } but apparently I get a runtime error as it can not add a blank or null command. (error log is useless) Not placing the [Command(string)] at all would never trigger the task for what I could make out. A: Assuming that you where following the Discord.NET documentation tutorials in setting up a command service... You probably have a HandleCommand function, or something equivalent to that. It should contain a line of code that looks like this: if(!(message.HasStringPrefix("PREFIX", ref argPos))) return; Which basically means "if this message does not have the prefix at the start, exit the function". (Where message is a SocketUserMessage and argPos is a int, usually 0) Put your line of code after that, so it would look like this... //Blah if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; } await message.Channel.SendMessageAsync("blah"); //stuff But, if you want the bot to only reply if the bot doesn't find a suitable command for the current command the user send, you can do this instead: if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; } var context = new CommandContext(client, message); var result = await commands.ExecuteAsync(context, argPos, service); if(!result.IsSuccess) { //If Failed to execute command due to unknown command if(result.Error.Value.Equals(CommandError.UnknownCommand)) { await message.Channel.SendMessageAsync("blah"); } else { //blah } } A: It's not possible to implement this as a command. You have to subscribe to the MessageReceived Event of your DiscordSocketClient and simply send a message back to the channel when it fires. private async Task OnMessageReceived(SocketMessage socketMessage) { // We only want messages sent by real users if (!(socketMessage is SocketUserMessage message)) return; // This message handler would be called infinitely if (message.Author.Id == _discordClient.CurrentUser.Id) return; await socketMessage.Channel.SendMessageAsync(socketMessage.Content); }
{ "language": "en", "url": "https://stackoverflow.com/questions/50813554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Three.js support OES_texture_float? I want to render position or depth to a floating texture. I use vsnTexture = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat ,type:THREE.FloatType }); as the render target. Then, I tested var gl = this.renderer.getContext(); if( !gl.getExtension( "OES_texture_float" ) ){ console.error( "No OES_texture_float support for float textures!" ); } and found no error. Chrome supports OES_texture_float, and I step into THREE.js: _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); //console.log(glType); I found glType =5126(gl.FLOAT) ,when I set the WebGLRenderTarget:type:THREE.FloatType. This means I could use OES_texture_float. Do I have something wrong? Because whatever I set the type:THREE.FloatType or use the default ( THREE.UnsignedByteType), I both get the same render texture. Am I not using the OES_texture_float correctly? A: Yes, it does. This example shows how to use it: http://threejs.org/examples/#webgl_gpgpu_birds
{ "language": "en", "url": "https://stackoverflow.com/questions/24126042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: UITableView scrollToRow breaks UIView.animate() in UITableViewCell I want to create a chat-like view, and in order to simulate a message being written, I have added a dot-bubble cell, with the dot's alphas animating from 0 to 1. I have added this animation in the custom cell's layoutSubviews() method. However, I am also calling tableView.scrollToRow() so the table view always shows the last cells to the user. But I realized that calling this method would break the animations inside of my cells (whether I am animating or not the scrollToRow() method). What should I do? Thanks for your help. A: Just create two instance method in Your typing indicator cell one for start animation and another for resetAnimation class TypingCell: UITableViewCell { fileprivate let MIN_ALPHA:CGFloat = 0.35 @IBOutlet weak var dot0: UIView! @IBOutlet weak var dot1: UIView! @IBOutlet weak var dot2: UIView! private func startAnimation() { UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: [.repeat, .calculationModeLinear], animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1666, animations: { self.dot0.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.16, relativeDuration: 0.1666, animations: { self.dot0.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 0.33, relativeDuration: 0.1666, animations: { self.dot1.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.49, relativeDuration: 0.1666, animations: { self.dot1.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 0.66, relativeDuration: 0.1666, animations: { self.dot2.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.83, relativeDuration: 0.1666, animations: { self.dot2.alpha = 1 }) }, completion: nil) } func resetAnimation() { dot0.layer.removeAllAnimations() dot1.layer.removeAllAnimations() dot2.layer.removeAllAnimations() DispatchQueue.main.async { self.startAnimation() } } } Reset your animation on tableView(_: willDisplay: cell: forRowAt:) func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? TypingCell { cell.resetAnimation() } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53965618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set current date to a fixed value in hsqldb? For my unit tests I need to freeze the current date. Otherwise the unit tests that work today will break next week. Is there a way to freeze the current date (or sysdate) in HSQLDB?
{ "language": "en", "url": "https://stackoverflow.com/questions/38154486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Restrict Multiple Items in Json I am creating a JSON schema in which a field is a array field and can have two custom types. Now i want that this field can have one custom type with max item as 1 and another as 0 to n. "field-1": { "type": "array", "system-generated": true, "anyOf": [{ "items": { "$ref": "customItem1" } }, { "items": { "$ref": "customItem2" } } ] } Considering the above same, i want that field-1 have customItem1 max one instance and customItem2 have zero to n instances. A: Unfortunately, there is no way to enforce that an array contains a specific number of something. The closest you can do is to enforce that something exists (1 to n) in an array. If "customItem1" is always the first item, it can be done. { "type": "array", "anyOf": [ { "items": [ { "$ref": "#/definitions/customItem1" } ], "additionalItems": { "$ref": "#/definitions/customItem2" }, }, { "items": { "$ref": "#/definitions/customItem2" } } ], "definitions": { "customItem1": { "type": "string" }, "customItem2": { "type": "boolean" } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/50830226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to deal with large data in Apriori algorithm? I would like to analyze customer data from my e-shop using association rules. These are steps that I took: First: My dataframe raw_data has three columns ["id_customer","id_product","product_quantity"] and it contains 700,000 rows. Second: I reorder my dataframe and I get a dataframe with 680,000 rows and 366 columns: customer = ( raw_data.groupby(["id_customer", "product_id"])["product_quantity"] .sum() .unstack() .reset_index() .fillna(0) .set_index("id_customer") ) customer[customer != 0] = 1 Finally: I would like to create a frequency of items: from mlxtend.frequent_patterns import apriori frequent_itemsets = apriori(customer, min_support=0.00001, use_colnames=True) but now I got an error MemoryError: Unable to allocate 686. GiB for an array with shape (66795, 2, 689587) and data type float64 How to fix it? Or how to compute frequent_itemsets without using apriori function? A: If you have data that is too large to fit in memory, you may pass a function returning a generator instead of a list. from efficient_apriori import apriori as ap def data_generator(df): """ Data generator, needs to return a generator to be called several times. Use this approach if data is too large to fit in memory. """ def data_gen(): yield [tuple(row) for row in df.values.tolist()] return data_gen transactions = data_generator(df) itemsets, rules = ap(transactions, min_support=0.9, min_confidence=0.6)
{ "language": "en", "url": "https://stackoverflow.com/questions/69521918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to use two @* in an xpath selector to select an element? I have an HTML element I would like to select that looks like this: <button data-button-id="close" class="modal__cross modal__cross-web"></button> Now clearly I can use this XPath selector: //button[(contains(@data-button-id,'close')) and (contains(@class,'modal'))] to select the element. However, I would really like to select buttons that have both close and modal contained in any attributes. So I can generalize the selector and say: //button[(contains(@*,'close')) and (contains(@class,'modal'))] and that works. What I'd love to do is extend it to this: //button[(contains(@*,'close')) and (contains(@*,'modal'))] but that doesn't return any results. So clearly that doesn't mean what I'd like it to mean. Is there a way to do it correctly? Thanks, Craig A: It looks like you're using XPath 1.0: in 1.0, if you supply a node-set as the first argument to contains(), it takes the first node in the node-set. The order of attributes is completely unpredictable, so there's no way of knowing whether contains(@*, 'close') will succeed or not. In 2.0+, this gives you an error. In both 1.0 and 2.0, @*[contains(., 'close')] returns true if any attribute contains "close" as a substring. A: This expression works: //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]] Given this html <button data-button-id="close" class="modal__cross modal__cross-web"></button> <button key="close" last="xyz_modal"></button> Testing with xmllint echo -e 'cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]\nbye' | xmllint --html --shell test.html / > cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]] ------- <button data-button-id="close" class="modal__cross modal__cross-web"></button> ------- <button key="close" last="xyz_modal"></button> / > bye A: Try this one to select required element: //button[@*[contains(., 'close')] and @*[contains(., 'modal')]]
{ "language": "en", "url": "https://stackoverflow.com/questions/72410786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pass arguement to custom permision class in django I have a custom permission class that extends the rest framework base permission. I am trying to pass an argument allowed_groups that will be a list of all the groups that have access to the particular view. This is my current custom permission implementation. class CustomUserPermisions(BasePermission): message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): allowed_groups = [ 'group_hr', 'super_admin', 'employee'] user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in allowed_groups: return True return False I have tried adding an argument as follows. class CustomUserPermisions(BasePermission, allowed_groups): message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): allowed_groups = [ 'group_hr', 'super_admin', 'employee'] user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in allowed_groups: return True return False but this is the error I am currently receiving. class CustomUserPermisions(BasePermission, allowed_groups): NameError: name 'allowed_groups' is not defined Is there a better way that I can do this? A: I guess you are a newcomer to python. You should read https://docs.python.org/3/tutorial/classes.html to get better understanding about python classes. class CustomUserPermisions(BasePermission, allowed_groups): means that the class CustomUserPermisions inherits from the classes BasePermission and allowed_groups. allowed_groups is not a class, so you get an error. You should create a class attribute for allowed group : class CustomUserPermisions(BasePermission): def __init__(self, allowed_groups): self.allowed_groups = allowed_groups self.message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in self.allowed_groups: return True return False and then call the class constructor : permissions = CustomUserPermisions(['group_hr', 'super_admin', 'employee'])
{ "language": "en", "url": "https://stackoverflow.com/questions/73384214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you track down JavaScript's "Unexpected token" errors when you get an irrelevant line number? I've looked through a few questions about JavaScript reporting an unexpected token without giving a helpful line number (line 1 at localhost/index.html is "<!DOCTYPE html>"): Uncaught SyntaxError: Unexpected token u localhost:/1 Now I've seen a number of "Uncaught SyntaxError" posts, but I wanted to step back one meta-level and ask not just what is wrong with my current code (React JSX is at http://pastebin.com/P3Epzi0q and the HTML at http://pastebin.com/0abjnmZz is not particularly interesting), but how to best pin down what to do when dealing with an "Uncaught SyntaxError" that includes only irrelevant attribution as to where the culprit is. My present attempt, besides using breakpoints and stepping through, is to drill down on where in my code it is happening. I am loading external sources including Showdown, jQuery, and ReactJS, but the crash is occurring between the two console.log() statements in my code: console.log("Reached 10"); React.render(<Pragmatometer />, document.getElementById('main')); console.log("Reached 11"); That's still an awful lot of territory, and I am drilling down to try and see where is the last place I can place a console.log() statement that happens before the crash, and what is the earliest place I can place a console.log() statement that does not happen, just the crash. Besides possibly more finesse with the Chrome debugger (or is that the answer?), what is the best way to tell where the issue is? Is there a linter that gives more helpful diagnostics and in particular a line number for the fault? Maybe this question belongs on programmers.stackexchange.com, but it seems that there are repeated questions about uncaught SyntaxErrors, and the responses have pinpointed faults in code snippets but have not (so far as I have seen) explained how to pinpoint a fault when you don't have a useful line number. Is my present vaguely binary-search-inspired use of drilling down in logging the best route? Is there something better? Thanks, A: Breadcrumb remark: I spent an hour with the debugger, partly because I did not realize that stepping-in would continue to move forward after the error was thrown. In this case, I was acting on bad or obsolete information that localStorage[foo] would return null if nothing was saved; it was returning undefined which passed my non-null check, and JSON.parse() was throwing an exception at being fed the string "undefined".
{ "language": "en", "url": "https://stackoverflow.com/questions/30511714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Connection of VB.NET to SQL server I had a project running perfectly i.e. entering values in database linked by code. But in the other project I am implementing it shows values correctly submitted, gives no error while running but values are not entered in database. Private Sub frmAddresume_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cn.ConnectionString = "Data Source=ROHAN-PC\SQLEXPRESS;initial catalog=Libeasy;Integrated Security=true" DateTimePicker1.Value = DateTime.Now.ToShortDateString() End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click If (TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "") Then cn.Open() cmd.Connection = cn cmd.CommandText = "insert into StudResume values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DateTimePicker1.Value.ToShortDateString() + "'," + TextBox3.Text + ")" cmd.Dispose() cn.Close() MsgBox("Details saved Successfully", MsgBoxStyle.Information, "Done") TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" DateTimePicker1.Value = Now TextBox1.Focus() Else MsgBox("Please Enter Complete Details", MsgBoxStyle.Critical, "Error") End If End Sub A: You've missed the executenonquery(),so the query you have provided is niether executed.replace the below code and eeverything will be working. cmd.Connection = cn cmd.CommandText = "insert into StudResume values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DateTimePicker1.Value.ToShortDateString() + "'," + TextBox3.Text + ")" cmd.ExecuteNonQuery() cmd.Dispose() cn.Close() Ie Add cmd.ExecuteNonQuery() after providing the commandtext. A: change your button3 code as the following, it will give u an error message in msgbox, post the error message here so may we can help, If (TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "") Then Try cn.Open() cmd.Connection = cn cmd.CommandText = "insert into StudResume values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DateTimePicker1.Value.ToShortDateString() + "'," + TextBox3.Text + ")" cmd.Dispose() cn.Close() MsgBox("Details saved Successfully", MsgBoxStyle.Information, "Done") TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" DateTimePicker1.Value = Now TextBox1.Focus() Catch ex As Exception MsgBox(ex.Message) Finally End Try Else MsgBox("Please Enter Complete Details", MsgBoxStyle.Critical, "Error") End If A: Try this way cn =new SqlConnection("Data Source=ROHAN-PC\SQLEXPRESS;initial catalog=Libeasy;Integrated Security=true")
{ "language": "en", "url": "https://stackoverflow.com/questions/28470108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I add ImageView's with swipe option IMAGE. How can I achive effect shown in image. Im working on browser and for choosing current active tab I want to build something similarlike this. User will be able to swipe view right or left and if user click on view there will be zooming animation to fit the screen. A: You can use this library to swipe between images with effects: https://github.com/daimajia/AndroidImageSlider dependencies { compile "com.android.support:support-v4:+" compile 'com.squareup.picasso:picasso:2.3.2' compile 'com.nineoldandroids:library:2.4.0' compile 'com.daimajia.slider:library:1.1.5@aar' } Add the Slider to your layout: <com.daimajia.slider.library.SliderLayout android:id="@+id/slider" android:layout_width="match_parent" android:layout_height="200dp" /> Wiki: https://github.com/daimajia/AndroidImageSlider/wiki/Slider-view
{ "language": "en", "url": "https://stackoverflow.com/questions/42602038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why a jquery datepicker change days for months? I'm working on MVC project, and using the jquery datepicker I have problems in the post. I use a partial view which contains the text box and the jquery function. Like this: @model Nullable<System.DateTime> <div class="row-fluid input-append"> @if (Model.HasValue && Model.Value != DateTime.MinValue) { @Html.TextBox("", String.Format("{0:dd/MM/yyyy}", Model.Value), new { @class = "input-small date-picker",@readonly = true, style = "cursor:pointer; background-color: #FFFFFF; text-align: center;" }) } else { @Html.TextBox("", String.Format("{0:dd/MM/yyyy}", ""), new { @class = "input-small date-picker", @readonly = true, style = "cursor:pointer; background-color: #FFFFFF; text-align: center;" }) } </div> @{ string name = ViewData.TemplateInfo.HtmlFieldPrefix; string id = name.Replace(".", "_"); } <script type="text/javascript"> $('#@id').datepicker({ dateFormat: 'dd/mm/yy', todayHighlight: true, clearBtn: true, forceParse: true, autoclose: true, }); </script> When I format the datepicker to pick the date in days/months/years, and when I pick a date the format it's ok! I mean, I select 5th of august in the calendar, and the textbox shows 05/08/2013, but the problem arise when a click save because, in the controller, the value on the date is changed days to months! Thanks! A: In web.config add the following: <system.web> <globalization culture="en-GB" uiCulture="en-GB" /> </system.web> It should change the default date parsing.
{ "language": "en", "url": "https://stackoverflow.com/questions/19279831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Read or Fetch all the column headers in a excel sheet I wanted to just read all the column headers of my excel sheet. public class Reader_2 { public static final String SAMPLE_XLSX_FILE_PATH = "C:/Users/kqxk171/Documents/Records Management Application/9.2_initial_test_report.xlsx"; public static void main(String[] args) throws IOException { Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH)); System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : "); Iterator<Sheet> sheetIterator = workbook.sheetIterator(); System.out.println("Retrieving Sheets using Iterator"); while (sheetIterator.hasNext()) { Sheet sheet = sheetIterator.next(); System.out.println("=> " + sheet.getSheetName()); } Sheet sheet = workbook.getSheetAt(0); DataFormatter dataFormatter = new DataFormatter(); for (Row row: sheet) { for(Cell cell: row) { row.getRowNum(); String cellValue = dataFormatter.formatCellValue(cell); System.out.print(cellValue + "\t"); } System.out.println(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53928960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing a dataframe column with index I have dataframe with A,B,C as its columns. I have set an index on it using df.set_index('A') Now I want to filter rows using a condition statement like df[df.loc['A'] == '10001'] This gives me the following error: KeyError: 'the label [A] is not in the [index]' How do I apply a condition on the column I have set as an index? A: You have to specify 'inplace=True' df.set_index('A', inplace=True) otherwise it doesn't persist. A: Consider this df val A 10001 5 10002 6 10003 3 You can filter the rows using df[df.index == '10001'] You get val A 10001 5
{ "language": "en", "url": "https://stackoverflow.com/questions/46182117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What exception to throw - "Wrong Scenario" (Java) This is a silly question - but it bugs me. From the existing (library) Java exceptions, which should I throw in the following. I have a method that is used in the wrong scenario (it's basic assumption doesn't hold). This method has no arguments - so I tend to skip the IllegalArgumentException. As an example - consider a BinaryNode class having just two left/right child nodes. For brevity it's nice to have a removeOnlyChild() method, which applies only if this node actually has just one child (not 0 or 2). Obviously if someone calls n.removeOnlyChild() on a node n that has 2 children, an exception should be thrown. Out of the standard Java exceptions - which do you think it should be, and why? I'm actually going over the list every-once-in-a-while, when this pops-up, and just go with IllegalStateException or with InternalError. A: I have a method that is used in the wrong scenario (it's basic assumption doesn't hold). That sounds like an exact match for IllegalStateException: Signals that a method has been invoked at an illegal or inappropriate time. Admittedly the "time" part feels a little misleading, but given the name it seems reasonable to extend the meaning to "a method has been invoked when the object is in an inappropriate state for that call". Your use is similar to that of Iterator.remove() which throws IllegalStateException if the iterator is before the first element or has already removed the "current" element. I'd definitely go with that over InternalError which is for Virtual Machine errors, not application code errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/20339167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can I use fs in react with electron? I want use react+webpack+electron to build a desktop app.How can I inject fs module into react so that I can use it to read native files? I have a component such as: class Some extends Component { render() { return <div>{this.props.content}</div> } } export default Some; in entry.js: import React from 'react'; import { render } from 'react-dom'; import Some from './src/some.jsx'; const data = "some content"; /* How can I read data by fs module? import fs from 'fs' doesn't work here */ render( <Some content={data} />, document.getElementById('app') ); I use webpack to build js codes into a bundle.js,and in index.html ... <div id="app"></div> <script src="bundle.js"></script> ... In webpack.config.js: ... plugins: [new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))] ... I find this config on the internet because if I don't add it the webpack will report error,but I don't know how this means. And I have a very easy main.js which is the same as electron-quick-start's main.js Do I lose some important things? It can't be better if u can provide a existed example on github repo. A: The easiest thing to do is probably to use webpack-target-electron-renderer, you can find examples of using it in electron-react-boilerplate. A: First of all: Don't lost time with webpack with react and electron, react already have everything it need itself to pack themself when building. As Hossein say in his answer: const fs = window.require('fs'); that works for me. Additionally on webpreferences on the main.js of electron i set this settings: webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, enableRemoteModule: true, contextIsolation: false, nodeIntegrationInWorker: true, nodeIntegrationInSubFrames: true } following the electron website that webpreferences are a security problem so we need to found a better a more safer ways as described here A: use window.require() instead of require(). const fs = window.require('fs'); A: Since Electron 12 contextIsolation is true by default and it is recommended. So with nodeIntegration: true and contextIsolation: true First see https://www.electronjs.org/docs/latest/tutorial/context-isolation/ FIRST in preload.js expose the require function to renderer: require: (callback) => window.require(callback) THEN in renderer you can import it by: const { myAPI } = window const fs = myAPI.require('fs')
{ "language": "en", "url": "https://stackoverflow.com/questions/35428639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: cshtml Razor Error messages, Conditional Formatting I'm having a strange issue with my CSHTML files this morning. One moment everything is working fine... then next moment, everything is still working, but all my code highlighting for anything with @ infront of it has gone. The project still compiles and runs fine, but I'm getting red highlights where ever there is a Code block. There are loads of posts for Conditional Formatting on this site, but they all suggest changing the code. I don't want to change any code, it's all working fine. I just want to get the yellow colouring behind the @ back. It's all working fine in the aspx files. I can't think of what I did to turn this off. Edit I've created a new project and copied every code file over manually. This is how it looks in the new project. And like this in the old A: That's a bug in Visual Studio. You can't do anything about it. It's just that the dudes at Microsoft didn't get Syntax Highligthing and Intellisense right in Razor views. Hopefully they will in some future version of Visual Studio. There's nothing wrong with the code you have shown. It works perfectly fine at runtime. Just the tools you are using aren't capable of realizing that.
{ "language": "en", "url": "https://stackoverflow.com/questions/20745908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cufon glyphs support I have a problem with cufon and a few Turkish glyphs. This is the context: I used the @font-face property to embed the custom font (Delicious-Roman) on a website. The client didn't like the fact that the font was the last one to load on each page (common issue with font-face) so I switched to cufon. When I was using font-face all the characters worked as they should, but when I used cufon a few glyphs stopped working (they simply don't show up on the page). I opened up Photoshop to test the font and indeed it doesn't have those Turkish characters (ğĞİşŞ). * *Why the font-face property managed to show all the characters even if the font didn't have them? *How can I add those Turkish characters (ğĞİşŞ) to cufon? I tried the "...and also these single characters" option on the cufon website but it didn't worked. I simply inserted the characters - ğĞİşŞ - in that text field. Is that correct? If there is no way to add these glyphs to cufon, what is the easiest way to add them directly in the font I use? A: The easiest way I found was to simply include the missing characters into the font and the re-use cufon. For this task I used the Glyph App - Demo version works perfectly for 30 days and you can export fonts without restriction.
{ "language": "en", "url": "https://stackoverflow.com/questions/11208149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fade in/out transition between pages I've written the following to create a fade in/out transition between pages. On my local setup, the page loads in smoothly, but there's no exit animation whatsoever on beforeunload, which is obviously pretty jarring. I've created a quick demo of what I'm currently using on JSFiddle: https://jsfiddle.net/6r605auw/ Is this even the best way to handle this? If you've any suggestions as to why the beforeunload animation seems to be failing, or if you've got a better way, then I'd love to hear them. jQuery(document).ready( function($){ $('body').css('display, none'); $('body').fadeIn(1000); }); $(window).on('beforeunload', function() { $('body').fadeOut(1000); }); A: You can try to use the History API with pushState and popState - in order to move from page to page seamlessly. What you're doing is bad and the mistake you're making will be more visible as more elements you put in your page. At the time JS kicks in (and DOM is ready etc) it's already too late to do hide() or .css({display: "none"}) because the page was building and visible. You'll end up having an ugly flashy unstable-looking website/application :( The "other" solution is to hide initially using CSS... but search engines will penalize you for that. Use an overlay A better way is to have a fixed full-size CSS visible overlay element - <div id="loaderOverlay"></div> that overlays your entire page content - and JS-(+CSS3) fadeOut that element instead (by adding a CSS class like) #loaderOverlay{ position: fixed; z-index: 99999; top:0; left:0; right:0; bottom:0; background: #fff; transition: 2s; /* transition timing */ } #loaderOverlay.hide{ /* JS-add this class on DOM ready or window load */ visibility: hidden; opacity: 0; } Triggering the "fadeOut" in jQuery look like: $(window).on("load", function(){ // The overlay is initially visible, we need to hide it! $("#loaderOverlay").addClass("hide"); // CSS3 will animate it nicely }); Now, the fadeIn problem... the **beforeunload** event will kick in at the moment when the page resources are just about to be unloaded. The unloading can last a couple of ms (+ waiting for HTTP requests...), clearly not enough time for an animation of 2s to take place - and the only way I see fit is to target all your links on the page, get the href attribute, prevent the browser to navigate - and navigate only on transitionend (not well supported) or after a 2100ms timeout period: // When we click on some link we want our overlay to show up! // Additionally instead of `"a"` you could make sure it's not an external link, // a #hash anchor etc... $(document).on("click", "a", function(evt) { evt.preventDefault(); // Don't navigate! var href = $(this).attr("href"); // grab the href // Animate-In our overlay $("#loaderOverlay").removeClass("hide"); // wait for CSS3 to animate-in the overlay and than navigate to our next page setTimeout(function() { window.location = href; // Navigate finally }, 2100); }); as you can see the above works for links, but clearly the browser's Back button is not a link in your page, and for that... recurse to the beginning of my answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/43599022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS: Show an element only when you hover over it The following hides the element, but I cannot recover when I hover over it. I've checked devtools to see that it is indeed rendered on the screen, I just can't see the contents of the div. How do I make it so the div is visible only on hover? .visible-on-hover { visibility: hidden; } .visible-on-hover:hover { visibility: visible !important; } A: Elements with visibility: hidden; don't receive any mouse events, so :hover never triggers on such an element. Instead of visibility, you can work with opacity: div { background-color: orange; height: 200px; width: 400px; padding: 50px; } .visible-on-hover { opacity: 0; transition: opacity .3s ease; } .visible-on-hover:hover { opacity: 1; } <div class="visible-on-hover">visible only on hover</div> A: you can not hover, focus or select a hidden element. you can use opacity .visible-on-hover { opacity: 0; } .visible-on-hover:hover { opacity: 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/66756374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my oAuth signature need "%26" at the end? I am working with imgur's API and need to set up oAuth authentication. It's going pretty smoothly but I ran into a snag... I couldn't get the oAuth request_token endpoint to give me a success message, so I contacted the imgur devs and they gave me a critical piece of information. However, I could not find where this information comes from. The information I am talking about is my oAuth signature. I knew the oAuth signature is just my api_secret, but in the working code provided by the imgur dev there was an ampersand tagged on the end. This ampersand was URL-encoded, twice. It went from & to %26, then to %2526 API Secret => 7fc6ff69*snip*c4016e7f99e076 // This does not work by itself [oauth_signature] => 7fc6ff69*snip*c4016e7f99e076%2526 // Works [oauth_signature] => 7fc6ff69*snip*c4016e7f99e076& // This also works Why is an ampersand required? Is this a bug, or is it actually mentioned somewhere in the oAuth 1.0 documentation? Is it always an ampersand, or is that just a strange coincidence? I have no idea where it came from... EDIT: It's worth mentioning that the oauth_signature is the last variable in the request, so it should not be merging with another variable. Basically, The end of the URL must end with an ampersand (or html-encoded version of one). A: For protected OAuth requests, the signature is typically generated by using a pair of secrets (often a shared secret and an authorized token secret). As you've probably guessed, an ampersand ("&") is used to separate the two secrets. However, when a single secret is used as the signature (as with imgur) the ampersand is still required, but because there is no second secrete to separate, the ampersand appears at the end of string. Another way to think of it is the ampersand is separating the api_secret and an empty secret.
{ "language": "en", "url": "https://stackoverflow.com/questions/10529368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ES6 / JS: Regex for replacing delve with conditional chaining How to replace delve with conditional chaining in a vs code project? e.g. delve(seo,'meta') delve(item, "image.data.attributes.alternativeText") desired result seo?.meta item?.image.data.attributes.alternativeText Is it possible using find/replace in Visual Studio Code? A: I propose the following RegEx: delve\(\s*([^,]+?)\s*,\s*['"]([^.]+?)['"]\s*\) and the following replacement format string: $1?.$2 Explanation: Match delve(, a first argument up until the first comma (lazy match), and then a second string argument (no care is taken to ensure that the brackets match as this is rather quick'n'dirty anyways), then the closing bracket of the call ). Spacing at reasonable places is accounted for. which will work for simple cases like delve(someVar, "key") but might fail for pathological cases; always review the replacements manually. Note that this is explicitly made incapable of dealing with delve(var, "a.b.c") because as far as I know, VSC format strings don't support "joining" variable numbers of captures by a given string. As a workaround, you could explicitly create versions with two, three, four, five... dots and write the corresponding replacements. The version for two dots for example looks as follows: delve\(([^,]+?)\s*,\s*['"]([^.]+?)\.([^.]+?)['"]\s*\) and the format string is $1?.$2?.$3. You write: e.g. delve(seo,'meta') delve(item, "image.data.attributes.alternativeText") desired result seo?.meta item?.image.data.attributes.alternativeText but I highly doubt that this is intended, because delve(item, "image.data.attributes.alternativeText") is in fact equivalent to item?.image?.data?.attributes?.alternativeText rather than the desired result you describe. To make it handle it that way, simply replace [^.] with . to make it accept strings containing any characters (including dots).
{ "language": "en", "url": "https://stackoverflow.com/questions/72189196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How could 32bit kernel read efivars from 64bit UEFI? I'm booting a GRUB EFI application compiled to x86_64-efi, on a x86_64 firwmare in UEFI only mode. This GRUB app launches a 32bit Linux v3.18.48, with CONFIG_EFIVAR_FS=y and CONFIG_EFI_VARS=y. Now I want to read some efivars, but I cannot even mount the efivarfs: mount -t efivarfs efivarfs /sys/firmware/efi/efivars which returns "No such device" (ENODEV). It was expected since dmesg says: No EFI runtime due to 32/64-bit mismatch with kernel Looking at the Linux source: if (!efi_runtime_supported()) pr_info("No EFI runtime due to 32/64-bit mismatch with kernel\n"); else { if (efi_runtime_disabled() || efi_runtime_init()) return; } and static inline bool efi_is_native(void) { return IS_ENABLED(CONFIG_X86_64) == efi_enabled(EFI_64BIT); } static inline bool efi_runtime_supported(void) { if (efi_is_native()) return true; if (IS_ENABLED(CONFIG_EFI_MIXED) && !efi_enabled(EFI_OLD_MEMMAP)) return true; return false; } seems that efi_runtime_supported() will always return false to me, since CONFIG_X86_64=n and CONFIG_EFI_MIXED depends on CONFIG_X86_64=y. Is there any workaround that could allow me to read the efivars, under these conditions? Constraints: * *x86_64 firmware with UEFI only mode; *GRUB x86_64-efi will launch Linux; *Linux kernel v3.18.48 (may be patched), 32bits. A: No, the 32-bit OS can't make 64-bit UEFI calls. I hesitate to say anything can't be done in software, but this is about as close to impossible as you can get. You can't make 64-bit UEFI calls without switching to 64-bit mode, which would be extremely difficult to do the after the 32-bit OS boots. One possible approach would be to change GRUB to read the variables and save them and provide a 32-bit interface for the OS to retrieve them. Since GRUB doesn't generally persist after the OS boots, this would be a significant change. A: I was able to boot a 32-bit Ubuntu on 64-bit EFI machine with help of package grub-efi-amd64-signed, installed via chroot. See the HowTo here (in German): https://wiki.ubuntuusers.de/Howto/Installation_von_32-Bit_Ubuntu_auf_EFI-System/ Anyway I sometimes have trouble, when GRUB gets updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/46610442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rendering dinamically GenericHtmlControl/Literal merged with an Asp.net Control My Environment is: ASP.NET 4.62 / C# / Boostrap 4 framework My application renders bootstrap 4 menu from database query. I've a div in aspx page <div id="myNav" runat="server"></div> and i add code behind as myNav.InnerHtml = mystr.ToString() Now i need to integrate in the menu a LoginView asp.net control. Obviously if i add <asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled"> as string, the browser will receive a string a not renders a control ASP.NET. I need to render something like this ....previous items menu <asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled"> <AnonymousTemplate> <ul class='nav navbar-nav ml-auto'> <li class='nav-item'> <a class='nav-link' href='../../Account/Login.aspx'><span class='fas fa-user'> </span>Login</a> </li> <li class='nav-item'><a class='nav-link' href='~/Account/Login.aspx'> <span class='fas fa-sign-in-alt'></span> Login</a> </li> </ul> </AnonymousTemplate> <LoggedInTemplate> <ul class='nav navbar-nav ml-auto'> <li class='nav-item'> <a class='nav-link' href='~/Account/Login.aspx'><span class='fas fa-user'></span></a> </li> <li class='nav-item'> <span class="myText">Hallo, </span><a runat="server" class="username" href="~/Account/Manage.aspx" title="Profile"> <asp:LoginName runat="server" CssClass="username" /> </a>! <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Exit" LogoutPageUrl="~/Logout.aspx" /> </li> </ul> </LoggedInTemplate> </asp:LoginView> ...closing boostrap menu tag Which is best way to resolve this type of problem ? I need to change approach ? A: You are creating the HTML at the server side; that is a possibility, but as you see, it makes it hard to combine this with ASP.NET server controls. It would be better to put the HTML on the .aspx-page. I understand that your database knows which menu-items should be visible. And that you want to add 1 additional item, where users can login. You could use (for example) a GridView with one column. <Columns> <asp:TemplateField> <ItemTemplate> <div>Your HTML here </div> <div><%# Item.SomeProperty %></div> </ItemTemplate> </asp:TemplateField> </Columns> Use the data from your database to render one 'row' per menuitem in the grid. You can customize the TemplateField so it contains the bootstrap-layout as you need it. It might also be possible to keep your current approach. I think then you should at least not create your opening and closing bootstrap-menu tags in the code-behind. You should put those tags on the .aspx-page itself, the structure would then be: <opening tag bootstrap menu> <div id="myNav" runat="server"></div> <asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled"> ... </ ..> <closing tag bootstrap menu>
{ "language": "en", "url": "https://stackoverflow.com/questions/71218068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: image.Save lossless quality, in XP, pixelated on Windows7? So I've come across a rather odd situation. I'm using the following to Save a PNG (lossless) image, public static void SaveJpeg(string path, Image image, int quality) { if ((quality < 0) || (quality > 100)) { string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality); throw new ArgumentOutOfRangeException(error); } EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); ImageCodecInfo imgCodec = GetEncoderInfo("image/png"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; image.Save(path, imgCodec, encoderParams); } public static ImageCodecInfo GetEncoderInfo(string mimeType) { string lookupKey = mimeType.ToLower(); ImageCodecInfo foundCodec = null; if (Encoders.ContainsKey(lookupKey)) { foundCodec = Encoders[lookupKey]; } return foundCodec; } This code works great in XP, the image gets saved lossless, when I zoom in, I see no pixelation whatsoever however, when this same compiled application is ran on a windows7 machine, the saved image looks pixelated. Is this due to the way I'm saving the image or perhaps something changing with the image save functionality / encoding in windows 7? A: Your Win7 image is anti-aliased. This is good, not bad; it makes the text smoother. It's controlled by properties in the Graphics class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7287279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set the selectedIndex property and selectedItems is empty I have an wpf application that use the MVVM with a datagrid. I set the selectedIndex property in the viewModel, but the SelectedItems property is empty. Shouldn't it have the selected the selected item? A: Not necessarily. One way of doing this is to set SelectedItem property in the datagrid xaml to a property on your view model which implements INotifyPropertyChanged. Then set the xaml binding mode to two way. Then if you click on a selected item it will trigger a change from the xaml binding to update the value in the view model
{ "language": "en", "url": "https://stackoverflow.com/questions/13805839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decimal.MinValue costs more than you expect Recently during profiling session one method caught my eye, which in profiler's decompiled version looked like this: public static double dec2f(Decimal value) { if (value == new Decimal(-1, -1, -1, true, (byte) 0)) return double.MinValue; try { return (double) value; } catch { return double.MinValue; } } This is part of the legacy code written years ago and according to the profiler (which was in sampling mode) there were too much time wasted in this method. In my opinion this is because try-catch block preventing inlining and I spent some time to refresh my memories about decimal to double conversion tricks. After ensuring this conversion can't throw, I removed try-catch block. But when I looked again at simplified version of source code, I wondered why decompiled version shows strange Decimal constuctor while it is simple Decimal.MinValue usage: public static double dec2f(decimal value) { if (value == DecimalMinValue) { return Double.MinValue; } return (double)value; } First, I thought it is a decompiler's bug, but fortunately it also shows IL version of method: public static double dec2f(Decimal value) { if (value == new Decimal(-1, -1, -1, true, (byte) 0)) .maxstack 6 .locals init ( [0] float64 V_0 ) IL_0000: ldarg.0 // 'value' IL_0001: ldc.i4.m1 IL_0002: ldc.i4.m1 IL_0003: ldc.i4.m1 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: newobj instance void [mscorlib]System.Decimal::.ctor(int32, int32, int32, bool, unsigned int8) IL_000b: call bool [mscorlib]System.Decimal::op_Equality(valuetype [mscorlib]System.Decimal, valuetype [mscorlib]System.Decimal) IL_0010: brfalse.s IL_001c return double.MinValue; Well, looks like it is true that the Decimal constructor is involved EVERY time you use 'constant' like Decimal.MinValue! So next question arises - what is inside this constructor and is there any difference in using Decimal.MinValue and defining local field like: static readonly decimal DecimalMinValue = Decimal.MinValue; Well, the answer is - there is a difference if every penny counts in your case: Method | Mean | StdDev | --------------------------- |------------ |---------- | CompareWithDecimalMinValue | 178.4235 ns | 0.4395 ns | CompareWithLocalMinValue | 98.0991 ns | 2.2803 ns | And the reason of this behavior is DecimalConstantAttribute which specified how to create a decimal every time you use one of the decimal's 'constants'. The question is - I understand that cost of calling Decimal's constructor every time you use it as 'constant' affects almost nobody, but... Why it is implemented this way anyway? Is it because the lack of notion of copy-constructor from C++? A: If decimal.MinValue were only declared as a static readonly field, you wouldn't be able to use it as a compile-time constant elsewhere - e.g. for things like the default value of optional parameters. I suppose the BCL team could provide both a constant and a read-only field, but that would confuse many people. If you're in the very rare situation where it makes a difference, introducing your own field looks like an entirely reasonable workaround. Alternatively, the compiler could decide to just copy the value of the field in cases where it's feasible to do so instead of using the constructor. That would potentially end up accessing memory that wouldn't otherwise be touched - micro-tweaks like this can end up with unintended side-effects. I suspect that making the compiler handling of this simple was deemed more important than trying to guess what's going to be most efficient in every scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/43447716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can I use a base class method to enable a variety of ui controls in .net? I need to write a delegate for a worker thread that will handle a wide variety of form controls (buttons, textbox, list...) enable method. I'm thinking they must all be derived from a base class that handles the enable property, but I'm not finding any documentation, nor am I sure how to call the method. A: MSDN is the place to be for this type of info: System.Windows.Forms.Control.Enabled
{ "language": "en", "url": "https://stackoverflow.com/questions/1584027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }