id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23527600
A: The first checkout will be a full checkout/copy. All subsequent checkouts, will only pull changes since the previous checkout. For this to work, in your SCM portion of the job configuration, you need to make sure that Check-out Strategy is set to Use 'svn update' as much as possible
doc_23527601
network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) i am sure of the ports as i checked the named instance configuration on the DB server, i also telnet the dynamic IP from the application server and it is going through. i also tried to connect a copy of the application from a demo server i have with the same configuration as the application server and it was successful. from the application server it is not, any suggestions? A: Follow the steps in below link to get solution [http://relyonsoft.com/techsupport/?p=1045][1]
doc_23527602
I am attempting a fairly complex group of animations involving purely transitions and fixed backgrounds. And in Chrome everything is gravy, I apply the transitions and move elements within a parent container that has a background-image set and a background-attachment of fixed. From what i've observed; in safari whenever any sorts of transitions occur backface-visibility:hidden is attached to all elements on the page or certainly a number of ancestors or the target element. backface-visibility:hidden; has a fairly undocumented issue when used in conjunction with background-attatchment:fixed; it will remove the background-image that is being fixed form view see here. So therefore when any transitions occur anywhere on the page that involve opacity or 3d transforming my image flickers our and back in again when safari applys the backface-visibility effect. Does anyone know a way around this issue? Its rather annoying, and as I doubt apple will be updating for a while I'm hoping theres a solution.
doc_23527603
<table> <tr class="table-header"> <th>Title</th> <th>Name</th> <th>Modified By</th> <th>Date</th> </tr> <tr class="table-data" ng-repeat="item in items"> <td>item.title</td> <td>item.name</td> <td>item.modifiedByName</td> <td>item.modifiedDate</td> </tr> </table> In my ANGULAR JS controller my ITEMS array is of the below format $scope.items = [ { title: "string" name: "string" modifiedByName: "string" modifiedDate: "string" defaultOrder: 1 }, { title: "string" name: "string" modifiedByName: "string" modifiedDate: "string" defaultOrder: 2 }, { title: "string" name: "string" modifiedByName: "string" modifiedDate: "string" defaultOrder: 3 }, { title: "string" name: "string" modifiedByName: "string" modifiedDate: "string" defaultOrder: 4 } ] Angular JS Version - 1.5.8 * *Need to display rows as per 'defaultOrder' parameter. *Once the user updates his/her preference using drag and drop the default order should get updated and then sent to the server accordingly. A: Angular JS Team has provided a directive (library) to achieve the above functionality. Below is the github link. https://github.com/angular-ui/ui-sortable
doc_23527604
try { List<StorageFile> files = new List<StorageFile>(); foreach (StorageFile file in (await ApplicationData.Current.LocalFolder.GetFilesAsync())) if (Path.GetExtension(file.Name).ToLower() == ".item") files.Add(file); return files; } catch (Exception e) { var x = e.Message; return new List<StorageFile>(); } When I step through, the offending statement is GetFilesAsync(), but I believe at the time I call it, there is no reason why it should fail. In any case, shouldn't my exception handler be called when something goes wrong?
doc_23527605
I trying to detect the user clicks outside the element and remove the element from the DOM. Better i show you what appears to be the problem HTML <div class="worker-info"> <div (click)="showWorkersSelect = !showWorkersSelect" class="worker-name"> <fa-icon [icon]="['fal', 'user-circle']" size="1x"></fa-icon> Worker name: <span>Anna</span> <fa-icon class="select-worker-icon" [icon]="['fal', 'caret-down']" size="1x"></fa-icon> </div> <div #workerSelection @showWorkersSelect *ngIf="showWorkersSelect" class="select-worker-menu"> <div (click)="showWorkersSelect = !showWorkersSelect" class="select-worker-menu__worker-name"> Essti </div> <div (click)="showWorkersSelect = !showWorkersSelect"class="select-worker-menu__worker-name"> Ilana </div> </div> </div> So when the user clicks here <div (click)="showWorkersSelect = !showWorkersSelect" class="worker-name"> The showWorkersSelect becoming true and the selection appers. TS @ViewChild('workerSelection') workerSelection: ElementRef public showWorkersSelect = false @HostListener('document:click', ['$event', '$event.target']) onClick(event: MouseEvent, targetElement: HTMLElement): void { if (this.showWorkersSelect) { if (!targetElement) { return; } const clickedInside = this.workerSelection.nativeElement.contains(targetElement); if (!clickedInside) { this.showWorkersSelect = false; } } } Here I want to run the method only when the selection is shown and close it after the user clicks outside, but the method closing it immediately after it opens A: If your worker-selection has a z-index>0, You can use a "div" between with a z-index between 0 and z-index of worker-selection that cover all the screen <div class="backscreen" *ngIf="showWorkersSelect" (click)="showWorkersSelect=false"> .backscreen { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; //<--use a z-index between 0 and z-index of selectWorker background-color: transparent; }
doc_23527606
While I can access user data in my app, I am not able to see the same when I try to access while SQL command on the terminal. This problem is specific to the 'user' table, while other tables could be accessed normally on terminal too. This is the result of my user query: classroom=# SELECT * FROM user; user ------- fatih (1 row) and this is some other table in the same database: classroom=# SELECT * FROM course; id | title | code ----+-----------------------------+---------- 3 | Algorithms | COC2030 4 | Web development using Flask | FLASK001 (2 rows) I am expecting the same type of result as in the course table, as in the user table. A: Assuming there are more columns or rows in the user table that you'd like to see, you could try: * *Log in using the same user as the flask app. *Log in as user postgres and check if that changes things (sudo -u postgres psql classroom, or psql classroom postgres.) *Use the \dp command to see if there are column privileges. *Use the \dn+ command to see if there are row security policies.
doc_23527607
So question is how to run commad tcc hello.c on windows command prompt using php script. php script & cmd.exe are on the came machine. OS windows XP. code that i want to compile is hello.c is given below. php script that is executing hello.exe is also given below. code from hello.c #include<stdio.h> void main(void) { printf("hello"); } php code that is succefully accesing and displaying hello.exe enter code here <?php echo "Remote compilation:"; $path = escapeshellcmd('C:\\TC\\BIN\\HELLO.exe'); passthru( $path, $return_var); ?> please guide regards A: From the PHP documentation: The passthru() function is similar to the exec() function in that it executes a command. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. But here you are not expecting binary data to be generated from tcc and passed to the browser. A more appropriate function to use would be shell_exec(). E.g.: <?php echo "Remote compilation:"; $command = escapeshellcmd('YOUR TCC COMPILE COMMAND HERE'); shell_exec($command); ?>
doc_23527608
I have an error in this function, in the line with LSTM def creat_model(input_shape, num_class): init = initializers.Orthogonal(gain=args.norm) sequence_input =Input(shape=input_shape) mask = Masking(mask_value=0.)(sequence_input) if args.aug: mask = augmentaion()(mask) X = Noise(0.075)(mask) if args.model[0:2]=='VA': # VA trans = LSTM(args.nhid,recurrent_activation='sigmoid',return_sequences=True,implementation=2,recurrent_initializer=init)(X) trans = Dropout(0.5)(trans) trans = TimeDistributed(Dense(3,kernel_initializer='zeros'))(trans) rot = LSTM(args.nhid,recurrent_activation='sigmoid',return_sequences=True,implementation=2,recurrent_initializer=init)(X) rot = Dropout(0.5)(rot) rot = TimeDistributed(Dense(3,kernel_initializer='zeros'))(rot) transform = Concatenate()([rot,trans]) X = VA()([mask,transform]) X = LSTM(args.nhid,recurrent_activation='sigmoid',return_sequences=True,implementation=2,recurrent_initializer=init)(X) X = Dropout(0.5)(X) X = LSTM(args.nhid,recurrent_activation='sigmoid',return_sequences=True,implementation=2,recurrent_initializer=init)(X) X = Dropout(0.5)(X) X = LSTM(args.nhid,recurrent_activation='sigmoid',return_sequences=True,implementation=2,recurrent_initializer=init)(X) X = Dropout(0.5)(X) X = TimeDistributed(Dense(num_class))(X) X = MeanOverTime()(X) X = Activation('softmax')(X) model=Model(sequence_input,X) return model This is the traceback Traceback (most recent call last): File "B:\Stage\skeleton2\va-rnn.py", line 124, in <module> main(rootdir, args.case, results) File "B:\Stage\skeleton2\va-rnn.py", line 93, in main model = creat_model(input_shape, num_class) File "B:\Stage\skeleton2\va-rnn.py", line 58, in creat_model trans = LSTM(args.nhid,recurrent_activation='sigmoid',return_sequences=True,implementation=2,recurrent_initializer=init)(X) File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\layers\recurrent.py", line 482, in __call__ return super(RNN, self).__call__(inputs, **kwargs) File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\engine\topology.py", line 576, in __call__ self.build(input_shapes[0]) File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\layers\recurrent.py", line 444, in build self.cell.build(step_input_shape) File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\layers\recurrent.py", line 1734, in build self.bias = self.add_weight(shape=(self.units * 4,), File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper return func(*args, **kwargs) File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\engine\topology.py", line 397, in add_weight weight = K.variable(initializer(shape), File "C:\Users\Users\anaconda3\envs\myenv\lib\site-packages\keras\layers\recurrent.py", line 1728, in bias_initializer self.bias_initializer((self.units,), *args, **kwargs), TypeError: Zeros() takes no arguments Here are my imports import numpy as np import os os.environ['KERAS_BACKEND'] = 'theano' os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu) from keras import initializers from keras.optimizers import Adam from keras.models import Model from keras.layers import Input, Dropout, LSTM, Dense,Activation,TimeDistributed,Masking,Concatenate from keras.callbacks import EarlyStopping,CSVLogger,ReduceLROnPlateau, ModelCheckpoint from transform_rnn import VA, Noise,MeanOverTime, augmentaion from data_rnn import get_data, get_cases, get_activation I'm using python 3.9 in spyder (anaconda). I've tested this code with keras 2.2.2 and 2.1.2 I don't know what to do. Can someone help me please ? :) Thanks
doc_23527609
07-23 10:22:43.701 26585-26646/com.zspirytus.androidlua D/ScriptPkgDataFetcher: getPkgData: 0028 at Kotlin 07-23 10:22:43.701 26585-26646/com.zspirytus.androidlua D/LuaEngine: getPkgData: 0028�ض 07-23 10:22:44.221 26585-26646/com.zspirytus.androidlua D/ScriptPkgDataFetcher: getPkgData: 0028 at Kotlin 07-23 10:22:44.221 26585-26646/com.zspirytus.androidlua D/LuaEngine: getPkgData: 0028�ض 07-23 10:22:44.721 26585-26646/com.zspirytus.androidlua D/ScriptPkgDataFetcher: getPkgData: 0028 at Kotlin 07-23 10:22:44.721 26585-26646/com.zspirytus.androidlua D/LuaEngine: getPkgData: 0028�ض At Kotlin Layer, the result in String type is "0028"; at Jni Layer, the converted result is "0028�ض". The following is what I do in my code: At Kotlin, the function return a bytearray: fun getContentByEntryName(entryName: String): ByteArray { // data is always a String with value "0028" val data = ZipFileUtils.getFileContentFromZipFile(ZipFile(scriptPkg), entryName) Log.d("ScriptPkgDataFetcher", "getPkgDatagetPkgData: $data at Kotlin") return data.toByteArray() } At Jni, I convert jbytearray to char* like this: jbyteArray jba = (jbyteArray) env->CallStaticObjectMethod(clazz, methodId, dataPath); int len = env->GetArrayLength (jba); char* buff = new char[len]; env->GetByteArrayRegion (jba, 0, len, reinterpret_cast<jbyte*>(buff)); Log_d(LOG_TAG, "getPkgData: %s", buff); Seem that it is not work correct. I also try this code, but it still not work correct... jbyteArray jba = (jbyteArray) env->CallStaticObjectMethod(clazz, methodId, dataPath); const char *cStr = (char *) (env)->GetByteArrayElements(jba, NULL); Is any mistake existing in my code? Help me to correct it, Please. Thanks! A: If you're going to use new char[] to create string data, and then use that data in functions that require null-termination, you have to explicitly add the null terminator. In addition, you may not have allocated enough space for the terminating null, thus you need to allocate len + 1 bytes. You can do this: char* buff = new char[len + 1](); which fills the buffer with null characters or: char* buff = new char[len + 1]; buff[len] = '\0'; However I highly suggest you use a std::string or std::vector<char> instead of doing things this way. Since JNI is very fragile, if an exception is thrown, you may get memory leaks using raw pointers this way. Here is a small routine you can use to convert from a Java byte array to a vector: #include <vector> //... jbyteArray jba = (jbyteArray) env->CallStaticObjectMethod(clazz, methodId, dataPath); int len = env->GetArrayLength (jba); std::vector<char> buff(len + 1, 0); env->GetByteArrayRegion (jba, 0, len, reinterpret_cast<jbyte*>(buff.data())); Log_d(LOG_TAG, "getPkgData: %s", buff.data()); This will not suffer from memory leaks if an exception is thrown, since std::vector will automatically deallocate the memory when the vector goes out of scope for any reason.
doc_23527610
// I got a tiny model with only id loaded $model = Model::first(['id']); // Then some code runs // Then I decide I'd need `name` and `status` attributes $model->loadMoreAttributes(['name', 'status']); // And now I can joyously use name and status without additional queries $model->name; $model->status; Does Eloquent have something similar to my fictional loadMoreAttributes function? Notice kindly that I'm not a novice and am very well aware of Model::find($model->id) and such. They're just too wordy. Thanks for your attention in advance. A: You may extend the Eloquent model to have this loadMoreAttributes method like so: use Illuminate\Database\Eloquent\Model; class YourModel extends Model { public function loadMoreAttributes(array $columns) { // LIMITATION: can only load other attributes if id field is set. if (is_null($this->id)) { return $this; } $newAttributes = self::where('id', $this->id)->first($columns); if (! is_null($newAttributes)) { $this->forceFill($newAttributes->toArray()); } return $this; } } This way you can do this on your model: $model = YourModel::first(['id']); $model->loadMoreAttributes(['name', 'status']); LIMITATION However there's a limitation to this hack. You may only call loadMoreAttributes() method if the unique id of your model instance is already fetched. Hope this help!
doc_23527611
I have a table and one of its column's data type is timestamp. I am trying to setup a DbParameter for this column. Looking at https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings I can see that the DbParameter.DbType for this column should be Binary. But what should be the value of DbParameter.Size for this column? Thanks A: Sorry to read you got stuck in the past. I'll send Doc Brown to get you back to 2019. I mean, seriously, Don't you think it's high time to upgrade your VS and SQL Server? To answer your question, In SQL Server, Timestamp is a synonym to RowVersion. From documentation: [rowversion] Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The rowversion data type is just an incrementing number and does not preserve a date or a time. (emphasis mine) Also, from the same documentation page: Note The timestamp syntax is deprecated. This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. BTW, RowVersion is automatically generated - so unless your parameter is an out parameter, I see no reason to use it in a parameter.
doc_23527612
below is the code for the tooltip <li class="" > <a href="#MyActivity" data-bind="tooltip: { title: 'Assign points for activities', trigger: 'hover', placement: 'top' }" data-toggle="tab" aria-expanded="true"> <span>My Activity</span> </a> </li> I have used tooltip is similar fashion in lot of places throughout the application and all of them are working also.. I also tried adding it to the li and span still nothing happens Don't know why this is not working.. Please guide Thanks
doc_23527613
When placing a datagrid in first tab item, and binding to datatable,it works fine like so: private void LoadServices() { if (serviceData.GetAllServices(currentID) != null) { dataGridServices.ItemsSource = serviceData.GetAllServices(currentID).DefaultView; dataGridServices.Columns[0].Visibility = Visibility.Hidden; } } (btw I am calling the method above in Window_ContentRendered event and it works fine). I then add another datagrid in the second tabitem with the EXACT same code but now I get the error on the line below: "Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'": dataGridServices.Columns[0].Visibility = Visibility.Hidden; When debugging and hovering over the ItemSource property, I can see that there are three columns there, so how can it be index out of range? By the way the method for binding to the second datagrid is the same as above and I am also calling this from Window_ContentRendered event too. (Just to be clear, when I am not hiding the specific column, the data loads fine with the column names too which are defined in stored procedure) Is there something unique in the way datagrids and tabcontrols work together in WPF? LATEST CODE: XAML: <TabControl x:Name="tabControl"> <TabItem x:Name="FirstTabItem" Header="First"> <DataGrid x:Name="datagridServicesFirstTab"> </DataGrid> </TabItem> <TabItem x:Name="SecondTabItem" Header="Second"> <DataGrid x:Name="datagridServices" AutoGeneratedColumns="OnLoaded" > </DataGrid> </TabItem> </TabControl> Event Handler Method: private void OnLoaded(object sender, EventArgs e) { LoadServices(); } Data Method: private void LoadServices() { if (serviceData.GetAllServices(currentID) != null) { datagridServices.ItemsSource = serviceData.GetAllServices(currentID).DefaultView; datagridServices.Columns[0].Visibility = Visibility.Hidden; } } A: When debugging and hovering over the ItemSource property, I can see that there are three columns there, so how can it be index out of range? Probably because the columns of the DataGrid has not yet been generated. The content of a tab item is not rendered until you select that tab. Move your code from Window_ContentRenderer to a AutoGeneratedColumns event handler for the second DataGrid: private void OnLoaded(object sender, EventArgs e) { LoadServices(); } XAML: <TabItem Header="second..."> <DataGrid ... AutoGeneratedColumns="OnLoaded" />
doc_23527614
Here is my code: struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default" extends="struts-default"> <action name="sample" class="com.struts.sample.action.SampleAction"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts> web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts2Example</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> SampleAction.java: package com.struts.sample.action; public class SampleAction { public String execute(){ System.out.println("from execute"); return "success"; } } success.jsp: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> success </body> </html> I'm getting this output: HTTP Status 404 - There is no Action mapped for namespace [/] and action name [getTutorial] associated with context path [/Struts2Example]. Type Status report: message There is no Action mapped for namespace [/] and action name [getTutorial] associated with context path [/Struts2Example]. description The requested resource is not available. This is my console: Dec 13, 2013 11:40:46 AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter\Driver;;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Lenovo\Bluetooth Software\;C:\Program Files\Lenovo\Bluetooth Software\syswow64;C:\Program Files\Lenovo Fingerprint Reader\;C:\Program Files\Lenovo Fingerprint Reader\x86\;C:\ProgramData\Lenovo\ReadyApps;C:\Program Files\TortoiseSVN\bin;. Dec 13, 2013 11:40:47 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Struts2Example' did not find a matching property. Dec 13, 2013 11:40:47 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-8080"] Dec 13, 2013 11:40:47 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] Dec 13, 2013 11:40:47 AM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 733 ms Dec 13, 2013 11:40:47 AM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Dec 13, 2013 11:40:47 AM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.42 log4j:WARN No appenders could be found for logger (com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Dec 13, 2013 11:40:48 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] Dec 13, 2013 11:40:48 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Dec 13, 2013 11:40:48 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 1711 ms There should be something like "from execute" in the console because of this System.out.println("from execute"); but it does not go in the class I don't know how to debug it anymore. A: You have WEB-INF/class should be renamed to WEB-INF/classes. In the the package explorer right click on the folder name and choose rename or refactor/rename. If this doesn't work open a resource perspective and rename the folder name. After that clean and rebuild and redeploy the project. A: what i did was to delete the saved jar in WEB-INF/lib i think my problems was because i had double jar one from the tutorial way and the other was because i had paste the same jar in the said folder.jar redundant my have cause my problem so if you have done the same delete the saved jar and rerun the program it will work for sure
doc_23527615
From a related question, I implemented a very crude interface (untested) : // server const _cache = new Map(); const rooms = { registerObserver: (roomHash, observer) => { if (!_cache.has(roomHash)) { _cache.add(roomHash, { messages:[], observers:[] ); } const room = _cache.get(roomHash); room.observers.add(observer); observer.added("rooms", roomHash, { messages:room.messages }); observer.onStop(() => room.observers.delete(observer)); observer.ready(); } } Meteor.publish('chatroom', function (roomHash) { check(roomHash, String); rooms.registerObserver(roomHash, this); }); Meteor.methods({ pushMessage: function (roomHash, message) { check(roomHash, String); check(message, String); const room = _cache.get(roomHash); room.messages.push(message); room.observers.forEach(observer => observer.changed("rooms", roomHash, { messages:room.messags }) ); } }); But, now, I need to fetch the messages from the given room, so I added : // client, React hook const useChatMessages = roomHash => { const loading = useTracker(() => { const handle = Meteor.subscribe("chatroom", roomHash); return !handle.ready(); }, [orderHash]); const pushMessage = useCallback(message => { Meteor.call('pushMessage', roomHash, message); }, [roomHash]); const messages = []; // .... ??? return { loading, messages, pushMessage }; }; I have no idea how to fetch the messages. Since I removed the MongoDB dependencies, I do not have access to Mongo.Colllection, and it seems like Meteor.Collection is also unavailable (i.e. Meteor.Collection === undefined) So, I publish, and also subscribe, but how do I fetch the published messages? (Note: the above code compiles, but it is mostly untested as explained in the question.)
doc_23527616
Does anyone have an Idea on how to fix it? A: Installing JetBrains and opening your file in it once somehow fixes it. It has no .NET MAUI support, but after you close the program and open Visual studio it somehow works again... (Don't ask me how that works)
doc_23527617
So, currently I have this a-b-c-d But I want this a-b-c \-d How can I accomplish this? This question has been marked as a duplicate of questions asking how to undo the last commit, but these do not answer my question because it's not the last commit I'm trying to undo but instead a commit twice back. Rebasing to HEAD{2} also doesn't work because that still undo's the last commit. A: The easiest way: * *Remember the d's SHA1, let say it is 535dce28f1c68e8af9d22bc653aca426fb7825d8. *git reset --hard HEAD~2 *git cherry-pick 535dce28f1c68e8af9d22bc653aca426fb7825d8 More advanced: * *git rebase -i HEAD~3 *Change the second pick to drop, or remove that line, then save the file and exit from the editor. More advanced 2: * *git revert HEAD~1 will make b-c-d-^c *git reset --soft HEAD~3 will reset to b and keep the changes on the disk *git add -A && git commit will make b-d'.
doc_23527618
Unfortunately, this won't work and I can't find a proper, elegant workaround. The idea is, when adding a new animal category (e.g. birds), I just create a TemplateBird similar to TemplateMammals. When creating a new bird class, I will have only access to the proper methods, defined via class BirdStuff. I can create a non-abstract methods in the animal category templates (e.g. public MammalStuff getAnimalStuff{ return new MammalStuff()} for TemplateMammals) but I don't like this, since I want to create a Framework and thus want to force the user to implement such a method. Have you any idea for an elegant improvement? Or a complete other idea? Thanks! A: You could use a generic which is constrained to AnimalStuff. public class Dog : TemplateMammals { public void SomethingWhereINeedStuff() { var stuff = GetAnimalStuff(); // stuff is of type MammalsStuff } } public class TempalteMammals : TemplateAnimals<MammalsStuff> { public abstract MammalsStuff GetAnimalStuff() { ... } } public class TemplateAnimals<TStuff> where TStuff : AnimalStuff { public abstract TStuff GetAnimalStuff(); } A: How about using generics? AnimalStuff In first step, we'll have the stuff defined and the Stuff must derive from a base Interface or Abstract class: public interface AnimalStuff{ public void doAnimal(); } Then you'll define your hierarchy as you want. I mixed abstract classes and interface but you can do full abstract classes or full interface until the implemented classes: public abstract class MammalStuff implements AnimalStuff{ // no need to override unless there are mammal specific stuff public void doAnimal(){...} } public abstract class BirdStuff implements AnimalStuff{ // example of bird specific @Override public void doAnimal(){ System.out.println("I believe I can fly!!!"); } } If I follow the exemple of a bird: public class EagleStuff extends BirdStuff{ @Override public void doAnimal(){ super.doAnimal(); System.out.println("But I also eat preys!!!"); } } Animal classes Then you can create your Animals hierarchy: public abstract class TemplateAnimal<S extends AnimalStuff> { public abstract S getAnimalStuff(); } With the hierarchy you defined. The generics definition is valid here because MammalStuff and BirdStuff extends (or implements) AnimalStuff public abstract class TemplateMammal<S extends MammalStuff> extends TemplateAnimal<S>{ // no overriding here // public abstract S getAnimalStuff(); } public abstract class TemplateBird<S extends BirdStuff> extends TemplateAnimal<S>{ // no overriding here // public abstract S getAnimalStuff(); } Then, you'll have your Eagle: public class Eagle extends TemplateBird<EagleStuff>{ @Override public EagleStuff getAnimalStuff(){ // return ... } } In the Eagle class, in you have the getAnimalStuff() with this signature public AnimalStuff getAnimalStuff(), it is illegal because the generic requires to return S type, not an AnimalStuff
doc_23527619
I need to write a query that will list all customers with the same phone number. Thanks for your help. A: ;WITH dupes AS ( SELECT Phone_Number FROM dbo.Customer_Table GROUP BY Phone_Number HAVING COUNT(*) > 1 ) SELECT c.Customer_Name, dupes.Phone_Number FROM dupes INNER JOIN dbo.Customer_Table AS c ON dupes.Phone_Number = c.Phone_Number;
doc_23527620
wget --mirror --page-requisites --convert-link --no-clobber --no-parent --domains typingstudy.com https://www.typingstudy.com/ And wget creates directories, which contain html files on the site, only at the end of the scrapping and, accordingly, when it tries to download those html files, before the creation of the directories in which this files are located, wget says:powershell output Sometimes it downloads only 1 file, like at this example, to the directory "part" and refuses to see this directory while trying downloading all other ~10 files from this exact directory, saying that this directory does not exist: enter image description here Can someone help me understand what's wrong with my commands? Or is it a bug of wget?(Probably not) Thanks in advance. When I start the downloading process again - everything is neat, wget downloads all those ~10 other html files to created in the previous download session ("part") directories. So the problem is that I need to start the downloading 2 times, at least in case of this site. And I totally do not understand why this is happening.
doc_23527621
[ {name: 'ParentOne', children: [ {name: 'ParentOneChildOne'}, {name: 'ParentOneChildTwo', children: [ {name: 'ParentOneChildTwoGrandChildOne'}, ]}, ]}, {name: 'ParentTwo', children: [ {name: 'ParentTwoChildOne', children: [ {name: 'ParentTwoChildOneGrandChildOne'}, {name: 'ParentTwoChildOneGrandChildTwo'} ]}, {name: 'ParentTwoChildTwo'} ]} ]; I want to flatten it: [ {name: 'ParentOne'}, {name: 'ParentOneChildOne'}, {name: 'ParentOneChildTwo'}, {name: 'ParentOneChildTwoGrandChildOne'}, {name: 'ParentTwo'}, {name: 'ParentTwoChildOne'}, {name: 'ParentTwoChildOneGrandChildOne'}, {name: 'ParentTwoChildOneGrandChildTwo'}, {name: 'ParentTwoChildTwo'} ] I have tried _.flatten() and _.flatMap(), but it does not produce what I need. What is the best way to achieve it preferably using lodash.js or underscore.js. A: Recursive functions is the way to go for any depth of iteration. With some ES2015 and LoDash/Underscore var arr = [{ name: 'ParentOne', children: [{ name: 'ParentOneChildOne' }, { name: 'ParentOneChildTwo', children: [{ name: 'ParentOneChildTwoGrandChildOne' }, ] }, ] }, { name: 'ParentTwo', children: [{ name: 'ParentTwoChildOne', children: [{ name: 'ParentTwoChildOneGrandChildOne' }, { name: 'ParentTwoChildOneGrandChildTwo' }] }, { name: 'ParentTwoChildTwo' }] }]; var res = _.reduce(arr, (a, b) => { (rec = item => { _.each(item, (v, k) => (_.isObject(v) ? rec(v) : a.push(_.zipObject([k], [v])))) })(b); return a; }, []); console.log(res); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> A: No need for underscore/lodash. const arr = [ {name: 'ParentOne', children: [ {name: 'ParentOneChildOne'}, {name: 'ParentOneChildTwo', children: [ {name: 'ParentOneChildTwoGrandChildOne'}, ]}, ]}, {name: 'ParentTwo', children: [ {name: 'ParentTwoChildOne', children: [ {name: 'ParentTwoChildOneGrandChildOne'}, {name: 'ParentTwoChildOneGrandChildTwo'} ]}, {name: 'ParentTwoChildTwo'} ]} ]; function flatten(arr) { return arr? arr.reduce((result, item) => [ ...result, { name: item.name }, ...flatten(item.children) ], []) : []; } console.log(flatten(arr)); A: I would use .reduce and recursion to do this. Here's my implementation using Array.reduce, but you could do much the same with underscore's reduce function. const arr = [ {name: 'ParentOne', children: [ {name: 'ParentOneChildOne'}, {name: 'ParentOneChildTwo', children: [ {name: 'ParentOneChildTwoGrandChildOne'}, ]}, ]}, {name: 'ParentTwo', children: [ {name: 'ParentTwoChildOne', children: [ {name: 'ParentTwoChildOneGrandChildOne'}, {name: 'ParentTwoChildOneGrandChildTwo'} ]}, {name: 'ParentTwoChildTwo'} ]} ]; function flatten(arr) { return arr.reduce((result, current) => { if (current.children) { const children = flatten(current.children); delete current.children; result.push(current); result.push(...children); } else { result.push(current); } return result; }, []) } console.log(flatten(arr)); A: You could try adapting the flatten function given in this answer, and slightly twist the logic to your object's structure. //Your object var data = [{ name: 'ParentOne', children: [{ name: 'ParentOneChildOne' }, { name: 'ParentOneChildTwo', children: [{ name: 'ParentOneChildTwoGrandChildOne' }, ] }, ] }, { name: 'ParentTwo', children: [{ name: 'ParentTwoChildOne', children: [{ name: 'ParentTwoChildOneGrandChildOne' }, { name: 'ParentTwoChildOneGrandChildTwo' } ] }, { name: 'ParentTwoChildTwo' } ] } ]; //georg's flatten function flatten = function(x, result, prefix) { if (_.isObject(x)) { _.each(x, function(v, k) { flatten(v, result, prefix ? prefix + '_' + k : k) }) } else { result[prefix] = x } return result } //using the function on your data result = flatten(data, {}); console.log(result); <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> Does this help at all? A: You could use some destruction and use a recursive function for collecting all wanted items. var array = [{ name: 'ParentOne', children: [{ name: 'ParentOneChildOne' }, { name: 'ParentOneChildTwo', children: [{ name: 'ParentOneChildTwoGrandChildOne' },] },] }, { name: 'ParentTwo', children: [{ name: 'ParentTwoChildOne', children: [{ name: 'ParentTwoChildOneGrandChildOne' }, { name: 'ParentTwoChildOneGrandChildTwo' }] }, { name: 'ParentTwoChildTwo' }] }], flat = (r, { name, children = [] }) => [...r, { name }, ...children.reduce(flat, []) ], result = array.reduce(flat, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } On EDGE, you need a different use of default values. var array = [{ name: 'ParentOne', children: [{ name: 'ParentOneChildOne' }, { name: 'ParentOneChildTwo', children: [{ name: 'ParentOneChildTwoGrandChildOne' },] },] }, { name: 'ParentTwo', children: [{ name: 'ParentTwoChildOne', children: [{ name: 'ParentTwoChildOneGrandChildOne' }, { name: 'ParentTwoChildOneGrandChildTwo' }] }, { name: 'ParentTwoChildTwo' }] }], flat = (r, { name, children }) => [...r, { name }, ...(children || []).reduce(flat, []) ], result = array.reduce(flat, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }
doc_23527622
return ( <mesh geometry={nodes.tshirt.geometry} > <a.meshStandardMaterial attachArray="material" color={props.color} /> <meshStandardMaterial attachArray="material" map={logo} transparent={true} /> </mesh> );
doc_23527623
Is it possible to generate the triangulation in a manner that preserves the edges defined by the input vertices? (EDIT: i.e. a constrained Delaunay triangulation.) As can be done with the triangle package for Python. For example, in the picture below there are several triangles (blue) that disregard the location of the edges (red) that are defined by the vertices. Is there a way to enforce these edges such that they are in all cases part of the triangulation result? A: What you are looking for is called constrained Delaunay triangulation, and unfortunately the scipy.spatial implementation does not support it. As you pointed out, triangle does have that feature -- why not use it instead?
doc_23527624
Which tool would do the job the fastest / cleanest (sed, awk, perl, shell)? A: Sed has a nice way of doing this: sed -ne '2p' -e '4,6p' for example: $ printf '%s\n' {1..100} | sed -ne '2p' -e '4,6p' 2 4 5 6 A: Use awk and its parameter NR. You can compose conditional expressions such as: $ cat a aa bb cc dd ee $ awk 'NR==3' a #print line number 3 cc $ awk 'NR==3, NR==5' a #print from line number 3 up to number 5 cc dd ee $ awk 'NR>2 && NR<7' a #print lines whose number is in the range (2,7) cc dd ee etc. In your case, $ awk 'NR==2; NR>=4 && NR<=6' a #print line number 2 and from 4 to 6 A: awk 'NR==2 || NR>=4 && NR<=6' or awk 'NR==2; NR==4,NR==6' A: You can do it using just head and tail ... For example: NR=3; cat test.txt | head -n $NR | tail -n -1 extracts line 3 from test.txt; and NB=2; NR=3; cat test.txt | head -n $(expr $NR \+ $NB) | tail -n -$NB extracts line 3 to 5. A: Use awk and keep it clear and simple: awk 'NR==2 || (NR>=4 && NR<=6)' file
doc_23527625
Somebody help me solve problems. The link is here. A: NSBeginAlertSheet was deprecated in OS X 10.10 and it is recommended to use NSAlert instead. Source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/index.html#//apple_ref/c/func/NSBeginAlertSheet That specific error is not related to ImageKit.
doc_23527626
Just te be clear: The request works, and the authentication works. The only thing that isn't working is the recurrence... data.recurrence = ["RDATE:20140308T000000"] the rest of the fields are working. Can someone please tell my why the recurring events are not added? Thanks in advance. A: I've solved the problem by not using the JSON stringify function, and creating the request body as a String object. JSON changed " into /"
doc_23527627
Seeing that all of my data was stored in strings on the server, I would like to create a method to convert all of the timestamps to Unix timestamps as an integer. In other words, I need to convert: { "created_at" => "2015-01-18T00:58:58.903Z", "updated_at" => "2015-01-18T00:58:58.903Z", "user_id" => 1, "status_id" => 1 } to: { "created_at" => 1421542604, "updated_at" => 1421542604, "user_id" => 1, "status_id" => 1 } A: I wrote the following rspec, then realized I need to modify the default as_json method to perform this conversion: expect(response_json).to eq( { 'created_at' => user.created_at.as_json, 'updated_at' => user.updated_at.as_json, 'user_id' => user.user_id, 'status_id' => user.status_id } ) I then created /config/initializers/unix_timestamps.rb and it worked: class ActiveSupport::TimeWithZone def as_json self.to_time.to_i end end
doc_23527628
string binary = "000000100001000100010000000100000" bitset<32> set(binary); cout << hex << set.to_ulong() << endl; The code shows 2112010 but I want it to show 02112010. A: std::cout << std::setfill('0') << std::setw(5) << i << std::endl; A: that is the same number you can format it with the 0 by using format specifiers if you need to retain the zero you need to store it as a string,
doc_23527629
Everything works as expected when running the dev version. Unfortunately when I do npm run build and run this via serve -s build my styles are not working. The .css files are being found and compiled into a single minified version. But the problem is that the markup that is generated is having the class name prefixes changed to 'T-' instead of the prefix in the compiled .css file. (i.e) MyApp-header is getting changed to T-header, but in the minified css file, it still refers to MyApp-header. prefix changed to T- Any help would be appreciated. A: This issue turned out to be caused by some nuance of using this... @SuitCssify.decorator I was evaluating this library for potential use in a project, and didn't discover this issue until trying to produce an actual production build. I've since abandoned this approach and changed my configuration to use "CSS Modules" which are working out great. I would provide a link, but my reputation only allows me one link per post. ;( my 'webpack.config.[dev & prod].js' changes to enable css modules
doc_23527630
How do you transition an AVplayer from a uitableviewcell to a new instance of a uiviewcontroller seamlessly? A: I achieved this by implemnting the UIViewControllerTransitioningDelegate and using my own custom animator object, which conforms to the UIViewControllerAnimatedTransitioning protocol. I used https://github.com/recruit-mp/RMPZoomTransitionAnimator as a reference, with a few modifications to move an actual view (not a snapshot) between source and destination UIViewControllers : Within the animator object, using the animator object's delegate methods for "source frame" and "destiation frame" and "playerView", all which are implemented on the "to" and "from" view controllers, I grab the view containing the playing video, grab it's start frame, it's end frame, and properly animate the view from its start frame to the frame it will end up being located at on the "to" view controller. Upon completion of the transition, I then add the playing video UIView as a subview to the destination view controller, so that it becomes part of the "to" view controller's view, available for interacting with, etc.
doc_23527631
I was deploying this code in a terraform template: #!/bin/bash nlbcname=$(aws-env terraform output nlb_arn | grep arn | awk '$1=$1' FS="/" OFS=":" | awk 'BEGIN{ VAR1="elb";VAR2="amazonaws.com"; FS=":"; OFS="."} {print $8,$9,VAR1,$4,VAR2}' | sed -e 's/\./-/') echo -n "{\"nlburl\":\"${nlbcname}\"}" But I get Error refreshing state: 1 error occurred: * data.external.nlbcname: 1 error occurred: * data.external.nlbcname: data.external.nlbcname: command "bash" produced invalid JSON: invalid character '\r' in string literal
doc_23527632
def get_credentials(self): """Retrieve credentials from the Secrets Manager service.""" boto_config = BotoConfig(connect_timeout=3, retries={"max_attempts": 3}) secrets_client = self.boto_session.client( service_name="secretsmanager", region_name=self.boto_session.region_name, config=boto_config, ) secret_value = secrets_client.get_secret_value(SecretId=self._secret_name) secret = secret_value["SecretString"] I try to debug the lambda and later seems to be working again, without any change, those state changes happen in hours. Any hint why that could happen? Traceback (most recent call last): File "/opt/python/botocore/endpoint.py", line 249, in _do_get_response http_response = self._send(request) File "/opt/python/botocore/endpoint.py", line 321, in _send return self.http_session.send(request) File "/opt/python/botocore/httpsession.py", line 438, in send raise ConnectTimeoutError(endpoint_url=request.url, error=e) botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://secretsmanager.eu-central-1.amazonaws.com/" A: You are using the legacy retry mode (is the default one in boto3), which has very limited functionality as it only works for a very limited number of errors. You should try changing your retry strategy to something like Standard retry mode or Adaptative. In that case your code would look like: from botocore.config import Config as BotoConfig boto_config = BotoConfig( connect_timeout=3, retries={ "max_attempts": 3, "mode":"standard" } ) secrets_client = self.boto_session.client( service_name="secretsmanager", region_name=self.boto_session.region_name, config=boto_config, )
doc_23527633
document.body.addEventListener( "touchmove", function(t) { t.preventDefault(), e.scrollLock || ((e.deltaY = e.startY - t.touches[0].clientY), (e.deltaX = e.startX - t.touches[0].clientX), Math.abs(e.deltaY) > Math.abs(e.deltaX) && (e.deltaY > 3 && !e.isAnimating && e.currSection + 1 < e.sections.length && ((e.isAnimating = !0), e.getSection(e.currSection + 1), e.sectionTitle.getSection(e.currSection + 1)), e.deltaY < -3 && !e.isAnimating && e.currSection - 1 >= 0 && ((e.isAnimating = !0), e.getSection(e.currSection - 1), e.sectionTitle.getSection(e.currSection - 1)))); }, { passive: !1 } ), I need to disable this and make it scroll normally. A: If you want to remove it dynamically only for certain circumstances you can try it with calling: document.body.removeEventListener(type, listener[, options]) Here's a good read on removeEventListener From the docs: The EventTarget.removeEventListener() method removes from the EventTarget an event listener previously registered with EventTarget.addEventListener(). The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal Syntax: target.removeEventListener(type, listener[, options]); target.removeEventListener(type, listener[, useCapture]); Where type is your string which specifies the type of event for which to remove an event listener and listener is your EventListener-function of the event handler to remove from the event target. If you want to remove it alltogether - just comment it out or delete it in your code as suggested in the comments.. A: This function works for me $('#elementid').on('touchmove', function (e) { e.stopPropagation(); });
doc_23527634
Closest I can get is something like: h1 { font-size: 48px; color: #16343E; font-family: 'Roboto', sans-serif; font-weight: 900; display: inline; background-image: linear-gradient(#fff 60%, #863034 55%); } <h1>Welcome</h1> A: Here is another option with pseudo element: h1 { display: inline-block; padding: 0 3rem; text-transform: uppercase; position: relative; } h1::after { content: ''; left: 0; bottom: -10px; position: absolute; width: 100%; height: 30px; background: tomato; z-index: -1; } A: I've tried to approach it as best as I could. The HTML: <h1>WELCOME</h1> The CSS: h1 { font-family:helvetica; display: inline-block; border-bottom: 30px solid #A66; line-height: 0; padding: 0 15px; } See: This codepen. It looks like this: A: Html h1{ position: relative; } .under-lined-color{ position: absolute; bottom: 2px; //Change this accordingly } <h1>WELCOME</h1> <span class="under-lined-color"></span>
doc_23527635
cat ./file.txt | ./pargrep word I tried to get the file name fgets(buf, NULL, stdin); How can I get just the file name instead of the file content, which I get when used gets. I need to read the file, which is pretty huge and need to read it twice. A: I wouldn't use the pipe. I assume you are writing the program ./pargrep? I would pass the name of the file you want to process as the first argument to your pargrep program. The second argument would then be "word" Then you would open the file by name in the program. A: The problem is that cat outputs the contents of the file. If you want the filename, run as echo ./file.txt | ./pargrep word but better to use dernst suggestion rather than this
doc_23527636
I have a div with some markdown in it <div id="text"> > This is supposed to be a blockquote 1 < 2 </div> and I'm converting it to HTML with this code $(function () { var sanitizer = Markdown.getSanitizingConverter(); var text = $("#text").html(); $("#text").html(sanitizer.makeHtml(text)); }); There is no blockquote, and the left angle bracket (<) in the code block is converted to &lt;. You can observe my problem on jsFiddle. What do I have to do to fix this? A: Use .text() when extracting the text from the DOM. .html() will encode some symbols as entities. http://jsfiddle.net/fGNsM/3/ A: $(function() { var $text = $('#text'), convert = Markdown.getSanitizingConverter().makeHtml, result = convert($text.text()); $text.html(result); });
doc_23527637
build/intermediates/incremental/mergeReleaseAssets/merger.xml It cause me to push it again and again on my git repository. I used git ignore but it still modify the above file. Any help will be appreciated. Thanks in advance
doc_23527638
( requests | where timestamp > ago(-24h) | summarize day = avg(duration) ) | union ( requests | where timestamp > ago(-10m) | summarize now = avg(duration) ) I want to get the avg request duration of the last day and of the last 10 min. I do it now in 2 different queries, but I like to have them in 1 query for performance. When I run this query I get no response, I see the day and the now column, but it has no value. A: from a query language perspective, what you're doing is valid and should work. you should verify if you really intend to use the minus (-) sign in your call to the ago() function. if you want the result in a single row, you can also use a join instead of a union print ago(24h), ago(-24h) will output: | print_0 | print_1 | |-----------------------------|-----------------------------| | 2019-04-03 15:04:24.0178923 | 2019-04-05 15:04:24.0178923 | and: let requests = datatable(timestamp:datetime, duration:timespan) [ datetime(2019-03-03 14:00), 123s, datetime(2019-03-03 15:00), 12s, datetime(2019-04-03 16:00), 13s, datetime(2019-04-03 17:00), 456s, datetime(2019-04-03 18:00), 56s, datetime(2019-04-03 19:00), 45s, datetime(2019-04-03 20:00), 43s, datetime(2019-04-04 16:55), 77s, ] ; requests | where timestamp > ago(24h) | summarize day = avg(duration) | union ( requests | where timestamp > ago(10m) | summarize now = avg(duration) ) will output: | day | now | |----------|----------| | 00:01:55 | | | | 00:01:17 | and: let requests = datatable(timestamp:datetime, duration:timespan) [ datetime(2019-03-03 14:00), 123s, datetime(2019-03-03 15:00), 12s, datetime(2019-04-03 16:00), 13s, datetime(2019-04-03 17:00), 456s, datetime(2019-04-03 18:00), 56s, datetime(2019-04-03 19:00), 45s, datetime(2019-04-03 20:00), 43s, datetime(2019-04-04 16:55), 77s, ] ; requests | where timestamp > ago(24h) | summarize day = avg(duration) by dummy = 1 | join kind=inner ( requests | where timestamp > ago(10m) | summarize now = avg(duration) by dummy = 1 ) on dummy | project day, now will output: | day | now | |----------|----------| | 00:01:55 | 00:01:17 |
doc_23527639
For now, I want to get the data about the page Y. To do this, I wrote following code: final Facebook facebook = new FacebookFactory().getInstance(); facebook.setOAuthAppId("...", "..."); facebook.setOAuthAccessToken(new AccessToken("...")); final AccessToken oAuthAccessToken = facebook.getOAuthAccessToken(); try { final ResponseList<Page> pages = facebook.searchPages("Costume jewelry"); LOGGER.debug("oAuthAccessToken: " + oAuthAccessToken); } catch (FacebookException e) { LOGGER.error("", e); } When running this code, I get following exception: 22:56:38.405 [main] DEBUG f.internal.http.HttpResponseImpl - {"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190}} 22:56:38.481 [main] ERROR c.a.f.FbCustomerProfiler - facebook4j.FacebookException: message - Invalid OAuth access token. code - 190 Relevant information for error recovery can be found on the Facebook Developers Document: https://developers.facebook.com/docs/graph-api/using-graph-api/#errors at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:179) ~[facebook4j-core-2.1.0.jar:2.1.0] at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65) ~[facebook4j-core-2.1.0.jar:2.1.0] at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:93) ~[facebook4j-core-2.1.0.jar:2.1.0] at facebook4j.FacebookImpl.get(FacebookImpl.java:2584) ~[facebook4j-core-2.1.0.jar:2.1.0] at facebook4j.FacebookImpl.searchPages(FacebookImpl.java:2256) ~[facebook4j-core-2.1.0.jar:2.1.0] at facebook4j.FacebookImpl.searchPages(FacebookImpl.java:2251) ~[facebook4j-core-2.1.0.jar:2.1.0] at myproduct.FbCustomerProfiler.run(FbCustomerProfiler.java:32) [classes/:na] at myproduct.FbCustomerProfiler.main(FbCustomerProfiler.java:20) [classes/:na] Disconnected from the target VM, address: '127.0.0.1:50651', transport: 'socket' I took those examples from the Facebook4J site. The only difference between my code and theirs is that in my version I do not call facebook.setOAuthPermissions(commaSeparetedPermissions);. Therefore I suppose that missing permissions are the cause of the error. What permissions do I need in order to run a query, which returns the data (most importantly - the ID of the page, which I can use in the next query) about a page? A: To search for Pages, you need to pass an App Access Token with your request according to the Facebook docs: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0#search Searches across Page and Place objects requires an app access token. You can use {app_id}|{app_secret} for that. BTW, your original question "Find all people from city X, who like Y" will not work, because you're not able to query this kind of info from FB.
doc_23527640
These two are passed in the header of the request. The middleware class is the following : from models import MongoToken class TokenAuthenticationMiddleware(object): def process_request(self, request): if "HTTP_AUTHORIZATION" not in request.META: return tokenkey = get_authorization_header(request).split()[1] token = MongoToken.objects.get(key=tokenkey) user = User.objects.get(username=request.META.get("HTTP_USERNAME")) if token.key == tokenkey and token.user.is_active: request.user = user request.token = tokenkey I also put this in my MIDDLEWARE_CLASSES block of the settings.py files: MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'myproject.middleware.MongoAuthenticationMiddleware', 'myproject.middleware.TokenAuthenticationMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And when the considered view is reached, my token is here because thanks to the header params but the user is Null. Then I am wondering if I did something wrong with this because it does not work. Thank you for your help. Alex.
doc_23527641
CTRL + B : Set the highlighted text to bold, for example What happens under the hood is, the <b> tag is attached or removed to the marked phrase, word whatever. How is this done? Where do "they" know from, whether the element is already set to bold, and, primary question, where it is located? I am asking this because i can't get rid of this problem, mentioned earlier today: Get the highlighted text position in .html() and .text() Edit: I tried the following Rich-Text-Editing But first, it won't load correctly, but this should be caused by my own failure. Second, for learning purposes, i would like to implent my own minified version. As i am really at JavaScript, i could not figure out how this is be done. A: document.getSelection() / window.getSelection() should work for whatever you'd like to do with the selected stuff. Element styles get inherited. How this is kept track of depends on the CSS implementation. Taking a look at the source code of Chrome might pretty much help.
doc_23527642
We are facing a problem when the user was inactive for a time longer than the access token lifetime: We suspect, that this is a configuration problem and we did not configure the CORS Header on one component correctly. Do we need to configure the CORS-Header on our Keycloak aswell? If so, how can we add the missing configuration? This is our current code in ConfigureServices-Method form Startup.cs in the .NET Core Frontend: using DefectsWebApp.Middleware; using IdentityModel; using IdentityModel.Client; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Diagnostics; using System.IdentityModel.Tokens.Jwt; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; namespace DefectsWebApp { public class Startup { private bool isTokenRefreshRunning = false; private readonly object lockObj = new object(); readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; private bool IsTokenRefreshRunning { get { lock(lockObj) { return isTokenRefreshRunning; } } set { lock (lockObj) { isTokenRefreshRunning = value; } } } public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, }; services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.WithOrigins("http://keycloak:8080", "https://keycloak") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); // get URL from Config services.Configure<QRoDServiceSettings>(Configuration.GetSection("QRodService")); services.AddSession(); services.AddAuthorization(options => { options.AddPolicy("Users", policy => policy.RequireRole("Users")); }); // source: https://stackoverflow.com/a/43875291 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) // source: https://stackoverflow.com/questions/40032851/how-to-handle-expired-access-token-in-asp-net-core-using-refresh-token-with-open .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Events = new CookieAuthenticationEvents { // this event is fired everytime the cookie has been validated by the cookie middleware, // so basically during every authenticated request // the decryption of the cookie has already happened so we have access to the user claims // and cookie properties - expiration, etc.. OnValidatePrincipal = async x => { // since our cookie lifetime is based on the access token one, // check if we're more than halfway of the cookie lifetime var identity = (ClaimsIdentity)x.Principal.Identity; var accessTokenClaim = identity.FindFirst("access_token"); var refreshTokenClaim = identity.FindFirst("refresh_token"); var accessToken = new JwtSecurityToken(accessTokenClaim.Value); var now = DateTime.UtcNow.AddMinutes(2); var timeRemaining = accessToken.ValidTo.Subtract(now); var refreshtoken = new JwtSecurityToken(refreshTokenClaim.Value); var timeRemainingRT = refreshtoken.ValidTo.Subtract(now); timeRemaining = timeRemaining.TotalSeconds > 0 ? timeRemaining : new TimeSpan(0); timeRemainingRT = timeRemainingRT.TotalSeconds > 0 ? timeRemainingRT : new TimeSpan(0); Debug.WriteLine("Access-Token: {0} | timeleft: {1}", accessToken.Id, timeRemaining.ToString(@"hh\:mm\:ss")); Debug.WriteLine("Refresh-Token: {0} | timeleft: {1}", refreshtoken.Id, timeRemainingRT.ToString(@"hh\:mm\:ss")); if (timeRemaining.TotalMinutes <= 0 && !IsTokenRefreshRunning) { IsTokenRefreshRunning = true; // if we have to refresh, grab the refresh token from the claims, and request // new access token and refresh token var refreshToken = refreshTokenClaim.Value; var refreshTokenRequest = new RefreshTokenRequest { Address = Configuration["Authentication:oidc:OIDCRoot"] + Configuration["Authentication:oidc:Token"], ClientId = Configuration["Authentication:oidc:ClientId"], ClientSecret = Configuration["Authentication:oidc:ClientSecret"], RefreshToken = refreshToken, }; if (!refreshTokenRequest.Headers.Contains(Constants.ORIGIN_HEADER)) { refreshTokenRequest.Headers.Add(Constants.ORIGIN_HEADER, Configuration["Authentication:oidc:OIDCRoot"] + "/*, *"); } if (!refreshTokenRequest.Headers.Contains(Constants.CONTENT_HEADER)) { refreshTokenRequest.Headers.Add(Constants.CONTENT_HEADER, "Origin, X-Requested-With, Content-Type, Accept"); } var response = await new HttpClient().RequestRefreshTokenAsync(refreshTokenRequest); Debug.WriteLine("Cookie.OnValidatePrincipal - Trying to refresh Token"); if (!response.IsError) { Debug.WriteLine("Cookie.OnValidatePrincipal - Response received"); // everything went right, remove old tokens and add new ones identity.RemoveClaim(accessTokenClaim); identity.RemoveClaim(refreshTokenClaim); // indicate to the cookie middleware to renew the session cookie // the new lifetime will be the same as the old one, so the alignment // between cookie and access token is preserved identity.AddClaims(new[] { new Claim("access_token", response.AccessToken), new Claim("refresh_token", response.RefreshToken) }); x.ShouldRenew = true; x.HttpContext.Session.Set<string>(Constants.ACCESS_TOKEN_SESSION_ID, response.AccessToken); Debug.WriteLine("Cookie.OnValidatePrincipal - Token refreshed"); IsTokenRefreshRunning = false; } else { Debug.WriteLine(string.Format("Cookie.OnValidatePrincipal - {0}", response.Error)); IsTokenRefreshRunning = false; } } } }; }) .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => { //options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet; options.Authority = Configuration["Authentication:oidc:OIDCRoot"]; options.ClientId = Configuration["Authentication:oidc:ClientId"]; options.ClientSecret = Configuration["Authentication:oidc:ClientSecret"]; options.MetadataAddress = Configuration["Authentication:oidc:OIDCRoot"] + Configuration["Authentication:oidc:MetadataAddress"]; options.CallbackPath = new PathString("/Home"); options.RequireHttpsMetadata = false; // openid is already present by default: https://github.com/aspnet/Security/blob/e98a0d243a7a5d8076ab85c3438739118cdd53ff/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/OpenIdConnectOptions.cs#L44-L45 // adding offline_access to get a refresh token options.Scope.Add("offline_access"); // we want IdSrv to post the data back to us //options.ResponseMode = OidcConstants.ResponseModes.FormPost; // we use the authorisation code flow, so only asking for a code options.ResponseType = OidcConstants.ResponseTypes.Code; options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; // when the identity has been created from the data we receive, // persist it with this authentication scheme, hence in a cookie options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // using this property would align the expiration of the cookie // with the expiration of the identity token options.UseTokenLifetime = true; options.Events = new OpenIdConnectEvents { // that event is called after the OIDC middleware received the auhorisation code, // redeemed it for an access token and a refresh token, // and validated the identity token OnTokenValidated = x => { // store both access and refresh token in the claims - hence in the cookie var identity = (ClaimsIdentity)x.Principal.Identity; identity.AddClaims(new[] { new Claim("access_token", x.TokenEndpointResponse.AccessToken), new Claim("refresh_token", x.TokenEndpointResponse.RefreshToken) }); // so that we don't issue a session cookie but one with a fixed expiration x.Properties.IsPersistent = true; // align expiration of the cookie with expiration of the // access token var accessToken = new JwtSecurityToken(x.TokenEndpointResponse.AccessToken); x.Properties.ExpiresUtc = accessToken.ValidTo; x.Properties.IssuedUtc = DateTime.UtcNow; x.Properties.AllowRefresh = true; Debug.WriteLine("OIDC.OnTokenValidated - Token validated, Issued UTC: {0}, Expires UTC: {1}", x.Properties.IssuedUtc, x.Properties.ExpiresUtc); x.HttpContext.Session.Set<string>(Constants.ACCESS_TOKEN_SESSION_ID, x.TokenEndpointResponse.AccessToken); return Task.CompletedTask; } }; }); services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN"); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } loggerFactory.AddLog4Net(); app.UseSession(); //Register Syncfusion license Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("License"); app.UseAuthentication(); app.UseCors(); app.UseCorsHeaderMiddleware(); app.UseExceptionHandlingMiddleware(); if (!env.IsDevelopment()) { app.UseHttpsRedirection(); } app.UseStaticFiles(); app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } } For the sake of completeness, here is the code for our cors-middleware: using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using System.Threading.Tasks; namespace DefectsWebApp.Middleware { public class CorsHeaderMiddleware { private readonly RequestDelegate _next; private IConfiguration _configuration; private string _origin; /// <summary> /// Ctor /// </summary> /// <param name="next">Reference to following request</param> public CorsHeaderMiddleware(RequestDelegate next, IConfiguration configuration) { _next = next; _configuration = configuration; _origin = _configuration["Authentication:oidc:OIDCRoot"] + "/*, /*"; } /// <summary> /// Fügt dem Request IMMER den Header "Access-Control-Allow-Origin" hinzu /// </summary> public async Task Invoke(HttpContext httpContext) { var request = httpContext.Request; if (!request.Headers.ContainsKey(Constants.ORIGIN_HEADER)) { request.Headers.Add(Constants.ORIGIN_HEADER, _origin); } if (!request.Headers.ContainsKey(Constants.CONTENT_HEADER)) { request.Headers.Add(Constants.CONTENT_HEADER, "Origin, X-Requested-With, Content-Type, Accept"); } await _next(httpContext); } } public static class CorsHeaderMiddlewareExtensions { public static IApplicationBuilder UseCorsHeaderMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CorsHeaderMiddleware>(); } } } Edit 1 [2020-04-30 10:45] This is our current configuration. To eliminate problems regarding localhost, we entered our test machine's DNS name as web origin. A: I guess you didn't configure Web Origins (that is not the same as Redirect URIs) in your OIDC client configuration in the Keycloak. You can use '*', because you are using http protocol. I hope you know that https protocol is mandatory for OIDC flows and also that '*' is not valid Web Origin value for https protocol. So it is good idea to configure Web Origins explicitly, instead of wildcard for the future. The best idea is to use already in dev: * *https, because it may work in dev on http, but then you will move to https in prod and it will be broken *domain (you can "fake" it with local hosts file) instead of localhost, because some browsers may have a problem with localhost/127.0.0.1/... A: this is actually is a bug in dotnet core. try to add cors policy right in the "Configure" method. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseCors(option => option.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() ); }
doc_23527643
Added custom markers on the map according to positions fetched from API. I have displayed list of positions on UI. After click on position I want to replace that position's corresponding marker icon and reset all other icons. Following code is not working as expected. I have added this function to place markers on map: placeMarkers(markers: any, infoWindowContent: any) { // Display multiple markers on a map let infoWindow = new google.maps.InfoWindow(); let bounds = new google.maps.LatLngBounds(); let marker; // Loop through our array of markers & place each one on the map for(let i = 0; i < markers.length; i++ ) { let position = new google.maps.LatLng(<number>markers[i].lat, <number>markers[i].lang); bounds.extend(position); marker = new google.maps.Marker(<google.maps.MarkerOptions>{ position, map: this.map, title: markers[i].name, icon: this.iconUrl, }); // Allow each marker to have an info window google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infoWindow.setContent(infoWindowContent[i]); infoWindow.open(this.map, marker); } })(marker, i)); // Automatically center the map fitting all markers on the screen this.map.fitBounds(bounds); } } And this code to replace marker of selected position: selectSite(site: any, index: any) { this.placeMarkers(this.finalMarkers, this.finalInfoWindowContent); let selection = this.finalMarkers.find(function(item) { return item.name == site.Name }); let infowindow = new google.maps.InfoWindow(); let position = new google.maps.LatLng(<number>selection.lat, <number>selection.lang); let redMarker = new google.maps.Marker(<google.maps.MarkerOptions>{ position: position, map: this.map, title: selection.name, icon: {url: require('../../../assets/img/red-marker.png'), scaledSize: {height: 30, width: 20}} }); redMarker.addListener('click', function() { infowindow.setContent(selection.name); infowindow.open(this.map, redMarker); }); } Above code is working fine initially, but got stuck after multiple location changes. Any help is very much appreciated! A: **You can Set Following marker** var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { parking: { icon: iconBase + 'parking_lot_maps.png' }, library: { icon: iconBase + 'library_maps.png' }, info: { icon: iconBase + 'info-i_maps.png' } }; A: This is how I did it. I simply did it outside google maps and it works great. https://youtu.be/2cA3pQQoEr8
doc_23527644
I've started mining on www.multiport.us and as such I am mining many different coins. Scrypt coins and sha-256. I'd rather not have all my coins on Cryptsy or Vircuex, so I'm trying to get the Qt GUIs for each of the coins install compiled so I can have wallets on my PC. Problem I've been trying for several days now to get this stuff working and I just can't. I've tried with several different coins - Feathercoin, Novacoin, Namecoin, Worldcoin, Freicoin, Zetacoin, etc. I have tried terminal, and Qt Creator, but I get different errors on each wallet, almost always missing program errors. I get missing bitcoin.cpp, missing QApplication, etc, etc. They just refuse to compile. Fixes tried In Qt Creator I have tried adding QT += Widgets, tried a couple of other things too. In terminal I was originally using 'qmake', then 'make'. But that's been giving me various errors. Missing locale/****, or missing <QApplication> I have been getting all my source files from the official SourceForge pages, and trying the latest releases and the "master" file list. System Ubuntu 13.10 qmake QMake version 3.0 Using Qt version 5.0.2 in /usr/lib/x86_64-linux-gnu QTCreator version 2.7.1 Following the readme's and instructional files i have also installed the following dependancies qt4-qmake libqt4-dev build-essential libboost-dev libboost-system-dev libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev \ libssl-dev libdb++-dev libminiupnpc-dev libgmp3-dev libmpfr-dev I really don't know what the problem is. I'm guessing it has something to do with being on 13.10, either that or there is something major I'm just not seeing. But all the source files are the same, they are built so all you need to do is qmake and make, to compile on your own system and then run. But I'm just having no luck at all. QT Creator is version 2.7.1 from the repository. Here is the .pro file I'm using. TEMPLATE = app TARGET = bitcoin-qt macx:TARGET = "Bitcoin-Qt" VERSION = 0.8.3 INCLUDEPATH += src src/json src/qt QT += network DEFINES += QT_GUI BOOST_THREAD_USE_LIB BOOST_SPIRIT_THREADSAFE CONFIG += no_include_pwd CONFIG += thread # for boost 1.37, add -mt to the boost libraries # use: qmake BOOST_LIB_SUFFIX=-mt # for boost thread win32 with _win32 sufix # use: BOOST_THREAD_LIB_SUFFIX=_win32-... # or when linking against a specific BerkelyDB version: BDB_LIB_SUFFIX=-4.8 # Dependency library locations can be customized with: # BOOST_INCLUDE_PATH, BOOST_LIB_PATH, BDB_INCLUDE_PATH, # BDB_LIB_PATH, OPENSSL_INCLUDE_PATH and OPENSSL_LIB_PATH respectively OBJECTS_DIR = build MOC_DIR = build UI_DIR = build # use: qmake "RELEASE=1" contains(RELEASE, 1) { # Mac: compile for maximum compatibility (10.5, 32-bit) macx:QMAKE_CXXFLAGS += -mmacosx-version-min=10.5 -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk macx:QMAKE_CFLAGS += -mmacosx-version-min=10.5 -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk macx:QMAKE_OBJECTIVE_CFLAGS += -mmacosx-version-min=10.5 -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk !win32:!macx { # Linux: static link and extra security (see: https://wiki.debian.org/Hardening) LIBS += -Wl,-Bstatic -Wl,-z,relro -Wl,-z,now } } !win32 { # for extra security against potential buffer overflows: enable GCCs Stack Smashing Protection QMAKE_CXXFLAGS *= -fstack-protector-all QMAKE_LFLAGS *= -fstack-protector-all # Exclude on Windows cross compile with MinGW 4.2.x, as it will result in a non-working executable! # This can be enabled for Windows, when we switch to MinGW >= 4.4.x. } # for extra security (see: https://wiki.debian.org/Hardening): this flag is GCC compiler-specific QMAKE_CXXFLAGS *= -D_FORTIFY_SOURCE=2 # for extra security on Windows: enable ASLR and DEP via GCC linker flags win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat # on Windows: enable GCC large address aware linker flag win32:QMAKE_LFLAGS *= -Wl,--large-address-aware # use: qmake "USE_QRCODE=1" # libqrencode (http://fukuchi.org/works/qrencode/index.en.html) must be installed for support contains(USE_QRCODE, 1) { message(Building with QRCode support) DEFINES += USE_QRCODE LIBS += -lqrencode } # use: qmake "USE_UPNP=1" ( enabled by default; default) # or: qmake "USE_UPNP=0" (disabled by default) # or: qmake "USE_UPNP=-" (not supported) # miniupnpc (http://miniupnp.free.fr/files/) must be installed for support contains(USE_UPNP, -) { message(Building without UPNP support) } else { message(Building with UPNP support) count(USE_UPNP, 0) { USE_UPNP=1 } DEFINES += USE_UPNP=$$USE_UPNP STATICLIB INCLUDEPATH += $$MINIUPNPC_INCLUDE_PATH LIBS += $$join(MINIUPNPC_LIB_PATH,,-L,) -lminiupnpc win32:LIBS += -liphlpapi } # use: qmake "USE_DBUS=1" contains(USE_DBUS, 1) { message(Building with DBUS (Freedesktop notifications) support) DEFINES += USE_DBUS QT += dbus } # use: qmake "USE_IPV6=1" ( enabled by default; default) # or: qmake "USE_IPV6=0" (disabled by default) # or: qmake "USE_IPV6=-" (not supported) contains(USE_IPV6, -) { message(Building without IPv6 support) } else { count(USE_IPV6, 0) { USE_IPV6=1 } DEFINES += USE_IPV6=$$USE_IPV6 } contains(BITCOIN_NEED_QT_PLUGINS, 1) { DEFINES += BITCOIN_NEED_QT_PLUGINS QTPLUGIN += qcncodecs qjpcodecs qtwcodecs qkrcodecs qtaccessiblewidgets } INCLUDEPATH += src/leveldb/include src/leveldb/helpers LIBS += $$PWD/src/leveldb/libleveldb.a $$PWD/src/leveldb/libmemenv.a !win32 { # we use QMAKE_CXXFLAGS_RELEASE even without RELEASE=1 because we use RELEASE to indicate linking preferences not -O preferences genleveldb.commands = cd $$PWD/src/leveldb && CC=$$QMAKE_CC CXX=$$QMAKE_CXX $(MAKE) OPT=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\" libleveldb.a libmemenv.a } else { # make an educated guess about what the ranlib command is called isEmpty(QMAKE_RANLIB) { QMAKE_RANLIB = $$replace(QMAKE_STRIP, strip, ranlib) } LIBS += -lshlwapi genleveldb.commands = cd $$PWD/src/leveldb && CC=$$QMAKE_CC CXX=$$QMAKE_CXX TARGET_OS=OS_WINDOWS_CROSSCOMPILE $(MAKE) OPT=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\" libleveldb.a libmemenv.a && $$QMAKE_RANLIB $$PWD/src/leveldb/libleveldb.a && $$QMAKE_RANLIB $$PWD/src/leveldb/libmemenv.a } genleveldb.target = $$PWD/src/leveldb/libleveldb.a genleveldb.depends = FORCE PRE_TARGETDEPS += $$PWD/src/leveldb/libleveldb.a QMAKE_EXTRA_TARGETS += genleveldb # Gross ugly hack that depends on qmake internals, unfortunately there is no other way to do it. QMAKE_CLEAN += $$PWD/src/leveldb/libleveldb.a; cd $$PWD/src/leveldb ; $(MAKE) clean # regenerate src/build.h !win32|contains(USE_BUILD_INFO, 1) { genbuild.depends = FORCE genbuild.commands = cd $$PWD; /bin/sh share/genbuild.sh $$OUT_PWD/build/build.h genbuild.target = $$OUT_PWD/build/build.h PRE_TARGETDEPS += $$OUT_PWD/build/build.h QMAKE_EXTRA_TARGETS += genbuild DEFINES += HAVE_BUILD_INFO } QMAKE_CXXFLAGS_WARN_ON = -fdiagnostics-show-option -Wall -Wextra -Wformat -Wformat-security -Wno-unused-parameter -Wstack-protector # Input DEPENDPATH += src src/json src/qt HEADERS += src/qt/bitcoingui.h \ src/qt/transactiontablemodel.h \ src/qt/addresstablemodel.h \ src/qt/optionsdialog.h \ src/qt/sendcoinsdialog.h \ src/qt/addressbookpage.h \ src/qt/signverifymessagedialog.h \ src/qt/aboutdialog.h \ src/qt/editaddressdialog.h \ src/qt/bitcoinaddressvalidator.h \ src/alert.h \ src/addrman.h \ src/base58.h \ src/bignum.h \ src/checkpoints.h \ src/compat.h \ src/sync.h \ src/util.h \ src/hash.h \ src/uint256.h \ src/serialize.h \ src/main.h \ src/net.h \ src/key.h \ src/db.h \ src/walletdb.h \ src/script.h \ src/init.h \ src/bloom.h \ src/mruset.h \ src/checkqueue.h \ src/json/json_spirit_writer_template.h \ src/json/json_spirit_writer.h \ src/json/json_spirit_value.h \ src/json/json_spirit_utils.h \ src/json/json_spirit_stream_reader.h \ src/json/json_spirit_reader_template.h \ src/json/json_spirit_reader.h \ src/json/json_spirit_error_position.h \ src/json/json_spirit.h \ src/qt/clientmodel.h \ src/qt/guiutil.h \ src/qt/transactionrecord.h \ src/qt/guiconstants.h \ src/qt/optionsmodel.h \ src/qt/monitoreddatamapper.h \ src/qt/transactiondesc.h \ src/qt/transactiondescdialog.h \ src/qt/bitcoinamountfield.h \ src/wallet.h \ src/keystore.h \ src/qt/transactionfilterproxy.h \ src/qt/transactionview.h \ src/qt/walletmodel.h \ src/qt/walletview.h \ src/qt/walletstack.h \ src/qt/walletframe.h \ src/bitcoinrpc.h \ src/qt/overviewpage.h \ src/qt/csvmodelwriter.h \ src/crypter.h \ src/qt/sendcoinsentry.h \ src/qt/qvalidatedlineedit.h \ src/qt/bitcoinunits.h \ src/qt/qvaluecombobox.h \ src/qt/askpassphrasedialog.h \ src/protocol.h \ src/qt/notificator.h \ src/qt/paymentserver.h \ src/allocators.h \ src/ui_interface.h \ src/qt/rpcconsole.h \ src/version.h \ src/netbase.h \ src/clientversion.h \ src/txdb.h \ src/leveldb.h \ src/threadsafety.h \ src/limitedmap.h \ src/qt/splashscreen.h SOURCES += src/qt/bitcoin.cpp \ src/qt/bitcoingui.cpp \ src/qt/transactiontablemodel.cpp \ src/qt/addresstablemodel.cpp \ src/qt/optionsdialog.cpp \ src/qt/sendcoinsdialog.cpp \ src/qt/addressbookpage.cpp \ src/qt/signverifymessagedialog.cpp \ src/qt/aboutdialog.cpp \ src/qt/editaddressdialog.cpp \ src/qt/bitcoinaddressvalidator.cpp \ src/alert.cpp \ src/version.cpp \ src/sync.cpp \ src/util.cpp \ src/hash.cpp \ src/netbase.cpp \ src/key.cpp \ src/script.cpp \ src/main.cpp \ src/init.cpp \ src/net.cpp \ src/bloom.cpp \ src/checkpoints.cpp \ src/addrman.cpp \ src/db.cpp \ src/walletdb.cpp \ src/qt/clientmodel.cpp \ src/qt/guiutil.cpp \ src/qt/transactionrecord.cpp \ src/qt/optionsmodel.cpp \ src/qt/monitoreddatamapper.cpp \ src/qt/transactiondesc.cpp \ src/qt/transactiondescdialog.cpp \ src/qt/bitcoinstrings.cpp \ src/qt/bitcoinamountfield.cpp \ src/wallet.cpp \ src/keystore.cpp \ src/qt/transactionfilterproxy.cpp \ src/qt/transactionview.cpp \ src/qt/walletmodel.cpp \ src/qt/walletview.cpp \ src/qt/walletstack.cpp \ src/qt/walletframe.cpp \ src/bitcoinrpc.cpp \ src/rpcdump.cpp \ src/rpcnet.cpp \ src/rpcmining.cpp \ src/rpcwallet.cpp \ src/rpcblockchain.cpp \ src/rpcrawtransaction.cpp \ src/qt/overviewpage.cpp \ src/qt/csvmodelwriter.cpp \ src/crypter.cpp \ src/qt/sendcoinsentry.cpp \ src/qt/qvalidatedlineedit.cpp \ src/qt/bitcoinunits.cpp \ src/qt/qvaluecombobox.cpp \ src/qt/askpassphrasedialog.cpp \ src/protocol.cpp \ src/qt/notificator.cpp \ src/qt/paymentserver.cpp \ src/qt/rpcconsole.cpp \ src/noui.cpp \ src/leveldb.cpp \ src/txdb.cpp \ src/qt/splashscreen.cpp RESOURCES += src/qt/bitcoin.qrc FORMS += src/qt/forms/sendcoinsdialog.ui \ src/qt/forms/addressbookpage.ui \ src/qt/forms/signverifymessagedialog.ui \ src/qt/forms/aboutdialog.ui \ src/qt/forms/editaddressdialog.ui \ src/qt/forms/transactiondescdialog.ui \ src/qt/forms/overviewpage.ui \ src/qt/forms/sendcoinsentry.ui \ src/qt/forms/askpassphrasedialog.ui \ src/qt/forms/rpcconsole.ui \ src/qt/forms/optionsdialog.ui contains(USE_QRCODE, 1) { HEADERS += src/qt/qrcodedialog.h SOURCES += src/qt/qrcodedialog.cpp FORMS += src/qt/forms/qrcodedialog.ui } contains(BITCOIN_QT_TEST, 1) { SOURCES += src/qt/test/test_main.cpp \ src/qt/test/uritests.cpp HEADERS += src/qt/test/uritests.h DEPENDPATH += src/qt/test QT += testlib TARGET = bitcoin-qt_test DEFINES += BITCOIN_QT_TEST macx: CONFIG -= app_bundle } CODECFORTR = UTF-8 # for lrelease/lupdate # also add new translations to src/qt/bitcoin.qrc under translations/ TRANSLATIONS = $$files(src/qt/locale/bitcoin_*.ts) isEmpty(QMAKE_LRELEASE) { win32:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]\\lrelease.exe else:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]/lrelease } isEmpty(QM_DIR):QM_DIR = $$PWD/src/qt/locale # automatically build translations, so they can be included in resource file TSQM.name = lrelease ${QMAKE_FILE_IN} TSQM.input = TRANSLATIONS TSQM.output = $$QM_DIR/${QMAKE_FILE_BASE}.qm TSQM.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_OUT} TSQM.CONFIG = no_link QMAKE_EXTRA_COMPILERS += TSQM # "Other files" to show in Qt Creator OTHER_FILES += README.md \ doc/*.rst \ doc/*.txt \ src/qt/res/bitcoin-qt.rc \ src/test/*.cpp \ src/test/*.h \ src/qt/test/*.cpp \ src/qt/test/*.h # platform specific defaults, if not overridden on command line isEmpty(BOOST_LIB_SUFFIX) { macx:BOOST_LIB_SUFFIX = -mt win32:BOOST_LIB_SUFFIX = -mgw44-mt-s-1_50 } isEmpty(BOOST_THREAD_LIB_SUFFIX) { BOOST_THREAD_LIB_SUFFIX = $$BOOST_LIB_SUFFIX } isEmpty(BDB_LIB_PATH) { macx:BDB_LIB_PATH = /opt/local/lib/db48 } isEmpty(BDB_LIB_SUFFIX) { macx:BDB_LIB_SUFFIX = -4.8 } isEmpty(BDB_INCLUDE_PATH) { macx:BDB_INCLUDE_PATH = /opt/local/include/db48 } isEmpty(BOOST_LIB_PATH) { macx:BOOST_LIB_PATH = /opt/local/lib } isEmpty(BOOST_INCLUDE_PATH) { macx:BOOST_INCLUDE_PATH = /opt/local/include } win32:DEFINES += WIN32 win32:RC_FILE = src/qt/res/bitcoin-qt.rc win32:!contains(MINGW_THREAD_BUGFIX, 0) { # At least qmake's win32-g++-cross profile is missing the -lmingwthrd # thread-safety flag. GCC has -mthreads to enable this, but it doesn't # work with static linking. -lmingwthrd must come BEFORE -lmingw, so # it is prepended to QMAKE_LIBS_QT_ENTRY. # It can be turned off with MINGW_THREAD_BUGFIX=0, just in case it causes # any problems on some untested qmake profile now or in the future. DEFINES += _MT QMAKE_LIBS_QT_ENTRY = -lmingwthrd $$QMAKE_LIBS_QT_ENTRY } !win32:!macx { DEFINES += LINUX LIBS += -lrt # _FILE_OFFSET_BITS=64 lets 32-bit fopen transparently support large files. DEFINES += _FILE_OFFSET_BITS=64 } macx:HEADERS += src/qt/macdockiconhandler.h macx:OBJECTIVE_SOURCES += src/qt/macdockiconhandler.mm macx:LIBS += -framework Foundation -framework ApplicationServices -framework AppKit macx:DEFINES += MAC_OSX MSG_NOSIGNAL=0 macx:ICON = src/qt/res/icons/bitcoin.icns macx:QMAKE_CFLAGS_THREAD += -pthread macx:QMAKE_LFLAGS_THREAD += -pthread macx:QMAKE_CXXFLAGS_THREAD += -pthread macx:QMAKE_INFO_PLIST = share/qt/Info.plist # Set libraries and includes at end, to use platform-defined defaults if not overridden INCLUDEPATH += $$BOOST_INCLUDE_PATH $$BDB_INCLUDE_PATH $$OPENSSL_INCLUDE_PATH $$QRENCODE_INCLUDE_PATH LIBS += $$join(BOOST_LIB_PATH,,-L,) $$join(BDB_LIB_PATH,,-L,) $$join(OPENSSL_LIB_PATH,,-L,) $$join(QRENCODE_LIB_PATH,,-L,) LIBS += -lssl -lcrypto -ldb_cxx$$BDB_LIB_SUFFIX # -lgdi32 has to happen after -lcrypto (see #681) win32:LIBS += -lws2_32 -lshlwapi -lmswsock -lole32 -loleaut32 -luuid -lgdi32 LIBS += -lboost_system$$BOOST_LIB_SUFFIX -lboost_filesystem$$BOOST_LIB_SUFFIX -lboost_program_options$$BOOST_LIB_SUFFIX -lboost_thread$$BOOST_THREAD_LIB_SUFFIX win32:LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX macx:LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX contains(RELEASE, 1) { !win32:!macx { # Linux: turn dynamic linking back on for c/c++ runtime libraries LIBS += -Wl,-Bdynamic } } system($$QMAKE_LRELEASE -silent $$TRANSLATIONS) As I have said the instructions that all of the wallets I'm trying to compile come with say the exact same thing. Bitcoin-Qt: Qt4 GUI for Bitcoin =============================== Build instructions =================== Debian ------- First, make sure that the required packages for Qt4 development of your distribution are installed, these are :: for Debian and Ubuntu <= 11.10 : :: apt-get install qt4-qmake libqt4-dev build-essential libboost-dev libboost-system-dev \ libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev \ libssl-dev libdb4.8++-dev for Ubuntu >= 12.04 (please read the 'Berkely DB version warning' below): :: apt-get install qt4-qmake libqt4-dev build-essential libboost-dev libboost-system-dev \ libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev \ libssl-dev libdb++-dev libminiupnpc-dev then execute the following: :: qmake make Alternatively, install `Qt Creator`_ and open the `bitcoin-qt.pro` file. An executable named `bitcoin-qt` will be built. .. _`Qt Creator`: http://qt-project.org/downloads/ Mac OS X -------- - Download and install the `Qt Mac OS X SDK`_. It is recommended to also install Apple's Xcode with UNIX tools. - Download and install either `MacPorts`_ or `HomeBrew`_. - Execute the following commands in a terminal to get the dependencies using MacPorts: :: sudo port selfupdate sudo port install boost db48 miniupnpc - Execute the following commands in a terminal to get the dependencies using HomeBrew: :: brew update brew install boost miniupnpc openssl berkeley-db4 - If using HomeBrew, edit `bitcoin-qt.pro` to account for library location differences. There's a diff in `contrib/homebrew/bitcoin-qt-pro.patch` that shows what you need to change, or you can just patch by doing patch -p1 < contrib/homebrew/bitcoin.qt.pro.patch - Open the bitcoin-qt.pro file in Qt Creator and build as normal (cmd-B) .. _`Qt Mac OS X SDK`: http://qt-project.org/downloads/ .. _`MacPorts`: http://www.macports.org/install.php .. _`HomeBrew`: http://mxcl.github.io/homebrew/ Build configuration options ============================ UPnP port forwarding --------------------- To use UPnP for port forwarding behind a NAT router (recommended, as more connections overall allow for a faster and more stable bitcoin experience), pass the following argument to qmake: :: qmake "USE_UPNP=1" (in **Qt Creator**, you can find the setting for additional qmake arguments under "Projects" -> "Build Settings" -> "Build Steps", then click "Details" next to **qmake**) This requires miniupnpc for UPnP port mapping. It can be downloaded from http://miniupnp.tuxfamily.org/files/. UPnP support is not compiled in by default. Set USE_UPNP to a different value to control this: +------------+--------------------------------------------------------------------------+ | USE_UPNP=- | no UPnP support, miniupnpc not required; | +------------+--------------------------------------------------------------------------+ | USE_UPNP=0 | (the default) built with UPnP, support turned off by default at runtime; | +------------+--------------------------------------------------------------------------+ | USE_UPNP=1 | build with UPnP support turned on by default at runtime. | +------------+--------------------------------------------------------------------------+ Notification support for recent (k)ubuntu versions --------------------------------------------------- To see desktop notifications on (k)ubuntu versions starting from 10.04, enable usage of the FreeDesktop notification interface through DBUS using the following qmake option: :: qmake "USE_DBUS=1" Generation of QR codes ----------------------- libqrencode may be used to generate QRCode images for payment requests. It can be downloaded from http://fukuchi.org/works/qrencode/index.html.en, or installed via your package manager. Pass the USE_QRCODE flag to qmake to control this: +--------------+--------------------------------------------------------------------------+ | USE_QRCODE=0 | (the default) No QRCode support - libarcode not required | +--------------+--------------------------------------------------------------------------+ | USE_QRCODE=1 | QRCode support enabled | +--------------+--------------------------------------------------------------------------+ Berkely DB version warning ========================== A warning for people using the *static binary* version of Bitcoin on a Linux/UNIX-ish system (tl;dr: **Berkely DB databases are not forward compatible**). The static binary version of Bitcoin is linked against libdb4.8 (see also `this Debian issue`_). Now the nasty thing is that databases from 5.X are not compatible with 4.X. If the globally installed development package of Berkely DB installed on your system is 5.X, any source you build yourself will be linked against that. The first time you run with a 5.X version the database will be upgraded, and 4.X cannot open the new format. This means that you cannot go back to the old statically linked version without significant hassle! .. _`this Debian issue`: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=621425 Ubuntu 11.10 warning ==================== Ubuntu 11.10 has a package called 'qt-at-spi' installed by default. At the time of writing, having that package installed causes bitcoin-qt to crash intermittently. The issue has been reported as `launchpad bug 857790`_, but isn't yet fixed. Until the bug is fixed, you can remove the qt-at-spi package to work around the problem, though this will presumably disable screen reader functionality for Qt apps: :: sudo apt-get remove qt-at-spi .. _`launchpad bug 857790`: https://bugs.launchpad.net/ubuntu/+source/qt-at-spi/+bug/857790 But when I try and compile with QT Creator or through terminal I get: home/kun7/CoinMining/zetacoin-0.8.3/src/qt/bitcoin.cpp:5: error: QApplication: No such file or directory I have found that lots of people are adding 'QT += widgets' to their .ro files and it fixes it, but when I do that I get: /home/kun7/CoinMining/zetacoin-0.8.3/src/qt/bitcoin.cpp:122: error: 'setCodecForTr' is not a member of 'QTextCodec' /home/kun7/CoinMining/zetacoin-0.8.3/src/qt/bitcoin.cpp:123: error: 'setCodecForCStrings' is not a member of 'QTextCodec' /home/kun7/CoinMining/zetacoin-0.8.3/src/qt/bitcoin.cpp:123: error: 'codecForTr' is not a member of 'QTextCodec' What am I missing? A: The issue has been fixed!!! I was a moron. I was trying to run qmake make But my system has qmake version 5 installed and i installed verion 4 as per the dependencies. So instead, to get the program to compile correctly, i need to force the use of version 4... qmake-qt4 make Voiala!!!!!
doc_23527645
Here's the project navigator. I added all the frameworks because another answer suggested it, but it didn't need them before. Here is the device log... Jun 3 22:16:57 Ians-iPhone com.apple.xpc.launchd1 (UIKitApplication:com.MyApp.MyApp.UI[0x8927][902]) : Service exited due to signal: Killed: 9 Jun 3 22:16:57 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [901] : Got a 'k' packet, killing the inferior process. Jun 3 22:16:57 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [901] : Sending ptrace PT_KILL to terminate inferior process. Jun 3 22:16:57 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [901] : 1 +0.000000 sec [0385/0c07]: error: ::ptrace (request = PT_THUPDATE, pid = 0x0386, tid = 0x2b07, signal = 0) err = Resource busy (0x00000010) Jun 3 22:16:57 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [901] : Waited 10 ms for process to be reaped (state = Exited) Jun 3 22:16:57 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [901] : 2 +0.013070 sec [0385/1107]: error: ::read ( -1, 0x16e2d2a38, 1024 ) => -1 err = Bad file descriptor (0x00000009) Jun 3 22:16:57 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [901] : Exiting. Jun 3 22:16:57 Ians-iPhone SpringBoard[58] : Application 'UIKitApplication:com.MyApp.MyApp.UI[0x8927]' exited abnormally via signal. Jun 3 22:17:16 Ians-iPhone installd[753] : 0x16e1bb000 -[MIClientConnection _doBackgroundInstallationForPath:withOptions:completion:]: Install of "/var/mobile/Media/PublicStaging/UI.app_sparse.ipa" type Developer (LSInstallType = (null)) requested by streaming_zip_conduit (pid 792) Jun 3 22:17:16 Ians-iPhone installd[753] : 0x16e1bb000 -[MIInstaller performInstallationWithError:]: Installing Jun 3 22:17:16 Ians-iPhone installd[753] : 0x16e1bb000 -[MIInstallableBundlePatch applyPatchWithError:]: Attempting patch update of com.MyApp.MyApp.UI from 1 (1.0) to 1 (1.0) Jun 3 22:17:16 Ians-iPhone profiled[157] : (Note ) MC: Provisioning profiles changed Jun 3 22:17:16 Ians-iPhone profiled[157] : (Note ) MC: Updating MIS trust... Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:16 Ians-iPhone installd[753] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:16 Ians-iPhone installd[753] : 0x16e1bb000 -[MIInstallableBundle _refreshUUIDForContainer:withError:]: Data container for com.MyApp.MyApp.UI is now at /private/var/mobile/Containers/Data/Application/89118C1E-9A27-4EA0-B26D-8698EEF941D5 Jun 3 22:17:17 Ians-iPhone installd[753] : 0x16e1bb000 -[MIContainer makeContainerLiveReplacingContainer:reason:withError:]: Made container live for com.MyApp.MyApp.UI at /private/var/containers/Bundle/Application/FD7042F3-8D64-454F-A646-A7C3553E7B4A Jun 3 22:17:17 Ians-iPhone installd[753] : 0x16e1bb000 -[MIInstaller performInstallationWithError:]: Install Successful; Staging: 0.00s; Waiting: 0.00s; Preflight/Patch: 0.27s, Verifying: 0.11s; Overall: 1.11s Jun 3 22:17:17 Ians-iPhone pkd[111] : releasing plug-in hold 18687614-D5AE-4471-998C-6C6D4B0E00A1 at client's request Jun 3 22:17:17 Ians-iPhone online-auth-agent[170] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:17 Ians-iPhone syncdefaultsd[908] : (Note ) marked "com.me.keyvalueservice" topic as "opportunistic" on Jun 3 22:17:17 Ians-iPhone syncdefaultsd[908] : (Note ) marked "com.me.keyvalueservice" topic as "enabled" on Jun 3 22:17:17 Ians-iPhone SpringBoard[58] : Installed apps did change. Added: {( )} Removed: {( )} Modified: {( "com.MyApp.MyApp.UI" )} Jun 3 22:17:18 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 for arm64. Jun 3 22:17:18 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : Connecting to com.apple.debugserver service... Jun 3 22:17:18 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : Got a connection, waiting for process information for launching or attaching. Jun 3 22:17:19 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : Sending AppProxy info: sequence no: 202, GUID: B89B714A-35DE-43E5-9655-D4EDC8D8ED76. Jun 3 22:17:19 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : error: Unrecognized event type: . Ignoring. Jun 3 22:17:19 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : About to launch process for bundle ID: com.MyApp.MyApp.UI Jun 3 22:17:19 Ians-iPhone SpringBoard[58] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:19 Ians-iPhone SpringBoard[58] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:19 Ians-iPhone com.apple.xpc.launchd1 (UIKitApplication:com.MyApp.MyApp.UI[0xb236]) : The DisableASLR key is no longer respected. Please remove it. Jun 3 22:17:19 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:19 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:19 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:19 Ians-iPhone kernel[0] : xpcproxy[910] Container: /private/var/mobile/Containers/Data/Application/89118C1E-9A27-4EA0-B26D-8698EEF941D5 (sandbox) Jun 3 22:17:19 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : In completion handler, got pid for bundle id, pid: 910. Jun 3 22:17:19 Ians-iPhone com.apple.debugserver-@(#)PROGRAM:debugserver PROJECT:debugserver-340.3.124 [909] : Got a connection, launched process /private/var/containers/Bundle/Application/FD7042F3-8D64-454F-A646-A7C3553E7B4A/UI.app (pid = 910). Jun 3 22:17:19 Ians-iPhone SpringBoard[58] : LICreateIconForImage passed NULL CGImageRef image Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone securityd[92] : secTaskDiagnoseEntitlements MISSING keychain entitlements: no stored taskRef found Jun 3 22:17:21 Ians-iPhone amfid[250] : SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName] Any ideas? A: I synced the device to my computer and examined the crash report. It said... Dyld Error Message: Dyld Message: Library not loaded: @rpath/SwiftyJSON.framework/SwiftyJSON Referenced from: /private/var/containers/Bundle/Application/7DC13701-64BE-4DED-9DEB-5346E0A18EE3/UI.app/Frameworks/DataAccess.framework/DataAccess Reason: image not found Dyld Version: 390.7 So, I'd not added one of the libraries.
doc_23527646
I've got something like that http://jsfiddle.net/ot6fe3no/ but when I click rows are added in all tables. Here is the code: (function( $ ){ $.fn.tablaraize = function() { var numShown = 5; // Initial rows shown & index var numMore = 5; // Increment var $table2 = $(this); // tbody containing all the rows var $table = $(this).find('tbody'); // tbody containing all the rows var numRows = $table.find('tr').length; // Total # rows // Hide rows and add clickable div $table.find('tr:gt(' + (numShown - 1) + ')').hide().end() .after('<tbody id="more"><tr><td colspan="' + $table.find('tr:first td').length + '"><div>Show more</div</tbody></td></tr>'); $table2.find('#more').click(function() { numShown = numShown + numMore; // no more "show more" if done if (numShown >= numRows) { $table2.find('#more').remove(); } $table.find('tr:lt(' + numShown + ')').show(); }); }; })( jQuery ); $('table').tablaraize(); A: Just update your fiddle (function( $ ){ $.fn.tablaraize = function() { var numShown = 5; // Initial rows shown & index var numMore = 5; // Increment var $table2 = $(this); // tbody containing all the rows var $table = $(this).find('tbody'); // tbody containing all the rows var numRows = $table.find('tr').length; // Total # rows // Hide rows and add clickable div $table.find('tr:gt(' + (numShown - 1) + ')').hide().end() .after('<tbody id="more"><tr><td colspan="' + $table.find('tr:first td').length + '"><div>Show more</div</tbody></td></tr>'); $table2.find('#more').click(function() { numShown = numShown + numMore; // no more "show more" if done if (numShown >= numRows) { $table2.find('#more').remove(); } // $table.find('tr:lt(' + numShown + ')').show(); this will run on all table $(this).parent("table").find('tr:lt(' + numShown + ')').show(); // show the rows of current clicked }); }; })( jQuery ); $('table').tablaraize(); fiddle link A: Thanks for help, it's working but I found two problems: 1. Show more is not disapearing when all rows are visible, I fix it with: // no more "show more" if done if (numShown+1 >= numRows) { //$table2.find('#more').remove(); $(this).parent("table").find('#more').remove(); } *When there is 2 rows - Show more is appearing, I cant find the way the way around this
doc_23527647
I have created below file: .ebextentions/nginx/conf.d/myapp.conf And I added the below content based on this article: server { if ($http_x_forwarded_proto != 'https') { rewrite ^(.*) https://$host$1 redirect; } } I have installed SSL certificate in certificate manager and set it in my environment. Now the application serves both HTTP and https request. I want to redirect all HTTP requests to https without falling into a redirect loop. but doesn't work. A: I don't think you should add the server part to the .conf file. The entire .conf file should be something like this: if ($http_x_forwarded_proto = 'http') { return 301 https://www.example.com$request_uri; } See this answer on Server Fault.
doc_23527648
A: That is an embedded copy of the ConcurrentLinkedHashMap library. The tutorial provides an example using an EvictionListener and can be written as, ConcurrentMap<K, V> cache = new ConcurrentLinkedHashMap.Builder<K, V>() .maximumWeightedCapacity(3_000) .listener((key, value) -> System.out.printf("Evicted key=%s, value=%s%n", key, value)) .build(); While this library is small and nibble, it was written in the Java 5 timeframe. It is still excellent for embedded cases to minimize the jar size, but general purpose usages should prefer Caffeine instead. That library provides a richer feature set and additional performance improvements. Cache<K, V> graphs = Caffeine.newBuilder() .maximumSize(3_000) .removalListener((K key, V value, RemovalCause cause) -> System.out.printf("%s: key=%s, value=%s%n", cause, key, value)) .build();
doc_23527649
I want filter the people in my cohort have completed a certain measure at at least 3 time points out of a potential 8, i.e., DO NOT have missing data for at least 3 time points. Except for the first year, It doesn't matter which of those 3 time points they completed, it just needs to be three total. So, how do I say to R: Please return me back participants who have participated in 3 or more of the following: Y1_Q-Sort AND ANY OF THE FOLLOWING 2 OR MORE: Y2_Q-Sort, Y3_Q-Sort, Y4_Q-Sort, Y5_Q-Sort, Y6_Q-Sort, Y7_QSort, and Y8_QSort. Thank you so much for your help!
doc_23527650
User case: an user establishes a connection to a server. I create a WebSocket object and put it into webSocketInstance. When an user enters his usename I add the name to Redux and it causes re-render of the component which is okay. Now as he has the username I want him to reconnect with a new url(also this part of reconnection logic). So I want him to close the previous connection and open a new one. export default function GameKeeper() { // Redux states here const { adminWsUrl, clientWsUrl, clientCode, playerName } = useSelector( (state: RootState) => state.hosting ); const [webSocketInstance, setWebSocketInstance] = useState<WebSocket>(); useEffect(() => { if (webSocketInstance) { webSocketInstance.close(); } if (adminWsUrl) { setWebSocketInstance(new WebSocket(adminWsUrl)); } else if (clientWsUrl && playerName) { setWebSocketInstance(new WebSocket(`${clientWsUrl}${playerName}/`)); } else if (clientWsUrl && !playerName) { setWebSocketInstance(new WebSocket(clientWsUrl)); } }, [adminWsUrl, clientWsUrl, playerName]); return ( ... ); } The current code gives me a warning that webSocketInstance is not in useEffect dependencies. If I add it, I get infinite loop. A: Here's a basic template for how I'd go about setting up a useReducer to handle this. I can't really think of a good way to do this with just useState without also utilising some mutative state (i.e. useRef) to hold the Web Socket instead. The drawback there of course is you've escaped React's state system altogether and can no longer watch your socket for updates. function wsReducer(wsInstance, action) { if (action.type === "reset") { wsInstance && wsInstance.close(); return new WebSocket(action.payload); } } export default function App() { const { adminWsUrl, clientWsUrl, clientCode, playerName } = useSelector( (state: RootState) => state.hosting ); const [wsInstance, dispatch] = useReducer(wsReducer, null); useEffect(() => { const url = (() => { if (adminWsUrl) return adminWsUrl; if (clientWsUrl && playerName) return `${clientWsUrl}${playerName}/`; if (clientWsUrl && !playerName) return clientWsUrl; return false; })(); if (url) { dispatch({ type: "reset", payload: url }); } }, [adminWsUrl, clientWsUrl, playerName]); return ( ... ); } Also, some recommended reading - particularly the stuff on decoupling updates/actions and using useReducer in this context. I'd suggest trying to get through the whole thing, it was really useful for me when I started doing functional React.
doc_23527651
String[] args={"/storage/sdcard1/Music/Drive soundtrack/A Real Hero (feat. Electric Youth).mp3"}; File file = new File(args[0]); if(!file.canRead()) { printUsage(); System.out.println("Insert a valid path!"); } System.out.println("validd path!"); EchoNestAPI echoNest = new EchoNestAPI("080NXJV4Y...."); System.out.println("hello!"); Track track = echoNest.uploadTrack(file,true); System.out.println("uploaded!"); track.waitForAnalysis((60*1000)/2); System.out.println("ID: "+track.getID()); System.out.println("Artist: "+track.getArtistName()); System.out.println("Title: "+track.getTitle()); I came across similar problems while searching over the internet but i couldn't come across a solution. http://archive-com.com/page/3694036/2014-02-11/http://developer.echonest.com/forums/thread/365 http://developer1072.rssing.com/chan-22893681/all_p31.html#item617 http://developer.echonest.com/forums/thread/1624 here is the error I am receiving 08-17 02:27:28.555: I/System.out(2776): EchoNestAPI Error: java.net.UnknownHostException: Unable to resolve host "developer.echonest.com": No address associated with hostname cmd: http://developer.echonest.com/api/v4/track/profile?md5=2fff2dc89742ea6aadf89a96590a2174&api_key=080NXJV4YHVLIVBFA 08-17 02:27:28.555: I/System.out(2776): EchoNestAPI retry failure cmd: http://developer.echonest.com/api/v4/track/profile?md5=2fff2dc89742ea6aadf89a96590a2174&api_key=080NXJV4YHVLIVBFA A: It appears that your api key was invalid and your jar imports were conflicting with each other. You have to make sure you are making that call inside an AsyncTask. After that, all is going to work ok.
doc_23527652
what I am getting is this What I want is this: A: Using padding you can do this... android:paddingLeft="5dp" A: Add below line to your xml: android:drawablePadding="5dip" For more info please refer to the Android developer reference.
doc_23527653
A: You can use the date_part function, like this: date_part('hour', timestamp '2001-02-16 20:38:40') This would give you 20 for example. For more information, refer to http://www.postgresql.org/docs/8.2/interactive/functions-datetime.html A: Not sure what you exactly mean. Perhaps answer to your question is: select now(); or maybe it's: select now()::time; A: Maybe: select to_char (field, 'HH24:MI:SS') FROM table; Example: select to_char ('2011-04-13 11:22:33'::timestamp, 'HH24:MI:SS'); It gives you: 11:22:33 Replace
doc_23527654
models.py from django.db import models # Create your models here. from django.contrib.auth.models import User class ValidateMeUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobileNumber = models.BigIntegerField(blank=True, null=True) serializers.py from django.contrib.auth.models import User from rest_framework import viewsets from rest_framework import serializers from phone.models import ValidateMeUser class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email','password') extra_kwargs = {'password': {'write_only': True}, } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ValidateMeUserSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = ValidateMeUser fields = ('mobileNumber','user') def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) validateMeUser = ValidateMeUser.objects.create(user=user, **validated_data) return validateMeUser views.py from django.shortcuts import render # Create your views here. from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from phone.serializers import ValidateMeUserSerializer from phone.models import ValidateMeUser @api_view(['GET', 'POST']) def user_list(request): """ List all snippets, or create a new snippet. """ if request.method == 'GET': users = ValidateMeUser.objects.all() serializer = ValidateMeUserSerializer(users, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ValidateMeUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py from django.conf.urls import include, url from django.contrib import admin from phone import views urlpatterns = [ url(r'^list/$', views.user_list), url(r'^admin/', include(admin.site.urls)), ] When I run the curl command I get following message: curl --data "username=user123455&password=sdasd&mobileNumber=2618221" http://127.0.0.1:8000/list/ {"user":{"username":["This field is required."],"password":["This field is required."]}} It seems to me that the UserSerializer is either not getting called or not getting initialized properly. Can anyone help me out what might be causing this issue. Thanks in advance. A: You're defining a nested serializer and provide flat data. If you want to keep data flat, you'll only need one serializer and add the extra fields to it: class ValidateMeUserSerializer(serializers.ModelSerializer): username = serializers.CharField(...) email = serializers.CharField(...) password = serializers.CharField(...) class Meta: model = ValidateMeUser fields = ('mobileNumber', 'username', 'email', 'password') def create(self, validated_data): username = validated_data.pop('username') ... user = User.objects.create_user(username=username, ...) validateMeUser = ValidateMeUser.objects.create(user=user, **validated_data) return validateMeUser
doc_23527655
The user is going to enter a word and then hit enter... How do i capture that into an array of chars? If the word was coming in one char at a time I could just add it to the array, dynamically expanding if needed, but when it comes in a block of char's like that I am lost for ideas. Thanks! A: The member function cin.getline() allows you to specify a character buffer and length. char name[32]; cin.getline(name, 32); Though any C++ assignment that would ask you specifically to use character arrays instead of strings (especially in this context), is suspect. A: Try this: char arr[100]; cin >> arr;
doc_23527656
A: You can use the following: Joomla 2.5: $parser = JFactory::getXMLParser('Simple'); $xml = JPATH_SITE .'/components/com_wrapper/wrapper.xml'; $parser->loadFile($xml); $doc = $parser->document; $element = $doc->getElementByPath('version'); $version = $element->data(); echo $version; Joomla 3.x (Platform 13.3 and below) $xml = JFactory::getXML(JPATH_SITE .'/components/com_wrapper/wrapper.xml'); $version = (string)$xml->version; echo $version; Joomla 3.2+: getXML was made deprecated as of 2 weeks after this answer. Instead, use SimpleXML Obviously this is an example for the Wrapper component so change the paths to whatever suits your needs. Hope this helps A: If you are looking for a listing of all components within your Joomla site, you can find them by using the Extension Manager -> Manage and select type filter "Components". This will give you a listing with a Version column showing the versions of all the Components. That's an answer to your original question without coding. A: Based on the answer of CoalaWeb, but with less code (more code use from the framework): /** @var JTableExtension $extension */ $extension = JTable::getInstance('extension'); $id = $extension->find(array('element' => $extension)); $extension->load($id); $componentInfo = json_decode($extension->manifest_cache, true); return $componentInfo['version']; A: Joomla 1.5, 2.5, 3.X. We are using different XML files for Joomla 1.5 (com_ponent.xml) and for 2.5, 3.X (_manifest.xml) versions. Using SimpleXML : public static function getVbssoVersion() { $xml_path = JPATH_ADMINISTRATOR . '/components/com_ponent/'; $xml_path .= (defined('JVER') && JVER == '1.5') ? 'com_ponent.xml' : '_manifest.xml'; $xml_obj = new SimpleXMLElement(file_get_contents($xml_path)); return strval($xml_obj->version); } A: To fully leverage the Joomla API, use the JComponentHelper, \Joomla\Registry\Registry and JTable classes: $component = \JComponentHelper::getComponent('com_myextension'); $extension = \JTable::getInstance('extension'); $extension->load($component->id); $manifest = new \Joomla\Registry\Registry($extension->manifest_cache); echo $manifest->get('version'); This applies mainly to newer 3.x versions of Joomla; 3.6+ probably. A: Joomla 3.2+: Because getXML is deprecated, you could use SimpleXML in the following way: $xml = simplexml_load_file(JPATH_COMPONENT_ADMINISTRATOR . '/wrapper.xml'); $version = $xml->version; A: Hi I use this function to return versions from the extensions table based on element (I find its more reliable than name) but you could easily substitute element for name. I have this in a plugin and the function only needs the element($ext) to check against the current extension in the table. function extversion($ext) { $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('manifest_cache'); $query->from($db->quoteName('#__extensions')); $query->where('element = "' . $ext . '"'); $db->setQuery($query); $manifest = json_decode($db->loadResult(), true); return $manifest['version']; }
doc_23527657
Empty array : [ {0: undefined} ] Full array : [ {0: "Name"}, {1: "img.src"}, {2: name: string, family: string, age: number} ] 0: "Name" , 1: "img.src" 2 {name: string, family: string; age: number} My try which isn't working : <div *ngFor="let fam of familyArray" class="grid-item"> <button ion-button> <img *ngIf="fam[1] != undefined && fam[1] != null " class="selectImg" src="{{fam[1]}}" alt=""> </button> <span *ngIf="fam[2].name != undefined && family[2].age != undefined && family[2].age != null && family[2].name != null " class="image-text">{{fam[2].name}}, {{family[2].age}}m.</span> <p *ngIf="fam[2].family != undefined && fam[2].family != null " class="family-status">{{fam[2].family}}</p> </div> I always get this errors : TypeError: Cannot read property '1' of undefined or TypeError: Cannot read property 'name' of undefined A: You don't need to put checks for undefined and null, It take cares it self for undefined and nulls, you just need to specify like below: <div *ngFor="let fam of familyArray" class="grid-item" > <button *ngIf="fam[0]" ion-button> <img *ngIf="fam[1]" class="selectImg" src="{{fam[1]}}" alt=""> </button> <span *ngIf="fam[2] && fam[2].name && family[2].age" class="image-text">{{fam[2].name}}, {{family[2].age}}m.</span> <p *ngIf="fam[2].family" class="family-status">{{fam[2].family}}</p> </div> The array of object which you are receiving is actually a wrong format, all the object should be in same types and some standard conventions need to be followed though. A: <div *ngFor="let fam of familyArray" class="grid-item"> <button ion-button> <img *ngIf="fam['1'] != undefined && fam['1'] != null " class="selectImg" src="{{fam['1']}}" alt=""> </button> <span *ngIf="fam['2'].name != undefined && family['2'].age != undefined && family['2'].age != null && family['2'].name != null " class="image-text">{{fam['2'].name}}, {{family['2'].age}}m.</span> <p *ngIf="fam['2'].family != undefined && fam['2'].family != null " class="family-status">{{fam['2'].family}}</p> </div> Above code 3 times as there are 3 objects in your array. First time value of fam is {0: Name}, Second time {1: img.src}, and third time {2: name: Example, family: example, age:15} there is not such object fam[1] I hope I have explained enough. A: Fixed it by doing this : HTML (added ngIf to the button) : <div *ngFor="let fam of familyArray" class="grid-item" > <button *ngIf="familyArray[0] != undefined " ion-button> <img *ngIf="fam[1] != undefined && fam[1] != null " class="selectImg" src="{{fam[1]}}" alt=""> </button> <span *ngIf="fam[2].name != undefined && family[2].age != undefined && family[2].age != null && family[2].name != null " class="image-text">{{fam[2].name}}, {{family[2].age}}m.</span> <p *ngIf="fam[2].family != undefined && fam[2].family != null " class="family-status">{{fam[2].family}}</p> </div> And made that my array would be empty, not 0:undefined if nothing is there. A: You had added the additional checks for undefined and null and missed the check in couple of places. Here is the working copy of your example - https://stackblitz.com/edit/angular-e8zjsq A: ` <div class="count-section" fxLayout="row"> <span fxFlex="13.3%" >Super cell: <b>{{countAnalysisDrugInfo[2].value}}</b></span> <span fxFlex="12.3%" >Locking cell: <b>{{countAnalysisDrugInfo[0].value}}</b></span> <span fxFlex="12.3%" >Regular cell: <b *ngIf="countAnalysisDrugInfo[4]">{{countAnalysisDrugInfo[4].value}}</b></span> <span fxFlex="16.3%" >Super locking cell: <b>{{countAnalysisDrugInfo[3].value}}</b></span> <span fxFlex="12.3%" >Schedule ll: <b>{{countAnalysisDrugInfo[0].value}}</b></span> <span fxFlex="12.3%" >Schedule lll: <b>{{countAnalysisDrugInfo[1].value}}</b></span> </div>`
doc_23527658
A: It is best to initialize a new Git repo locally in command-line first: cd /path/to/new/folder git init . # Add some project files, including at least one with `__init__.py` (see "Import directory into pycharm") Then import that folder into PyCharm.
doc_23527659
Link to site: http://christap4.sg-host.com A: From your link this is what I came up with. body { margin: 0 } /* this is just for the snippet, ignore it */ <video id="wp-custom-header-video" autoplay="" loop="" playsinline="" src="http://christap4.sg-host.com/wp-content/uploads/2022/06/2AE-Hero-Video-20220616.mp4" style="width: 100vw;height: auto;opacity: 1;aspect-ratio: 1.77777778;"></video> To get 100% of the screen width you can use width: 100vw (vw = viewport width). I've also included ascpect-ratio: 1.77777778 (video width / video height) and then set the height to auto A: Looks like there are a couple of things here. Looking at your output it looks like you have over-complicated the solution. Anything that is position absolute with 100% width will be as wide as it's most relative parent (by default the body). If you set the width to 100% you can set the height using aspect-ratio ( https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio ). I'm not sure how far back you are going in browser support but this will cover most uses. Alternatively you can give it a fixed height and use object-fit cover but this will cause some cropping. The poster image will just inherit the same dimensions as the video. That being said short videos can now autoplay providing they are the right format, muted and have the right attributes set on them.
doc_23527660
var NFA = function(par) { this.stack = []; this.op_stack = []; this.parent = par; }; NFA.prototype.parse = function(pattern) { var done = false; for(var i in pattern) { if (done === true) { break; } switch(pattern.charAt(i)) { case "(": var sub_nfa = new NFA(this); this.stack.push(sub_nfa); sub_nfa.parse(pattern.substring(i+1, pattern.length)); done = true; break; case ")": if (this.parent !== null) { var len = pattern.length; /*TROUBLE SPOT*/ this.parent.parse(pattern.substring(i, pattern.length)); done = true; break; } case "*": this.op_stack.push(operator.KLEENE); break; case "|": this.op_stack.push(operator.UNION); break; default: if(this.stack.length > 0) { //only push concat after we see at least one symbol this.op_stack.push(operator.CONCAT); } this.stack.push(pattern.charAt(i)); } } }; Note the area marked "TROUBLE SPOT". Given the regular expression "(a|b)a", the call this.parent.parse, is called exactly once: when the sub-automaton encounters ")". At this point, pattern.substring(i, pattern.length) = ")a". This "works", but it isn't correct because I need to consume the ")" input before I pass the string to the parent automaton. However, if I change the call to this.parent.parse(pattern.substring(i+1, pattern.length), parse gets handed the empty string! I have tried stepping through the code and I cannot explain this behavior. What am I missing? At Juan's suggestion, I made a quick jsfiddle to show the problem when trying to parse "(a|b)a" with this algorithm. In the ")" case, it populates an empty div with the substring at the i index and the substring at the i+1 index. It shows that while there are 2 characters in the substring at i, the substring at i+1 is the empty string! Here's the link: http://jsfiddle.net/XC6QM/1/ EDIT: I edited this question to reflect the fact that using charAt(i) doesn't change the behavior of the algorithm. A: I think the previous answer was on the right track. But there also looks to me to be an off-by-one error. Shouldn't you be increasing the index for your substring? You don't want to include the ")" in the parent parse, right? this.parent.parse(pattern.substring(i + 1, pattern.length)); But this will still fail because of the error Juan mentioned. A quick temporary fix to test this would be to convert the i to a number: this.parent.parse(pattern.substring(+i + 1, pattern.length)); This might do it for you. But you should probably go back and switch away from the for-in loop on the string. I think that's causing your issue. Turn it into an array with str.split('') and then use an integer to loop. That will prevent further such issues. A: The real problem is the fact that you were using a for in to iterate through the characters of the string. With the for in loop, your i is going to be a string, therefore, when you try to do i+1, it does string concatenation. If you change your iteration to be for(var i=0; i < pattern.length; i++) { Then it all works fine http://jsfiddle.net/XC6QM/2/ Scott's answer correctly identified the problem but I think his solution (converting the indexes to numbers) is not ideal. You're better off looping with a numeric index to begin with Also, you should not use brackets to access characters within a string, that does not work in IE 7 switch(pattern[i]) { should be switch(pattern.charAt(i)) {
doc_23527661
I have debugged my code and I think it is because of QAudioInput library. I attached my error image. QBuffer m_buffer; m_buffer.open(QBuffer::ReadWrite); void Recorder::toggleRecord(QString state) { if(state == "1") { m_buffer.open(QBuffer::ReadWrite); m_audioInput->start(&m_buffer); QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice(); if (!info.isFormatSupported(m_format)) { qWarning() << "Default format not supported, trying to use the nearest."; m_format = info.nearestFormat(m_format); } } if(state == "0") { m_buffer.close(); m_audioInput->stop(); } } A: You will need run-time access request for this Android version (8). auto result = QtAndroid::checkPermission(QString("android.permission.RECORD_AUDIO")); if(result == QtAndroid::PermissionResult::Denied){ QtAndroid::PermissionResultMap resultHash = QtAndroid::requestPermissionsSync(QStringList({"android.permission.RECORD_AUDIO"})); if(resultHash["android.permission.CAMERA"] == QtAndroid::PermissionResult::Denied) // do whatever needed if denied else // do whatever needed if granted } You can launch it whenever your application starts.
doc_23527662
I know how the event-mechanism works and what the recommended ways of using are. Works well.(Note: My application is single-threaded) What I want to is, to set a value to a property in my EventArgs. I've never had the need to set properties there. This is a simplified situation of my current situation: (Note, I don't need answers telling me to use regex, or stringreplace, because that won't work in this situation) I have this EventArgs: public class TestEventArgs : EventArgs { public String OldString { get; private set; } public String NewString { get; set; } public TestEventArgs(String oldString) { this.OldString = oldString; } } I do normally raise events this way: public event EventHandler<TestEventArgs> ChangeString; protected virtual void OnChangeString(String oldString) { EventHandler<TestEventArgs> handler = this.ChangeString; if (handler != null) { handler(this, new TestEventArgs(oldString)); } } and by calling the OnChangeString method, because I read that this in the way to raise events a long time ago. Modified code where I need a value of the EventArgs after it's been raised: public event EventHandler<TestEventArgs> ChangeString; protected virtual void OnChangeString(TestEventArgs args) { EventHandler<TestEventArgs> handler = this.ChangeString; if (handler != null) { handler(this, args); } } public void Foo() { String oldString = "this is the old string"; // this.OnChangeString(oldString) // this is the way I called before // now I need to keep a reference to the EventArgs TestEventArgs args = new TestEventArgs(oldString); this.OnChangeString(args); // here I do have full access to args.NewString } So, is it ok to keep a reference for the EventArgs and to raise the event with a method that accepts my EventArgs as parameter? A: I think your question boils down to: Is it OK to use the the arguments of an event to communicate data back to the source of the event? First and foremost: at the low level, this will work. You can modify the event object, and you can see those changes in the code that raises the event. But what if there are multiple event listeners. Who gets to set NewString? If you expect only one, it is more clear to pass a delegate (of type Func<String, String>) to the class that now raises the event. A: If I get your question right, you generally don't want to keep a reference to your TestEventArg, and reuse this object on another event. In your case, your TestEventArg has a public properties call NewString. If any event handler updates this property, while it is begin reference by multiple part of your program, you may accidentally running into problem where the NewString property kept changing from another part of your problem. However, if your TestEventArg has only readable property, then I see no problem keeping the reference and reuse it. public class TestEventArgs : EventArgs { public String OldString { get; private set; } public String NewString { get; private set; } public TestEventArgs(String oldString, String newString) { this.OldString = oldString; this.NewString - newString } } In general, you want to keep your event arg immutable which will makes your program easier understand and debug. A: Only time I keep the TestEventArg arg (in this case) is if you need access to the variable after the method has been called. Example of this is the OnClosing event for a Form. It has a variable you can set to tell it to cancel the close. In this case, if the client registers the callback, and can set a property on the TestEventArg class, then you'd want to have a variable pointed to it. If all you want to do is pass information to the callback and don't need anything back, then the first method is what I use. One caveat for me is that if I use the OnChangeString method, I write it so that it encapsulates the details of the event args. protected virtual void OnChangeString(string oldString) { EventHandler<TestEventArgs> handler = this.ChangeString; if (handler != null) { var args = new TestEventArgs(oldString); handler(this, args); // Do something with args } }
doc_23527663
Compiler --> avrdude --> Ethernet port of the compiler host PC --> Ethernet port of a Raspberry Pi --> Pins of the Raspberry Pi --> avr microcontroller My question is about the code which I should run on the Raspberry Pi to do all the work required on that side. I'm guessing in this specific example it's possible to install avrdude on the Raspberry Pi and pipe the compiled code from the PC to the avrdude on the pi but I'm looking for a general solution that can be used with all microcontrollers, essentially turning the Raspberry Pi into a transparent, Ethernet connected, USB to TTL converter, either existing libraries or directions to how to write such code and where to read the documentations. Edit1: There's a C language library called pigpio already installed on the Raspberry Pi OS and it can output UART. But I don't know how to read the USB data coming to the Raspberry Pi through its Ethernet port and convert it to UART data. Edit2: I Changed USB port to Ethernet port since you can't connect two computers directly through USB. The data coming from the PC is still intended for USB to TTL converters since that's how avrdude and similar softwares are written(I guess it'll be "USB over Ethernet").
doc_23527664
I have done this to check $ python Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from petl import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/user/.env/lib/python3.4/site-packages/petl/__init__.py", line 10, in <module> from petl.util import header, fieldnames, data, records, rowcount, look, see, \ File "/home/user/.env/lib/python3.4/site-packages/petl/util.py", line 14, in <module> from string import maketrans ImportError: cannot import name 'maketrans' >>> I tried to check whether maketrans is present in string package i run this >>> from string import maketrans Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'maketrans' >>> Found that the default python string package does not have this . I am not sure that why petl package have used this without mentioning it in its dependency and if its the default python package then why its giving import error. Not sure what is happening can any one please help A: use str to invoke maketrans LETTERS = 'abcdefghijklmnopqrstuvwxyz' NUMBERS = '22233344455566677778889999' ## translate a-z char to phone digits TRANS = str.maketrans(LETTERS, NUMBERS) A: In Python2, maketrans is a function belongs to the string module. However in Python3, maketrans is a static method of the str type. A: Update: petl >= 1.0 supports Python 3.4. Clearly petl does not work on Python 3.x. This specific error is because the Python 2.x string.maketrans function doesn't exist in 3.x.* But if you got past that, you'd find lots of other errors. While the PyPI entry doesn't list supported versions (which it really should), a quick google turned up Issue #240, to add Python 3 support, which has been on the backlog since 26 Aug 2014. And a 2to3 pass over the source shows hundreds of issues.** So, how do you fix this? * *Use something other than petl. *Use Python 2.7 for your petl work. *Help port it. * Actually, in 3.0, it still existed, but only worked on bytes objects. In 3.1, maketrans and translate methods were added to bytes and bytearray, equivalent to the ones on str, and the string functions were deprecated, and then in 3.2 or 3.3 they were removed. ** Some of these issues are using things that were already deprecated in 2.6 or 2.7, which is odd given that petl originally worked only in 2.7, and was later ported to also work in 2.6. A: Because I was looking for a clear example of how it works in python 3.4, I post what I've found: #in py2 you need to "from string import maketrans" table = "".maketrans('cs', 'kz') #py2 table = maketrans('cs', 'kz') len(table) #in py2 you will get **len(table) = 256 in py3.4 len(table) = 2** sentence = "cause koala is causing trouble" sentence.translate(table)
doc_23527665
Here is what I have <?php if (!empty($content['relationship_graph'])){ print render($content['relationship_graph']); echo '<hr>'; } ?> Not very pro in PHP but looked at some documentation...Cant seem to figure out what I might be doing wrong A: Value in it could be a blank space. try.. <?php if(!empty($content['relationship_graph']) && $content['relationship_graph']!=''){ print render($content['relationship_graph']); echo '<hr>'; } ?> A: Here is what I ended up doing. It worked. if($content['relationship_graph']['#markup']['length'] != 0){ print render($content['relationship_graph']); echo '<hr>'; }
doc_23527666
The problem I am running into is that Glass occasionally moves the focus to the button. As a result, a tap keeps activating the button. It seems Glass automatically converts toolbar menu items to live cards when top-to-bottom swing is used. This is nice. It gives the users the ability to select a menu item. I am thinking if I could set the default state of the button to "disabled," it could solve my problem. However, this also results in disabling the button in the live cards. I would like to enable the button only during live cards. Is there a way to achieve this? Or, is there a better way to remove focus out of the toolbar? Regards.
doc_23527667
def read_cred(file): in_handle = open(file,'r') cred = {} for ln in in_handle: data = ln.strip('\r\n').split('=') if len(data) > 1: key = data[0].strip(' ').lower() value = data[1].strip(' ') cred[key] = value else: print "error in parsing credentials file" return cred cred = read_cred(sys.argv[1]) class MyStreamer(TwythonStreamer): def on_success(self, data): act(data) def on_error(self, status_code, data): print status_code, data stream = MyStreamer(cred['consumer_key'], cred['consumer_secret'], cred['access_token_key'], cred['access_token_secret']) keywords = sys.argv[2] stream.statuses.filter(track=keywords) However, I want to create a UI in django framework which consist of a 'start' and a 'stop' button. What should I do to stop the twython streaming when I clicked on the button 'stop' ? Can give me some simple examples pls? A: As long as the stop button is bound to the rest of the app (I haven't used Django, so I can't provide a simple example) then calling sys.exit() should do the job. Django might have some other method for terminating a process built into it or some specific examples in its documentation. You should check that to confirm this answer. A: You can use the disconnect() function as described in the documentation of Twython - https://twython.readthedocs.org/en/latest/api.html#twython.TwythonStreamer.disconnect def on_stop(self, status_code, data): self.disconnect() def on_start(keywords): stream = MyStreamer(cred['consumer_key'], cred['consumer_secret'], cred['access_token_key'], cred['access_token_secret']) stream.statuses.filter(track=keywords)
doc_23527668
I would do something like this : s---> A | empty string A---> aB| empty String b---> Ab but How do we keep count of the number in the grammar? meaning How does it know when there are more that 100 a's. Also I'm not even sure if my way makes sense. Any help would be appreciated. A: As the members of this language are clearly limited, you can just give them as a listing of all possible cases: S -> ab | aabb | aaabbb | ... | a^100b^100 A: Let's say that S is the start symbol: 1) S -> aXb 2) X -> aXb 3) X -> ab And I can prove this works: 1) S -> aXb 2) aXb -> a aXb b ... (n-3) times a^(n-1) X b^(n-1) -> a^n b^n (using the third rule, X -> ab)
doc_23527669
void getWord(char words[][MAXWORDLENGTH]){ int i; char newWord[MAXWORDLENGTH]; FILE* file; file = fopen("wordbank.txt","r"); if(file==NULL){ printf("Error\n"); }else{ printf("File read\n"); for(i=0;i<=MAXWORDS;i++){ fgets(newWord, "%s", file); printf("newWord: %s", newWord); strcpy(words[i], newWord); } } fclose(file); } Unfortunately my array "words" does not fill each element with a string, it is able to capture the first word in my text file into the [0] element and then the rest is gibberish. my text file looks like this: apple winter summer skunk clouds pencil grape Would it be easier for me to use a pointer instead of an array? Thanks for the help! A: Alright, you may be making things more difficult than they need to be. The comment wasn't meant to pick on you, but whatever compiler/IDE you are using should have been spitting out ERRORS right and left. The fact that it compiled at all is surprising. The advise in the comment was sound. Always, always compile with warnings enabled and fix all warnings before you consider your code trustworthy. That being said, you have a couple of areas where you are making things hard on yourself. You should pass the array, and a FILE* pointer (or filename) rather than hardcoding a filename in a function. That makes the function of very limited use. Your use of fgets, as you now know, was not correct. Further, after you pass your array, you need only read each word (assuming 1-per line) into the array while making sure your don't exceed the number of rows you have declared. Here is a short example that will read from the filename given on the command line (or from stdin by default). It makes use of a ternary operator to either accept a filename as the first argument or set fp to stdin. Give it a try and let me know if you have questions: #include <stdio.h> #define MAXW 64 /* maximum number of lines to read */ #define MAXC 32 /* longest word in abridged Dict. is 28 char "Antidisestablishmentarianism" */ size_t getwords (char (*words)[MAXC], FILE *fp); int main (int argc, char **argv) { char words [MAXW][MAXC] = {{0}}; /* array to hold words */ size_t nwords = 0; /* number of words read */ size_t i; /* open argv[1] for reading (default: stdin) */ FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin; if (!fp) { /* validate file open */ fprintf (stderr, "error: file open failed '%s'.\n", argv[1]); return 1; } nwords = getwords (words, fp); if (fp != stdin) fclose (fp); /* close file */ printf ("\n words read from '%s':\n\n", argc > 1 ? argv[1] : "stdin"); for (i = 0; i < nwords; i++) printf (" words[%2zu] : %s", i, words[i]); return 0; } /* function to read words, 1 - per line, from 'fp' */ size_t getwords (char (*words)[MAXC], FILE *fp) { size_t idx = 0; /* index of words read */ /* read each line in file into words array note: includes trailing newline character */ while (idx < MAXW && fgets (words[idx], MAXC, fp)) { idx++; /* note you should check if chars remain in line */ } if (idx == MAXW) /* check word count against MAXW */ fprintf (stderr, "warning: MAXW words read.\n"); return idx; } Compile gcc -Wall -Wextra -O3 -o bin/fgets_array_words_fn fgets_array_words_fn.c Input File $ cat dat/captnjack1.txt This is a tale Of Captain Jack Sparrow A Pirate So Brave On the Seven Seas. Output $ ./bin/fgets_array_words_fn dat/captnjack1.txt words read from 'dat/captnjack1.txt': words[ 0] : This words[ 1] : is words[ 2] : a words[ 3] : tale words[ 4] : Of words[ 5] : Captain words[ 6] : Jack words[ 7] : Sparrow words[ 8] : A words[ 9] : Pirate words[10] : So words[11] : Brave words[12] : On words[13] : the words[14] : Seven words[15] : Seas. or reading from stdin: $ ./bin/fgets_array_words_fn <dat/captnjack1.txt words read from 'stdin': words[ 0] : This words[ 1] : is ... A: Use fread() method while(fread(newWord, MAXWORDLENGTH,1,file)){ printf("newWord: %s", newWord); strcpy(words[i], newWord); }
doc_23527670
I am trying to write another command button code which say: If I input a "point" & (due to other criteria etc), the [row 79] of that column = "p", copy the value in [row 75] of that column. (Let's call this "Aboverow" Then search backwards (to column C) along [row 79] for all cells/columns with "r" present in them. For every column with "r" present in it, paste "Aboverow's" value into [row 80] of that column. I have written the code for this but I keep getting "out of stack space error", I have tried to debug it, but am not sure where I am going wrong. The code is below. Any help will be very much appreciated. Private Sub commandButton12_Click() For Checkcol = 3 To 801 Dim Isnote As Variant GoSub Isnote Isnote: If Cells(78, Checkcol) <> "o" Then GoSub Isap Else End If Dim Isap As Variant Isap: If Cells(80, Checkcol) = "p" Or Cells(80, Checkcol) = "pf" Or Cells(80, Checkcol) = "ps" Then GoSub Myprocess ElseIf Cells(80, Checkcol) = "r" Or Cells(80, Checkcol) = "rf" Or Cells(80, Checkcol) = "rs" Then End If Dim Myprocess As Variant Dim Reg As Variant Reg = "r" Dim Rainj As Variant If ActiveCell.Column = Range("J79") Then Rainj = Range("J79") & ("C79") End If Dim Aboverow As Variant Aboverow: If ActiveCell.Column = Range("J79") Then Range("J75").Select Selection.Copy End If Dim Belowrow As Variant Belowrow: If Range("I79") = Reg Then Range("I80").Select End If Myprocess: GoSub Aboverow For Each Reg In Rainj GoSub Belowrow Selection.Paste Next Reg Next End Sub A: As mentioned in the comments, this is why you should always avoid GoTo and GoSub like the plague. The immediate cause of your stack overflow is that you are calling GoSub and don't have any Return statements. That means in this section of code (the first infinite recursion I noticed, but probably not the only one)... Aboverow: If ActiveCell.Column = Range("J79") Then Range("J75").Select Selection.Copy End If Dim Belowrow As Variant Belowrow: If Range("I79") = Reg Then Range("I80").Select End If Myprocess: GoSub Aboverow For Each Reg In Rainj GoSub Belowrow Selection.Paste Next Reg ...your exceution jumps from the line with GoSub Belowrow, then it falls right back into the code below the Myprocess: label, which jumps above the Belowrow: label, which falls back into the code below the Belowrow: label, which...you get the idea. While you could experiment with using Return to exit your "Subs", that style of coding died sometime in the 1970s for this exact reason. If you need a subroutine, you should make a sub-routine. Note that this is just an example - the flow control is convoluted enough that I have no idea what the code is supposed to do: Sub AboveRow() If ActiveCell.Column = Range("J79") Then Range("J75").Select Selection.Copy End If End Sub Sub BelowRow() If Range("I79") = Reg Then Range("I80").Select End If End Sub Sub Myprocess() AboveRow For Each Reg In Rainj BelowRow Selection.Paste Next Reg End Sub Then the code quoted above would become just: AboveRow BelowRow Myprocess Note that there are many other issues around relying on Select and tracking the active cell, but that should at least get you closer to a point that you can start doing some more meaningful debugging on this. A: In addition to what was already said... * *Don't declare line labels as local variables. *Declare actual variables with actual data types. Using Variant when you mean Long can cost you some performance. *Avoid working for nothing: if there's no code in an Else block, then there's no reason to have an Else If condition at all. *Avoid working off the current Selection and ActiveCell. Use Range object references and work against that. *Avoid implementing logic in click handlers - often you'll need more click handlers and you'll end up duplicating logic everywhere: that means you can have one bug, and twelve places to fix it. So execution starts and assigns an undeclared Checkcol variable in a For loop that runs from 3 to 801. For Checkcol = 3 To 801 That should probably be reworded to eliminate the hard-coded magic numbers: Dim targetSheet As Worksheet Set targetSheet = ActiveSheet 'ideally something more robust than that Dim firstColumn As Long firstColumn = FindFirstColumn(targetSheet) 'function that returns the first column with a heading in a specified worksheet Dim lastColumn As Long lastColumn = FindLastColumn(targetSheet) 'function that returns the last column with a heading in a specified worksheet Dim currentColumn As Long For currentColumn = firstColumn To LastColumn Next instruction declares an Isnote variable, but that variable is really just a line label and shouldn't be declared at all. Next we have a GoSub jump, that's redundant because it jumps to the line that would be executing next anyway - except here's the thing with GoSub: the VBA interpreter uses a mechanism called the call stack to track where it's at in the program. Because there is no Return statement, after that GoSub jump this is what the call stack might look like: at label:Isnote at sub:commandButton12_Click Now, say Cells(78, Checkcol) <> "o". The call stack becomes this: at label:Myprocess at label:Isnote at sub:commandButton12_Click Now the MyProcess label starts by jumping to Aboverow, so the call stack grows again: at label:Aboverow at label:Myprocess at label:Isnote at sub:commandButton12_Click AboveRow completes, but doesn't Return to the caller, so the last "frame" on the call stack is never "popped". Execution continues into Belowrow (without pushing the label to the stack) and then back into Myprocess (again without pushing it to the stack), and jumps back to Aboverow because that's what Myprocess does: at label:Aboverow at label:Aboverow at label:Myprocess at label:Isnote at sub:commandButton12_Click At that point execution is stuck: the stack will eventually fill up completely with at label:Aboverow stack frames, until it overflows its capacity and the runtime raises the run-time error you're seeing - "Out of stack space". Let's rewind to here: at label:Isnote at sub:commandButton12_Click If Cells(78, Checkcol) does contain an o, then we don't jump and everything is great, no? Execution resumes into Isap (without pushing it to the call stack), and then conditionally jumps to Myprocess which we know is going to get us stuck. The ElseIf condition is otherwise evaluated... for nothing, because nothing happens anyway. We assign Reg to a string value of "r", then Rainj to an interesting concatenated value of whatever string is found in Range("J79"), with the string literal value "C79", so if J79 contains Hello then that makes Rainj contain HelloC79 - I very much doubt that this is the intended behavior. Anyway we eventually reach MyProcess, where we get stuck in that loop again. This code is therefore unreacheable, there's no way it can ever get executed: For Each Reg In Rainj GoSub Belowrow Selection.Paste Next Reg ...which is a good thing, because it's trying to iterate what we now know is a string that ends with "C79". Even if Range("J79") contained something clever, e.g. "Sheet12!" so Rainj would be "Sheet12!C79", it would still be a string literal at that point, and that loop is trying to iterate it. Looks like the intent was something like: For Each Reg In Range(Rainj) But what's Reg anyway? Reg contains the string literal value "r", and we're not doing anything with it... except in the BelowRow label, where we compare it against Range("I79"): If Range("I79") = Reg Then So when Range("I79").Value is "r" then we .Select cell I80... right? Except, that For Each loop is using Reg as an iterator, which in theory only has a meaningful value inside the body of the loop - and this is where my brain explodes and gives up trying to figure out what this is supposed to be doing: it looks like it wants to .Paste something in I80 when I79 has some hard-to-figure-out-without-a-debugger value... but then, the only thing that ever gets copied is J75 - so everything is constant here, except the value of J79. Seems a very, very convoluted way to do: ActiveSheet.Range("J75").Copy ActiveSheet.Range("I80") ...800 times over (well, not really, since execution can never reach the Next statement before overflowing the call stack). A: Just thought I would post the working answer for my question, having fixed the code given to me: Sub Macro1() Dim targetSheet As Worksheet Set targetSheet = ActiveSheet For I = ActiveCell.Column - 1 To 1 Step -1 If Cells(78, I).Value2 = "r" Then Cells(80, I).Value = Cells(75, ActiveCell.Column).Value ElseIf Cells(78, I).Value2 = "p" Then Cells(80, I).Value = Cells(75, ActiveCell.Column).Value Exit For End If Next I End Sub Thanks again for the replies.
doc_23527671
Uncaught TypeError: Cannot read property 'value' of null On this line: fullname = document.getElementById('namefull').value; I am 100% sure that the field 'namefull' is on the form and I also have a value typed in the form. I actually have a check to make sure it's not null and that passes. Here is form: <table border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td> </tr> <tr> <td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td> <td colspan="3" bgcolor="#CCFFFF"><input type="text" size="30" maxlength="30" name="namefull"></td> </tr> The full code is below: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="GENERATOR" content="Microsoft FrontPage 2.0"> <title>HABLA Order Form</title> </head> <script language="javascript"> // Do not steal, modify, or claim these scripts as your own! Thank You. // Alterations and additions by Gordon Smith Mearns@mearns.org.uk index = 0; function getFields() { fullname = document.getElementById('namefull').value; email = document.getElementById('email').value; phone = document.getElementById('phone').value; zip = document.getElementById('zip').value; amount = document.getElementById('total').value; type = document.getElementById('order_type').value; seller = 'TestSeller'; specinstruct = document.getElementById('specinstr').value; xact_num = 'StripeDummy'; }; function writeXact() { var sendtext; getFields(); if (fullname == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } } sendtext = fullname + "||" + email + "||" + phone + "||" + zip + "||" + amount + "||" + type + "||" + seller + "||" + specinstruct + "||" + xact_num; xmlhttp.open("GET","writeXact.php?q="+sendtext,true); xmlhttp.send(); } }; function format(val, post) { var decpoint; var begin; var end; var valstr; var temp_char; valstr = "" + val; //alert('valstr = ' + valstr); decpoint = valstr.indexOf(".") if (decpoint != -1) { //alert('decpoint = ' + decpoint); begin = valstr.substring(0,decpoint); end = valstr.substring(decpoint+1,valstr.length); //alert('begin = ' + begin + '\nend= ' + end); } else { begin = valstr; end = ""; } if (end.length < post) {while (end.length < post) { end += "0"; } } end = end.substring(0,post); //alert('begin = ' + begin + '\nend= ' + end); return (begin+"."+end); }; function orderSubmit(type) { if (type == 'order') {if ( ! ( (document.order.order_type.checked) || checkRequired() )) {document.order.form_action.value = type; getFields(); writeXact(fullname, email, phone, zip, amount, type, seller, specinstruct, xact_num); document.order.submit(); return true; } else { // alert('first false'); return false; } } }; var infowin = null; function checkRequired() { if (!document.order.namefull.value.length || !document.order.email.value.length || !document.order.zip.value.length || !document.order.phone.value.length) { alert('You have not completed all required fields:\n' + 'Please enter Name, Email, Phone, Zip'); return true; } else { return false; } }; <!-- --> </script><!-- --><a name="top"></a> <body background="images/thisback.gif" bgcolor="#FFFFFF" text="#000000" onLoad=parent.refresh_order_details(parent.order_details) onUnload=parent.add_order_details(parent.order_details)> <center> <script language="javascript"> <!-- hide if (self==parent){document.write('<font color=#ff000><b>This is a frame element, click <a href=shopcartindex.html> here </a>for correct page</b></font>')}; <!-- end hide --> </script> <p><size="6" color="black" font face="Calibri"><b>HABLA Event Order Form</b><br> </font></p> <!-- YOU CAN PUT YOUR EMAIL ADDRESS IN THE FORM COMMAND BELOW AND THE --> <!-- THEN IT WILL BE SENT TO YOU AS A SIMPLE MAILTO GUESTBOOK FORM --> <!-- IF YOU DO THAT - BE SURE TO ADD THE COMMAND enctype="plain/text" --> <!-- IN ORDER TO DELINEATE THE MAIL FOR YOU --> <!-- YOU CAN ALSO USE TE .PL FILE AS A CGI TO HELP WTH THE MAIL. SEE THE TUTORIAL --> <!-- FOR MORE ON HOW THAT IS DONE --> <form action="MAILTO:hablariverglen@gmail.com" method="POST" name="order"> <input type="hidden" name="subject" value="Order Forms - HABLA Balie 2015"><input type="hidden" name="recipient" value="YOUR EMAIL ADDRESS HERE"><input type="hidden" name="redirect" value="thanku.htm"><input type="hidden" name="retailer" value="NAME OF YOUR BUSINESS HERE"><input type="hidden" name="form_action" value="order"> <script language="javascript"> <!-- hide from Browsers document.write('<table width=400><td align=center>'); document.write('<table width=400 ><tr><tr><td align=right colspan=3 ><font face="Calibri"><b>Total Purchase $</b></td><td colspan=3> <input type=text name=total font face="Calibri" value='+ format(parent.all_order_totals(),2) + '></font></td><tr>'); if (parent.items_ordered == 0) document.write('<font color=#000080><b>There are no items in your cart<b></font>'); if (parent.item_num > 0); { for (i =1;i < parent.item_num;i++) { if (parent.itemlist[i].quan > 0) {index = index + 1; document.write('<input size=10 type=text font face="Calibri" name= ' + parent.itemlist[i].code + ' value= ' + parent.itemlist[i].code + '><input size=6 type=text name= ' + parent.itemlist[i].code + ' value=' + parent.itemlist[i].price + '><input size=20 type=text name= ' + parent.itemlist[i].code + ' value= '+ parent.itemlist[i].desc + '><input size=2 type=text name= ' + parent.itemlist[i].desc + ' value= '+ parent.itemlist[i].quan + '><br>'); } } }; <!-- end hiding --> </script> <!-- Customer Info Table --> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td> </tr> <tr> <td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td> <td colspan="3" bgcolor="#CCFFFF"><input type="text" size="30" maxlength="30" name="namefull"></td> </tr> <tr> <td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Email Address:</b></td> <td colspan="3" bgcolor="#CCFFFF"><input type="text" size="30" maxlength="60" name="email"></td> </tr> <tr> <td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Zip:</b></td> <td bgcolor="#CCFFFF"><input type="text" size="9" maxlength="10" name="zip"></td> </tr> <tr> <td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Phone:</b></td> <td colspan="3" bgcolor="#CCFFFF"><input type="text" size="25" maxlength="15" name="phone"></td> </tr> </table> <p align="center"> <table border="0" width=400> <tr> <td align="center" colspan="6"<b><font face = "Calibri"><b>Special Instructions</b><br></td> </tr> <tr> <td colspan="6"><center><textarea name="specinstr" rows="3" cols="40"></textarea></center></td> </tr> </table> <!-- Order Method Table --> </p> <table border="0" cellspacing="0" width=400> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF"><font size="4"><b>Choose Order Method:</b></font></td> </tr> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF">&nbsp;&nbsp; <font size="2">Credit Card: <input type="radio" name="order_type" value="phone"></font>&nbsp;&nbsp; </td> </tr> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF">&nbsp;&nbsp; <font size="2">Cash: <input type="radio" name="order_type" value="phone"></font>&nbsp;&nbsp; </td> </tr> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF">&nbsp;&nbsp; <font size="2">Check: <input type="radio" name="order_type" value="phone"></font>&nbsp;&nbsp; </td> </tr> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF"><a href="options.htm" target=navigate> </td> </tr> </table> <p><br> <p><br> <! Stripe Credit Card Integration > <form action="" method="POST"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_zzzzzz" data-amount="2000" data-name="Demo Site" data-description="2 widgets ($20.00)" data-image="/128x128.png" data-locale="auto"> </script> </form> <input type="button" value="Place Order" onclick="orderSubmit('order')" <input type="reset" value="Reset Cart"> </p> <b>HABLA Friends of River Glen <a href=mailto:hablariverglen@gmail.com>hablariverglen@gmail.com</a> </b> </form> </td></table> </center> </p> </body > </html> Yes, I know the code is a mess, but I'm doing this for a school/charity fundraiser, so any help is much appreciated. A: You are looking for an element with id="namefull", but in your html, you only specify the name attribute: <input type="text" size="30" maxlength="30" name="namefull"> Try including id="namefull" in here: <input type="text" id="namefull" name="namefull" size="30" maxlength="30"> You'll want to follow suit on each of your inputs to specify the id, since that's what you're looking for with document.getElementById(). A: getElementById() get's an element by it's ID. You need to set the id for that to work. Change your markup to: <table border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td> </tr> <tr> <td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td> <td colspan="3" bgcolor="#CCFFFF"><input type="text" size="30" maxlength="30" name="namefull" id="namefull"></td> </tr> Notice I added id="namefull" to the input element.
doc_23527672
Tho as much as I have tried, and normally I don't ask people for help because I like to figure things out on my own, I am stuck. I am writing in Python 3.2.2. So please can anyone see where I'm going wrong? import urllib import sys import http.cookiejar cookieJar = http.cookiejar.LWPCookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookieJar)) opener.addheaders = [('User-agent', "Mozilla/5.0")] username = "insert email here" password = "insert password here" url = "http://yakedi.com/login/do" form = { "email" : username, "pass" : password, "submit": "login"} encodedForm = urllib.parse.urlencode(form).encode("UTF-8") request = urllib.request.Request(url, encodedForm) page = opener.open(request) contents = page.read() print(contents) Thank you in return
doc_23527673
Ringtone ringtone = RingtoneManager.getRingtone(mainActivity.getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); ringtone.play(); This code is not in my MainActivity, or any other activity for that matter. It is in a thread that is started in the MainActivity. I passed a reference of MainActivity into the thread at start-up so I could do things like this, toasts, and such. This works perfectly. Whenever a chat comes in, the notification sound is heard loud and clear. My issue is this. In the logcat in AndroidStudio, I am getting this error: E/MediaPlayer: Uri is content://settings/system/notification_sound Like the title says, it appears to have no affect on my app, but I am worried that something is wrong, and that it could break my app in the future. Do I need to worry about this? If so, how do I fix it? Thanks!
doc_23527674
Currently I take screenshots like this: public void tearDown(Scenario scenario) { if (scenario.isFailed()) { final byte[] screenshot = ((TakesScreenshot) driver1).getScreenshotAs(OutputType.BYTES); scenario.attach(screenshot, "image/png", null); } } which always screen shots the first driver when either runs into a failure. how do i get the driver that has the error to screen shot?
doc_23527675
A: Webpack has that feature called Hot module. You should implement this into your development webpack because it helps alot when you have big project https://webpack.js.org/guides/hot-module-replacement
doc_23527676
([a-zA-Z]|[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]) Please tell me where am I wrong? A: You regex matches 2 alternatives: 1 lower- or uppercase letter with [a-zA-Z], or a number with [0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]. It seems you are looking for \b([a-zA-Z]+[0-9]*|(?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))\b See demo Or, if the strings are tested against the regex individually, use ^/$ anchors: ^([a-zA-Z]+[0-9]*|(?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))$ See another demo
doc_23527677
The array is @@players_list, which has an unknown number of players. I tried: @@players_list = [player1, player2, player3] tied = @@Players_.list.find_all {|p| p.win_value.to_s.count(p.win_value.to_s) > 1} This does not return an error, but also does not identify the duplicate score values tied = @@players_list.select {|p| array{|p| p.score_value}.count(p.score_value) > 1}.uniq This returns: syntax error, unexpected '}', expecting keyword_end ..._value}.count(p.win_value) > 1}.uniq A: Thanks to Sergio Tulentsev for getting me 90% there. Here's what I came up with that seems to work. group_by_win_value = @@players_list.group_by(&:win_value) group_by_win_value.each do |key, value| @tied_players = [] if value.count > 1 puts "the following players are tied" value.each do |player| puts player.name`` @tied_players << player end end end
doc_23527678
For my local testing, First way: "php artisan serve" on the project root directory ---> localhost:8000/item Second way: "php -S localhost:8080" in the public folder ---> localhost:8080/item However, when upload my laravel project to server via FileZilla. It returns HTTP Error 500 when "xxx.com/item" but I can see "xxx.com/index.html" when I put index.html on the same directory How to deploy the project? need to install or config something? SSH? Thanks A: I have already answered a question like this here Archive/Compress/Zip your project and upload it to public_html and Extract it Create a Database in mysql databases ( in cPanel ) Import .sql file from local phpmyadmin to online hosting Now go to public_html and edit .env file, change the following DB_DATABASE=DatabaseName DB_USERNAME=DatabaseUsername DB_PASSWORD=DatabasePassword and now just open yourwebsite.com and your app will be there ! A: you have to link your domain path to /public in your project or you could use .htaccess file on root folder to redirect it in /public folder. Because public folder contains the index.php file.
doc_23527679
com.mongodb.util.JSONParseException: ^{"id":"92824502157","name":"Eric CX"} It points in the beggining of the string and indicates that there is a space.I checked the file and there is no space in front of the json string.
doc_23527680
The problem I have with these files is that when I try to open them with R, they generate a blank dataframe. This is fixed by opening the xls file and saving it without making any other changes. I would like to know if anyone else has had this problem? The solution of opening and saving each file is not useful for me, since the number of files is large. I have used the read_xls function from the readxl package. This is my sessionInfo() * *R version 4.1.2 (2021-11-01) *Platform: x86_64-w64-mingw32/x64 (64-bit) *Running under: Windows 10 x64 (build 19044)
doc_23527681
I have just one user that gets periodic errors saying "The handle is invalid". If she tries printing a second time, it works just fine. I've looked over her machine and it looks like it has all the same software as everyone else, and of course it never happens when I'm around. The code I'm using is: frmPrint.LogTag1.PrintToPrinter(1, True, 1, 0) I'm not sure if there is any other information that I can get from an end user machine to help me figure out where the problem is. ErrorToString() only returns that one line. A: It is a low-level Windows error. Could be a bug in Crystal Reports, could be a bug in the printer driver, could be environmental with some kind of misbehaving system add-on. You'll never find out which it is if you don't have the source code for these large chunks of code so you can debug it. You don't and you can get it. It is not a bug in your code, ask the IT staff to get that user another machine. If that doesn't help then you'll have to bounce this to Crystal Decisions (or whatever they are called these days). This is otherwise a standard IT matter.
doc_23527682
Or get all JPopupMenu components that then could be filtered by visibility, validity etc. I need this for writing tests. Stuck on JPopupMenu-s is not part of parent-child (container-component) relations. Thanks. resolved: JPopupMenu is Window and it is listed in java.awt.Window.getWindows() A: For all unit tests with swing we use the Fest framework. There is a popup menu fixture that will allow you to test stuff on the popup menu. https://github.com/alexruiz/fest-swing-1.x Using the framework I am sure you can search for all popup menus shown by searching with the name you set for the JPopupMenu. EDIT: The framework maintenance changed hands a few years ago. Please check before using it. A: As comments show this is not trivial as effected by light and heavyweight concerns... For example in some cases JPopupMenu can be nested inside a JRootPane. However this in an alternative public API that be used - javax.swing.MenuSelectionManager which can be used to get list of JPopupMenus. I found this inside javax.swing.plaf.basic.BasicPopupMenuUI.getPopups() static List<JPopupMenu> getPopups() { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement[] p = msm.getSelectedPath(); List<JPopupMenu> list = new ArrayList<JPopupMenu>(p.length); for (MenuElement element : p) { if (element instanceof JPopupMenu) { list.add((JPopupMenu) element); } } return list; } Original solution using Window.getWindows() private boolean isPopupMenuOpen() { for (Window each : Window.getWindows()) { if (findPopup(each) != null) { return true; } } return false; } private JPopupMenu findPopup(Component root) { if (root instanceof JPopupMenu) { return (JPopupMenu) root; } if (root instanceof JWindow) { return findPopup(((JWindow)root).getContentPane()); } if (root instanceof JRootPane) { return findPopup(((JRootPane)root).getLayeredPane()); } if (root instanceof Container) { for (Component each : ((Container) root).getComponents()) { return findPopup(each); } } return null; } A: JPopupMenu is Window and it is listed in java.awt.Window.getWindows()
doc_23527683
So far, I have created a new profile: General section - put 'dir_1' in the badge field and selected 'Home Directory' as the Working Directory Option. Advanced section - I am having trouble figuring out the formatting - I've tried iterations of ... "/Users/erica.dohring/dir_1" "~/dir_1" without the quotes, etc Could someone provide guidance as to how to do this? A: I realize this is a reasonably old question, but google led me here for a similar question (how to change background color based on directory). Was able to make this work by creating a couple of profiles, then using the equivalent of the pwd in the Preferences>Advanced>Automatic Profile Switching list, i.e. /Users/ted_foss/workspace/ or, for all sub-dirs under that, /Users/ted_foss/workspace/* .
doc_23527684
The xaml of my DataGrid: <DataGrid ItemsSource="{Binding SysModel.SystemCollection}" MinColumnWidth="50" ColumnHeaderStyle="{StaticResource HeaderStyle}" RowStyle="{StaticResource RowStyleWithAlternation}" CellStyle="{StaticResource CenterCellStyle}" RowHeaderWidth="0" AlternationCount="2" GridLinesVisibility="Horizontal" SelectionUnit="Cell" CanUserAddRows="False" AutoGenerateColumns="False" Height="471" Name="dataGrid1" Width="468" Canvas.Left="40" Canvas.Top="17"> <DataGrid.Columns> <DataGridTextColumn Header="{DynamicResource cart}" Width="Auto" IsReadOnly="True" Binding="{Binding cartNum}" /> <DataGridTextColumn Header="{DynamicResource ipAddress}" Width="100" IsReadOnly="False" Binding="{Binding ipAddress}" /> <DataGridTextColumn Header="{DynamicResource portNumber}" Width="70" IsReadOnly="False" Binding="{Binding PortNumber}" /> <!-- **This is the column that contains the cells I want to have this event for** --> <DataGridTextColumn Header="{DynamicResource configuration}" Width="*" IsReadOnly="False" Binding="{Binding Configuration}" /> </DataGrid.Columns> <DataGrid.Resources> <SolidColorBrush Color="#726AA5" x:Key="{x:Static SystemColors.HighlightBrushKey}" /> </DataGrid.Resources> </DataGrid> A: DataGridCell fires Selected event when it is selected. I presume Before it is being edited by user, it should be selected. Source: DataGridCell Events
doc_23527685
"%E3%83%9C%E3%83%89%E3%82%AB%E3%81%95%E3%82%93" It actually means this ボドカさん This string seems to be encoded in UTF-8 because when I write this in python encoded_str = b'\xe3\x83\x9c\xe3\x83\x89\xe3\x82\xab\xe3\x81\x95\xe3\x82\x93' print(encoded_str) print(encoded_str.decode('utf-8')) Here is the output I get b'\xe3\x83\x9c\xe3\x83\x89\xe3\x82\xab\xe3\x81\x95\xe3\x82\x93' ボドカさん But now I would like a script that will allow me to decode any string in the initial format and here is my code. import re import os mystr = "%E3%83%9C%E3%83%89%E3%82%AB%E3%81%95%E3%82%93" mystr = mystr.lower() mystr = re.sub('%', r'\\x', mystr) encoded_str = bytes(mystr, "utf-8") print(mystr) print(encoded_str) print(encoded_str.decode('utf-8')) Output: \xe3\x83\x9c\xe3\x83\x89\xe3\x82\xab\xe3\x81\x95\xe3\x82\x93 b'\\xe3\\x83\\x9c\\xe3\\x83\\x89\\xe3\\x82\\xab\\xe3\\x81\\x95\\xe3\\x82\\x93' \xe3\x83\x9c\xe3\x83\x89\xe3\x82\xab\xe3\x81\x95\xe3\x82\x93 I tried so many possibilities but I couldn't find the right way to encode proprely my string like the b'STRING' thing would do. I always get extra \ characters from the encoding process that then spoil the decoding process too. I tried all the encoding methods existing in python for the bytes() function. I need help please. Thank you. Stack overflow banned me for that question lol A: mystr = "%E3%83%9C%E3%83%89%E3%82%AB%E3%81%95%E3%82%93" encoded_str = bytes.fromhex(mystr.replace('%', '')) print(encoded_str.decode('utf-8')) Output: ボドカさん
doc_23527686
But when I try to build the suggester, I get an error Caused by: java.lang.IllegalArgumentException: Document contains at least one immense term in field="exacttext" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is... There is no field named exacttext in my entire setup, though. When I use the FreeTextLookupFactory, this doesn't happen, but then I can't use the contextField, of course. I tried adding <filter class="solr.LengthFilterFactory" min="2" max="32700"/> as well as <filter class="solr.TruncateTokenFilterFactory" prefixLength="100"/> to the managed schema, but this didn't work, either. Here's the searchComponent I tried using: <searchComponent name="suggest" class="solr.SuggestComponent"> <lst name="suggester"> <str name="name">mySuggester</str> <str name="lookupImpl">AnalyzingInfixLookupFactory</str> <str name="dictionaryImpl">DocumentDictionaryFactory</str> <str name="field">suggestText</str> <str name="highlight">false</str> <str name="storeDir">mySuggester</str> <str name="separator"> </str> <str name="suggestAnalyzerFieldType">suggestField</str> <str name="buildOnCommit">false</str> <str name="buildOnStartup">false</str> <str name="contextField">context_field</str> </lst> </searchComponent> And this is the config for the suggester in the managed-schema: <fieldType name="suggestField" class="solr.TextField" positionIncrementGap="100"> <analyzer> <tokenizer class="solr.WhitespaceTokenizerFactory"/> <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" catenateWords="1" generateNumberParts="0" splitOnCaseChange="0"/> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.LengthFilterFactory" min="2" max="32700"/> <filter class="solr.TruncateTokenFilterFactory" prefixLength="100"/> </analyzer> </fieldType> -- the part for the fields --- <field name="ID" type="text_general" indexed="true" stored="true"/> <field name="TITLE" type="tokenized" indexed="true" stored="true"/> <field name="ANRISS" type="tokenized" indexed="true" stored="true"/> <field name="LEAD" type="tokenized" indexed="true" stored="true"/> <field name="BODY" type="tokenized" indexed="true" stored="true"/> <field name="PDFDOC" type="text_general" indexed="true" stored="true"/> <field name="MAGID" type="text_general" indexed="true" stored="true"/> <field name="MAGNAME" type="text_general" indexed="true" stored="true"/> <field name="MAGISSUE" type="text_general" indexed="true" stored="true"/> <field name="ARTICLETYPE" type="text_general" indexed="true" stored="true"/> <field name="IS_FREE" type="text_general" indexed="true" stored="true" /> <field name="THEMA" type="text_general" indexed="true" stored="true"/> <field name="CREATIONDATE" type="pdate" indexed="true" stored="true"/> <field name="LASTUPDATE" type="pdate" indexed="true" stored="true"/> <copyField source="TITLE" dest="fulltext" /> <copyField source="ANRISS" dest="fulltext" /> <copyField source="LEAD" dest="fulltext" /> <copyField source="BODY" dest="fulltext" /> <field name="fulltext" stored="true" type="tokenized" multiValued="true" indexed="true" /> <copyField source="TITLE" dest="suggestText" /> <copyField source="ANRISS" dest="suggestText" /> <copyField source="LEAD" dest="suggestText" /> <copyField source="BODY" dest="suggestText" /> <field name="suggestText" stored="true" type="text_general" multiValued="true" indexed="true" /> <copyField source="MAGID" dest="context_field" /> <copyField source="ARTICLETYPE" dest="context_field" /> <field name="context_field" stored="true" type="suggestField" multiValued="true" indexed="true" />
doc_23527687
alembic upgrade head I am getting this error: ERROR [alembic.util.messaging] Online migration expected to match one row when updating '3aae6532b560' to 'a1d8dae7cc' in 'alembic_version'; 2 found FAILED: Online migration expected to match one row when updating '3aae6532b560' to 'a1d8dae7cc' in 'alembic_version'; 2 found alembic current gives two similar versions of alembic like: 3aae6532b560 3aae6532b560 How do I delete one of the similar versions of alembic, i.e a copied version? alembic history doesn't show any messed up output. Thanks! A: Alembic version is stored within your database in alembic_version table. I see that you have two self same rows inside the table. You can do something like this: DELETE FROM alembic_version WHERE version_num='3aae6532b560'; INSERT INTO alembic_version VALUES ('3aae6532b560'); Above query could be done in one query by limiting number of deleted rows, but limiting within DELETE query is different between different databases engines.
doc_23527688
* *connect-rest.log.2018-07-01-21, connect-rest.log.2018-07-01-22 ... *connectDistributed.out The thing is that I don't know how to configure connectDistributed.out file in Kafka Connect. Following is the sample output of the file: [2018-07-11 08:42:40,798] INFO WorkerSinkTask{id=elasticsearch-sink- connector-0} Committing offsets asynchronously using sequence number 216: {test-1=OffsetAndMetadata{offset=476028, metadata=‘’}, test-0=OffsetAndMetadata{offset=478923, metadata=‘’}, test-2=OffsetAndMetadata{offset=477944, metadata=‘’}} (org.apache.kafka.connect.runtime.WorkerSinkTask:325) [2018-07-11 08:43:40,798] INFO WorkerSinkTask{id=elasticsearch-sink-connector0} Committing offsets asynchronously using sequence number 217: {test-1=OffsetAndMetadata{offset=476404, metadata=‘’}, test-0=OffsetAndMetadata{offset=479241, metadata=‘’}, test-2=OffsetAndMetadata{offset=478316, metadata=‘’}} (org.apache.kafka.connect.runtime.WorkerSinkTask:325) Not having configured any logging option, the file size is getting bigger as time goes by. Today, it reached 20GB and I had to manually empty the file. So my question is how do I configure this connectDistributed.out? I'm configuring log options for other components such as the kafka broker log. Following is some of the Kafka Connect-related log configurations under confluent-4.1.0/etc/kafka that I'm using. log4j.properties log4j.appender.requestAppender.File=${kafka.logs.dir}/kafka-request.log log4j.appender.requestAppender.layout=org.apache.log4j.PatternLayout log4j.appender.requestAppender.layout.ConversionPattern=[%d] %p %m (%c)%n log4j.appender.cleanerAppender=org.apache.log4j.DailyRollingFileAppender log4j.appender.cleanerAppender.DatePattern='.'yyyy-MM-dd-HH log4j.appender.cleanerAppender.File=${kafka.logs.dir}/log-cleaner.log log4j.appender.cleanerAppender.layout=org.apache.log4j.PatternLayout log4j.appender.cleanerAppender.layout.ConversionPattern=[%d] %p %m (%c)%n log4j.appender.controllerAppender=org.apache.log4j.DailyRollingFileAppender log4j.appender.controllerAppender.DatePattern='.'yyyy-MM-dd-HH log4j.appender.controllerAppender.File=${kafka.logs.dir}/controller.log log4j.appender.controllerAppender.layout=org.apache.log4j.PatternLayout log4j.appender.controllerAppender.layout.ConversionPattern=[%d] %p %m (%c)%n log4j.appender.authorizerAppender=org.apache.log4j.DailyRollingFileAppender log4j.appender.authorizerAppender.DatePattern='.'yyyy-MM-dd-HH log4j.appender.authorizerAppender.File=${kafka.logs.dir}/kafka-authorizer.log log4j.appender.authorizerAppender.layout=org.apache.log4j.PatternLayout log4j.appender.authorizerAppender.layout.ConversionPattern=[%d] %p %m (%c)%n # Change the two lines below to adjust ZK client logging log4j.logger.org.I0Itec.zkclient.ZkClient=INFO log4j.logger.org.apache.zookeeper=INFO # Change the two lines below to adjust the general broker logging level (output to server.log and stdout) log4j.logger.kafka=INFO log4j.logger.org.apache.kafka=INFO # Change to DEBUG or TRACE to enable request logging log4j.logger.kafka.request.logger=WARN, requestAppender log4j.additivity.kafka.request.logger=false # Uncomment the lines below and change log4j.logger.kafka.network.RequestChannel$ to TRACE for additional output # related to the handling of requests #log4j.logger.kafka.network.Processor=TRACE, requestAppender #log4j.logger.kafka.server.KafkaApis=TRACE, requestAppender #log4j.additivity.kafka.server.KafkaApis=false log4j.logger.kafka.network.RequestChannel$=WARN, requestAppender log4j.additivity.kafka.network.RequestChannel$=false log4j.logger.kafka.controller=TRACE, controllerAppender log4j.additivity.kafka.controller=false log4j.logger.kafka.log.LogCleaner=INFO, cleanerAppender log4j.additivity.kafka.log.LogCleaner=false log4j.logger.state.change.logger=TRACE, stateChangeAppender log4j.additivity.state.change.logger=false # Access denials are logged at INFO level, change to DEBUG to also log allowed accesses log4j.logger.kafka.authorizer.logger=INFO, authorizerAppender log4j.additivity.kafka.authorizer.logger=false connect-log4j.properties log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c:%L)%n log4j.logger.org.apache.zookeeper=ERROR log4j.logger.org.I0Itec.zkclient=ERROR log4j.logger.org.reflections=ERROR log4j.appender.kafkaConnectRestAppender=org.apache.log4j.DailyRollingFileAppender log4j.appender.kafkaConnectRestAppender.DatePattern='.'yyyy-MM-dd-HH log4j.appender.kafkaConnectRestAppender.File=/home/ec2-user/logs/connect-rest.log log4j.appender.kafkaConnectRestAppender.layout=org.apache.log4j.PatternLayout log4j.appender.kafkaConnectRestAppender.layout.ConversionPattern=[%d] %p %m (%c)%n log4j.logger.org.apache.kafka.connect.runtime.rest=INFO, kafkaConnectRestAppender log4j.additivity.org.apache.kafka.connect.runtime.rest=false A: The connectDistributed.out file only exists if you use daemon mode, e.g. connect-distributed -daemon connect-distributed.properties Reason: From kafka-run-class script, CONSOLE_OUTPUT_FILE is set to connectDistributed.out # Launch mode if [ "x$DAEMON_MODE" = "xtrue" ]; then nohup $JAVA $KAFKA_HEAP_OPTS $KAFKA_JVM_PERFORMANCE_OPTS $KAFKA_GC_LOG_OPTS $KAFKA_JMX_OPTS $KAFKA_LOG4J_OPTS -cp $CLASSPATH $KAFKA_OPTS "$@" > "$CONSOLE_OUTPUT_FILE" 2>&1 < /dev/null & else... Option 1: Load a custom log4j property file You can update the KAFKA_LOG4J_OPTS environment variable to point at any log4j property file that you want to before starting connect (see example below) $ export KAFKA_LOG4J_OPTS="-Dlog4j.configuration=file://path/to/connect-log4j-new.properties" $ connect-distributed connect-distributed.properties Notice: Not using -daemon here If you no longer have ConsoleAppender in the log4j properties, this will output next to nothing, and just hang, so would be good to nohup it. The default log4j config is named connect-log4j.properties, and in Confluent Platform, this is at etc/kafka/ folder. This is what it looks like by default log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender In order to set a max log file size, you'll need change the root logger to go to a FileAppender rather than ConsoleAppender, but I prefer using a DailyRollingFileAppender. Here is an example log4j.rootLogger=INFO, stdout, FILE log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.DatePattern='.'yyyy-MM-dd log4j.appender.FILE.File=/var/log/kafka-connect/connect.log log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=[%d] %p %m (%c)%n log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c:%L)%n log4j.logger.org.apache.zookeeper=ERROR log4j.logger.org.I0Itec.zkclient=ERROR log4j.logger.org.reflections=ERROR A: I don't have enough reputation to comment (but I can answer...) so I just want to point out in response to cricket's answer I would NOT use DailyRollingFileAppender. In the docs themselves it says it is unadvised due to synchronization and data loss issues. Instead I would use RollingFileAppender in conjunction with TimeBasedRollingPolicy. I noticed this after some odd behavior with DailyRollingFileAppender in Kafka Connect. You will need to include the log4j "extras" jar in the classpath to make this work.
doc_23527689
Thank you. Sorry for my bad English. The Code: * { margin: 0; padding: 0; } a:hover { text-decoration: none; } a:focus { text-decoration: none; } a:visited { text-decoration: none; } ul { margin: 0; padding: 0; list-style-type: none; } h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0 } body { font-family: 'Open Sans', sans-serif; color: #7e8287; } .floatleft { float: left } .floatright { float: right } .colum { width: 1170px; margin: 0 auto; } .fix { overflow: hidden; } .clear { clear: both; } .header_area { background: #02918c; min-height: 60px; } .header {} .header h1 { font-size: 26px; font-weight: 900; margin-top: 15px; text-transform: uppercase; } .header a { color: #fff; } .header a h1 span { color: #cfc91d; } .mainmenu {} .mainmenu ul {} .mainmenu ul#nav {} .mainmenu ul#nav li { display: inline } .mainmenu ul#nav li a { color: #fff; font-size: 14px; font-weight: 900; text-transform: uppercase; display: inline-block; padding-top: 20px; padding-left: 50px; } .mainmenu ul#nav li a:hover {} .welcome_text_area { background: url(../img/bg-2.jpg) no-repeat scroll center center / cover } .wel-overlay { background: rgba(0, 0, 0, .7) } .welcome_text { text-align: center; color: #fff; padding: 200px 0 } .welcome_text h1 { font-size: 68px; font-weight: 900; text-transform: uppercase; margin: 5px 0; letter-spacing: 20px; } .welcome_text h4 { font-size: 30px; } .welcome_text p { font-size: 18px } .welcome_text a.know_more { text-align: center; background-color: #cfc91d; display: inline-block; padding: 15px; color: #0b1016; font-weight: 900; width: 200px; height: 50px; margin-top: 130px; position: relative } .welcome_text a.know_more:before { position: absolute; content: "}"; top: -145px; left: 90px; font-size: 120px; font-weight: 100; color: #fdfdfd; transform: rotate(90deg); } .promo_area { text-align: center; margin-bottom: 30px; } .colum {} .promo {} .promo_title, .work_title { padding: 100px 0; } .promo_title h1, .work_title h1 { color: #02918c; font-size: 48px; font-weight: 900; padding-bottom: 60px; position: relative } .promo_title h1:before { content: ""; background: url(../img/about-bg.png) no-repeat scroll 0 0; width: 160px; height: 10px; bottom: 27px; position: absolute; left: 50%; margin-left: -80px; } .promo_title p, .work_title p { font-size: 16px; color: #7e8287; padding: 0 115px; } .promo_title p span { font-size: 23px; color: #7e8287; font-weight: 900; } .promo_list { text-align: center; margin-bottom: 250px; } .promo_list div:last-child { border-right: 0 } .single_list { width: 290px; padding: 0 15px; border-right: 1px solid #d9dbdb } .single_list h3 { font-size: 16px; color: #7e8287; margin: 34px 0; font-weight: 900; } .single_list p { font-size: 11px; color: #7e8287; } .single_list img {} .service_area { background: #f0f0e8; position: relative } .rightimg { position: absolute; background: url(../img/rightimg.jpg) no-repeat scroll 0 0 / cover; right: 0; top: 0; width: 50%; height: 100%; opacity: 0.3 } .leftarea { width: 590px } .service_list { padding: 60px 60px; } .service_list h1 { padding: 20px 0; font-size: 46px; color: #02918c; font-weight: 900; position: relative } .service_list h1:before { content: ""; background: url(../img/about-bg.png) no-repeat scroll 0 0; width: 160px; height: 10px; position: absolute; bottom: -12px; } .service_list p { padding: 35px 0 } .service_item .ss_list { width: 295px; padding-left: 60px; padding-bottom: 30px; text-align: left } .service_item .ss_list h3 { padding: 20px 0; margin-bottom: 10px; } .service_item .ss_list p { margin-bottom: 15px; } .service_item .ss_list img { margin-bottom: 15px; } .work_title h1 { text-align: center } .work_title p { max-width: 920px; margin: 0 auto; text-align: center; } .work_area { margin: 0; } .work_slider{ position: relative } .work_list {} .work_slider { width: 25%; } .work_slider img { width: 100%; } .work_slider:hover .slider_overlay, .work_slider:hover .slider_detail h3, .work_slider:hover .slider_detail p {display: block;} .slider_detail {position: absolute; width: 100%;height: 100%; left: 0;top: 0;} .slider_overlay {background: #1c9584; position: absolute; width: 80%; height: 80%; left:10%;top: 10%;opacity: .85;display: none; } .slider_detail h3 {position: relative; z-index: 9999; color: #fff; font-size: 16px; font-weight: 900; text-align: center;padding-top: 85px;display: none;} .slider_detail p {position: relative; z-index: 9999; color: #fff; font-size: 13px; text-align: center;padding: 20px 70px;display: none;} <div class="work_area"> <div class="colum"> <div class="mywork"> <div class="work_title fix"> <h1>MY WORK</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> </div> </div> <div class="work_list fix"> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> <div class="work_slider floatleft"> <img src="http://lorempixel.com/320/230" /> <div class="slider_detail"> <div class="slider_overlay"></div> <h3>Title goes here</h3> <p>onsectetur adipisicing elit, sedo eiusmod tempor incidi et dolorerserss eerhfre mag.</p> </div> </div> </div> </div> A: You can't add a transition to display:none; rules. You must change all of them to opacity, like follows. Take into account that here's only the code that has been changed: .work_slider:hover .slider_detail h3, .work_slider:hover .slider_detail p { opacity: 1; } .work_slider:hover .slider_overlay { opacity: .85; } .slider_overlay { transition: all .3s ease; opacity: 0; } .slider_detail h3 { transition: all .3s ease; opacity: 0; } .slider_detail p { transition: all .3s ease; opacity: 0; } Here's a live example: https://jsfiddle.net/9skyL8rk/
doc_23527690
The problem I encounter it returns a string which is an array of objects. If I use JSON.parse() is going to give me an error such as unexpected token ‘ in JSON at position 2 in JSON.parse [{1:a, name:name, etc...}, {1:a, name:name, etc...}, {1:a, name:name, etc...}, {1:a, name:name, etc...}, {1:a, name:name, etc...},] I got this string from: twitter_search.py ... for tweet in tweets: # data.append({"tweet": tweet.full_text}) data.append({"time": str(tweet.created_at), "user" : str(tweet.user.screen_name), "tweet": str(tweet.full_text)}) ... in app.py @app.route('/') def index(): ip = supp.get_data('https://freegeoip.app/json/') iptojson = json.loads(ip.content) sctojson = ip.sc data = twitter_search.twsejs() s1 = json.dumps(data) d2 = json.loads(s1) return render_template('index.html',data=d2, iptojson = iptojson, sctojson = sctojson) But it is a string and I need to use it as a JSON what can I do? I tried everything JSON.dumps dump parse can't figure it out This is an example of a get req [{'time': '2022-03-16 19:24:07+00:00', 'user': 'AnnBrock432', 'tweet': 'Yes, I\'m primarily on here for GAWs. Not because I\'m a "bad person" I\'m frozen w/ anxiety over possible homelessness. I\'d like to be in the mindset to socialize, but even in real time it\'s hard rn. Depression is real. If I had a solution to pressing matters it would change things'}, {'time': '2022-03-16 19:24:04+00:00', 'user': 'SiameseCatsMom', 'tweet': 'I must do something\nDepression and back pain has me just like a slug in bed'}, {'time': '2022-03-16 19:24:02+00:00', 'user': 'TheCrabyMermade', 'tweet': 'My depression is so bad that even my two mile walk in the morning doesn’t give me nearly as much of the feel good hormones that everyone raves about. I just feel slightly madder bcuz here I am working out &amp; not feeling the effects so why am I even walking 2 miles on the morning?!'}, {'time': '2022-03-16 19:24:02+00:00', 'user': 'AntiMysterious', 'tweet': "@jorgemarqueza @krisjw2630 @seanhannity Sorry buddy. It doesn't matter. Obama had to deal with the biggest recession since the great depression and all you guys did was cry about his spending. \n\nSo you guys are not only failures but you are hypocrites. Lol."}, {'time': '2022-03-16 19:24:01+00:00', 'user': 'TheDuke256', 'tweet': 'RT @Chiomy_mi: This country is so hard &amp; messed up rn! \nAlot of people out there are going through tough time, hence many have fall into de…'}, {'time': '2022-03-16 19:24:01+00:00', 'user': 'Triphighalways1', 'tweet': 'Transcend the multiverse and easy #depression with #lsd and #shrooms link'}, {'time': '2022-03-16 19:23:59+00:00', 'user': 'i_depress_me', 'tweet': 'One of the upsides of crippling depression is that you occasionally get to have a box of Girl Scout cookies for breakfast.'}, {'time': '2022-03-16 19:23:59+00:00', 'user': '0bviouSquirre1', 'tweet': "in realistic terms it has been two and a half months since the cold weather set in such that i couldn't ride my bike\n\nseasonal depression has me acting like i've been locked inside for six months minimum, good lord"}, {'time': '2022-03-16 19:23:58+00:00', 'user': 'sunshiineo_o', 'tweet': "@OthelloVen that's OK for real idk where i sit but it might be on the depression side of the spectrum"}] A: Making a request to an API comports to receive all sorts of responses. In order to have a well-formatted JSON, all I had to do is use a regex and avoid things such as double quotes, special characters, and brake lines. This made me have a cleaner JSON.
doc_23527691
Test Class- public static void main(String[] args) { GeographyList g = new GeographyList(); g.addCountry ("Scotland"); g.addCountry ("Wales"); g.addCountry ("Ireland"); g.addCountry ("Italy"); System.out.println(g.toString()); ArrayList setup public class GeographyList { private ArrayList<String> countries; public GeographyList(){ countries = new ArrayList<>(); } public ArrayList<String> getCountries() { return countries; } public String getCountry(int index){ return countries.get(index); } public void addCountry(String aCountry){ countries.add(aCountry); System.out.println(aCountry + " added."); } A: The reason it prints geographylist.GeographyList@15db9742 is because you are not printing an ArrayList. You are printing a GeographyList. A GeographyList may contain an ArrayList, but that's incidental. The default implementation of toString, inherited from the Object class, is to print the package name geographylist, the class name GeographyList and the hash code 15db9742. If you want to override this behaviour, you will need to override the behaviour of toString, just as the ArrayList class will have done itself. That might look something like this: public class GeographyList { //... @Override public String toString() { return countries.toString(); } } Alternatively, since you already have the ability to get the ArrayList from your class, you could call System.out.println(g.getCountries().toString()); instead of System.out.println(g.toString());
doc_23527692
Here is ASP.NET Code <form id="form1" runat="server"> <div id="dvLeft"></div> <div id="dvRight"></div> <div id="dvMiddle"></div> <div id="dvBottom"> <asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="True"> <asp:ListItem >FirstTheme</asp:ListItem> <asp:ListItem>SecondTheme</asp:ListItem> <asp:ListItem>ThirdTheme</asp:ListItem> </asp:DropDownList> </div> </form> And Here is C# Code: protected override void OnPreInit(EventArgs e) { if (Request["ddlTheme"] != null) { string theme = Request["ddlTheme"].ToString(); Page.Theme = theme; } base.OnPreInit(e); } A: I'd suggest you set selected theme value in the PreRender event handler instead of PreInit because of the way ASPX page life cycle works. Below is revised version from your original code <form id="form1" runat="server"> <div id="dvLeft"></div> <div id="dvRight"></div> <div id="dvMiddle"></div> <div id="dvBottom"> <asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlTheme_SelectedIndexChanged"> <asp:ListItem Value="FirstTheme">FirstTheme</asp:ListItem> <asp:ListItem Value="SecondTheme">SecondTheme</asp:ListItem> <asp:ListItem Value="ThirdTheme">ThirdTheme</asp:ListItem> </asp:DropDownList> </div> </form> protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e) { // save value into a session variable Session["SelectedTheme"] = ddlTheme.SelectedValue; } protected void PreRender() { // works when page reloads if (Session["SelectedTheme"] != null){ Page.Theme = Session["SelectedTheme"].ToString(); } // following line works on postback only //Page.Theme = ddlTheme.SelectedValue; } Update My original suggestion would only work on postback because when the page reloads, a new page life cycle begins and the selected value from the drop down list would be lost. However, there's a way to persist the change, which is to use session. To do this, you will attach a new event handler OnSelectedIndexChanged where you can save the selected value into a session variable. Then read this value from session after page reloads. See the added code snippet above.
doc_23527693
I'm trying to query for a certain element type, say a "city". However, this element is listed under various other types of elements, such as "country" and "region". What is a good way to query for all "city" element types regardless of their parent element? thank you A: * *You could write //city to find all city elements anywhere in the document. *You could also use /descendant-or-self::city, which is different from the first statement in that it will give you any city elements from the context (starting point where you are executing the statement from). *If you would like to limit the city elements to all with country as parent, you would write: //country/city. *If you would like to get city elements at a specific depth in a tree, write something like: /*/*/city.
doc_23527694
so, that's my code: function getTableValues($table_name) { // $link = connect_db(); $front_end_query = "SELECT * FROM `".$table_name."` WHERE `type` = 'front_end'"; $front_end_query_result = mysql_query($front_end_query); $cur_row = 0; /*while ($line = mysql_fetch_assoc($queryresult)) { $values = $line; $cur_row++; }*/ $front_end = mysql_fetch_assoc($front_end_query_result); $i=0; while ($line = mysql_fetch_assoc($front_end_query_result)){ #if ($line['type'] === 'front_end'){ # $line[$line['type']][$line['name']] = $line['value']; # $line[$line['type']][$line['name']]['desc'] = $line['description']; # $line[$line['type']][$line['name']]['visible_name'] = $line['visible_name']; # $line[$line['type']][$line['name']]['write_roles'] = $line['write_roles']; # $line[$line['type']][$line['name']]['read_roles'] = $line['read_roles']; #} $values['front_end'][$line['name']] = $line; $i++; } return $values; } And my MySQL table: id type write_roles read_roles name value description visible_name 1 front_end 0 any title sometitle exampletitle Title 2 front_end 0 any description somedesc example Description And that's what I want to get: $config[(someType)][(SomeName)] = (value of line) $config[(someType)][(SomeName)][(SomeOption)] = (value of option) E.g.: $config['front_end']['title']['description'] that returns exampletitle How I can do that? UPD0: so I tried to echo my array with foreach, and it's returned just one row from my DB. What I doing wrong? A: $values = array(); //base array while ($line = mysql_fetch_assoc($front_end_query_result)){ //fetch the rows //in the base array create a new array under 'name' $values[$line['name']] = array(); //for each item in the result set, add it to the new array foreach ($line as $key => $value) { $values[$line['name']][$key] = $value; } }
doc_23527695
My first attempt: template< typename T > class invert; template< typename port > class invert< port > : public port { public: static int n_pins(){ return port::n_pins(); } static void set( unsigned int x ){ port_out::set( x ^ 0xFFFF ); } }; template< typename pin > class invert< pin > : public pin { public: static void set( bool x ){ pin::set( ! x ); } }; I hoped the first specialization would be selected when a T::n_pins() was available, but the compiler complains my specializations do not specialize any template argument. Is there another way I can specialize on a property of the typename argument? A: Why your code didn't work The template parameters port and pin are just formal parameters. E.g. for regular functions, would you expect that void foo(int x) { /* bla */ } and void foo(int y) { /* meh */ } to be different from each other? In fact, you can simply declare such functions in a header by their signature void foo(int) only. To overload functions you need to provide different arguments. With template parameters, it works exactly the same template<typename port> class invert { /* bla */ }; and template<typename pin> class invert { /* bla */ }; have the same template signature and can in fact be declared as template<typename> class invert; inside a header. Here, the analogy breaks down because class templates don't overload, but have to be specialized. This means that your two versions of invert need to be "different enough" in their parameter structure, regardless of what you write in the class implementation itself. How to fix it To get what you want, you actually need to specialize at least one of the tempaltes. The typical way to do that has been explained on here before, and is to define a traits class and use SFINAE to select at compile-time: template <typename T> class has_n_pins { typedef char one; typedef long two; template <typename C> static one test( typeof(&C::n_pins) ) ; template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<typename T, bool = has_n_pins<T>::value > class invert: public T { // your current port implementation }; // specialization for types T that don't have a n_pins() member function template<typename T> class invert<T, false>: public T { // your current pin implementation }; Now there are two specializations: invert<T, true> (all T that have n_pins()) and invert<T, false> (all T that don't). The compiler will now be able to select the appropriate one depending on the template argument you actually provided.
doc_23527696
I want to echo my url from my index.php, it didnt work for me so i included the php code. if it help i have include .htaccess file.thanks Notice: Undefined index: url in /var/www/mvc/index.php on line 3 <?php $url = isset($_GET['url']); echo $url; ?> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.*)$ index.php?url=$1 [PT,L] </IfModule> A: This doesn't relate to your htaccess file, it simply states that the get param has no index with that name. Try dumping out your $_GET to see its contents. A: isset returns a boolean. So you need to wrap it in an if statement in case. $url = (isset($_GET['url'])) ? $_GET['url'] : 'index'; echo $url; Doing so will suppress the notice.
doc_23527697
What I need is a way to remove the old data and replace it with new data. I have read that it is easy to update a div tag with some javascript. However, I have only seen examples with a certain amount of time has passed or when a button is clicked. Neither of these are options for what I am doing. I do not know javascript. I see this link, but without any context, it means nothing to me. How to use python variable in javascript getElementById()? How can I accomplish this? Thanks in advance! A: So I found this workaround. I do not really like it. I create a text variable with javascript code in it and the number that needs to update. Then I print that line. As the number updates, I reprint that text variable. #! /usr/bin/env python import cgi import time import sys import json print "Content-type: text/html\n\n" #<meta http-equiv='refresh' content='5'> print """ <head></head> <body> <p id='p'> </p> """ num = 19 #js = "<script>document.getElementById('p').innerHTML = " + str(num) + "; </script>" js = "<script>document.getElementById('p').innerHTML = " + json.dumps(num) + "; </script>" print js sys.stdout.flush() while num < 22: num += 1 time.sleep(1) #js = "<script>document.getElementById('p').innerHTML = " + str(num) + "; </script>" js = "<script>document.getElementById('p').innerHTML = " + json.dumps(num) + "; </script>" print js sys.stdout.flush() print""" </body> </html> """
doc_23527698
How can I extract these event handlers with my own so I can easily mock them? A: You'll need to wrap the class in your own class supporting an interface. For example if your service usage looks like this: var service = new SomeService(); service.SomeEvent =+ (o, e) => DoSomething(e); service.DoStuff(); You'll create an interface: public interface ISomeService { event EventHandler SomeEvent; void DoStuff(); } And your implementing class: public class SomeServiceWrapper : ISomeService { private readonly SomeService _containedService; public event EventHandler SomeEvent; public SomeServiceWrapper() { _containedService = new SomeService(); _containedService.SomeEvent += (o, e) => RaiseSomeEvent(e); } public void DoStuff() { _containedService.DoStuff(); } private void RaiseSomeEvent(EventArgs e) { EventHandler evt = SomeEvent; if (evt != null) { evt(this, e); } } } Then you can create a dummy ISomeService via mocking or your own dummy class, and you use the ISomeService instance SomeServiceWrapper in production. Hope that helps.
doc_23527699
DATA DATA_ID | SAMPLE_ID | ASSAY_ID | SIGNAL 101 | 201 | 301 | 2.87964 102 | 201 | 302 | 7.64623 103 | 202 | 301 | 1.98473 ... And SAMPLES: SAMPLE_ID | SAMPLE_NAME | CATEGORY 201 | SAMP0001 | CAT A 202 | SAMP0002 | CAT B 203 | SAMP0003 | CAT A ... There are about 20,000 rows in SAMPLES. For each sample, there are about 40,000 rows in DATA. Each ASSAY_ID occurs exactly once per sample in DATA. I need to take a subset of the samples in SAMPLE and calculate a standard/z-score value for each signal value in DATA, grouping by ASSAY_ID. I am trying to create a stored procedure that will be called repeatedly, which will accept a single ASSAY_ID value and return SAMPLE_ID and ZSCORE pairs for all of the samples in the predefined sample subset. Given a set of sample signal values (X = [3.21, 4.56, 1.12, ..]) for a given assay, the standard/z-score in this case is calculated as (X[i] - median(X))/(K * MAD) Where K is a scale factor equal to 1.4826 and MAD is the median adjusted deviation, equal to: median(|X[i]-median(X)|) Got that? Good :) Now, what is the most efficient way to perform this calculation using a SQL query? Execution time is key, given that there are close to a billion rows in DATA and a z-score needs to be calculated for almost every SIGNAL value. Here is the best query I have been able to come up with so far: WITH BASE AS ( SELECT S.SAMPLE_ID, D.SIGNAL FROM DATA D JOIN SAMPLES S ON D.SAMPLE_ID = S.SAMPLE_ID WHERE S.CATEGORY IN ('CAT A', 'CAT B') AND D.ASSAY_ID = 12345 AND S.SAMPLE_NAME NOT IN ('SAMP0003', 'SAMP0005', 'SAMP0008') ) SELECT A.SAMPLE_ID, (A.SIGNAL-B.MED)/(1.4826*C.MAD) AS ZSCORE FROM BASE A, ( SELECT MEDIAN(X.SIGNAL) AS MED FROM BASE X ) B, ( SELECT MEDIAN(ABS(Y.SIGNAL-YY.MED)) AS MAD FROM BASE Y, (SELECT MEDIAN(SIGNAL) AS MED FROM BASE) YY ) C Is there a more efficient way to perform this query? Bonus Question: Can I write a single SQL query that would perform this calculation for EVERY ASSAY_ID in a single execution? A: Can you have a look at: SELECT ASSAY_ID, SAMPLE_ID, (SIGNAL - MED)/(1.4826F * MAD) AS ZSCORE FROM ( SELECT ASSAY_ID, SAMPLE_ID, SIGNAL, MED, MEDIAN(ABS(SIGNAL - MED)) OVER (PARTITION BY ASSAY_ID) AS MAD FROM ( SELECT ASSAY_ID, SAMPLE_ID, SIGNAL, MEDIAN(SIGNAL) OVER (PARTITION BY ASSAY_ID) AS MED FROM DATA D JOIN SAMPLES S USING (SAMPLE_ID) WHERE S.CATEGORY IN ('CAT A', 'CAT B') AND S.SAMPLE_NAME NOT IN ('SAMP0003', 'SAMP0005', 'SAMP0008') AND D.ASSAY_ID = 301 ) ); Is it correct? Is it faster? If it is, just remove the AND D.ASSAY_ID = 301 clause for the bonus question :-) On the physical side, I would look into the data type for signal (BINARY_FLOAT or BINARY_DOUBLE are supposedly faster than NUMBER). And, if this is an option, I'd try to physically collocate the assays with partitions.