instruction
stringlengths
0
30k
{"Voters":[{"Id":354577,"DisplayName":"Chris"},{"Id":2287576,"DisplayName":"Andrew Truckle"},{"Id":349130,"DisplayName":"Dr. Snoopy"}],"SiteSpecificCloseReasonIds":[16]}
Npm command not working in powershell but works in cmd
Here is my `formSlice` and I am getting "Expression expected" after the closing brackets of the `builder` and the arrow function. ```javascript import { createAsyncThunk, createReducer, createSlice } from "@reduxjs/toolkit"; import axios from "axios"; export const getform = createAsyncThunk("form/getForm", async () => { try { const result = await axios.get("http://localhost:5000/autoroute/"); return result.data; } catch (error) {} }); export const addform = createAsyncThunk("form/add", async (form) => { try { const result = await axios.post("http://localhost:5000/autoroute/", form); return result.data; } catch (error) {} }); export const deleteform = createAsyncThunk("form/deleteForm", async (id) => { try { const result = await axios.delete(`http://localhost:5000/autoroute/${id}`); return result.data; } catch (error) {} }); export const updateform = createAsyncThunk( "form/deleteForm", async ({ id, form }) => { try { const result = await axios.put( `http://localhost:5000/autoroute/${id}`, form ); return result.data; } catch (error) {} } ); createReducer(initialState, builder = { form: [], status: null, }); export const formSlice = createSlice({ name: "form", initialState, reducers: {}, extraReducers: builder =>{ builder.getform(pending, (state) => { state.status = "pending"; }), builder.getform(pending, (state) => { state.status = "success"; }), builder.getform(pending, (state) => { state.status = "fail"; }), }, }); // Action creators are generated for each case reducer function // export const { increment, decrement, incrementByAmount } = counterSlice.actions; export default formSlice.reducer; ``` It says "expression expected" after the closing bracket `builder` of the `extraReducers`. I was working on an older version of the Redux-Toolkit but the error showed me that I need to match my code with the newer version.
After migrating to Redux-Toolkit 2.0 and Redux 5.0 I am struggling in the extraReducer and createSlice a bit
Vim also sports a `:terminal` command. Looking at [`:help :terminal`](https://vimhelp.org/terminal.txt.html#%3Aterminal) will reveal the following information: ```none :[range]ter[minal] [options] [command] Open a new terminal window. If [command] is provided run it as a job and connect the input and output to the terminal. [...] If [range] is given the specified lines are used as input for the job. It will not be possible to type keys in the terminal window. ``` This looks pretty complete: you can run a command (here: your Python interpreter) in a terminal, feeding it some lines from your buffer as input. You would enter linewise Visual mode with <kbd>Shift</kbd><kbd>V</kbd>, select the lines to run and call ``` :'<,'>terminal python ``` where `'<,'>` stands for the current visual selection. Vim will already populate your command line with this when you type `:` in Visual mode. On hitting enter, Vim will open a terminal window which will show the output (if any) of the Python code you just ran. Type `:q` to close the terminal and return to your normal editing. For convenience, consider writing a command or a mapping to quickly run Python code. The following line will define a `:Python` command that runs the current visual selection or the whole buffer if nothing is selected: ``` :command -range=% Python <line1>,<line2>terminal python ```
|android|kotlin|android-jetpack-compose|composable|
I'm looking to update rows of a MySQL database from a Google Sheet. My current workflow is to import the existing table into one sheet in Google Sheets, copy it to another one where I make changes, then run a new script to update the table. I could probably do this more efficiently but doing it this way means that I can't do anything automatically and risk breaking my database. I have created a script where I only update one column and it works except that in my database the id column is not sequential as records have been deleted (eg it starts with row 3 then 5,6,7,9 etc). But my script doesn't account for that and will just use the Google Sheets Row ID to match it (eg in MySQL the first row is row 3, but in Google Sheets it'll be row 1). This means there's a mismatch. My script is below and I've been tinkering but can't seem to make it work. The Unique IDs are in Column A. The other thing is that I don't think my loop is efficient as the database will grow beyond 400 rows. ``` function UpdateDB(e) { ss = SpreadsheetApp.getActiveSpreadsheet(); sheet = ss.getSheetByName("writeSheet"); hookn = sheet.getRange("M2:M300").getDisplayValues() ; uid = sheet.getRange("A2:A300").getDisplayValues() ; server = "1******"; port = '3306'; dbName = "*****"; username = "*******"; password = "*********"; url = "jdbc:mysql://" + server + ":" + port + "/" + dbName + "?characterEncoding=UTF-8"; conn = Jdbc.getConnection(url, username, password); stmt = conn.createStatement(); for (i=0 ; i<400 ; i++ ) { stmt.execute("UPDATE wp_tripetto_forms SET hooks ='" + hookn[i] + "' WHERE id = " + (i+1) + " ;"); } conn.close(); } ``` While the rows do update, the IDs are not correct due to the script using the Google Sheet row ID as the MySQL unique ID.
Update a MySQL row depending on the ID in Google Sheets Apps Script
|javascript|mysql|google-apps-script|jdbc|
null
IIUC, you can build a directed graph with [`networkx`](https://networkx.org), then find the [`shortest_path`](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html#networkx.algorithms.shortest_paths.generic.shortest_path) between each node and `'0'`, then use that to map the `path_variable`: ``` import networkx as nx G = nx.from_pandas_edgelist(df, source='m_eid', target='eid', create_using=nx.DiGraph) s = df.set_index('eid')['path_variable'] mapper = {n: '|'.join(s.get(x, '') for x in nx.shortest_path(G, source='0', target=n)[1:]) for n in df['eid'].unique() } df['complete_path'] = df['eid'].map(mapper) ``` Output: ``` eid m_eid level path_variable complete_path 0 1 0 0 0 0 1 2 1 1 0 0|0 2 3 1 1 1 0|1 3 4 2 2 0 0|0|0 4 5 2 2 1 0|0|1 5 6 2 2 2 0|0|2 6 7 3 2 0 0|1|0 7 8 3 2 1 0|1|1 8 9 3 2 2 0|1|2 9 10 3 2 3 0|1|3 10 11 4 3 0 0|0|0|0 11 12 4 3 1 0|0|0|1 12 13 10 3 0 0|1|3|0 ``` Graph: [![organization graph, networkx graphviz][1]][1] To make it easier to understand, here is a more classical path with the nodes ids (not the path_variables): ``` mapper = {n: '|'.join(nx.shortest_path(G, source='0', target=n)[1:]) for n in df['eid'].unique() } df['complete_path'] = df['eid'].map(mapper) ``` Output: ``` eid m_eid level path_variable complete_path 0 1 0 0 0 1 1 2 1 1 0 1|2 2 3 1 1 1 1|3 3 4 2 2 0 1|2|4 4 5 2 2 1 1|2|5 5 6 2 2 2 1|2|6 6 7 3 2 0 1|3|7 7 8 3 2 1 1|3|8 8 9 3 2 2 1|3|9 9 10 3 2 3 1|3|10 10 11 4 3 0 1|2|4|11 11 12 4 3 1 1|2|4|12 12 13 10 3 0 1|3|10|13 ``` [1]: https://i.stack.imgur.com/1PZMQ.png
Complete email addresses in a flat array using static domains (only where missing), then implode
|php|arrays|string|replace|email-address|
null
This is not a question, but a summary of the steps required to address multi tenancy with spring (the partitioned approach where every table will have a tenant id column). I hope this helps others facing issues or looking for sample code ... Two things to consider here - 1. The tenant id will be set in the header and passed with every http request. 2. I have enabled spring data rest in my application. Firstly we need an determine the tenant for each http request. We can do that by intercepting the http request before it is processed, determine the tenant and store it until the request is completely processed and clear the tenant before the next http request is processed. import jakarta.validation.constraints.NotNull; @FunctionalInterface public interface TenantResolver<T> { String resolveTenantId(@NotNull T object); } Tenant context is the class which will store the tenant Id once it is identified by intercepting http requests. public class TenantContext { private static final ThreadLocal<String> tenantId = new InheritableThreadLocal<>(); public static void setTenantId(String tenant) { tenantId.set(tenant); } public static String getTenantId() { return tenantId.get(); } public static void clear() { tenantId.remove(); } } HTTPHeaderTenantResolver implements TenantResolver. X-TenantId is the name of the header which contains the tenant id and passed along with every http request. import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.constraints.NotNull; import org.springframework.stereotype.Component; @Component public class HttpHeaderTenantResolver implements TenantResolver<HttpServletRequest> { @Override public String resolveTenantId(@NotNull HttpServletRequest request) { return request.getHeader("X-TenantId"); } } We then need to intercept each request by implementing HandlerInterceptor. In the preHandle() method, we resolve the tenant id and store it in the TenantContext class. In postHandle() and afterCompletion(), we clear the tenant id in TenantContext so we are ready to process new http requests. @Component @RequiredArgsConstructor public class HttpRequestInterceptor implements HandlerInterceptor { private final HttpHeaderTenantResolver tenantResolver; @Override public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception { var tenantId = tenantResolver.resolveTenantId(request); TenantContext.setTenantId(tenantId); return true; } @Override public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception { TenantContext.clear(); } @Override public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception { TenantContext.clear(); } } We then need to register HttpRequestInterceptor with Spring. We do that by implementing addInterceptors method of WebMvcConfigurer. @Configuration @RequiredArgsConstructor public class WebConfigurer implements WebMvcConfigurer { private final HttpRequestInterceptor httpRequestInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(httpRequestInterceptor); } } With this, spring starts intercepting every http request and will try to resolve the tenant id. We now have to let hibernate know of the current tenant id so that hibernate can use the tenant id in all sql statements. We can do that by implementing the interfaces CurrentTenantIdentifierResolver and HibernatePropertiesCustomizer. @Component public class JPATenantIdentifierResolver implements CurrentTenantIdentifierResolver<String>, HibernatePropertiesCustomizer { @Override public String resolveCurrentTenantIdentifier() { return (TenantContext.getTenantId() == null ? "" : TenantContext.getTenantId()); } @Override public boolean validateExistingCurrentSessions() { return false; } @Override public void customize(Map<String, Object> hibernateProperties) { hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this); } } Now hibernate is aware of the current tenant and it will add the tenant id in all sql statements. Lastly, as I have enabled spring data rest, we will require one additional step. Spring does not intercept data rest urls by default. We need to define an addition bean to achieve this step. @Configuration public class JPARequestInterceptor { @Bean public MappedInterceptor addJPARestHttpInterceptor() { return new MappedInterceptor( null, // => maps to any repository new HttpRequestInterceptor(new HttpHeaderTenantResolver()) ); } } Below are some links which will provide more information on multi tenancy - [https://www.youtube.com/watch?v=pG-NinTx4O4&t=1164s][1] [https://stackoverflow.com/questions/69816821/mappedinterceptor-bean-vs-webmvcconfigurer-addinterceptors-what-is-the-correct][2] [https://github.com/spring-projects/spring-data-rest/issues/1522][3] [1]: https://www.youtube.com/watch?v=pG-NinTx4O4&t=1164s [2]: https://stackoverflow.com/questions/69816821/mappedinterceptor-bean-vs-webmvcconfigurer-addinterceptors-what-is-the-correct [3]: https://github.com/spring-projects/spring-data-rest/issues/1522
Multi Tenancy in Spring - Partitioned Data Approach
|spring|spring-boot|spring-data-rest|
I am trying to run macro that can call Isometric View in Catia I run this bellow line to execute the ISO view, but not working ``` CATIA.StartCommand "Isometric View" ``` or ``` CATIA.StartCommand "*iso" ```
I ran into the same issue; assuming you are injecting the Router instance using the inject method, try changing and injecting it using the constructor constructor(private router: Router) {} instead of ... router = inject(Router); Also be sure to use the correct import. After implementing the above code change I then realized a mistake I made; there is a difference between `Inject(Router)` and `inject(Router)` import { Inject, inject } from '@angular/core'; You need to use the later.
int originalHeight = header.height; ... int lineSize = newWidth * header.bpp / 8 + padding; int skippedLines = originalHeight - newHeight; long skippedBytes = ((long)lineSize) * skippedLines; fseek(inputFile, skippedBytes, SEEK_CUR); // Skip half the lines at top. unsigned char *linePixels = malloc(lineSize); if (!linePixels) exit(137); for (int y = 0; y < newHeight; y++) { fread(linePixels, sizeof(unsigned char), lineSize, inputFile); // You could copy the old padding. //memset(linePixels + lineSize - padding, '\0', padding); fwrite(linePixels, sizeof(unsigned char), lineSize, outputFile); } free(linePixels); This will skip reading the first half containing the top lines (reversed **y** direction). As already was commented there are more `header` fields (`biSizeImage`). The BMP format contains many variants. Also copying a bit buffered, more the 3-4 bytes apiece, would be better. As I introduced a `lineSize` I used that as buffer size. The code does not become _less_ but _more_ readable.
The Best solution in these situation is **cleaning and rebuild your project.** If it still doesn't work, try searching for duplicate resources, such as layout files, drawable resources, or other assets, within your Android project.
**Updating in 2024** I was searching for a way to achieve string concatenation in modern JavaScript. Here's a simple function that demonstrates how to concatenate two values into a single string: ```javascript /** * Concatenates two values into a single string. * * @param {any} arg1 - The first value to be concatenated. * @param {any} arg2 - The second value to be concatenated. * @returns {string} The concatenated string. */ const arg1 = 'Hello'; const arg2 = 'World'; const concatStr = (arg1, arg2) => String(arg1) + String(arg2); console.log(concatStr(arg1, arg2)); // Output: HelloWorld
Goal of my program is to send data to the RS232 and read them in with a different function. I have a direct connection (wire) between the RS232 pin 2 and pin 3. I'm getting randomly occurring timeouts in WPF when I'm reading the serial port, but I receive the data and can print it. Create a serial port and a delegate in my class. ``` SerialPort _serialPort; `public delegate void ReceiveData(object sender);` ``` Create a SerialDataReceivedEventHandler after InitializeComponent() `_serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceive);` Define method for event. ``` private void SerialPort1_DataReceive(object sender, SerialDataReceivedEventArgs e) { Dispatcher.BeginInvoke(new ReceiveData(OutputDataToList), sender); } ``` Define method for the delegate. ``` private void OutputDataToList(object sender) { SerialPort sp = (SerialPort)sender; _inChar = '1'; while (_inChar != '\n') { try { _inChar = (char)sp.ReadChar(); } catch (Exception ex) { MessageBox.Show("Error while receiving the serial port. " + ex.Message); break; } if (_inChar != '\n') { _inMessage += _inChar; } } if (_inMessage != "") { lstReads.Items.Add(_inMessage); lstReads.SelectedIndex = lstReads.Items.Count - 1; } _inMessage = ""; } ``` In 70%-90% of the tests, the program works fine but sometimes, this error occurs: [![enter image description here][1]][1] I changed the timeout time. It gets better (but still happens sometimes) for shorter time but I don't understand why. ``` _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; ``` [1]: https://i.stack.imgur.com/X4SNO.png
Monaco editor удаление таба
I assume `/Wall` should work. But I am not sure, because `/W4` is working for me too. [/w, /W0, /W1, /W2, /W3, /W4, /w1, /w2, /w3, /w4, /Wall, /wd, /we, /wo, /Wv, /WX (Warning level)](https://learn.microsoft.com/en-us/cpp/build/reference/compiler-option-warning-level?view=msvc-170) Ensure the chosen build configuration and the build configuration in the project settings are the same. It's a common user experience mistake when they compile and tune different build configurations.
The Error is thrown in the context of the `setTimeout` callback function and it only exists in that context. The Promise does not know what happens inside that callback, until/unless you make it call `resolve` or `reject`.
I use hibernate for a desktop application and the database server is in another country. Unfortunately, connection problems are very common at the moment. These are: 1. 2024-03-19 14:08:42 2378 [Warning] Aborted connection 2378 to db: 'CMS_DB' user: 'JOHN' host: 'bba-83-130-102-145.alshamil.net.ae' ( Got an error reading communication packets) 2. 2024-03-19 13:44:45 1803 [Warning] Aborted connection 1803 to db: 'CMS_DB' user: 'REMA' host: '188.137.160.92' (Got timeout reading communication packets) 3. 2024-03-19 11:51:08 1526 [Warning] Aborted connection 1526 to db: 'unconnected' user: 'unauthenticated' host: '92.216.164.102' (Got an error reading packet communications) 4. 2024-03-19 11:51:08 1526 [Warning] Aborted connection 1526 to db: 'unconnected' user: 'unauthenticated' host: '92.216.164.102' (This connection closed normally without authentication) 5. 2024-03-19 11:55:26 1545 [Warning] IP address '94.202.229.78' could not be resolved: No such host is known. So far I had the following c3p0 configuration in my hibernate.cfg.xml. ``` <!-- Related to the connection START --> <property name="connection.driver_class">org.mariadb.jdbc.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Related to Hibernate properties START --> <property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property> <property name="hibernate.show_sql">false</property> <property name="hibernate.format_sql">false</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.temp.use_jdbc_metadata_defaults">false</property> <property name="hibernate.generate_statistics">true</property> <property name="hibernate.enable_lazy_load_no_trans">true</property> <!-- c3p0 Setting --> <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.min_size">4</property> <property name="hibernate.c3p0.max_size">15</property> <property name="hibernate.c3p0.timeout">300</property> <property name="hibernate.c3p0.max_statements">20</property> <property name="hibernate.c3p0.acquire_increment">3</property> <property name="hibernate.c3p0.idle_test_period">100</property> <property name="hibernate.c3p0.testConnectionOnCheckout">true</property> <property name="hibernate.c3p0.unreturnedConnectionTimeout">30</property> <property name="hibernate.c3p0.debugUnreturnedConnectionStackTraces">true</property> ``` Can someone look into whether the values for the remote connection make sense? Any change recommendation is warmly welcomed! Thanks in advance!
Emulator doesn't have an easy, built-in way to send custom `channelData`. There's a few different ways you can (kind of) do this, though: ### Debug Locally As @EricDahlvang mentioned (I forgot about this), you can [debug any channel locally](http://web.archive.org/web/20200722110139/https://blog.botframework.com/2017/10/19/debug-channel-locally-using-ngrok/) ### WebChat Emulator is built in [WebChat](https://github.com/Microsoft/BotFramework-WebChat), so the output will be the exact same. However, you miss some of the debugging functionality from Emulator. 1. Clone a [WebChat Sample](https://github.com/microsoft/BotFramework-WebChat/tree/54f67de4ff1740a050b2b5d9c07c3436e3ba314d/samples/15.a.backchannel-piggyback-on-outgoing-activities) 2. Edit `index.html` with `http://localhost:3978/api/messages` and your `channelData` 3. Run `npx serve` 4. Navigate to `http://localhost:5000` ### Modify Messages In OnTurnAsync() This would only be for testing/mocking purposes and you'd want to ensure this doesn't go into production, but you can modify incoming messages inside `OnTurnAsync()` and manually add the `channelData`. Something like: public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { var activity = turnContext.Activity; activity.ChannelData = new { testProperty = "testValue", }; You could even make it happen with only specific messages, with something like: if (turnContext.Activity.Text == "change channel data") { activity.ChannelData = new { testProperty = "testValue", }; } There's a lot of different options with this one, you just need to make sure it doesn't go into production.
`orientation` does not seem to work as desired.\ Working with `aspect-ratio` may be the better way. ``` @media only screen and (max-aspect-ratio: 1/1){ //portrait } @media only screen and (min-aspect-ratio: 1/1){ //landscape } ```
I have two columns, column 1 has product, column 2 has sales. I want to sort the table by sales descending. Total sales value/4 will give me quarter value. I want to then create a group based on this quarter value. Q1- 25% of data, Q2 - 50% of data, Q3 -75% of data, Q4 - 100% Name the group - Q1, Q2, Q3, Q4 and omit any rows with zero sales. Q1 then would be my highest selling products by value, Q2, second highest etc. How to do it in sql ? Sample table - [![enter image description here](https://i.stack.imgur.com/FvjN1.jpg)](https://i.stack.imgur.com/FvjN1.jpg) Expected output - [![enter image description here](https://i.stack.imgur.com/qCBFh.jpg)](https://i.stack.imgur.com/qCBFh.jpg) I tried a case when statement, but unlike the sample I have 1 million rows of data that needs to be grouped, hence hardcoding numbers in case when does not help, need some expert sql help here !
I have two components, one `Parent` and one `Child`. The latter should have `flex`-layout, so that it occupies 75% of the vertical space: const Parent: FC<PropsWithChildren> = (props) => { return (<View style={ styles.container }><MyChild /></View>) } const Child: FC<PropsWithChildren> = (props) => { return (<View style={ styles.childSytle }/>) } const styles = StyleSheet.create({ container: { flex: 1, flexdirection: 'column' }, childStyle: { flex: 9 } }); What I want to achieve now, is get the actual size of my `Child`-component from within `Parent`. Is it possible to get the size of a component, when it's `flex`? I already tried a `forwardref` for my `Child` to get a reference to `Child`. However I have no idea how to get its size.
question 1: python implementation (i'm sorry i don't believe a specific language was chosen so i picked the one i'm most comfortable with) <!-- language: lang-python --> base_tree = [0,1,2,3,4,5,6] trees = [base_tree] repr_2 = [] while len(trees): tree = trees.pop(0) if len(tree)==0: continue middle = len(tree)//2 repr_2.append(tree[middle]) subtree1 = tree[:middle] subtree2 = tree[middle+1:] trees.append(subtree1) trees.append(subtree2) print(base_tree) print(repr_2) question 2: i have no clue honestly
|arm|apple-silicon|denormal-numbers|
Suppose I have two entities : StudentDO and ParamDO. ParamDO is an entity that contains parameter code & values that are used throughout the application. I have already cached this entity using EhCache as Second Level Cache. @Entity @Table(name="PARAM") @jakarta.persistence.Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) class ParamDO { @Column(name="TYPE") private String type; @Column(name="CODE") private String code; @Column(name="VALUE") private String value; } ` Student Entity is associated to Param like this : @Entity @Table(name="STUDENT") class StudentDO { @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "SUBJECT_ID") private ParamDO subject; } ` My problem is despite caching the ParamDO , on querying StudentDO , associated ParamDO entity is still being fetched from DB. Is there a way this can be prevented? I have already set these properties in application.yml - spring.jpa.properties.hibernate.cache: use_second_level_cache: true use_query_cache: true From the logs I can see that a cache is created for ParamDO in EhCache. What am i missing?
Is there a way to fetch Associated Entity from second level Cache instead of hitting the DB in Hibernate?
|hibernate|spring-data-jpa|many-to-one|second-level-cache|ehcache-3|
null
I'm beginning with network programming, so my first exercise was to create a client/server system with 2 VMs. So, I have a problem with the VMs, because they don't communicate, but if I run the code local on my machine in 2 terminal windows the code run correctly. Instead, in the VMs, the server go on "listening" but when I run the code from the client machine the server receive nothing. Here is my server code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> int main(int argc, char** argv) { //controllo che da riga di comando venga inserita la porta a cui collegare la socket if (argc != 2) { printf("Usage: %s <port>", argv[0]); exit(0); } //creo tutte le variabili che mi serviranno int port = atoi(argv[1]); //porta presa da riga di comando int server_sock, client_sock; //socket per server e client struct sockaddr_in server_addr, client_addr; //struct per gestire gli indirizzi di server e client(IPv4, IPv6) socklen_t addr_size; //lunghezza degli indirizzi char buffer[1024]; //buffer per il trasferimento dei messaggi int n; //variabile di controllo //chiamata alla funzione socket che restituisce un valore int a server_sock server_sock = socket(AF_INET, SOCK_STREAM, 0); //controllo che la chiamata socket() abbia restituito un valore > 0, quindi esito della chiamata positivo if (server_sock < 0) { perror("[-] Error while creating socket.\n"); exit(1); } printf("[+] TCP socket created. \n"); //setto i byte della memoria a 0 memset(&server_addr, '\0', sizeof(server_addr)); //assegno i vari attributi dell'indirizzo server_addr.sin_family = AF_INET; server_addr.sin_port = port; server_addr.sin_addr.s_addr = INADDR_ANY; //chiamata alla funzione bind che associa la socket con la porta e ne metto il valore di ritorno in n n = bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)); //controllo che la chiamata precedente sia andata bene quindi n > 0 if (n < 0) { perror("[-] Error while binding the socket.\n"); exit(1); } printf("[+] Socket binded to the port %d\n", port); //metto in ascolto il server listen(server_sock, 5); printf("[+] Listening...\n"); //ciclo su i client che si collegano al server while(1) { addr_size = sizeof(client_addr); // size dell'indirizzo del client //chiamata alla funzione accept, che restituisce un valore int client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_size); char ipString[40]; // stringa per salvare l'ip del client che si è collegato al server inet_ntop(AF_INET, &client_addr, ipString, sizeof(client_addr)); //converto l'ip in un formato di testo printf("[+] Client connected.\n Client IP:%s\n", ipString); //stampo l'indirizzo che si è collegato al server bzero(buffer, 1024); //azzero i byte del buffer recv(client_sock, buffer, sizeof(buffer), 0); //ricevo il messaggio dal client printf("Client: %s\n", buffer); // stampo il messaggio salvato in buffer bzero(buffer,1024); //riazzero il buffer strcpy(buffer, "Hi from the server"); // passo una stringa nel buffer printf("Server: %s\n", buffer); send(client_sock, buffer, strlen(buffer), 0); // mando il messaggio del buffer al client close(client_sock); //chiudo la connessione printf("[+] Client disconnected.\n"); } return 0; } And here the client code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> int main(int argc, char ** argv) { //controllo che la porta venga indicata in riga di comando if (argc != 2) { printf("Usage: %s <port>", argv[0]); exit(0); } //variabili di controllo, socket e indirizzo int port = atoi(argv[1]); int sock; struct sockaddr_in addr; socklen_t addr_size; char buffer[1024]; int n; //chiamata a socket e subito dopo controllo sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("[-] Error while creating socket.\n"); exit(1); } printf("[+] TCP socket created. \n"); memset(&addr, '\0', sizeof(addr));//setto i byte a 0 //imposto gli attributi dell'indirizzo addr.sin_family = AF_INET; addr.sin_port = port; addr.sin_addr.s_addr = INADDR_ANY; //connetto la socket connect(sock, (struct sockaddr*)&addr, sizeof(addr)); printf("[+] Client connected.\n"); bzero(buffer, 1024);// azzero i byte del buffer strcpy(buffer, "Hello World"); printf("Client: %s\n", buffer); send(sock, buffer, strlen(buffer), 0); // mando il messaggio contenuto nel buffer bzero(buffer, 1024); recv(sock, buffer, sizeof(buffer), 0); //ricevo la risposta del server printf("Server: %s\n", buffer); close(sock); // chiudo la connessione lato client printf("[+] Disconnected from the server"); return 0; } I don't understand what I do wrong, I hope someone can explain me what are the errors. Thank you!
My server TCP doesn't receive messages from the client in C
|c|sockets|network-programming|virtual-machine|
Both have their pros and cons. You also have the option to deploy multiple workers on a single service, one worker per service, or scale up the number or multiple services for a single worker topic. It all depends on what your performance and scaling requirements are. I'd suggest starting with a single worker and only scaling when you need. The exceptions to this that you might want to consider are: - is there a benefit (for whatever reason) to have some activities/workflows implemented in Go and others in Java - are there specific workflows or activities that are performance bottlenecks - do you have multiple teams working on your infrastructure. If so, there may be benefits to each team having separately deployable workflows and applications.
I was attempting to solve the question for deleting a node in BST, and saw a strange output. In the case where node has only right child, I was trying to delete that node and return its right child. Somehow, both of the codes below gave the correct result, even though it seems to me like only code 1 should work since we're trying to access a deleted node. Can someone tell me why this happens? cpp Code 1: Node* temp = root->right; delete root; return temp; Code 2: Node* temp = root; delete temp; return root->right;
get size of flex component
|react-native|flexbox|
I have two tables: Schedules and Tasks, with a one-to-one relation ``` class Schedule extends Model { public function task() { return $this->belongsTo(Task::class, 'task_id'); } ``` And the Task model has a one-to-many relation with Spatie Roles with a task_role pivot table: ``` class Task extends Model { public function roles() { return $this->belongsToMany(Role::class); } ``` How can I make a query that retrieves all schedules associated with tasks with permission for the logged in user? For example: Tasks: | id | name | | -------- | -------------- | | 1| task1| | 2| task2 | | 3| task3 | task_role: | task_id | role_id | | -------- | -------------- | | 1| 1| | 2| 3 | | 3| 1| Schedule: | id| name | task_id | | -------- | -------------- |-| | 1| schedule1|1 | 2| schedule2|1 | 3| schedule3|5 Spatie model_has_roles: | role_id| model_type| model_id| | -------- | -------------- |-| | 1| App\Models\User|2 | 2| App\Models\User|1 | 3| App\Models\User|5 When user2 is logged in he should be able to see only schedule 1 and 2.
Hello I have an Oled that I bought on AliExpress and it's not working even with adafruit. this is a 2 inch TFT module 240x320 ST7789V GMT020-02 and it has 7 pins. Can someone help me please? i've tried even the ada fruit benchmark but it doesn't work:(
Arduino TFT module 240x320 OLED not working
|c++|arduino|
null
It seems you are setting the struct variable `test`'s attribute `a` to `5` only after you send the data. Make sure to initialize the payload to what you want prior to sending.
This is my first – ever post on Stack Overflow and it’s about an issue with the functionality of the VS Code terminal. Whenever I would run a piece of code via the terminal, the terminal would operate for several seconds and disappear. I would then be presented with a dialog box on the bottom – right corner of the screen, informing me that the terminal terminated with an exit code of ‘2’. Sometimes, the exit code would be different. It would be ‘3’, ‘1’, ‘-3’, or ‘-1’ depending on the situation. I’ve tried uninstalling VS Code, Windows Terminal, Windows Powershell and re – installing those programs only for the same issue to reoccur. I also have an issue with the terminal not accepting input i.e., when you would type a line of syntax in the terminal, it freezes, causing the input to be unrecognizable. The operation stalled. There were plenty of articles that I read on Stack Overflow in relation to my issues, but none were successful. I’m reaching out for assistance from anyone and am open to any suggestions in regards to this matter. Genuinely, Jayloneal
How do I get my terminal to work in VS Code? Exit Code:2, doesn't allow me to type anything
|powershell|visual-studio-code|terminal|crash|freeze|
null
You could try using the following formulas, this assumes there is no `Excel Constraints` as per the tags posted: [![enter image description here][1]][1] ---------- =TEXT(MAX(--TEXTAFTER(B$2:B$7,"VUAM")*($A2=A$2:A$7)),"V\U\A\M\00000") ---------- Or, using the following: =TEXT(MAX((--RIGHT(B$2:B$7,5)*($A2=A$2:A$7))),"V\U\A\M\00000") ---------- Or, you could use the following as well using `XLOOKUP()` & `SORTBY()`: [![enter image description here][2]][2] ---------- =LET( x, SORTBY(A2:B7,--RIGHT(B2:B7,5),-1), y, TAKE(x,,1), XLOOKUP(A2:A7, y, TAKE(x,,-1))) ---------- <sup> § Notes On **`Escape Characters`**: The use of `backslash` before & after the `V`, `U`, `A` & `M` is an **`escape character`**. Because the `V`, `U`, `A` & `M` on its own serves a different purpose, we are escaping it meaning hence asking Excel to **`literally form text`** with that character. </sup> ---------- Here is the **`Quick Fix`** to your **`existing formula`**, escape characters are not placed correctly, info on the same refer `§` [![enter image description here][3]][3] ---------- =TEXT(MAX(IF($A$2:$A$100=A2, MID($B$2:$B$100, 5, 5)+0)),"V\U\A\M\00000") ---------- One more alternative way using `SORT()` & `REPT()` with **`Implicit Intersection Operator`** <sup>@</sup> [![enter image description here][4]][4] ---------- =@SORT(REPT(B$2:B$7,(A2=A$2:A$7)),,-1) ---------- <sub>Notes on `Implicit Intersection Operator`<sup>**@**</sup> : It helps in reducing many values to a **`single value`**. **1.)** If the value is a single item, then return the item, **2.)** If the value is a range, then return the value from the cell on the same row or column as the formula., **3.)** If the value is an array, then pick the top-left value. --> Excerpts taken from `MSFT` Documentations, read [here][5]. </sub> ---------- [1]: https://i.stack.imgur.com/K0j2K.png [2]: https://i.stack.imgur.com/ovCkj.png [3]: https://i.stack.imgur.com/82vOL.png [4]: https://i.stack.imgur.com/Hu9WS.png [5]: https://support.microsoft.com/en-us/office/implicit-intersection-operator-ce3be07b-0101-4450-a24e-c1c999be2b34#:~:text=Implicit%20intersection%20logic%20reduces%20many%20values%20to%20a,it%20was%20technically%20being%20done%20in%20the%20background%29.
have recently deployed my Django project to a server, and while the index URL (mannyebi.com) loads correctly along with static files, accessing sub URLs such as mannyebi.com/blogs or even the admin panel (mannyebi.com/admin) results in a 404 error. Locally, the project runs smoothly, indicating the issue may stem from the deployment configuration. I've ensured that all necessary URL patterns are defined in the urls.py files and that Django's admin app is properly installed and configured. However, despite these measures, I'm still encountering difficulties accessing sub URLs beyond the homepage. Is there a specific configuration step or server setting that I might be overlooking to resolve this 404 error and enable access to sub URLs on my deployment? Any insights or troubleshooting suggestions would be greatly appreciated. I deployed my Django project to a server. Upon navigating to sub URLs such as mannyebi.com/blogs or mannyebi.com/admin, I encountered a 404 error. I verified that all necessary URL patterns were defined in urls.py and that Django's admin app was properly configured. I expected these URLs to load correctly, similar to how they did on my local development environment. However, despite these efforts, the 404 errors persisted. I'm seeking guidance on resolving this issue and enabling access to sub URLs on the deployment.
Django Admin Panel and Sub URLs Returning 404 Error on Deployment
|django|deployment|django-admin|django-urls|django-deployment|
null
{"Voters":[{"Id":26742,"DisplayName":"Sani Huttunen"},{"Id":349130,"DisplayName":"Dr. Snoopy"},{"Id":12265927,"DisplayName":"Puteri"}]}
Another solution is to use [jupyverse](https://github.com/jupyter-server/jupyverse) instead of `jupyter notebook`, as `jupyverse` supports `kernels.allow_external_kernels` and `kernels.external_connection_dir` options to reuse existing running kernels. ``` pip install jupyverse[auth,jupyterlab] ``` ``` STARTUP_CODE="a = 42" CONNECTION_DIR="$(mktemp -d)" (printf "%s\n" "$STARTUP_CODE" && sleep infinity) | jupyter console --kernel=python3 -f="$CONNECTION_DIR/connection-file.json" & jupyverse --set kernels.allow_external_kernels=true --set kernels.external_connection_dir="$CONNECTION_DIR" --open-browser ``` ``` 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off 0.00s - to python to disable frozen modules. 0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation. 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off 0.00s - to python to disable frozen modules. 0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation. [2024-03-31 21:23:30,474 INFO] Running in development mode [2024-03-31 21:23:30,488 INFO] Starting application Warning: Input is not a terminal (fd=0). Jupyter console 6.6.3 Python 3.11.8 (main, Feb 6 2024, 21:21:21) [GCC 13.2.0] Type 'copyright', 'credits' or 'license' for more information IPython 8.16.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: In [1]: a = 42 [2024-03-31 21:23:31,283 INFO] [2024-03-31 21:23:31,283 INFO] To access the server, copy and paste this URL: [2024-03-31 21:23:31,283 INFO] http://127.0.0.1:8000/?token=ce016c609cfa4d8bbcb8c663cbab0c64 [2024-03-31 21:23:31,283 INFO] [2024-03-31 21:23:31,289 INFO] Started server process [45786] [2024-03-31 21:23:31,289 INFO] Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) In [2]: ^[[27;1R[2024-03-31 21:23:32,425 INFO] Application started WARNING: your terminal doesn't support cursor position requests (CPR). In [2]: ``` Now visit http://127.0.0.1:8000/?token=ce016c609cfa4d8bbcb8c663cbab0c64, you will find the existing kernel under the KERNELS tab. Right click it and you will be able to create a new notebook that attaches to the existing kernel. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/YuZBu.png
If you're trying to access the service running on your localhost, simply set the `nifi.web.http.host` property to `0.0.0.0` or `localhost` instead of `nifi-0`. restart your docker and test `curl http://localhost:8080/nifi` Here's an example of a docker-compose.yml to run NiFi in secure mode: version: "3.9" services: nifi: image: apache/nifi:1.22.0 hostname: nifi container_name: nifi restart: on-failure environment: - NIFI_WEB_HTTPS_PORT=9443 - SINGLE_USER_CREDENTIALS_USERNAME=admin - SINGLE_USER_CREDENTIALS_PASSWORD=ctsBtRBKHRAx69EqUghvvgEvjnaLjFEB - NIFI_HOME=/opt/nifi/nifi-current - NIFI_LOG_DIR=/opt/nifi/nifi-current/logs - NIFI_TOOLKIT_HOME=/opt/nifi/nifi-toolkit-current - NIFI_PID_DIR=/opt/nifi/nifi-current/run - NIFI_BASE_DIR=/opt/nifi ports: - '9443:9443' healthcheck: test: ["CMD", "curl", "-f", "https://localhost:9443/health"] interval: '30s' timeout: '20s' retries: 3 start_period: '5s' volumes: - data:/var/data - nifi:/opt/nifi volumes: data: nifi:
You can use the `grid` method instead of `pack` for the radio buttons. The `grid` method allows you to specify the row and column where each widget should be placed, enabling them to be positioned side-by-side. url_pref_frame = tk.LabelFrame(self, text="URL Loading Preferences", padx=10, pady=10) url_pref_frame.pack(pady=(20, 0), padx=(10, 0), fill=tk.X) self.url_loading_preference = tk.StringVar(value="Most Recent") row = 0 # Keep track of the current row for grid placement tk.Radiobutton(url_pref_frame, text="Most Recent", variable=self.url_loading_preference, value="Most Recent", command=self.on_radio_change).grid(row=row, column=0, sticky=tk.W) row += 1 tk.Radiobutton(url_pref_frame, text="Oldest", variable=self.url_loading_preference, value="Oldest", command=self.on_radio_change).grid(row=row, column=0, sticky=tk.W) row += 1 tk.Radiobutton(url_pref_frame, text="Random page", variable=self.url_loading_preference, value="Random page", command=self.on_radio_change).grid(row=row, column=0, sticky=tk.W) By using `grid` and specifying the row for each radio button, you ensure they are placed horizontally within the frame, making them all clickable. [![Working Code][1]][1] [![Working code 2][2]][2] [1]: https://i.stack.imgur.com/tpAa1.png [2]: https://i.stack.imgur.com/Xu8PZ.jpg
just in case for those who are struggling to console log only the names of the fruits : Fruit.find() .then((fruits) => { fruits.forEach((fruits) => { console.log('Names of fruits:', fruits.name); }); }) .catch((error) => { console.error('Error retrieving documents:', error); }).finally(()=> { mongoose.connection.close(); });
My crontab file looks like: ``` */1 * * * * /Users/dmitriy/.asdf/shims/elixir ~/work/scripts/my_script.exs ``` And that script doesn't work. As I understand it, cron cannot detect the location of elixir. I run it on macOs Ventura. How can I solve this problem?
I fixed the error by finding out the $HOME/.buildozer/android/platform/android-sdk has a zip file, then i just unziped it and it worked.
When I try to add a log using the below code (app for logging theatre trips) or search logs I'm sent to the App.g.i.cs autogenerated code. I've used breakpoints and stepped through the code and it seems to get through the whole subroutine and then when it gets to the end it throws this, perhaps its something with the UI? ``` #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION UnhandledException += (sender, e) => { if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break(); }; #endif ``` This is my xaml code for the main page ``` <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyTheatreLog.MainPage" xmlns:viewmodel="clr-namespace:MyTheatreLog.ViewModel" x:DataType="viewmodel:MainViewModel" Title="Theatre Log"> <Grid RowDefinitions="50, Auto, Auto, *, Auto" ColumnDefinitions=".8*,.05*,.15*" Padding="10" RowSpacing="10" ColumnSpacing="10"> <Entry Placeholder="New Log" Grid.ColumnSpan="3" Text="{Binding Show}" Grid.Row="1"/> <DatePicker Grid.Row="2" Grid.Column="0" Date="{Binding Date}"/> <Button Text="+" FontSize="30" WidthRequest="20" HeightRequest="20" Command="{Binding AddCommand}" Grid.Row="2" Grid.Column="3" HorizontalOptions="End"/> <CollectionView Grid.Row="3" Grid.ColumnSpan="3" ItemsSource="{Binding Shows}" SelectionMode="None" > <CollectionView.ItemTemplate> <DataTemplate x:DataType="viewmodel:ShowItem"> <SwipeView> <Grid Padding="0,5"> <Frame CornerRadius="8" HasShadow="True"> <Frame.GestureRecognizers> <TapGestureRecognizer NumberOfTapsRequired="2" Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=DetailsCommand}" CommandParameter="{Binding .}"/> </Frame.GestureRecognizers> <Grid ColumnDefinitions="*, 90"> <Label Text="{Binding Title}" Grid.Column="0" FontSize="14"/> <Label Text="{Binding DateString}" Grid.Column="1"/> </Grid> </Frame> </Grid> </SwipeView> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> <Entry Placeholder="Search Logs" Grid.Row="4" Text="{Binding Searchentry}"/> <Button Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" Text="Search" Command="{Binding SearchCommand}"/> </Grid> </ContentPage> ``` and my ViewModel code ``` using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using System.Collections.ObjectModel; namespace MyTheatreLog.ViewModel { public class ShowItem { public string Title { get; set; } public string DateString { get; set; } } public partial class MainViewModel : ObservableObject { private LocalDatabase localDatabase; string appDataDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyTheatreLog"); public MainViewModel() { if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyTheatreLog"))) { Directory.CreateDirectory(Path.Combine(appDataDirectory, "MyTheatreLog")); } Shows = new ObservableCollection<ShowItem>(); localDatabase = new LocalDatabase(); LoadLogs(); } public void LoadLogs() { try { string[] logfiles = Directory.GetFiles(appDataDirectory, "*.txt"); Shows.Clear(); foreach (string file in logfiles) { using(StreamReader savefile = new StreamReader(file)) { Title = savefile.ReadLine(); Datestring = savefile.ReadLine(); savefile.Close(); } if (!string.IsNullOrEmpty(Title) && !string.IsNullOrEmpty(Datestring)) { var showItem = new ShowItem { Title = Title, DateString = Datestring }; Shows.Add(showItem); } } } catch(Exception ex) { Console.WriteLine("Error loading logs " + ex.Message); } } [ObservableProperty] ObservableCollection<ShowItem> shows; [ObservableProperty] string show; bool searching = false; [ObservableProperty] string title; [ObservableProperty] DateTime date = DateTime.Today; [ObservableProperty] string searchentry; [ObservableProperty] string filename; [ObservableProperty] String datestring; [RelayCommand] void Add() { // checks if entry is empty if (string.IsNullOrWhiteSpace(Show)) return; Datestring = Date.ToString("dd/MM/yyyy"); // adds show Show = Show.Trim(); string filetitle = Show.Replace(" ", "") + Datestring.Replace("/", ""); Filename = filetitle + ".txt"; using (StreamWriter savefile = new StreamWriter(System.IO.Path.Combine(appDataDirectory, Filename), true)) { //saves to file savefile.WriteLine(Show); savefile.WriteLine(Datestring); savefile.Close(); } LoadLogs(); Show = string.Empty; } [RelayCommand] void Search() { try { var Showsholder = new ObservableCollection<ShowItem>(); Showsholder.Clear(); if (searching == false) { // checks if entry is empty if (string.IsNullOrWhiteSpace(Searchentry)) return; // fills Shows placeholder foreach (var log in Shows) { Showsholder.Add(log); } Shows.Clear(); Searchentry = Searchentry.Trim(); Searchentry = Searchentry.ToLower(); foreach (var log in Showsholder) { string logtitle = log.Title; string logsearched = logtitle.ToLower(); // Adds logs that match search if (logsearched.Contains(Searchentry)) { Shows.Add(log); } } searching = true; } else { Shows.Clear(); LoadLogs(); searching = false; } Searchentry = string.Empty; } catch { Console.WriteLine("Error Searching"); } } [RelayCommand] async Task Details(ShowItem s) { //navigates to Details Page string filetitle = s.Title.Replace(" ", ""); string filedate = s.DateString.Replace("/", ""); Filename = filetitle + filedate + ".txt"; await Shell.Current.GoToAsync($"{"Details"}?Filename_={Filename}"); } } } ``` I'm very new to MAUI and I've been trying my best to read through it and work it out but no luck A new file containing the item info does get created in the correct location with the correct name and is displayed when I next run the code.
Visual Studio throwing DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION when I try to add a log
|c#|xaml|maui|
null
**I'm trying to create a curl in python to connect to a swagger api and download the data to a csv. This is the first time I use Python, before I had curl in PHP, but I needed to change This is the script** # Import necessary modules import pycurl import urllib.parse query = """ SELECT min({cart_pai.pk}) FROM {cart as carrinho JOIN cart AS cart_pai ON {carrinho.parent} = {cart_pai.pk}} """ safe_string = urllib.parse.quote_plus(query) url = """ https://api.cokecxf-commercec1-p1-public.model-t.cc.commerce.ondemand.com/clarowebservices/v2/claro/flexiblesearch/export/search/getAsCsv? """ # Define the headers headers = ['Authorization: Bearer 4DmQkomKs0z845705JIlfW-hhNg'] # Initialize a Curl object c = pycurl.Curl() # Set the URL to send the request to c.setopt(c.URL, url + safe_string) # Set the HTTPHEADER option with the headers c.setopt(pycurl.HTTPHEADER, headers) # Perform the request c.perform() # Close the Curl object to free system resources c.close()
I created a meta app using the email address associated with the base facebook account that created the page I am trying to get the posts from. In the Graph API Explorer I have selected my meta app and "user token". When I add the page ID to the query string field and click submit I get the error:"(#100) Object does not exist, cannot be loaded due to missing permission or reviewable feature, or does not support this operation. This endpoint requires the 'pages_read_engagement' permission or the 'Page Public Content Access' feature or the 'Page Public Metadata Access' feature." But I don't see 'pages_read_engagement' in the list of permissions to choose from. Do I need to apply for "page public content access"? Do I need to use a page token? When I try to select "Page Access Token" as the token type I get a pop up saying "Sorry, something went wrong. We're working on getting this fixed as soon as we can."
How can I get posts from a facebook page using the graph API?
|facebook-graph-api|
Read this on [anchor positioning](https://developer.chrome.com/blog/introducing-popover-api#anchor_positioning).
I'm on Laravel 10, and created an API using sanctum. In my controller, I want to call the local API to display in a view. The API works fine using postman, but when called in my controller the page doesn't load and times out. Below is my module route in `module/api/routes/api.php` ``` Route::group(['middleware' => ['auth:sanctum', 'api']], function () { Route::get('sample', [ApiController::class, 'sample']); }); ``` here is the HTTP code in my controller ``` $response = Illuminate\Support\Facades\Http::withHeaders([ "Accept"=> "application/json", "Authorization" => "Bearer " . env('SANCTUM_AUTH') ]) ->get(route('sample').'/', ['type' => '2']); dd($response); ``` and this is the error i'm getting. `cURL error 28: Operation timed out after 30006 milliseconds with 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://127.0.0.1:8000/sample/?type=2` my memory limit in php.ini is already set to 512M. I'm also on php 8.1.27 How do I call the API locally with sanctum?
C++: Program for Deleting a node and return its right child:
|c++|binary-tree|binary-search-tree|
I am building the kendo grid view from the Database, i am able to bind the grid view , how ever i could not able to edit. grid cell is not closing after edit the value. Please refer the link below. [https://jsfiddle.net/09jqht85](https://stackoverflow.com) I have tried with the Kendo UI sites and blogs.
Kendo Mvvm Dynamic grid view Edit issue
|kendo-grid|kendo-mvvm|
null
{"OriginalQuestionIds":[24159036],"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":7976758,"DisplayName":"phd","BindingReason":{"GoldTagBadge":"git"}}]}
I wait until the page is loaded and use the "DOMContentLoaded" method to add eventhandlers on some p tags. This works until I open and close the modal, then the page/js freezes. Why does it freeze? ``` <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="div_1"> <p>One</p> <p>Two</p> <p>Three</p> </div> <p id="open_modal">open the modal</p> <script> document.addEventListener("DOMContentLoaded", () => { let test = document.querySelector("#div_1") for (let i = 0; i < test.children.length; i++) { test.children[i].addEventListener("click", () => { console.log(test.children[i].innerHTML) }); }; }); document.querySelector("#open_modal").addEventListener("click", () => { if (!document.querySelector("#modal")) { document.body.innerHTML += ` <div id="modal" style="display: block; position: fixed; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4)"> <div id="modal_content"> <span id="modal_close">&times;</span> <p style="color: green;">Some text in the Modal..</p> </div> </div> `; document.querySelector("#modal_close").addEventListener("click", () => { document.querySelector("#modal").style.display = "none"; }); } else { document.querySelector("#modal").style.display = "block"; }; }); </script> </body> </html> ```
I've tried to render emoji flags such as notoColorEmoji (french flag) using google fonts, but for some reason they don't get rendered at all. It works fine for other monochromatic fonts, but I couldn't find out how to make them work on windows (I'm using windows 10). When I try this, the first two are rendered as expected, but the font "Noto Color Emoji" simply renders blank on all emojis. Text('Google Fonts Kanit', style: GoogleFonts.kanit( textStyle: const TextStyle(fontSize: 20), )), Text('Google Fonts notoEmoji', style: GoogleFonts.notoEmoji( textStyle: const TextStyle(fontSize: 20), )), Text('Google Fonts notoColorEmoji', style: GoogleFonts.notoColorEmoji( textStyle: const TextStyle(fontSize: 20), )), Output: > [![enter image description here][1]][1] Is there a fix for it, or another alternative to allow a windows app to render color emojis? ps: I'm looking for a solution that doesn't involve "hacks" or installing a font in the system, which can mess with other apps. [1]: https://i.stack.imgur.com/JGGzE.png
Use a `BY` statement. The statement will implicitly create automatic flag variables `first.<byvar>` and `last.<byvar>`. When both variables are `=1` the implied condition is that the by group contains a single row. You are looking to flag the inverse condition (when a by group contains more than one row). ``` data want ; set have ; by cpt product date ; flag = not (first.date and last.date) ; run ; ```
I am using [this package](https://pub.dev/packages/flutter_pixelmatching) and creating two instances of its class PixelMatching which uses dart ffi and some c++ code to perform feature matching using open cv. I initialise the two instances with different source images with which it compares my camera feed. However, both of the instances end up using the first image in their comparisons. Here is where I initialize the matching with two different images. [initializing the instances](https://i.stack.imgur.com/rhLIa.png) This is a part of the function where I call the methods to compare the image with my camera stream. The two instances are called alternatively, in one frame the first and in the next the second instance. [enter image description here](https://i.stack.imgur.com/i5lz9.png) Am I creating the classes in some wrong way? I don't understand why the two instances can't hold different states.
Creating multiple instances of a class with different initializing values in Flutter
|android|flutter|opencv|oop|
null
I have trained CNN model and saved it in .h5 format but when I use this for prediction with the help of camera I am not able to predict , the camera opens but there is no predictions and other content Here is my code , I am actually learning ML so could you please solve this problem ? Here is my code , I am actually learning ML so could you please solve this problem ? I am expecting to predict the image class when I show a image to laptop camera ``` import numpy as np import cv2 from keras.models import load_model # Load the model model = load_model('C:/Users/Win/Downloads/traffic_classifier.h5') # Parameters frameWidth = 640 # CAMERA RESOLUTION frameHeight = 480 brightness = 180 threshold = 0.5 # PROBABILITY THRESHOLD font = cv2.FONT_HERSHEY_SIMPLEX # SETUP THE VIDEO CAMERA cap = cv2.VideoCapture(0) cap.set(3, frameWidth) cap.set(4, frameHeight) cap.set(10, brightness) def preprocessing(img): # Convert image to RGB format img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Resize image to 30x30 img = cv2.resize(img, (30, 30)) # Normalize pixel values img = img / 255.0 # Add batch dimension img = np.expand_dims(img, axis=0) return img def getClassName(classNo): classes = { 0: 'Speed Limit 20 km/h', 1: 'Speed Limit 30 km/h', 2: 'Speed Limit 50 km/h', 3: 'Speed Limit 60 km/h', 4: 'Speed Limit 70 km/h', 5: 'Speed Limit 80 km/h', 6: 'End of Speed Limit 80 km/h', 7: 'Speed Limit 100 km/h', 8: 'Speed Limit 120 km/h', 9: 'No passing', 10: 'No passing for vehicles over 3.5 metric tons', 11: 'Right-of-way at the next intersection', 12: 'Priority road', 13: 'Yield', 14: 'Stop', 15: 'No vehicles', 16: 'Vehicles over 3.5 metric tons prohibited', 17: 'No entry', 18: 'General caution', 19: 'Dangerous curve to the left', 20: 'Dangerous curve to the right', 21: 'Double curve', 22: 'Bumpy road', 23: 'Slippery road', 24: 'Road narrows on the right', 25: 'Road work', 26: 'Traffic signals', 27: 'Pedestrians', 28: 'Children crossing', 29: 'Bicycles crossing', 30: 'Beware of ice/snow', 31: 'Wild animals crossing', 32: 'End of all speed and passing limits', 33: 'Turn right ahead', 34: 'Turn left ahead', 35: 'Ahead only', 36: 'Go straight or right', 37: 'Go straight or left', 38: 'Keep right', 39: 'Keep left', 40: 'Roundabout mandatory', 41: 'End of no passing', 42: 'End of no passing by vehicles over 3.5 metric tons' } return classes[classNo] while True: success, imgOriginal = cap.read() # Preprocess the image img = preprocessing(imgOriginal) # Predictions predictions = model.predict(img) classIndex = np.argmax(predictions, axis=1) probabilityValue = np.amax(predictions) # Display results if probability is above threshold if probabilityValue > threshold: class_name = getClassName(classIndex) cv2.putText(imgOriginal, "CLASS: " + class_name, (20, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA) cv2.putText(imgOriginal, "PROBABILITY: " + str(round(probabilityValue * 100, 2)) + "%", (20, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA) cv2.imshow("Result", imgOriginal) else: cv2.imshow("Processed Image", imgOriginal) if cv2.waitKey(1) & 0xFF == ord('q'): # Check for 'q' key press to exit break cap.release() cv2.destroyAllWindows() ```
I precompile template using this code: ``` func precompileTemplate() { // Menggunakan template.ParseGlob untuk memuat semua file template templates = template.Must(template.ParseGlob("static/*.html")) } ``` In my base.html: ``` <div id="content" class="p-5"> {{template "content" .}} </div> ``` And in my signup.html ``` {{ define "content" }} <h1>Signtup to RWID</h1> {{ end }} ``` In my go route: ``` err = templates.ExecuteTemplate(w, "signup.html", data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } ``` But opening /signup gives me a blank page. What's wrong?
How to properly use Golang html/template precompiled?
|go|go-html-template|
Based on your investigation, I suspect your DB version is older than you think. You could try adding the `ServerVersion.AutoDetect(connectionString)` to your EF core MySql configuration. See if that influences EF core to write SQL that in understandable to your DB version? It would look something like this when you are configuring services: ``` builder.Services.AddDbContext<ApplicationContext>(options => { //...your other configs var connectionString = builder.Configuration.GetConnectionString("or however you get the connection string..."); options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); }); ``` You can also try setting the version explicitly like this: ``` services.AddDbContextPool<YourDbContext>(options => options .UseMySql( Configuration.GetConnectionString("how ever you get this"), mySqlOptions => mySqlOptions.ServerVersion(new Version(10, 0, 40, ServerType.MariaDb) ) ); ``` Use which ever version you have, though
I am currently trying to build a web app with google apps script, and I have implemented a login function. The login happens as it should, but I then try to redirect the user to the dashboard of my web app. The current code for the dashboard is the basic code for a new HTML file within apps script with a h1 title, so there are no issues with it. In my login.html file, this is how it should redirect the user to the dashboard page: function onLoginSuccess(sessionId) { if (sessionId) { console.log('Success') console.log(sessionId) window.location.href = "dashboard?sessionId=" + sessionId; console.log('Success') } else { alert("Invalid email or password. Please try again."); } } I have tried an url with `"dashboard.html?sessionId=" +sessionId` and I get the following error in the F12 console: `Failed to load resource: the server responded with a status of 500 ()` I then tried an url without the html `"dashboard?sessionId=" +sessionId` and I now get the following error: `Refused to display 'https://developers.google.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.` I then tried adding `.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);` with my return HtmlService line, but I still get the error. With both URLs, both success and the session ID get called into the console. Is there a way to fix the issue? Maybe another way to redirect the user, or just a way to fix the error?
Error (Status of 500) and X-Frame-Options with google apps script redirect function
Cronjob does not work for the local asdf elixir path
|cron|elixir|macos-ventura|asdf|
This is Powershell/WPF (The loaded assemblies are pasted from my project and mostly not needed for this) I am making an animated flyout button, it works as intended, I click the button, it slides into position, at the end of the animation it hides and a different button appears in its place with the opposite animation ready waiting to be clicked, this behavior toggles fine. I would like to make clicking anywhere (not solely the second button) trigger moving the second button back. In the real script a popup window appears, and my intent is to make it dismissible by clicking anywhere outside the window in addition to the button itself. I currently have this working but if the button isnt directly clicked the close animation gets skipped because I cant(don't know how to) trigger it without the button. I know it's highly likely someone knows how to do this in C#, and I am willing to take examples and figure out how to make a comparable PS codebehind, so I tagged C# too, but if there is a PS method someone knows, that would be extremely helpful. ``` Add-Type -AssemblyName PresentationFramework, System.Drawing, System.Windows.Forms, WindowsFormsIntegration, presentationCore [xml]$xaml=' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" WindowStartupLocation="CenterScreen" WindowStyle="None" Background="Transparent" AllowsTransparency="True" Width="500" Height="300"> <Window.Resources> <ControlTemplate x:Key="NoMouseOverButtonTemplate" TargetType="Button"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Background" Value="{x:Static SystemColors.ControlLightBrush}"/> <Setter Property="Foreground" Value="{x:Static SystemColors.GrayTextBrush}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <Canvas> <Button Name="MovableButton1" Canvas.Left="70" Canvas.Top="0" FontSize="12" FontFamily="Calibri" FontWeight="Light" BorderBrush="#111111" Foreground="#EEEEEE" Background="#111111" Height="18" Width="70" Template="{StaticResource NoMouseOverButtonTemplate}">Button1<Button.Triggers> <EventTrigger RoutedEvent="PreviewMouseUp"> <BeginStoryboard> <Storyboard> <DoubleAnimation Name="ButtonAnimation1" From="70" To="207" Duration="0:0:0.25" Storyboard.TargetProperty="(Canvas.Left)" AutoReverse="False" FillBehavior="Stop"/> </Storyboard> </BeginStoryboard></EventTrigger> </Button.Triggers> </Button> <Button Name="MovableButton2" Canvas.Left="207" Canvas.Top="0" Visibility="Hidden" FontSize="12" FontFamily="Calibri" FontWeight="Light" BorderBrush="#111111" Foreground="#EEEEEE" Background="#111111" Height="18" Width="70" Template="{StaticResource NoMouseOverButtonTemplate}">Button2<Button.Triggers> <EventTrigger RoutedEvent="PreviewMouseUp"> <BeginStoryboard> <Storyboard> <DoubleAnimation Name="ButtonAnimation2" From="207" To="70" Duration="0:0:0.25" Storyboard.TargetProperty="(Canvas.Left)" AutoReverse="False" FillBehavior="Stop"/> </Storyboard> </BeginStoryboard></EventTrigger> </Button.Triggers> </Button> </Canvas> </Window>' $reader=(New-Object System.Xml.XmlNodeReader $xaml) $window=[Windows.Markup.XamlReader]::Load($reader) $Button1=$Window.FindName("MovableButton1") $Button2=$Window.FindName("MovableButton2") $ButtonAnimation1=$Window.FindName("ButtonAnimation1") $ButtonAnimation2=$Window.FindName("ButtonAnimation2") $Button1.Add_Click({ write-host FirstButtonClicked }) $Button2.Add_Click({ write-host SecondButtonClicked }) $ButtonAnimation1.Add_Completed({ write-host AnimationCompleted $Button1.Visibility="Hidden" $Button2.Visibility="Visible" }) $ButtonAnimation2.Add_Completed({ write-host AnimationCompleted $Button1.Visibility="Visible" $Button2.Visibility="Hidden" }) $window.Show() $appContext=New-Object System.Windows.Forms.ApplicationContext [void][System.Windows.Forms.Application]::Run($appContext) ``` The full project for reference: https://github.com/illsk1lls/PowerPlayer