text
stringlengths
15
59.8k
meta
dict
Q: how to redirect to a specefic route when validator failed in laravel 5.3? I am trying to register user from index page but When validator failed then want to redirect to register page. I am tired to solve this problem . can't customize Illuminate/Foundation/Validation/ValidatesRequests.php page. Here is the code protected function getRedirectUrl() { return route('register'); } protected function validator(array $data) { $this->getRedirectUrl(); return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', ]); } A: add the below method which generate the previous url in your controller and override the default one add following methods in your controller in your controller where you have defined $this->validate call define below method and use Request use Illuminate\Http\Request; // add at the top protected function getRedirectUrl() { return route('register'); } protected function validator(array $data) { return $this->validate(request(), [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', ]); } public function register(Request $request) { $this->validator($request->all()); event(new Registered($user = $this->create($request->all()))); $this->guard()->login($user); return $this->registered($request, $user) ?: redirect($this->redirectPath()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/41013369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get js localstorage items case insensitive After saving items in javascript local storage I want to retrieve them case insensitive based on the key saved in the localstorage. For example if I have 'Test' as a key in local storage localstorage.getItem('test'); doesn't return the value of 'Test' cause it is case sensitive. I want to be able to get the item regardless. Is there a way to do this without looping thourgh the local storage and using toLowerCase() function for each key I find as in the code below: for (var i = 0; i < localStorage.length; i++){ if( localStorage.key(i).toLowerCase()==searchedKey.toLowerCase() ){ matchingKey =true; break; } } A: localStorage is a Dictionary. It stores Key/Value pairs. Both Key and Value are string. As Dictionary keys must be unique, values as Test and test are not the same, and therefore must be saved into Dictionary as 2 separate entries. Also, localStorage has no functionality to get all added Keys or Values, unlike C# or Java. Don't know exact reason for this functionality being missed. It can be due to security, so that rogue JavaScript has no ability to interrogate the storage, or just to keep it simple. The only way to get value by case insensitive Key, is to store them case insensitive. You can use either toUpper or toLower on Key before adding it to localStorage. However, Microsoft says converting to upper case is safest: https://learn.microsoft.com/en-gb/visualstudio/code-quality/ca1308-normalize-strings-to-uppercase?view=vs-2015
{ "language": "en", "url": "https://stackoverflow.com/questions/38661622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to skip duplicates and blank values from JSON dataframe and store into an array? The following code displays data from a JSON Line file. import pandas as pd import numpy start = time.time() with open('stela_zerrl_t01_201222_084053_test_edited.json', 'r') as fin: df = pd.read_json(fin, lines=True) parsed_data = df[["SRC/Word1"]].drop_duplicates().replace('', np.NAN).dropna().values.tolist() print(parsed_data) The output is: [[' '], ['E1F25701'], ['E15511D7']] Is there a way remove the blank data, duplicates, and store it as an array? A: You can use .dropna(),.drop_duplicates(). parsed_data=parsed_data.drop.duplicates() parsed_data.dropna(how='all', inplace = True) # do operation inplace your dataframe and return None. parsed_data= parsed_data.dropna(how='all') # don't do operation inplace and return a dataframe as a result. # Hence this result must be assigned to your dataframe If directly .dropna() not working for you then you may use .replace('', numpy.NaN,inplace=True). Or you can try this too: json_df=json_df[json_df['SRC/Word1'].str.strip().astype(bool)] This is faster then doing .replace(), if you have empty string. And now we cleaned it, we can just use .values.tolist() to get those value in list. A: Yup! Pandas has built-in functions for all of these operations: import pandas as pd df = pd.read_json('stela_zerrl_t01_201222_084053_test_edited.json', lines=True) series = df['SRC/Word1'] no_dupes = series.drop_duplicates() no_blanks = no_dupes.dropna() final_list = no_blanks.tolist() If you want an numpy array rather than a python list, you can change the last line to the following: final_array = no_blanks.to_numpy() A: Drop the duplicates, replace empty string by NaN, then create the list. >>> df.drop_duplicates().replace('', np.NAN).dropna().values.tolist() [['E1F25701'], ['E15511D7']] PS: Since what you have is a dataframe so it will be a 2D List, if you want 1D list, you may do it for the specific column: >>> df['SRC/Word1'].drop_duplicates().replace('', np.NAN).dropna().tolist() ['E1F25701', 'E15511D7'] What you have is not an empty string, but white space character, Try this: replace \s+ to np.NAN with regex=True: >>>df['SRC/Word1'].drop_duplicates().replace('\s+', np.NAN, regex=True).dropna().tolist() ['E1F25701', 'E15511D7'] And apparently, below will also work: df['SRC/Word1'].drop_duplicates().str.strip().replace('', np.NAN).dropna().tolist() ['E1F25701', 'E15511D7']
{ "language": "en", "url": "https://stackoverflow.com/questions/68474569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Polars: Pivoting by Int64 column not keeping numeric order I have a column called VERSION_INDEX which is Int64 and is a proxy for keeping a list of semantic software versions ordered such that 0.2.0 comes after 0.13.0. When I pivot, the column names created from the pivot are sorted alphanumerically. pivot_df = merged_df.pivot(index=test_events_key_columns, columns='VERSION_INDEX', values='Status') print(pivot_df) Is it possible to keep the column order numeric during the pivot such that 9 comes before 87? thx A: In Polars, column names are always stored as strings, and hence you have the alphanumeric sorting rather than numeric. There is no way around the strings, so I think the best you can do is to compute the column order you want, and select the columns: import polars as pl df = pl.DataFrame({"version": [9, 85, 87], "testsuite": ["scan1", "scan2", "scan3"], "status": ["ok"] * 3}) wide = df.pivot(index="testsuite", columns='version', values='status') cols = df["version"].cast(pl.Utf8).to_list() wide[["testsuite"] + cols] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β” β”‚ testsuite ┆ 9 ┆ 85 ┆ 87 β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ str ┆ str ┆ str β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•ͺ══════β•ͺ══════β•ͺ══════║ β”‚ scan1 ┆ ok ┆ null ┆ null β”‚ β”œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”Όβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”Όβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”Όβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”€ β”‚ scan2 ┆ null ┆ ok ┆ null β”‚ β”œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”Όβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”Όβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”Όβ•Œβ•Œβ•Œβ•Œβ•Œβ•Œβ”€ β”‚ scan3 ┆ null ┆ null ┆ ok β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜
{ "language": "en", "url": "https://stackoverflow.com/questions/71384958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Modifying website through email I wanted to try to do something where I can make changes to my site based on emails received to the sites email. Does anyone know how to do that? I want something where if its from a specific email address, and follows a particular format, it will change a certain part of the site according to the contents of the email. A: Sure you can. You need: * *Script that parses emails on schedule and adds those changes to some type of database *Script that executes updates from the temporary database and adds that data to live database How to read email with PHP: $mb = imap_open("{host:port/imap}","username", "password" ); $messageCount = imap_num_msg($mb); for( $MID = 1; $MID <= $messageCount; $MID++ ) { $EmailHeaders = imap_headerinfo( $mb, $MID ); $Body = imap_fetchbody( $mb, $MID, 1 ); doSomething( $EmailHeaders, $Body ); } read more A: You would need some server side processing to be able to do this. This thread has a couple of ways of doing this using PHP, made easier with cPanel to make changes to the mail redirects. If you tell us more about your site and hosting environment, we may be able to give better suggestions. The server side script would need to then parse your email and perform whatever updates your commands intend. Security is also very important, and it is trivial to forge the 'From' address when sending email.
{ "language": "en", "url": "https://stackoverflow.com/questions/14206458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel remote method is giving 404 (Not Found)error for title existed checking I am using Laravel framework. When I am trying to check if title already exists it is giving a 404 error. How to solve this error? ServicesController.php Controller: public function checkEmail() { $service = Service::all()->where('title', Input::get('title'))->first(); if ($service) { return Response::json(Input::get('title').'is already taken'); } else { return Response::json(Input::get('title').'is available'); } } Routes.php: Route::get('checkEmail','ServicesController@checkEmail'); view(create.blade.php): $("#slider-form").validate({ rules: { title: { required: true, remote: { url: "checkEmail", type: "get", } }, ar_title: { required: true } }, messages: { title: { required: "<font color='red'>Please Enter Service Name</font>", remote: "<font color='red'>Service Already Exists</font>" }, ar_title: { required: "<font color='red'>Please Enter Service Name in Arabic</font>" } }, submitHandler: function(form) { form.submit(); } }); A: AS your form is like this <form class="form-horizontal tasi-form" method="post" name="user-form" action="{{url('services/store')}}" id="slider-form" enctype="multipart/form-data"> Add an route in your route file as Route::post('services/store','ServicesController@checkEmail'); Modified:- Change <form class="form-horizontal tasi-form" method="post" name="user-form" action="services/store" id="slider-form" enctype="multipart/form-data"> Route::post('services/store','ServicesController@checkEmail'); Then try It will work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/45137651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Opening a modal component with a button in another ccomponent using Vuetify I have 2 components. Modal and Navbar. I'm trying to open Modal using a button in Navbar using vuex. I have a state called modalIsOpen. This states value changes from false to true when clicked on the button in Navbar but only a blank row is rendered as a modal and modal content is not shown. I could not figure out what is wrong. At the beginning i thought it was a vuetify v-dialog problem. But ive tried other libraries too. And as i said nothing worked yet. Here is the components ,app.vue and store.js. AddUpdateModal.vue: <template> <v-dialog> <v-card width="50%" height="50%"> <v-card-title class="text-h5 grey lighten-2"> Privacy Policy </v-card-title> <v-card-text> Lorem </v-card-text> <v-divider></v-divider> <v-card-actions> <v-spacer></v-spacer> <v-btn color="primary" text @click="dialog = false"> I accept </v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script> export default { name: "AddUpdateModal", components: {}, data: () => ({}), } </script> <style> .v-card { display: block !important; } .v-easy-dialog { height: 500px !important; } </style> NavBar.vue: <template> <div id="Navbar"> <v-row> <v-btn color="primary" @click.stop="openModal" rounded> Add / Update </v-btn> <v-btn color="primary" @click="closeModal" rounded> Refresh </v-btn> </v-row> <v-row> <v-divider class="grey darken-4"></v-divider> </v-row> </div> </template> <script> export default { name: 'NavBar', components: {}, data: () => ({}), methods: { openModal() { this.$store.commit('openModal'); }, closeModal() { this.$store.commit('closeModal') } }, } </script> App.vue: <template> <v-app> <v-container> <NavBar /> <br> <div class="parent"> <!-- <AddButton></AddButton> --> <v-btn @click="konsol">Konsol</v-btn> <div id="modal" v-if="$store.state.modalIsOpen"> <template> <AddUpdateModal></AddUpdateModal> </template> </div> <v-row> <v-col> <DataTable /> </v-col> <v-divider class="grey darken-4" vertical inset></v-divider> <v-col> <PieChart /> </v-col> </v-row> </div> </v-container> </v-app> </template> <script> import NavBar from './components/NavBar.vue'; import PieChart from './components/PieChart.vue'; import DataTable from './components/DataTable.vue'; // import AddButton from './components/AddButton'; import AddUpdateModal from './components/AddUpdateModal'; // eslint-disable-next-line no-unused-vars import store from './store/store' // import axios from 'axios'; export default { name: 'App', components: { NavBar, AddUpdateModal, PieChart, DataTable, // AddButton, }, created() { this.$store.dispatch("initApp") }, data: () => ({ }), methods: { konsol() { console.log("modalIsOpen", this.$store.state.modalIsOpen) } }, }; </script> <style> * { margin: 5px; } .v-dialog__container { display: unset !important; position: relative !important; } </style> store.js: import Vue from "vue"; import Vuex from "vuex"; import axios from "axios"; Vue.use(Vuex); const store = new Vuex.Store({ state: { binance24HrData: [], modalIsOpen: false, }, mutations: { initPortfolioDetails(state, newCoin) { state.binance24HrData = newCoin; }, openModal(state) { state.modalIsOpen = true; }, closeModal(state) { state.modalIsOpen = false; }, }, actions: { initApp(context) { axios .get("https://api2.binance.com/api/v3/ticker/24hr") .then((response) => { context.commit("initPortfolioDetails", response.data); console.log("Binance", response.data); }); }, openModal({ commit }) { commit("openModal"); }, closeModal({ commit }) { commit("closeModal"); }, }, getters: { getCoinsDetails(state) { return state.binance24HrData; }, }, }); export default store; main.js: import Vue from "vue"; import App from "./App.vue"; import vuetify from "./plugins/vuetify"; import store from "./store/store.js"; Vue.config.productionTip = false; new Vue({ vuetify, store, render: (h) => h(App), }).$mount("#app"); A: I figured it out: all I had to do was add v-model to v-dialog. I thought it was unnecessary because I already had a v-if that wrapped the component containing the v-dialog. I assumed that with this requirement fulfilled, it should render the child component, but it didn't because I didn't have v-model in v-dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/75139930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to get the price of bitcoin in USD from the coinbase API for a specific time in the past? GET https://api.coinbase.com/v2/prices/:currency_pair/spot This price seems to be the current price A: This question already has answers. Copy and pasted from here: Coinbase API v2 Getting Historic Price for Multiple Days Any reason you aren't using coinbase pro? The new api is very easy to use. Simply add the get command you want followed by the parameters separated with a question mark. Here is the new historic rates api documentation: https://docs.pro.coinbase.com/#get-historic-rates The get command with the new api most similar to prices is "candles". It requires three parameters to be identified, start and stop time in iso format and granularity which is in seconds. Here is an example: https://api.pro.coinbase.com/products/BTC-USD/candles?start=2018-07-10T12:00:00&stop=2018-07-15T12:00:00&granularity=900 EDIT: also, note the time zone is not for your time zone, I believe its GMT.
{ "language": "en", "url": "https://stackoverflow.com/questions/68241584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to append to JSON with Java and Jackson I'm trying a simple test where the code appends a few json entries, however it is getting overwritten each time (the json file will only have 1 entry in it after running). I know I need to somehow create an array in JSON using '[]', but how would I go about doing that? Also, is there a better way to be doing this? I've been searching around and every library seems clunky with lots of user written code. Thanks public class REEEE { private static Staff createStaff() { Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(38); staff.setPosition(new String[] { "Founder", "CTO", "Writer" }); Map<String, Double> salary = new HashMap() { { put("2010", 10000.69); } }; staff.setSalary(salary); staff.setSkills(Arrays.asList("java", "python", "node", "kotlin")); return staff; } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); File file = new File("src//j.json"); for(int i = 0; i < 4; i++) { Staff staff = createStaff(); try { // Java objects to JSON file mapper.writeValue(file, staff); // Java objects to JSON string - compact-print String jsonString = mapper.writeValueAsString(staff); } catch (IOException e) { e.printStackTrace(); } } } } A: You can add staff in List and then write the list to file as below, List<Staff> staffList = new LinkedList<>() for(int i = 0; i < 4; i++) { Staff staff = createStaff(); staffList.add(staff); } mapper.writeValue(file, staffList); Hope it helps. A: Jackson was implemented to parse and generate JSON payloads. All extra logic related with adding new element to array and writing back to file you need to implement yourself. It should not be hard to do: class JsonFileAppender { private final ObjectMapper jsonMapper; public JsonFileAppender() { this.jsonMapper = JsonMapper.builder().build(); } public void appendToArray(File jsonFile, Object value) throws IOException { Objects.requireNonNull(jsonFile); Objects.requireNonNull(value); if (jsonFile.isDirectory()) { throw new IllegalArgumentException("File can not be a directory!"); } JsonNode node = readArrayOrCreateNew(jsonFile); if (node.isArray()) { ArrayNode array = (ArrayNode) node; array.addPOJO(value); } else { ArrayNode rootArray = jsonMapper.createArrayNode(); rootArray.add(node); rootArray.addPOJO(value); node = rootArray; } jsonMapper.writeValue(jsonFile, node); } private JsonNode readArrayOrCreateNew(File jsonFile) throws IOException { if (jsonFile.exists() && jsonFile.length() > 0) { return jsonMapper.readTree(jsonFile); } return jsonMapper.createArrayNode(); } } Example usage with some usecases: import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class JsonPathApp { public static void main(String[] args) throws Exception { Path jsonTmpFile = Files.createTempFile("json", "array"); JsonFileAppender jfa = new JsonFileAppender(); // Add POJO jfa.appendToArray(jsonTmpFile.toFile(), createStaff()); printContent(jsonTmpFile); //1 // Add primitive jfa.appendToArray(jsonTmpFile.toFile(), "Jackson"); printContent(jsonTmpFile); //2 // Add another array jfa.appendToArray(jsonTmpFile.toFile(), Arrays.asList("Version: ", 2, 10, 0)); printContent(jsonTmpFile); //3 // Add another object jfa.appendToArray(jsonTmpFile.toFile(), Collections.singletonMap("simple", "object")); printContent(jsonTmpFile); //4 } private static Staff createStaff() { Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(38); staff.setPosition(new String[]{"Founder", "CTO", "Writer"}); Map<String, Double> salary = new HashMap<>(); salary.put("2010", 10000.69); staff.setSalary(salary); staff.setSkills(Arrays.asList("java", "python", "node", "kotlin")); return staff; } private static void printContent(Path path) throws IOException { List<String> lines = Files.readAllLines(path); System.out.println(String.join("", lines)); } } Above code prints 4 lines: 1 [{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]}] 2 [{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson"] 3 [{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0]] 4 [{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0],{"simple":"object"}]
{ "language": "en", "url": "https://stackoverflow.com/questions/58888004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the most efficient way to find if a mac address is in range? I have a large range of number of strings that are mac addresses. If they're in a certain range, I want to be able to go to a certain case statement. For example, "78:A1:83:24:00:00 to 78:A1:83:24:0F:FF" I have my code going so that it removes the last two hex and selects off that such as below: 'remove last three characters mac = mac.TrimEnd() mac = mac.Substring(0, mac.Length - 3) 'convert Select Case mac 'Advidia Case "78:A1:83:40:00", "78:A1:83:40:01", "78:A1:83:40:02", "78:A1:83:40:03", _ "78:A1:83:40:04", "78:A1:83:40:05", "78:A1:83:40:06", "78:A1:83:40:07", _ "78:A1:83:40:08", "78:A1:83:40:09", "78:A1:83:40:0A", "78:A1:83:40:0B" ' it continues Return "VP-1" But this just looks like I'm wasting space. What's a better way to this? A: A MAC address is nothing more than a number represented by 6 bytes written in hexdecimal form. So, converting the lower and upper limit of the MAC address could give you a manageable range of values to check with a single IF Sub Main Dim lowRange = "78:A1:83:24:40:00" Dim upRange = "78:A1:83:24:40:FF" Dim startVal = GetValue(lowRange) Dim endVal = GetValue(upRange) Console.WriteLine(startVal) ' 132635085258752 Console.WriteLine(endVal) ' 132635085259007 Dim macToCheck = "78:A1:83:24:40:B0" Dim checkVal = GetValue(macToCheck) Console.WriteLine(checkVal) ' 132635085258928 if checkVal >= startVal AndAlso checkVal <= endVal Then ' VP-1 Console.WriteLine("In range") End If End SUb Function GetValue(mac as String ) as Long Dim clearText = mac.Replace(":", "") Dim result Long.TryParse(clearText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, result) return result End Function Now, as an example to avoid a long list of IF you could use a Dictionary filled with your ranges and then apply a simple For Each logic to find your ranges Sub Main Dim dc as New Dictionary(Of String, MacRange)() dc.Add("VP-1", new MacRange() with { .Lower = "78:A1:83:24:40:00", .Upper = "78:A1:83:24:40:FF" }) dc.Add("VP-2", new MacRange() with { .Lower = "78:A1:83:24:41:00", .Upper = "78:A1:83:24:41:FF" }) dc.Add("VP-3", new MacRange() with { .Lower = "78:A1:83:24:42:00", .Upper = "78:A1:83:24:42:FF" }) Dim result = "" Dim macToCheck = "78:A1:83:24:42:B0" Dim checkVal = GetValue(macToCheck) 'For Each k in dc ' Dim lower = GetValue(k.Value.Lower) ' Dim upper = GetValue(k.Value.Upper) ' if checkVal >= lower AndAlso checkVal <= upper Then ' result = k.Key ' Exit For ' End If 'Next 'Console.WriteLine(result) ' VP-3 ' The loop above could be replaced by this LINQ expression Dim m = dc.FirstOrDefault(Function(x) checkVal >= GetValue(x.Value.Lower) AndAlso _ checkVal <= GetValue(x.Value.Upper)) If m IsNot Nothing Then Console.WriteLine(m.Key) ' VP-3 Else Console.WriteLine("Range not found") End If End Sub Class MacRange Public Lower as String Public Upper as String End Class Function GetValue(mac as String ) as Long Dim clearText = mac.Replace(":", "") Dim result Long.TryParse(clearText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, result) return result End Function A: There aren't existing functions that provide such utility. You could just split each string and create your ranges manually. A: I'd use some sort of regex (Regular Expression) validation for various ranges. http://regexlib.com/Search.aspx?k=mac%20address&AspxAutoDetectCookieSupport=1 will give you a good starting point.
{ "language": "en", "url": "https://stackoverflow.com/questions/24868780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Method lookup in Ruby's interrelation diagram? Can someone explain the relation between the Ruby class interrelation diagram and the way method lookup is done in the actual Ruby C code? Interrelation diagram from https://ruby-doc.org/core-2.5.3/Class.html: +---------+ +-... | | | BasicObject-----|-->(BasicObject)-------|-... ^ | ^ | | | | | Object---------|----->(Object)---------|-... ^ | ^ | | | | | +-------+ | +--------+ | | | | | | | | Module-|---------|--->(Module)-|-... | ^ | | ^ | | | | | | | | Class-|---------|---->(Class)-|-... | ^ | | ^ | | +---+ | +----+ | | obj--->OtherClass---------->(OtherClass)-----------... and the lookup in Ruby code seems to traverse RClass's super member as a flat list here: pseudocode while (!st_lookup(RCLASS(klass)->m_tbl, ...)) { klass = RCLASS(klass)->super; ... } Where in the above diagram would the internal RClass.super and RBasic.klass (C structures) pointer-arrows be mapped ? Which path would the method lookup take in this diagram? In particular the diagram seems to contain cycles. How is that to be interpreted? What does the ... in obj--->OtherClass---------->(OtherClass)-----------... mean (singleton of a singleton ?), how is singleton of a singleton accessed in Ruby and how is it modeled in the C implementation? A: I diggged around a bit and the ancestor function seem to traverse the RClass.super c-struct member, the same as the method looup does. So when I do a class OtherClass end obj = OtherClass.new obj.class.singleton_class.singleton_class.ancestors => [#<Class:#<Class:OtherClass>>, \ #<Class:#<Class:Object>>, \ #<Class:#<Class:BasicObject>>, \ #<Class:Class>, \ #<Class:Module>, \ #<Class:Object>, \ #<Class:BasicObject>, \ Class, \ Module, \ Object, \ Kernel, \ BasicObject] BasicObject ^ +---------+ +--------+ | | | | | Kernel | #<Class:BasicObject> | #<Class:#<Class:BasicObject>> ^ | ^ | ^ | | | | | Object | #<Class:Object> | #<Class:#<Class:Object>> ^ | ^ | ^ | | | | | +-------+ | +--------+ | | | | | | | Module | #<Class:Module> | | ^ | ^ | | | | | | | Class | #<Class:Class> | | ^ | ^ | | +---+ +--------+ | | obj--->OtherClass --->#<Class:OtherClass>--->#<Class:#<Class:OtherClass>> That means the vertical arrows in the diagram can be seen as the RClass.super c-member traversal. The horizontal arrows on the other hand should be related to RBasic.klass, however the Ruby code seems asymetric. ... | obj---> OtherClass When a singleton class is created the former RBasic.klass will get the RClass.super of the new singleton class. ... ... Object #<Class:Object> ^ ^ | | OtherClass | ^ | | | obj--->#<Class:#OtherClass:0x...> ->#<Class:OtherClass> -+ ^-+ and going one step futher a singleton of a singleton then looks like: ... ... ... Object #<Class:Object> #Class<#<Class:Object>> ^ ^ ^ | | | OtherClass | | ^ | | | | | obj-->#<Class:#OtherClass:0x...>-->#<Class:OtherClass>-->#<Class:#<Class:OtherClass>>-+ ^-+ The meaning/usage of a singleton class is understandable, however there meaning/usage of the metaclasses is a bit esoteric.
{ "language": "en", "url": "https://stackoverflow.com/questions/53803295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search history in elasticsearch Is there any way to check search history in elasticsearch? I'm wondering how seek someone responsible for data leakage in organization if it happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/58447625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why don't my fabric control parameters work? Here is my fabric function: def replace_config(vim_sig, bash_sig): """ replace remote server config with local config """ default_path = change_path('config', default_path='~/') if vim_sig: local("scp %s.vimrc admin@%s:~/vimrc" % (default_path, env.host)) sudo("cp /home/admin/vimrc /home/admin/.vimrc") sudo("cp /home/admin/vimrc /root/.vimrc") sudo("rm /home/admin/vimrc") if bash_sig: local("scp %s.bashrc admin@%s:~/bashrc" % (default_path, env.host)) sudo("cp /home/admin/bashrc /home/admin/.bashrc") sudo("cp /home/admin/bashrc /root/.bashrc") sudo("rm /home/admin/bashrc") # Some other code was omitted here I executed it with fab replace_config:vim_sig=False,bash_sig=True, fab replace_config:False,True, and fab replace_config:0,1, but these commands copy vimrc to remote host and ignore the if vim_sig statement. Why did this happen? How can I fix it? My fabric version is 1.10.1, and the way I execute the fab with parameters was taken from here.
{ "language": "en", "url": "https://stackoverflow.com/questions/31064994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get elements and count of Array of unknown type Let's say we have an Array, assigned to a variable with the type Any let something: Any = ["one", "two", "three"] Let's also assume we don't know if it's an array or something entirely else. And we also don't know what kind of Array.Element we are dealing with exactly. Now we want to find out if it's an array. let isArray = something is Array // compiler error let isArray = (something as? [Any?] != nil) // does not work (array is [String] and not [Any?]) Is there any elegant solution to tickle the following information out of the swift type system: * *Is the given object an Array *What's the count of the array *Give me the elements of the array (bridging to NSArray is not a solution for me, because my array could also be of type [Any?] and contain nil-values) A: I love @stefreak's question and his solution. Bearing in mind @dfri's excellent answer about Swift's runtime introspection, however, we can simplify and generalise @stefreak's "type tagging" approach to some extent: protocol AnySequenceType { var anyElements: [Any?] { get } } extension AnySequenceType where Self : SequenceType { var anyElements: [Any?] { return map{ $0 is NilLiteralConvertible ? Mirror(reflecting: $0).children.first?.value : $0 } } } extension Array : AnySequenceType {} extension Set : AnySequenceType {} // ... Dictionary, etc. Use: let things: Any = [1, 2] let maybies: Any = [1, nil] as [Int?] (things as? AnySequenceType)?.anyElements // [{Some 1}, {Some 2}] (maybies as? AnySequenceType)?.anyElements // [{Some 1}, nil] See Swift Evolution mailing list discussion on the possibility of allowing protocol extensions along the lines of: extension<T> Sequence where Element == T? In current practice, however, the more common and somewhat anticlimactic solution would be to: things as? AnyObject as? [AnyObject] // [1, 2] // ... which at present (Swift 2.2) passes through `NSArray`, i.e. as if we: import Foundation things as? NSArray // [1, 2] // ... which is also why this fails for `mabyies` maybies as? NSArray // nil At any rate, what all this drives home for me is that once you loose type information there is no going back. Even if you reflect on the Mirror you still end up with a dynamicType which you must switch through to an expected type so you can cast the value and use it as such... all at runtime, all forever outside the compile time checks and sanity. A: As an alternative to @milos and OP:s protocol conformance check, I'll add a method using runtime introspection of something (foo and bar in examples below). /* returns an array if argument is an array, otherwise, nil */ func getAsCleanArray(something: Any) -> [Any]? { let mirr = Mirror(reflecting: something) var somethingAsArray : [Any] = [] guard let disp = mirr.displayStyle where disp == .Collection else { return nil // not array } /* OK, is array: add element into a mutable that the compiler actually treats as an array */ for (_, val) in Mirror(reflecting: something).children { somethingAsArray.append(val) } return somethingAsArray } Example usage: /* example usage */ let foo: Any = ["one", 2, "three"] let bar: [Any?] = ["one", 2, "three", nil, "five"] if let foobar = getAsCleanArray(foo) { print("Count: \(foobar.count)\n--------") foobar.forEach { print($0) } } /* Count: 3 -------- one 2 three */ if let foobar = getAsCleanArray(bar) { print("Count: \(foobar.count)\n-------------") foobar.forEach { print($0) } } /* Count: 5 ------------- Optional("one") Optional(2) Optional("three") nil Optional("five") */ A: The only solution I came up with is the following, but I don't know if it's the most elegant one :) protocol AnyOptional { var anyOptionalValue: Optional<Any> { get } } extension Optional: AnyOptional { var anyOptionalValue: Optional<Any> { return self } } protocol AnyArray { var count: Int { get } var allElementsAsOptional: [Any?] { get } } extension Array: AnyArray { var allElementsAsOptional: [Any?] { return self.map { if let optional = $0 as? AnyOptional { return optional.anyOptionalValue } return $0 as Any? } } } Now you can just say if let array = something as? AnyArray { print(array.count) print(array.allElementsAsOptional) } A: This works for me on a playground: // Generate fake data of random stuff let array: [Any?] = ["one", "two", "three", nil, 1] // Cast to Any to simulate unknown object received let something: Any = array as Any // Use if let to see if we can cast that object into an array if let newArray = something as? [Any?] { // You now know that newArray is your received object cast as an // array and can get the count or the elements } else { // Your object is not an array, handle however you need. } A: I found that casting to AnyObject works for an array of objects. Still working on a solution for value types. let something: Any = ["one", "two", "three"] if let aThing = something as? [Any] { print(aThing.dynamicType) // doesn't enter } if let aThing = something as? AnyObject { if let theThing = aThing as? [AnyObject] { print(theThing.dynamicType) // Array<AnyObject> } }
{ "language": "en", "url": "https://stackoverflow.com/questions/36411115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Convert Array of object to json in javascript I want to Convert Arraylist of object to json in javascript to use it in highchart and angularjs. Can Anyone help me how can i do that? data should look like that [ ['Firefox', 45.0], ['IE', 26.8], ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] A: You can use JSON.stringify(array) if you just need to create a string out of an array
{ "language": "en", "url": "https://stackoverflow.com/questions/27789973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: PHP - Fatal Error - is any way to not stop script? I have a simple script: <?php $source = '../path/img.jpg'; $image = imagecreatefromjpeg($source); ?> Finally I got: Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted But when I try do something like that: <?php $source = '../path/img.jpg'; $image = @imagecreatefromjpeg($source); // Mute Fatal Error if ( !$image ) { die('Image file is too large'); } ?> but it doesn't work. Fatal error is stopping my script. Is any way to change this situation? I would like to know when fatal error is exist (then i got FALSE as $image) and then I would like to stop script, but first I want to print an information about it. Thanks. A: Fatal errors can't be muted or catched. You need to raise amount of memory allowed for PHP script by using memory_limit setting in php.ini
{ "language": "en", "url": "https://stackoverflow.com/questions/46797422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RETURN cannot have a parameter in function returning set; use RETURN NEXT at or near "QUERY" Postgres When I try to compile this function: CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ BEGIN RETURN QUERY SELECT select sr_number,product_serial_number from temp_table where sr_number=sr_num END; $$ LANGUAGE 'plpgsql' VOLATILE; Why do I get this error? RETURN cannot have a parameter in function returning set; use RETURN NEXT at or near "QUERY" I am using postgres version 8.4. A: Aside from a typo (you duplicated select, and you didn't terminate the RETURN statement with a semicolon), I think you were quite close - just needed to disambiguate the table columns within the query by qualifying them with the table name. Try this (reformatted hopefully to improve readability): CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ BEGIN RETURN QUERY SELECT temp_table.sr_number, temp_table.product_serial_number from temp_table where temp_table.sr_number=sr_num; END; $$ LANGUAGE 'plpgsql' VOLATILE; Caveat: I only tested this in PG 9.4, so haven't tested it in your version yet (which is no longer supported, I might add). In case there are issues regarding PLPGSQL implementation between your version and 9.4, you can try this form as an alternative: CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ BEGIN FOR sr_number, product_serial_number IN SELECT temp_table.sr_number, temp_table.product_serial_number from temp_table where temp_table.sr_number=sr_num LOOP RETURN NEXT; END LOOP; RETURN; END; $$ LANGUAGE 'plpgsql' VOLATILE; A small sanity check using a table I populated with dummy data: postgres=# select * from temp_table; sr_number | product_serial_number -----------+----------------------- 1 | product 1 2 | product 2 2 | another product 2 (3 rows) postgres=# select * from test_proc4(1); sr_number | product_serial_number -----------+----------------------- 1 | product 1 (1 row) postgres=# select * from test_proc4(2); sr_number | product_serial_number -----------+----------------------- 2 | product 2 2 | another product 2 (2 rows)
{ "language": "en", "url": "https://stackoverflow.com/questions/27968966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: wx.Image from image URL Well I've been doing a ton of searching and there doesn't seem to be too many people talking about this. With the help of the documentation for wxPython, I've got this far. I'm looking to create a wx.Image widget from an image URL. http://wxpython.org/docs/api/wx-module.html#ImageFromStream imgStream = urllib2.urlopen(captchaURL).read() captchaImg = wx.Image(wx.ImageFromStream(wx.InputStream(imgStream)), wx.BITMAP_TYPE_ANY) Does anybody have some advice for me? Much appreciated. Oh, the error I'm getting is TypeError: Not a file-like object, with the code snippet above. A: buf = urllib2.urlopen(URL).read() sbuf = StringIO.StringIO(buf) Image = wx.ImageFromStream(sbuf).ConvertToBitmap() wx.StaticBitmap(Panel, -1, Image, (10,10)) A: import requests import io url = "" content = requests.get(url).content io_bytes = io.BytesIO(content) image = wx.Image(io_bytes).ConvertToBitmap() staticImage = wx.StaticBitmap(Panel, wx.ID_ANY, image, wx.DefaultPosition, wx.DefaultSize, 0) replace url and Panel with your url and panel object
{ "language": "en", "url": "https://stackoverflow.com/questions/20736213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't get Jest expo app to work with react-navigation I am trying to snapshot test with Jest, Expo, React Navigation and my whole app uses hooks only. I'd like to eventually make these into e2e tests where Jest clicks through and snapshot tests everything but I can't even get react navigation to render. My snapshot after the expo loader always shows "null." I followed the basic example from the tabs starter that comes with expo init but the way it outlines how to setup the mocks simply doesn't work for my app. I've tried all sorts of things but nothing works. App.tsx import { Ionicons } from '@expo/vector-icons'; import { AppLoading } from 'expo'; import { Asset } from 'expo-asset'; import * as Font from 'expo-font'; import React, { useState } from 'react'; import { YellowBox } from 'react-native'; import { Provider as PaperProvider } from 'react-native-paper'; import { useScreens } from 'react-native-screens'; import { Provider as RxProvider } from 'reactive-react-redux'; import { applyMiddleware, compose, createStore } from 'redux'; import thunk from 'redux-thunk'; import SnackBar from './components/UI/Snackbar'; import { socketMiddleware } from './lib/socketMiddleware'; import SwitchNavigator from './navigation/AppNavigator'; import rootReducer from './reducers/rootReducer'; import { theme } from './Theme'; const middleware = [thunk, socketMiddleware()]; const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; export const store = createStore<iAppState, any, any, any>( rootReducer, composeEnhancers(applyMiddleware(...middleware)) ); // Must be called prior to navigation stack rendering useScreens(); YellowBox.ignoreWarnings(['Require cycle:']); const App = (props) => { const [isLoadingComplete, setLoadingComplete] = useState(false); if (!isLoadingComplete && !props.skipLoadingScreen) { return ( <AppLoading startAsync={loadResourcesAsync} onError={handleLoadingError} onFinish={() => handleFinishLoading(setLoadingComplete)} /> ); } else { return ( <RxProvider store={store}> <PaperProvider theme={theme}> <SwitchNavigator /> <SnackBar /> </PaperProvider> </RxProvider> ); } }; const loadResourcesAsync = async () => { await Promise.all([ Asset.loadAsync([ //nothing ]), Font.loadAsync({ ...Ionicons.font, TitilliumText250: require('./assets/fonts/TitilliumText22L-250wt.otf'), TitilliumText800: require('./assets/fonts/TitilliumText22L-800wt.otf') }) ]); }; const handleLoadingError = (error: Error) => { console.warn(error); }; const handleFinishLoading = (setLoadingComplete) => { setLoadingComplete(true); }; export default App; App.test.tsx: import React from 'react'; import { Provider as PaperProvider } from 'react-native-paper'; import NavigationTestUtils from 'react-navigation/NavigationTestUtils'; import renderer from 'react-test-renderer'; import App from './App'; import { theme } from './Theme'; jest.mock('expo', () => ({ AppLoading: 'AppLoading' })); jest.mock('react-native-screens'); jest.mock('react-native-paper'); jest.mock('redux'); jest.mock('reactive-react-redux'); jest.mock('./navigation/AppNavigator', () => 'SwitchNavigator'); describe('App', () => { jest.useFakeTimers(); beforeEach(() => { NavigationTestUtils.resetInternalState(); }); // success it(`renders the loading screen`, () => { const tree = renderer.create(<App />).toJSON(); expect(tree).toMatchSnapshot(); }); // this snapshot is always null it(`renders the root without loading screen`, () => { const tree = renderer .create( <PaperProvider theme={theme}> <App skipLoadingScreen></App> </PaperProvider> ) .toJSON(); expect(tree).toMatchSnapshot(); }); }); /navigation/AppNavigator.tsx: import { createAppContainer, createSwitchNavigator } from 'react-navigation'; import LoginStack from './LoginStack'; import TabStack from './TabStack'; /** The most root navigator which allocates to the others. */ const SwitchNavigator = createAppContainer( createSwitchNavigator( { LoginStack: LoginStack, TabStack: TabStack }, { initialRouteName: 'LoginStack' } ) ); export default SwitchNavigator; A: I was having a similar issue and found a fix via: https://github.com/expo/expo/issues/7155#issuecomment-592681861 Seems like the act() worked magically for me to stop it from returning null (not sure how) Update your test to use it like this: import { act, create } from 'react-test-renderer'; it('renders the root without loading screen', () => { let tree; act(() => { tree = create( <PaperProvider theme={theme}> <App skipLoadingScreen></App> </PaperProvider> ); }); expect(tree.toJSON()).toMatchSnapshot(); }); Note: When I changed how I was using the imports from 'react-test-renderer' my tests couldn't find act() as a function, a simple re-install of npm packages solved this problem!
{ "language": "en", "url": "https://stackoverflow.com/questions/59144867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I check that a label has fallen off the screen? I have a question about UIKit Dynamics. Let's say I'm designing some interactivity, and when the user taps, I want a label with some text to fall off the screen (at which point, I'll destroy it, and a new label will spawn and fall from the top, snap to center, and when the user taps, that too falls off the screen, and on it goes.) import UIKit class ViewController: UIViewController { var myLabel: UILabel! var gravity: UIGravityBehavior! var animator: UIDynamicAnimator! override func viewDidLoad() { super.viewDidLoad() myLabel = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) myLabel.backgroundColor = UIColor.blueColor() myLabel.text = "Some sample text." view.addSubview(myLabel) animator = UIDynamicAnimator(referenceView: view) gravity = UIGravityBehavior(items: [myLabel]) animator.addBehavior(gravity) } The code above will spawn a UILabel and make it drop off the screen. I understand how to do all of that. However, I'm at a loss concerning how to determine whether or when the label has fallen completely from view, at which point it is removedFromSuperView, and my new label can spawn and fall from the top. Should I be using a method to determine if the label is intersecting with the view (like CGRectIntersectsRect() )? Or should I try and check whether the center point of the label is inside the bounds of the screen? I've tried hacking together a solution using both of those options but so far nothing has worked. Any suggestions?
{ "language": "en", "url": "https://stackoverflow.com/questions/29087443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to build with electron-packager within electron-forge I have created a default project with electron-forge. When I try to package my project with the command electron-forge, the process exits with the following error. What am I doing wrong? I followed the instructions to a tee at electron-forge. $ electron-forge package βœ” Checking your system βœ” Preparing to Package Application for arch: x64 βœ” Compiling Application βœ” Preparing native dependencies β ¦ Packaging Application An unhandled rejection has occurred inside Forge: Command failed: npm prune --production npm WARN [email protected] No repository field. npm ERR! May not delete: /tmp/electron-packager/linux-x64/electron-example-linux-x64/resources/app/node_modules/.bin npm ERR! A complete log of this run can be found in: npm ERR! /home/maxchehab/.npm/_logs/2017-07-21T04_40_37_618Z-debug.log Error: Command failed: npm prune --production npm WARN [email protected] No repository field. npm ERR! May not delete: /tmp/electron-packager/linux-x64/electron-example-linux-x64/resources/app/node_modules/.bin npm ERR! A complete log of this run can be found in: npm ERR! /home/maxchehab/.npm/_logs/2017-07-21T04_40_37_618Z-debug.log at ChildProcess.exithandler (child_process.js:270:12) at emitTwo (events.js:125:13) at ChildProcess.emit (events.js:213:7) at maybeClose (internal/child_process.js:921:16) at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) Thank you for your time. A: It looks like the latest version of npm has introduced a bug for the electron make process. Issue is being tracked here. Github Issue Try this workaround for a possible fix(untested): rm -rf node_modules npm install --production --ignore-scripts npm install --no-save electron-rebuild --ignore-scripts node_modules/.bin/electron-rebuild npm remove electron-rebuild --ignore-scripts Or downgrade your npm to a version less than 5.3(tested, works). npm i -g [email protected] A: Problem is solved in later versions of npm, please consider upgrading to the latest v ( > 5.4.2) instead of downgrading to 5.2: npm i -g npm
{ "language": "en", "url": "https://stackoverflow.com/questions/45229218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Post Authentication custom response to client from Cognito We have lambda triggers set up in Cognito for Pre-Authentication/Post-Authentication, and Post Confirmation. In all the triggers we are checking against our DynamoDB in order to proceed and the db entries are coming properly as expected. However, we also want to send some details from our database back to the client at the time of login. In this case, it's a user object containing our DynamoDB user's uuid. Our iOS developer is using AWSAuthUIViewController and is expecting to access our custom response here: AWSAuthUIViewController .presentViewController(with: self.navigationController!, configuration: config, completionHandler: { (provider: AWSSignInProvider, error: Error?) in //... let user = AWSCognitoUserPoolsSignInProvider .sharedInstance() .getUserPool() .currentUser() /* do something to access custom response of user object */ }) We've looked at Custom Message Lambda Trigger documentation but this one relates to MFA so it's not what we're looking for. The main question is how to have Cognito respond to the client with a custom object containing entries from our DynamoDB. A: A better flow to use is probably the Custom Authentication Flow. It is not supported in the AWSAuthUIViewController, but you may use the AWSCognitoIdentityUserPool to perform the flow. The custom challenge could be leveraged to pass information back to the client before ending the flow.
{ "language": "en", "url": "https://stackoverflow.com/questions/53722975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove Baidu's cookie How to remove viglink & baidu's cookie. I create a empty html file and testing on my Chrome I notice there are 3 files is reading from baidu 2 from viglink I use Chrome Network to check this what files are reading. I'm not sure what are those files for, r those secure? I check cookies and try to remove it from Chrome but it comeing back. hm.js?3d143f0a07b6487f65609d8411e5464f hm.baidu.com vglnk.js cdn.viglink.com/api ping?format=jsonp&key=084c74521c465af0d8f08b63422103cc&loc=http%3A%2F%2Flocalhost%2Fz.php&v=1&ref=http%3A%2F%2Flocalhost%2F&jsonp=vglnk_jsonp_13800321595965 api.viglink.com/api hm.gif?cc=1&ck=1&cl=32-bit&ds=1920x1080&ep=59502%2C7996&et=3&fl=11.8&ja=1&ln=zh-TW&lo=0&lt=1380031859&nv=0&rnd=632137474&si=3d143f0a07b6487f65609d8411e5464f&st=4&su=http%3A%2F%2Flocalhost%2F&v=1.0.47&lv=3&u=http%3A%2F%2Flocalhost%2Fz.php hm.baidu.com hm.gif?cc=1&ck=1&cl=32-bit&ds=1920x1080&et=0&fl=11.8&ja=1&ln=zh-TW&lo=0&lt=1380031859&nv=0&rnd=998891479&si=3d143f0a07b6487f65609d8411e5464f&st=4&su=http%3A%2F%2Flocalhost%2F&v=1.0.47&lv=3 hm.baidu.com
{ "language": "en", "url": "https://stackoverflow.com/questions/18984252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error converting bytecode to dex: Cause: java.lang.RuntimeException: Exception parsing classes - Android studio 2.0 beta 6 I updated to the last version of Android studio 2.0 Beta 6 with the gradle : dependencies { classpath 'com.android.tools.build:gradle:2.0.0-beta6' } The app works perfectly fine on emulator and devices I tested every thing and it works fine. I got many errors only when I try to Generate Signed APK, I got some errors in dependencies, all of them solved when i excluded vector drawable, vector animate drawable and Support-v4 library Now i dont have any dependencies error. now my gradle.build for the app module looks like this: apply plugin: 'com.android.application' android { configurations { //all*.exclude group: 'com.android.support', module: 'support-v4' all*.exclude module: 'animated-vector-drawable' all*.exclude module: 'support-vector-drawable' //all*.exclude module: 'support-v4' } repositories { maven { url "https://jitpack.io" } } compileSdkVersion 23 buildToolsVersion '23.0.2' defaultConfig { applicationId "com.test.test" minSdkVersion 11 targetSdkVersion 23 versionCode 1 versionName "1" // multiDexEnabled true vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile('com.github.afollestad.material-dialogs:commons:0.8.5.5@aar') { transitive = true exclude module: 'support-v4' exclude module: 'appcompat-v7' exclude module: 'recyclerview-v7' } compile('com.google.android.gms:play-services-ads:8.4.0') { exclude module: 'support-v4' } compile('com.google.android.gms:play-services-analytics:8.4.0') { exclude module: 'support-v4' } compile('com.android.support:appcompat-v7:23.2.0') { exclude module: 'support-v4' exclude module: 'animated-vector-drawable' exclude module: 'support-vector-drawable' } compile('com.android.support:support-v4:23.2.0') { exclude module: 'animated-vector-drawable' exclude module: 'support-vector-drawable' } compile('com.android.support:palette-v7:23.2.0') { exclude module: 'support-v4' } compile('com.android.support:cardview-v7:23.2.0') { exclude module: 'support-v4' } compile('com.android.support:recyclerview-v7:23.2.0') { exclude module: 'support-v4' } compile('com.android.support:design:23.2.0') { exclude module: 'support-v4' } compile('com.nineoldandroids:library:2.4.0') { exclude module: 'support-v4' } compile('com.baoyz.swipemenulistview:library:1.2.1') { exclude module: 'support-v4' exclude module: 'appcompat-v7' exclude module: 'recyclerview-v7' } compile('com.squareup.picasso:picasso:2.5.2') { exclude module: 'support-v4' } compile('com.nononsenseapps:filepicker:2.5.0') { exclude module: 'support-v4' exclude module: 'appcompat-v7' exclude module: 'recyclerview-v7' } compile 'com.google.code.gson:gson:2.6.1' } The errors shows up only when I build for release: This is the error when i turn on multiDex: Error:Execution failed for task ':app:transformClassesWithMultidexlistForRelease'. > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1 And this is the error when i turn it off: :app:transformClassesWithDexForRelease Error:Error converting bytecode to dex: Cause: java.lang.RuntimeException: Exception parsing classes Error:Execution failed for task ':app:transformClassesWithDexForRelease'. > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1 I tried to change the buildToolsVersion '23.0.2' to every possible version and nothing changed. when i put the version 22.0.1 i got this error: Error:Error converting bytecode to dex: Cause: com.android.dx.cf.iface.ParseException: name already added: string{"a"} Error:Execution failed for task ':app:transformClassesWithDexForRelease'. > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1 I tried with all possible support libraries version and same result. I tried with Java 1.6 and 1.7 and nothing has changed ! what can be other possible solution please ? A: just do Build > Clean Project Wait for Cleaning Ends and then Build > Rebuild Project, and the error was gone. that's it. A: I also faced the same error, and i was searching through many existing answers with duplicate dependencies or multidex etc. but none worked. (Android studio 2.0 Beta 6, Build tools 23.0.2, no multidex) It turned out that i once used a package names which didn't match the package name that is depicted in the Manifest. In other ParseException lines, i found out that i had files in different modules whith similiar package names/paths that possibly conflicted the dexer. Example: Module A: com.example.xyz.ticketing.modulea.Interface.java Module B: com.example.Xyz.ticketing.moduleb.Enumerations.java Module C: Has dependencies on A and B After fixing "Xyz" to lowercase, the dexer was fine again. How to find out: When i looked through the output of the gradle console for the ParseExceptions that looks like this: AGPBI: {"kind":"error","text":"Error converting bytecode to dex:\nCause: java.lang.RuntimeException: Exception parsing classes" I scrolled close to the end of the exception. There is a part in that long exception line that actually mentions the cause: Caused by: com.android.dx.cf.iface.ParseException: class name (at/dummycompany/mFGM/hata/hwp/BuildConfig) does not match path (at/dummycompany/mfgm/hata/hwp/BuildConfig.class) This way i found out where to search for missmatching package names/paths A: I had a wrong package name in one of the helper class,hence I was having the error.So check all the Classes and make sure you have correct package name. A: My solution was different, I was added these lines in proguard-rules.pro -optimizationpasses 5 -overloadaggressively -repackageclasses '' -allowaccessmodification Make sure to update everything from SDK manager as well. A: If your targetSdkVersion is 25 or higher version and you use JDK 8 you have to add in your build.gradle file the following: android { compileSdkVersion 26 buildToolsVersion "26.0.0" defaultConfig { ... jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } More info: https://stackoverflow.com/a/37294741 A: The solution for me is to modifing the Build Gradle file. I found out, that the problem is a GC overhead (out of memory). So I add some code to my configuration android { dexOptions { incremental = true; preDexLibraries = false javaMaxHeapSize "2g" } } There is some other problem with proguard. You've to set minifyEnabled to false also. A: Removing -overloadaggressively from my proguard-rules.pro fixed this for me. Alternatively, adding -useuniqueclassmembernames also fixed it. A: I tried ./gradlew clean build, Invalidating studio cache, restarting machine. But what solved the issue is turning Instant run off A: Got this issue while using the Android studio template for Login activity. I've selected "activity" package to put my activity into. The template in AndroidManifest.xml, instead of .activity.LoginActivity used the .LoginActivity thus causing the error. A: If you faced this error, certainly your package in manifest differ from the others that you have set in your classes. be careful. A: I ran into the same issue today and the problem was that in my Constants.java classed I have defined (by mistake) public static final class Checkout { ....... } and public static final class CHECKOUT { ...... } A: In my case, there was a class that I made that I didn't use yet. So I have to delete the class or use the class. A: I faced the same error. Appears that its due to renaming a package to lower case and a class had the previous case wording. A: Your gradle.build file will contain compile files('libs/httpclient-4.2.1.jar') compile 'org.apache.httpcomponents:httpclient:4.5' compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1' By removing this line from file. compile files('libs/httpclient-4.2.1.jar') It will work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/35680979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Haskell: Shuffling deck I'm working on a lab in which we work with randomness and monads. The parts of the lab are: * *write a function randR that generates a random numbers within a given range *write a function rollTwoDice that simulates rolling two dice *write a function removeCard which randomly removes a card from a list of PlayingCards *write a function shuffleDeck which takes the removed card, puts it in front of the deck, then repeats itself until the deck has been completely shuffled. I have done 1, 2, and 3, but I'm having trouble with 4. Here's the given code: RandState.hs module RandState where import UCState import System.Random -- In order to generate pseudo-random numbers, need to pass around generator -- state in State monad type RandState a = State StdGen a -- runRandom runs a RandState monad, given an initial random number generator runRandom :: RandState a -> StdGen -> a runRandom (State f) s = res where (res, state) = f s -- rand is a helper function that generates a random instance of any -- type in the Random class, using the RandState monad. rand :: Random a => RandState a rand = do gen <- get let (x, gen') = random gen put gen' return x UCState.hs {- - Simplified implementation of the State monad. The real implementation - is in the Control.Monad.State module: using that is recommended for real - programs. -} module UCState where data State s a = State { runState :: s -> (a, s) } instance Monad (State s) where {- - return lifts a function x up into the state monad, turning it into - a state function that just passes through the state it receives -} return x = State ( \s -> (x, s) ) {- - The >>= combinator combines two functions p and f, and - gives back a new function (Note: p is originally wrapped in the - State monad) - - p: a function that takes the initial state (from right at the start - of the monad chain), and gives back a new state and value, - corresponding to the result of the chain up until this >>= - f: a function representing the rest of the chain of >>='s -} (State p) >>= f = State ( \initState -> let (res, newState) = p initState (State g) = f res in g newState ) -- Get the state get :: State s s get = State ( \s -> (s, s) ) -- Update the state put :: s -> State s () put s = State ( \_ -> ((), s)) Here's my code, which I just wrote inside RandState.hs since I couldn't figure out how to import it (help with importing would be nice as well, although not what I'm most concerned about at this point): randR :: Random a => (a, a) -> RandState a randR (lo, hi) = do gen <- get let (x, gen') = randomR (lo, hi) gen put gen' return x testRandR1 :: IO Bool testRandR1 = do gen <- newStdGen let genR = runRandom (randR (1,5)) gen :: Int return (genR <=5 && genR >=1) testRandR2 :: IO Bool testRandR2 = do gen <- newStdGen let genR = runRandom (randR (10.0, 11.5)) gen :: Double return (genR <= 11.5 && genR >= 10.0) rollTwoDice :: RandState Int rollTwoDice = do gen <- get let (a, gen') = randomR (1, 6) gen :: (Int, StdGen) put gen' let (b, gen'') = randomR (1, 6) gen' :: (Int, StdGen) put gen'' return $ a + b testRollTwoDice :: IO Bool testRollTwoDice = do gen <- newStdGen let genR = runRandom (rollTwoDice) gen return (genR <= 12 && genR >= 2) -- Data types to represent playing cards data CardValue = King | Queen | Jack | NumberCard Int deriving (Show, Eq) data CardSuit = Hearts | Diamonds | Spades | Clubs deriving (Show, Eq) data PlayingCard = PlayingCard CardSuit CardValue deriving (Show, Eq) {- - fullCardDeck will be a deck of cards, 52 in total, with a King, a Queen, - a Jack and NumberCards from 1 to 10 for each suit. -} -- fullCardDeck and its definition were given in the lab fullCardDeck :: [PlayingCard] fullCardDeck = [ PlayingCard s v | s <- allsuits, v <- allvals ] where allvals = King : Queen : Jack : [ NumberCard i | i <- [1..10] ] allsuits = [Hearts, Diamonds, Spades, Clubs] removeCard :: [a] -> RandState [a] removeCard deck = do gen <- get let n = runRandom (randR(1, length (deck))) gen :: Int let (xs, ys) = splitAt (n-1) deck return $ head ys : xs ++ tail ys shuffleDeck deck = do gen <- get let f deck = head $ runRandom (removeCard deck) gen return $ take (length(deck)) (iterate f deck) shuffleDeck doesn't work. The error: RandState.hs:88:31: Occurs check: cannot construct the infinite type: a0 = [a0] Expected type: [a0] -> [a0] Actual type: [a0] -> a0 In the first argument of `iterate', namely `f' In the second argument of `take', namely `(iterate f deck)' In the second argument of `($)', namely `take 52 (iterate f deck)' I guess the issue is that iterate takes a value, applies a function to this value, applies the function to the result, and so on, returning an infinite list of results. I'm handing iterate a function that takes a list, and returns a card, so the result cannot be passed to the next iteration. What would be a better way to approach this problem (4)? I'm also worried that my removeCard function is a little janky since it just puts the "removed" card in front, which I did to make shuffleDeck easier to write. If necessary, what would be a better way to approach this problem (3)? Thanks, Jeff A: You should stop trying to runRandom inside your functions. You should only use runRandom once you actually want a result (for example - to print the result, since you can't do this inside the monad). Trying to 'escape' from the monad is a futile task and you will only produce confusing and often non-functioning code. The final output of all of your functions will be inside the monad, so you don't need to escape anyways. Note that gen <- get let n = runRandom (randR(1, length (deck))) gen :: Int is exactly equivalent to n <- randR (1, length deck) The <- syntax executes a computation in monad on the right and 'puts' it into the variable name on the left. Shuffling: shuffleR [] = return [] shuffleR xs = do (y:ys) <- removeR xs -- 1 zs <- shuffleR ys -- 2 return (y:zs) -- 3 The function is straightforward recursion: 1) extract a random element, 2) shuffle what is left, 3) combine the results. edit: extra info requested: randSum :: (Num b, Random b) => State StdGen b randSum = do a <- randR (1,6) b <- randR (1,6) return $ a + b compiles just fine. Judging from your description of the error, you are trying to call this function inside the IO monad. You cannot mix monads (or at least not so simply). If you want to 'execute' something of type RandState inside of IO you will indeed have to use runRandom here. n <- randR (1, length deck) makes n an Int because length deck has type Int and randR :: Random a => (a, a) -> RandState a, so from the context we can infer a ~ Int and the type unifies to (Int, Int) -> RandState Int. Just to recap Wrong: try = do a <- randomIO :: IO Int b <- randR (0,10) :: RandState Int return $ a + b -- monads don't match! Right: try = do a <- randomIO :: IO Int let b = runRandom (randR (0,10)) (mkStdGen a) :: Int -- 'execute' the randstate monad return $ a + b
{ "language": "en", "url": "https://stackoverflow.com/questions/19967276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ project is build successfully but gives g++ compiler error message I have an C/C++ project. Build Tool chain: Cross GCC Current builder: CDT Internal Builder When I build my project, I got 2 error on the Problem tab: Program "g++" not found in PATH Preferences, C++/Build/Settings/Discovery, [CDT GCC Built-in Compiler Settings MinGW] options Program "gcc" not found in PATH Preferences, C++/Build/Settings/Discovery, [CDT GCC Built-in Compiler Settings MinGW] options C/C++ Scanner Discovery Problem On the console: there is no error: Buil Cross Setting Prefix: x86_64-pc-elf- Path: build_tools\x86_64_gcc_pc_elf_4.8.1-1\bin x86_64-pc-elf-gcc.exe and x86_64-pc-elf-g++.exe are located in that path. I don't understand the problem. It gives fake error. I also get the same error for rm.exe when I try to clean.It is cleaned successfully, but it gives error. Do you know why? A: It looks to me that * *your paths configuration (in the CDT settings) has problems (some executables cannot be located) *your actual build doesn't need these (e.g. you're just using a Makefile based project) It appears that whenever you invoke an external tool (make, rm, ...) Eclipse is doing a sanity check on the configuration settings, just to be more userfriendly. If you don't like the warnings, fix the missing configuration entries, or you can accept the warnings (and keep it in mind in case you start a different type of C++ project)
{ "language": "en", "url": "https://stackoverflow.com/questions/25911243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: http.host: 0.0.0.0 - ERROR lookup logstash : no such host I'm deploying ELK on k8s but getting error on Filebeat kubectl describe pod filebeat-filebeat-rpjbg -n elk /// Error: Warning Unhealthy 8s (x5 over 48s) kubelet Readiness probe failed: logstash: logstash:5044... connection... parse host... OK dns lookup... ERROR lookup logstash on 10.245.0.10:53: no such host In logstash values.yaml may be this causing error? logstashConfig: logstash.yml: | http.host: 0.0.0.0 xpack.monitoring.enabled: false PODS: NAME READY STATUS RESTARTS AGE elasticsearch-master-0 1/1 Running 0 146m filebeat-filebeat-rpjbg 0/1 Running 0 5m45s filebeat-filebeat-v4fxz 0/1 Running 0 5m45s filebeat-filebeat-zf5w7 0/1 Running 0 5m45s logstash-logstash-0 1/1 Running 0 14m logstash-logstash-1 1/1 Running 0 14m logstash-logstash-2 1/1 Running 0 14m SVC: NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE elasticsearch-master ClusterIP 10.245.205.251 <none> 9200/TCP,9300/TCP 172m elasticsearch-master-headless ClusterIP None <none> 9200/TCP,9300/TCP 172m logstash-logstash ClusterIP 10.245.104.163 <none> 5044/TCP 16m logstash-logstash-headless ClusterIP None <none> 9600/TCP 16m elasticsearch - values.yaml logstash - values.yaml filebeat - values.yaml A: Filebeat is trying to resolve "logstash", but you don't have a service with that name. You have "logstash-logstash". Try to change filebeat config (line 49 and 116 in filebeat values.yaml) or change the name of your logstash service accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/74685600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: receive an alert when job is *not* running I know how to set up a job to alert when it's running. But I'm writing a job which is meant to run many times a day, and I don't want to be bombarded by emails, but rather I'd like a solution where I get an alert when the job hasn't been executed for X minutes. This can be acheived by setting the job to alert on execution, and then setting up some process which checks for these alerts, and warns when no such alert is seen for X minutes. I'm wondering if anyone's already implemented such a thing (or equivalent). Supporting multiple jobs with different X values would be great. A: The danger of this approach is this: suppose you set this up. One day you receive no emails. What does this mean? It could mean * *the supposed-to-be-running job is running successfully (and silently), and so the absence-of-running monitor job has nothing to say or alternatively * *the supposed-to-be-running job is NOT running successfully, but the absence-of-running monitor job has ALSO failed or even * *your server has caught fire, and can't send any emails even if it wants to Don't seek to avoid receiving success messages - instead devise a strategy for coping with them. Because the only way to know that a job is running successfully is getting a message which says precisely this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7317655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get .NET CryptoStream to read last block I have a client/server setup with CryptoStream around TcpClient's NetWorkStream on both ends. Communication works great biderectionally when I read from the NetworkStream directly but with CryptoStream I can't read a single block of available data. I am closing the CryptoStream to cause FlushLastBlock to be called from the server and indeed the one and only block of 16 bytes (AES encrypted) shows up at the client end. So why does CryptoStream.Read() block waiting for data when there is a full block of data available? P.S. I've verified that sending an additional block allows the reader to read the first block. Is this just a bug or by design? A: Have you called FlushFinalBlock() on the CryptoStream on the sending side? using (var stream = new MemoryStream()) { using (var cs = new CryptoStream(stream, your_encryptor, CryptoStreamMode.Write)) { your_formatter.Serialize(cs, your_graph); cs.FlushFinalBlock(); your_socket.Send(stream.GetBuffer(), 0, (int)stream.Length); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/20671774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Append records to existing hive table does not write all records I am trying to append some records to an existing hive external table created from a csv file stored in HDFS. The problem is that only a portion of the dataset is written, can anyone help me? Here is my code with 2 alternatives: if fs.exists(jvm.org.apache.hadoop.fs.Path(analysis_result_path_formatted)): analysisFinal.write.format("hive") .mode("append") .saveAsTable(output_hive_db + "." + hive_table + "_analyzersresult") analysisFinal.write .mode("append") .insertInto(output_hive_db + "." + hive_table + "_analyzersresult" ,overwrite=False) I tried both the solutions but they write the same portion of the total records. Also, here is the code for the original csv file and for the creation of the hive table: #Writing to Analysis Result to HDFS analysisFinal.coalesce(1).write.option("header","true") .option("delimiter","\t") .csv(hdfs_url + analysis_result_path_formatted) create_analyzer_query_formatted = CREATE EXTERNAL TABLE IF NOT EXISTS {}.{}_AnalyzersResult (name STRING,entity STRING, value STRING, instance STRING, provenienza_tabella STRING, date STRING, table_name STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' STORED AS TEXTFILE LOCATION '{}' TBLPROPERTIES ("skip.header.line.count"="1") #Creating external table based on previously written file spark.sql(create_analyzer_query_formatted)
{ "language": "en", "url": "https://stackoverflow.com/questions/74876790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting the Ids of a table where 3 or more column are duplicates I am trying to select the ids of 3 columns that I have in my table that all contain the same data except for when the first occurrence of the duplicate was inserted. For example my table is as follows: Select * From Workers +----+--------+--------+--------------+ | id | name |JobTitle| description | +----+--------+--------+--------------+ | 1 | john |Plumber |Installs Pipes| | 2 | mike | Doctor |Provides Meds | | 3 | john |Plumber |Installs Pipes| | 4 | john |Plumber |Installs Pipes| | 5 | mike | Doctor |Provides Meds | | 6 | mike | Doctor |Provides Meds | +----+--------+--------+--------------+ What im basically trying to get is the ids of all the duplicates records expect for the lowest or first id where a duplicate has occurred. SELECT t1.id From workers t1, workers t2 Where t1.id > t2.Id and t1.name = t2.name and t1.jobTitle = t2.jobTitle and t1.description = t2.description; The table i am working with had hundred of thousands of records and I have tried the statement above to get the ids i want but due to the size of the table I get the error: Error Code: 1054. Unknown column 't1.userId' in 'where clause' I have tried increasing the timeout in workbench but to no avail. In this example I am basically trying to get all the ids except for 1 and 2. I thought the above query would have got me what i was looking for but this has not been the case and now I am not sure what else to try. Any help is greatly appreciated. Thanks in advance. A: The error message does not match your query (there is no userId column in the query) - and it is not related to the size of the table. Regardless, I would filter with exists: select w.* from workers w where exists ( select 1 from workers w1 where w1.name = w.name and w1.jobTitle = w.jobTitle and w1.description = w.description and w1.id < w.id ) For performance, consider an index on (name, jobTitle, description, id). A: You can do it with an 'INNER JOIN SELECT DISTINCT t1.* From workers t1 INNER JOIN workers t2 ON t1.name = t2.name and t1.jobTitle = t2.jobTitle and t1.description = t2.description Where t1.id > t2.Id ; But i can't figure out how you got your message, there is no userid in sight
{ "language": "en", "url": "https://stackoverflow.com/questions/61581037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sha1 encryption of password when creating SOAP request in c# Im trying to integrate using SOAP to a web service but I'm getting stucked in the authorization part, and more specifically when creating sha1 encrypted password. Documentation for this specific authorization can be found at https://www.beautyfort.com/api/docs/AuthHeader-t1 I have been searching the net trying to find different ways to create the password but none seems to generate the same password as the example in the documentation page. string testDateString = "2015-07-08T11:31:53+01:00"; string testNonce = "186269"; string testSecret = "Ok4IWYLBHbKn8juM1gFPvQxadieZmS2"; SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider(); byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(testNonce + testDateString + testSecret)); string Sha1Password = Convert.ToBase64String(hashedDataBytes); The input variables is from documentation page. According to the documentation the password should get the value "ZDg3MTZiZTgwYTMwYWY4Nzc4OGFjMmZhYjA5YzM3MTdlYmQ1M2ZkMw==" but the code I am using is generating "2HFr6Aowr4d4isL6sJw3F+vVP9M=". Anyone have a bright idea of what I am doing wrong? A: I took a wild guess that maybe the output of "sha1()" in the documention psuedo-code was a hex-string (like sha1() in PHP, etc), and that seems to output the expected password. Updated code: string testDateString = "2015-07-08T11:31:53+01:00"; string testNonce = "186269"; string testSecret = "Ok4IWYLBHbKn8juM1gFPvQxadieZmS2"; SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider(); byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(testNonce + testDateString + testSecret)); var hexString = BitConverter.ToString(hashedDataBytes).Replace("-", string.Empty).ToLower(); string Sha1Password = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexString));
{ "language": "en", "url": "https://stackoverflow.com/questions/57887351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the difference between char *exp="a+b" and char exp[]="a+b"? Are they stored the same way in memory or they differ? Also, why we can't use int *exp = [1,2,3] for creating an array of integers using pointers if we can use char *exp? A: In this declaration char *exp="a+b"; the compiler at first creates the string literal that has the array type char[4] with static storage duration and the address of the first character of the string literal is assigned to the pointer exp. You may imagine that the following way char unnamed_string_literal[4] = { 'a', '+', 'b', '\0' }; char *exp = unnamed_string_literal; That is in the last declaration of the variable exp the array unnamed_string_literal is implicitly converted to a pointer to its first element and this pointer is assigned to the pointer exp. You may not change the string literal. Any attempt to change a string literal result in undefined behavior. That is you may not write for example exp[0] = 'A'; In this declaration char exp[]="a+b"; there is created the character array exp elements of which are initialized by elements of the string literal. You may imagine the declaration the following way char exp[4] = { 'a', '+', 'b', '\0' }; As the array is not declared with qualifier const then you may change elements of the array. On the other hand, you may not write int *exp = { 1,2,3 }; because the construction { 1, 2, 3 } does not represent an object of an array type. You may use such a construction to initialize an array like int exp[] = { 1, 2, 3 }; But you may not initialize a scalar object (pointers are scalar objects0 with a braced list that contains more than one expression. However you may initialize the pointer by a compound literal that has an array type like int *exp = ( int [] ){ 1,2,3 }; In this case the compiler creates an unnamed array of the type int[3] and the address of its first element is assigned to the pointer exp. You should pay attention to these key concepts. * *Scalar objects may not be initialized by a braced list containing more than one expression. *Array designators used in expressions with rare exceptions are converted to pointers to their first elements. *String literals have array types. A: What is the difference between char *exp="a+b"… char *exp declares exp to be a pointer. When this appears inside a function, a pointer is created for the duration of execution of the block it is in. When it appears outside a function, a pointer is created for the duration of execution of the program. It is initialized with the string literal "a+b". When a string literal is used this way, it is automatically converted to a pointer to its first element, so exp is initialized to point to the β€œa”. The string literal exists for the duration of execution of the program. Because the pointer points to the characters of the string literal, any use of the pointer uses the string literal. The C standard does not define the behavior if you attempt to modify a string literal. … and char exp[]="a+b"? char exp[] declares exp to be an array. Its duration is the same as for a pointer, above. It is initialized by copying the string literal "a+b" into it, and the size of the string literal also determines the size of the array. An array is automatically converted to a pointer to its first element except when it is the operand of sizeof, is the operand of unary &, or is a string literal used to initialize an array. Since the latter is the case here, the string literal is not converted to a pointer. Because exp contains a copy of the string literal, you may modify exp without affecting the string literal. int *exp=[1,2,3] First, [1,2,3] is not a notation meaning an array. [ and ] are used for subscripts, not for array contents. In initializers, we can use braces, { and }, for lists of initial values, but these designate only lists, not arrays. C originally did not have an β€œarray literal” notation like a string literal. However, later a compound literal was added to the language. You can create an object directly in source code by writing (type) { initial values }. So you can create an array of int with (int []) { 1, 2, 3 }. int *exp = (int []) { 1, 2, 3 }; will create a pointer named exp and initialize it to point to the first element of the array. Unlike a string literal, which exists for the duration of the program, a compound literal inside a function exists only for the duration of the block of code it is in.
{ "language": "en", "url": "https://stackoverflow.com/questions/72614962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Which Formula/Function To Use to Rotate a Series Of Points What mathematical formula can I use to rotate a series of 3d Vectors about a given 3d Vector? I am attempting to use the 3rd party library: Math.NET Iridium to calculate my rotations but I dont know what formulas or mathematical concepts I should use. As you can see Maths is not my strong point thus the need for the library. PS: I've attempted to use the standard System.Windows.Shapes.Polyline and System.Windows.Media.RotateTransform but it looks like the rotation is only applied at rendering time (correct me if I am wrong). I need to know the location of the rotated point right after I apply the RotateTransform. public static XYZ rotateXYZ(XYZ pnt) { Polyline polyline = new Polyline(); polyline.Points.Add(new Point(pnt.X, pnt.Y)); //, pnt.Z)); System.Windows.Media.RotateTransform rotateTransform = new System.Windows.Media.RotateTransform(projectRotation, pnt.X, pnt.Y); polyline.RenderTransform = rotateTransform; return new XYZ(polyline.Points[0].X, polyline.Points[0].Y, pnt.Z); // the points coordinates are the same - not rotated } A: See Rotation Matrix for the mathematical background/formula, section "Rotation matrix from axis and angle". If you'd like to use a library: Math.NET Iridium (and its successor Math.NET Numerics) are numerical methods libraries, but you could use Math.NET Spatial instead. var point = new Point3D(1,1,1); var vector = new Vector3D(0,0,1); // will have coordinates (-1,-1,1) var rotated = point.Rotate(vector, Angle.FromDegrees(180)); Note that Math.NET Spatial is in a very early phase, so there is no release or NuGet package yet. But you can compile it yourself, or simply have a look at the code to see how it was implemented.
{ "language": "en", "url": "https://stackoverflow.com/questions/25152542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: close the gap in the bottom of a relativelayout After creating a relative layout on rendering it, I observed that there is space below the layout that is not needful. I have ensured that all the height of the elements used has a wrap_content attribute as the specification parameter for the height. Below is the snippet <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#338FD8D8"> <TextView android:id="@+id/banner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|center" android:textSize="25sp" android:padding="3px" android:textColor="#000"/> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:orientation="horizontal"> <ImageView android:id="@+id/logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.1" android:layout_gravity="left" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|right" android:textSize="15sp" android:padding="3px" android:layout_marginRight="100px" android:textColor="#000"/> </LinearLayout> </RelativeLayout> My challenge is how can I close the gaps that occurs inside the layout below the the last content A: Not sure what exactly you are trying to achieve, but you can change your RelativeLayout height to android:layout_height="match_parent" Also have a look at docs for android:fitsSystemWindows="true". Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/45545593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set text on uiimage center? UIGraphicsBeginImageContext(targetSize); NSString *txt = @"my String"; UIColor *txtColor = [UIColor whiteColor]; UIFont *txtFont = [UIFont systemFontOfSize:30]; NSDictionary *attributes = @{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor}; [txt drawAtPoint:CGPointMake(0, 0) withAttributes:attributes]; UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); I don't know how to fix it to make text to Center. //Edit I add your device but in vain NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; styleCenter.alignment = kCTCenterTextAlignment; NSDictionary *attributes = @{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter}; [txt drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height) withAttributes:attributes]; the text show at right not center, so weird A: Try this: UIGraphicsBeginImageContext(targetSize); NSString *txt = @"my String"; UIColor *txtColor = [UIColor whiteColor]; UIFont *txtFont = [UIFont systemFontOfSize:30]; NSDictionary *attributes = @{NSFontAttributeName:txtFont, NSForegroundColorAttributeName:txtColor}; CGRect txtRect = [txt boundingRectWithSize:CGSizeZero options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; [txt drawAtPoint:CGPointMake(targetSize.width/2 - txtRect.size.width/2, targetSize.height/2 - txtRect.size.height/2) withAttributes:attributes]; UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); A: NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; styleCenter.alignment = NSCenterTextAlignment; NSDictionary *attributes = @{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter}; [txt drawInRect:rect withAttributes:attributes]; A: This category on NSString will draw the centered text in rect with given below font: @implementation NSString (Helpers) - (void)drawCentredInRect:(CGRect)rect withFont:(nullable UIFont *)font andForegroundColor:(nullable UIColor *)foregroundColor { NSMutableDictionary *attributes = [NSMutableDictionary new]; if (font) { attributes[NSFontAttributeName] = font; } if (foregroundColor) { attributes[NSForegroundColorAttributeName] = foregroundColor; } CGSize textSize = [self sizeWithAttributes:attributes]; CGPoint drawPoint = CGPointMake( CGRectGetMidX(rect) - (int) (textSize.width / 2), CGRectGetMidY(rect) - (int) (textSize.height / 2) ); [self drawAtPoint:drawPoint withAttributes:attributes]; } A: I tried the answer for your clever question,Now I got the solution +(UIImage*) drawText:(NSString*)text inImage:(UIImage*)image atPoint:(CGPoint)point { UIGraphicsBeginImageContextWithOptions(image.size, YES, 0.0f); [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); [[UIColor whiteColor] set]; if([text respondsToSelector:@selector(drawInRect:withAttributes:)]) { //iOS 7 or above iOS 7 NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; style.alignment = NSTextAlignmentCenter; NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName]; [text drawInRect:rect withAttributes:attr]; } UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } Please call the above method in where you pick the image like below - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *imagePicked = info[UIImagePickerControllerEditedImage]; picker.delegate = self; self.imageViewTextCenter.image = [ViewController drawText:@"WELCOME" inImage:imagePicked atPoint:CGPointMake(0, 0)];; [picker dismissViewControllerAnimated:YES completion:nil]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/33797445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Any reference for a good free tamil font for android app I have an android application that displays content in tamil. I understand how I can display tamil fonts in my application by adding a font. My problem is, the fonts that are being used for web is not properly displaying in android app. So, the questions are.. * *My content is stored in db in UTF-8 format. So, If I display this in the client side, do you have any ref for free tamil fonts that I can use in my app? *I saw some references about TSCII fonts. If I want to use that in my app, should I store the content also in TSCII encoding? Or Can I store the content in UTF-8 and display using TSCII font? Thanks A: try Bamini, it works for my application. http://www.jagatheswara.com/tamil.php
{ "language": "en", "url": "https://stackoverflow.com/questions/6319405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Power BI - Percentage change from year on year based on avg sale price in row Im new to PowerBI and was wondering if someone could help me how to calculate a Year on year % change. I have made a measure for Total Sales in the year and Average sales Price. I would now like to calcualte the %change of the Avg sale price year on year. Measures used: AVG_SALE = AVERAGE([PRICE]) TOTAL_SALES = COUNT([CITY]) A: Use the following measure: YoY = [AVG_SALE]/CALCULATE([AVG_SALE];SAMEPERIODLASTYEAR('yourTable'[Year]))-1 If you want to treat the possible errors (maybe you miss some years in your data, or you've got no sales on specific year): YoY = IFERROR([AVG_SALE]/CALCULATE([AVG_SALE];SAMEPERIODLASTYEAR('tableName'[Year]))-1;BLANK()) Remember to replace tableName with the name of your table!
{ "language": "en", "url": "https://stackoverflow.com/questions/61189086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery validationEngine validate on email domain Im using this validation plugin: https://github.com/posabsolute/jQuery-Validation-Engine The email input field i have should validate if its a reall email and not allow certain email domains (hotmail, gmail). i have read trough the whole readme on the plugin website but theres nothing usefull i could find there on how to make it do this. so if anyone knows how to do it or has a link to documentation on how to would make you a life safer. thanks in advance. A: I can suggest you to do the next (I didn't test this so let me know if it does not work). This plugin allows you to specify custom regexes for validation. All regexes are placed in the so called translation file (jquery.validationEngine-en.js for English). There you can see $.validationEngineLanguage.allRules object. Add to it your custom rule where you need to set your own regex to forbid (gmail, hotmail etc): "custom_email": { "regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@(?!gmail\.com|hotmail\.com)[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/, "alertText": "* Invalid email address" }, You can see that I added almost default regexp, which was specified in the "email" rule, but included to it the negative lookahead (?!gmail\.com|hotmail.com) (you can add another domains with |newemail\.com approach). Then you need to set this custom rule for your input: <input value="" class="validate[custom[custom_email]]" type="text" name="email" id="email" />
{ "language": "en", "url": "https://stackoverflow.com/questions/12474795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rules with two % marks in GNU make I'm trying to use GNU make to automate my analysis pipeline. I have a script that reads files with the pattern data/sub001/sub001_input.txt and writes to data/sub001/sub001_output.txt. How could I write a rule that matches this pattern for each subject? Here is my attempt so far: # List of all the subjects SUBJECTS ?= sub001 sub002 sub003 /data/%/%_output.txt : process.py data/%/%_input.txt python process.py $* # for each $SUBJECT in $SUBJECTS all : /data/$(SUBJECT)/$(SUBJECT)_output.txt @echo 'Data analysis complete!' I would like the all target to call: python process.py sub001 python process.py sub002 python process.py sub003 And I would like a single subject to be re-processed if the corresponding sub###_input.txt file changes, and I would like all subjects to be re-processed if the process.py file changes. A: You cannot use multiple pattern characters in pattern rules. You can use a single pattern which will stand for the entire middle portion, then strip out the part you want like this: /data/%_output.txt : process.py data/%_input.txt python process.py $(*F)
{ "language": "en", "url": "https://stackoverflow.com/questions/45825031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Releasing Managed Objects in Objective-C Okay, PLEASE bear with my description of my situation: I have a Core Data model that (in a simplified description) includes a GridManager object. The GridManager holds a set of Grid objects (via a to-many relationship). The Grid object contains a set of Cell objects (via a to-many relationship). In my app, I have a GridView that contains a series of sub-views (of type CellView). The GridView has a representedGrid property and the CellView has a representedCell property (both nonatomic, retain). In the setRepresentedGrid method of GridView, I set the representedCell property of each CellView (subviews of the GridView) to one of the cells in the representedGrid. NOW, I have two questions: First, since the cells and the grid are Managed objects, do I still need to release the representedGrid and representedCell properties of the GridView and CellView classes when they dealoc? I figure I do (just as with any retained property), but at one point I thought this was causing a problem with my app--hmmm... just thought, since I write my own setters, and I don't actually retain the grid/cell, perhaps I DON'T need to release them? Second, only one grid from the gridManager is active at a time. When I switch the gridView.representedGrid from one grid to another, how do I "release" the first grid (and it's associated cells) so that it isn't needlessly taking up memory (given that we're talking about managed objects). Thanks SO much! A: As I understand it you should and can avoid custom getters and setters and then you can leave core data to do it's thing and not worry about retain/release. As for reducing memory overhead you can ask core data to turn your object to fault using this method: refreshObject:mergeChanges: Check out the Apple documentation here: http://gemma.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/index.html. It's all there and hopefully I've been able to give you the right terms to look for. Hope that's some help. A: If your setters are retaining the managed objects then you need to release them to match the retain/release. However you may not need to retain the managed objects depending on how the application is designed. Without seeing all of the code it is difficult to give solid advice but you can use the analyzer to check for leaks, use instruments to make sure your memory is not increasing out of control, etc. And last but not least you can turn off retains, switch them to assigns and see if it crashes. Since the NSManagedObjectContext will retain the objects there is a fair chance that your views do not need to retain the NSManagedObject instances at all. A: Yes, you need to release your representedGrid and representedCell properties in your dealloc method. If you didn't, the retain/release methods would not be balanced- your setter would be retaining the object, and with no corresponding release, the object will never be deallocated. When written properly, a retain setter will release its old value and retain the new value. So there is no need to release the old grid when setting gridView.representedGrid. Why are you writing your own setters, out of curiosity?
{ "language": "en", "url": "https://stackoverflow.com/questions/2017975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get proper line breaks for code cells when converting iPython notebook to tex? I am writing a documentation for a python application. For this I am using iPython notebook where I use the code and the markdown cells. I use pandoc to transform the notebook to a .tex document which I can easily convert to .pdf. My problem is this: Line breaks (or word wrap) does not seem to work for the code cells in the .tex document. While the content of the markdown cells is formatted nicely, the code from the code cells (As well as the output from this code) is running over the margins. Any help would be greatly appreciated! A: I've been searching for the same question. It looks like in python 2.7 you can add the following line to a file called custom.js: IPython.Cell.options_default.cm_config.lineWrapping = true; Custom.js is located in ~\Lib\site-packages\notebook\ or ~\Lib\site-packages\jupyter_core\ Note, however, that this isnt working for me yet. I will update here as soon as I get something working.
{ "language": "en", "url": "https://stackoverflow.com/questions/33776599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Toggle based on value in drop down <form> <p><strong>Would you like to receive the Stay Safe newsletter</strong> <select name="newsletter"> <!-- dropdown box allows user to select if they want to receive newsletter--> <option value="yes">Yes</option> <option value="no">No</option> </select> </p> <p><textarea name="message" id="address" placeholder="Address"></textarea></p> <p><input type="email" name="email" placeholder="Valid email"></p> <button class="smallButton" type="submit">Send</button> <!-- submission button to send the form--> </form> I need help with coding my form what i want it to do is only show <p><textarea name="message" id="address" placeholder="Address"></textarea></p> <p><input type="email" name="email" placeholder="Valid email"></p> <button class="smallButton" type="submit" >Send</button><!-- submission button to send the form--> based on them selecting yes in the drop down box but unsure how to do this any help would be greatly appreciated A: I would use onchange and javascript to solve your question. Here is some documentation: <select name="newsletter" onchange="newsletterChanged()"> then you can add javascript to hide or show the html you wish to: function newsletterChanged() { //do work whenever newsletter changes. }; Hope this helps you on the way to solve your question. Happy coding :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/53830322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Reverse Travelling Salesman Module I'm learning VBA slowly and am working on a version of the travelling salesman problem to help myself out. In this particular case, the salesman moves from city to city by selecting the longest route possible between two points. The routes are calculated using cartesian coordinates and Euclidean distances. For this particular example, I have the table of coordinates below: City X Y 1 2 4 2 5 3 3 6 1 4 2 3 5 1 2 6 3 6 7 3 8 8 2 6 9 7 6 10 3 3 My code for this is below, and I hope it's commented enough to make sense: Option Explicit Sub newTSP() Dim nCities As Integer Dim distance() As Single Dim wasVisited() As Boolean Dim route() As Integer Dim totalDistance As Single Dim step As Integer Dim nowAt As Integer Dim nextAt As Integer Dim minDistance As Single 'TODO remove this Dim maxDistance As Single 'just to use in the distance loop Dim i As Integer, j As Integer Dim x1 As Integer, x2 As Integer, y1 As Integer, y2 As Integer Dim temp_dist As Single Dim coords As Range 'this is the table of coordinates 'my Euclidean distance array 'count number of cities in the cartesian coordinates matrix nCities = Range(TSP.Range("a3").Offset(1, 0), TSP.Range("a3").Offset(1, 0).End(xlDown)).Rows.Count 'now that we know the number of cities, redimension distance array ReDim distance(1 To nCities, 1 To nCities) 'take the coordinates as a range Set coords = Range(TSP.Range("a3"), TSP.Range("a3").End(xlDown)).Resize(, 3) 'put in the first arm of the matrix TSP.Range("e3") = "City" TSP.Range("e3").Font.Bold = True TSP.Range("e1") = "Distance Matrix" TSP.Range("e1").Font.Bold = True With TSP.Range("e3") For i = 1 To nCities .Offset(i, 0) = i .Offset(i, 0).Font.Bold = True Next 'second arm of the matrix For j = 1 To nCities .Offset(0, j) = j .Offset(0, j).Font.Bold = True Next 'fill it in with distances For i = 1 To nCities For j = 1 To nCities 'the default value is 0 If i = j Then TSP.Range("e3").Offset(i, j) = 0 'otherwise look for euclidean distance Else 'search for the coordinates for each value x1 = WorksheetFunction.VLookup(i, coords, 2, False) 'x of i y1 = WorksheetFunction.VLookup(i, coords, 3, False) 'y of i x2 = WorksheetFunction.VLookup(j, coords, 2, False) 'x of j y2 = WorksheetFunction.VLookup(j, coords, 3, False) 'y of j temp_dist = Sqr(((x1 - x2) ^ 2) + ((y1 - y2) ^ 2)) TSP.Range("e3").Offset(i, j) = temp_dist End If Next Next End With 'Array where route will be stored. Starts and ends in City 1 ReDim route(1 To nCities + 1) route(1) = 1 route(nCities + 1) = 1 'Boolean array indicating whether each city was already visited or not. Initialize all cities (except City 1) to False ReDim wasVisited(1 To nCities) wasVisited(1) = True For i = 2 To nCities wasVisited(i) = False Next 'Total distance traveled is initially 0. Initial current city is City 1 totalDistance = 0 nowAt = 1 'Find at each step the FARTHEST not-yet-visited city For step = 2 To nCities 'initialize maxDistance to 0 maxDistance = 0 For i = 2 To nCities If i <> nowAt And Not wasVisited(i) Then If distance(nowAt, i) > maxDistance Then nextAt = i maxDistance = TSP.Range("e3").Offset(nowAt, i) 'TODO: does this distance call work with the new table format? End If End If Next i 'store the next city to be visited in the route array route(step) = nextAt wasVisited(nextAt) = True 'update total distance travelled totalDistance = totalDistance + maxDistance 'update current city nowAt = nextAt Next step 'Update total distance traveled with the distance between the last city visited and the initial city, City 1. totalDistance = totalDistance + distance(nowAt, i) 'TODO: does this call work? Original had it as 1, not i. 'Print Results With TSP.Range("A3").Offset(nCities + 2, 0) .Offset(0, 0).Value = "Nearest neighbor route" .Offset(1, 0).Value = "Stop #" .Offset(1, 1).Value = "City" For step = 1 To nCities + 1 .Offset(step + 1, 0).Value = step .Offset(step + 1, 1).Value = route(step) Next step .Offset(nCities + 4, 0).Value = "Total distance is " & totalDistance End With End Sub I seem to be running into issues with my line "wasVisited(nextAt) = True, where it gives me a subscript out of range. The subscript should here should be firmly within the range i=1 to nCities, and I'm not sure where my issue is coming from. Any ideas? A: It's probably not entering the If distance(nowAt, i) > maxDistance Then statement where the nextAt variable is set. So nextAt will still be set to its default value 0 when it reaches that line, which is out of range. Have you stepped through it with the debugger and checked that it enters this If statement? If you manually set nextAt to a 1 in the Locals window while debugging, does it work then? If that's the problem, either set an initial value for nextAt outside of the If statement, or ensure that it enters this If statement in its first round in the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/19675284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: socket.io-redis keeps throwing NOAUTH error I am trying to connect to my redis server that password protected but for some reason I keep getting the error: events.js:141 throw er; // Unhandled 'error' event ^ ReplyError: Ready check failed: NOAUTH Authentication required. at parseError (/home/ubuntu/TekIT/ITapp/node_modules/redis-parser/lib/parser.js:193:12) at parseType (/home/ubuntu/TekIT/ITapp/node_modules/redis-parser/lib/parser.js:303:14) I know the password is correct because i tried it in the redis-cli and it works fine. Here is the code below: var redis = require('redis'); var client = redis.createClient(redisPort, redisHostname, { auth_pass: 'password1' }); var redisSubscriber = redis.createClient(redisPort, redisHostname, { auth_pass: 'password1' }); // Create and use a Socket.IO Redis store var RedisStore = require('socket.io-redis'); io.set('store', new RedisStore({ redisPub: client, redisSub: redisSubscriber, redisClient: client })); Does anyone know why I am getting this error? A: You should initialize socket.io-redis after ready event. Also you should call to client.auth('password1', ()=>{}) function. Check this part of documentation: When connecting to a Redis server that requires authentication, the AUTH command must be sent as the first command after connecting. This can be tricky to coordinate with reconnections, the ready check, etc. To make this easier, client.auth() stashes password and will send it after each connection, including reconnections. callback is invoked only once, after the response to the very first AUTH command sent. NOTE: Your call to client.auth() should not be inside the ready handler. If you are doing this wrong, client will emit an error that looks something like this Error: Ready check failed: ERR operation not permitted. Try this code: var redis = require('redis'); const redisPort = 6379 const redisHostname = 'localhost' const password = 'password1' var p1 = new Promise((resolve, reject)=>{ var client = redis.createClient(redisPort, redisHostname, { auth_pass: 'password1' }); client.auth(password) client.on('ready', ()=>{ resolve(client) }) }) var p2 = new Promise((resolve, reject)=>{ var redisSubscriber = redis.createClient(redisPort, redisHostname, { auth_pass: 'password1' }); redisSubscriber.auth(password) redisSubscriber.on('ready', ()=>{ resolve(redisSubscriber) }) }) Promise.all([p1,p2]).then(([client, redisSubscriber])=>{ console.log('done', client) client.ping((err, data)=>{ console.log('err, data', err, data) }) // Create and use a Socket.IO Redis store var RedisStore = require('socket.io-redis'); io.set('store', new RedisStore({ redisPub: client, redisSub: redisSubscriber, redisClient: client })); })
{ "language": "en", "url": "https://stackoverflow.com/questions/43646577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Self referencing loop detected in ASP.NET Core When I try to serialize some domain objects using ASP.NET Core Newsoft JSON.NET it is throwing an exception because it is detecting a self referencing loop. In ASP.NET 4 we used to fix it globally this way: JSON.NET Error Self referencing loop detected for type How can we fix this in ASP.NET Core? A: There is no difference in the way self-referencing loops are handled in ASP.NET 4 compared to ASP.NET Core (previously Asp.Net 5). The principles outlined in the question you referenced in your post still apply. However, setting this property in ASP.NET Core is obviously slightly different, given the new method of configuring and bootstrapping the app: public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); services.AddEntityFramework().AddSqlServer().AddDbContext<IvoryPacketDbContext>( options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]) ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/34753498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Rails subclass method not overwriting the parent class method in favors_controller I have private def current_resource @favor ||= Favor.find(params[:id]) if params[:id] end end and then in application_controller I have def current_permission @current_permission ||= Permission.new(current_user) end def current_resource nil end def authorize if !current_permission.allow?(params[:controller], params[:action], current_resource) redirect_to root_url, alert: "No no no. You can't do that!" end end The problem is that current_resource is nil. I tried putting @favor ||= Favor.find(params[:id]) if params[:id] directly in application controller and nothing changed! What do you think is the problem? Thanks in advance for your time! A: The problem is that params[:id] is not truthy, and therefore the @favor ||= Favor.find(params[:id]) if params[:id] statement is evaluating to nil
{ "language": "en", "url": "https://stackoverflow.com/questions/35118558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you decode html in a url? In my project I have got a "back button" that is calling a javaScript function that remembers the previous url when called. //back button function function goBack() { $window.history.back(); } the url being remembered or being called when the back button is clicked contains an ID and this is ID is used to filter data. The main problem i'm having is that this ID is being returned as a string encoded in html. for example this is the url being called: //Lookups?$filter=VehicleId%20eq%20%272415%27& As you can see VehicleId is 2415 in above url, which is also encoded to %20%272415%27&. this in plain text is VehicleId = "2415". This is clashing with my program as my program is expecting an int variable instead of a string. To resolve this i am trying to de -encode?? from html to make the ID to an int. and i having been looking at this http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_unescape but i still can't figure how to put this in my project. I am using $location in order to remember the ID in url like so: if ($location.search().vehicle) { var str = vehicle; var strEsc = unescape(str); vehicle = strEsc; vehicle = $location.search().vehicle; } To be honest i don't if i am doing this right (which i'm not sure) ..Is any one to help with this please? A: decodeURIComponent is the key: decodeURIComponent('VehicleId%20eq%20%272415%27&'); // "VehicleId eq '2415'&" That's definitely not a proper ID (not to mention you're trying to do $filter=VehicleId=2135, of course that will break the query string, find a way to encode that value). You should probably make those IDs a bit more standard as then you'd get more accurate results. A: You could use regexp to parse the VehicleId, such as : var tab=unescape(location.search).match(/VehicleId eq '(\d+)'/); if (tab) { var id=tab[1]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/26927085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IntelliJ IDEA - Error: JavaFX runtime components are missing, and are required to run this application I'm running IntelliJ IDEA Ultimate 2018.2.5 with JDK 11.0.1 and JavaFX 11 from OpenJFX. I know it's a common error and I tried many of the proposed fixes but nothing works. No matter which JavaFX project I try to run I get the error: Error: JavaFX runtime components are missing, and are required to run this application If I add the following to the VM options --module-path="C:\Program Files\Java\javafx-sdk-11\lib" --add-modules=javafx.controls I get these errors: Exception in Application start method java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464) at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051) Caused by: java.lang.RuntimeException: Exception in Application start method at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900) at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x5fce9dc5) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x5fce9dc5 at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38) at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056) at sample.Main.start(Main.java:13) at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846) at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455) at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428) at java.base/java.security.AccessController.doPrivileged(Native Method) at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427) at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96) at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174) ... 1 more Exception running application sample.Main I tried reinstalling without any luck. I have also tried to change getClass().getResource(...) to getClass().getClassLoader().getResource(...) or to something like Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml")); but still doesn't work. A: There are similar questions like this or this other one. Before JavaFX 11, whenever you were calling something JavaFX related, you had all the javafx modules available within the SDK. But now you have to include the modules/dependencies you need. Your error says that you are using FXML but it can't be resolved, but you have just added the javafx.controls module: --add-modules=javafx.controls As you can see in the JavaDoc the javafx.controls module depends on javafx.graphics and java.base, but none of those modules includes the FXML classes. If you need FXML classes like the FXMLLoader, you need to include javafx.fxml module: --module-path="C:\Program Files\Java\javafx-sdk-11\lib" \ --add-modules=javafx.controls,javafx.fxml The same will apply if you need media or webkit, those have their own modules.
{ "language": "en", "url": "https://stackoverflow.com/questions/52906773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Sending ETX to NSTask I have an NSTask that's executing another program I wrote. In that command line program, it expects the ETX (control-C, or ASCII value 3) to pause one of its processes and call another function. How can I send this? I know I'm sending commands correctly because the program interacts with every command I've sent it so far except ETX. I'm using the following code but it does not work: NSString *cmdScan = [NSString stringWithFormat:@"%c", 3]; [inputHandle writeData: [cmdScan dataUsingEncoding:NSUTF8StringEncoding]]; A: (I'm assuming you want to emulate the behavior of the ctrl+c keystroke in a terminal window. If you really mean to send an ETX to the target process, this answer isn't going to help you.) The ctrl+c keyboard combination doesn't send an ETX to the standard input of the program. This can easily be verified as regular keyboard input can be ignored by a running program, but ctrl+c (usually) immediately takes effect. For instance, even programs that completely ignore the standard input (such as int main() { while (1); }) can be stopped by pressing ctrl+c. This works because terminals catch the ctrl+c key combination and deliver a SIGINT signal to the process instead. Therefore, writing an ETX to the standard input of a program has no effect, because the keystroke is caught by the terminal and the resulting character isn't delivered to the running program's standard input. You can send SIGINT signals to processes represented by a NSTask by using the -[NSTask interrupt] method. [task interrupt]; Otherwise, you can also send arbitrary signals to processes by using the kill function (which, mind you, doesn't necessarily kills programs). #include <signal.h> kill(task.processIdentifier, SIGINT);
{ "language": "en", "url": "https://stackoverflow.com/questions/7776251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: "Deprecation Notice" error in PhpMyAdmin with ubuntu 20.04, php8.0 I'am getting error when i login to phpmyadmin Deprecation Notice in ./libraries/classes/Di/ReflectorItem.php#82 Method ReflectionParameter::getClass() is deprecated Backtrace ./libraries/classes/Di/ReflectorItem.php#50: PhpMyAdmin\Di\ReflectorItem->_resolveArgs( array, array, ) ./libraries/classes/Di/FactoryItem.php#27: PhpMyAdmin\Di\ReflectorItem->invoke(array) ./libraries/classes/Di/Container.php#62: PhpMyAdmin\Di\FactoryItem->get(array) ./libraries/classes/Di/AliasItem.php#44: PhpMyAdmin\Di\Container->get( string 'PhpMyAdmin\Controllers\Database\DatabaseStructureController', array, ) ./libraries/classes/Di/Container.php#62: PhpMyAdmin\Di\AliasItem->get(array) ./db_structure.php#35: PhpMyAdmin\Di\Container->get( string 'DatabaseStructureController', array, ) A: This is most likely caused by using PHP 8 and PHPMyAdmin < v5 either upgrade you PHPMyAdmin to 5.0 or higher or downgrade your PHP to 7 A: You can also disable notifications and warnings adding this line to config.inc.php: $cfg['SendErrorReports'] = 'never'; Source: PMA Docs A: I had the same error. phpMyAdmin 5.1.3 uses PHP 7.1 and phpMyAdmin 4.9.10 uses PHP 5.5 to 7.4 You can see that info here: https://www.phpmyadmin.net/downloads/ I have installed 4.9.5 with apache, so what I did was install PHP7.4 and php7.4-fpm, then I modified the phpMyAdmin apache config file to indicate that it should work with PHP7.4 Install php7.4-fpm: sudo apt install libapache2-mod-fcgid sudo apt install software-properties-common sudo add-apt-repository ppa:ondrej/php && sudo apt update sudo apt install php7.4-fpm sudo a2enmod actions alias proxy_fcgi fcgid sudo systemctl restart apache2 Modify phpMyAdmin apache config file: sudo nano /etc/phpmyadmin/apache.conf After Alias /phpmyadmin /usr/share/phpmyadmin paste: <FilesMatch \.php> # Apache 2.4.10+ can proxy to unix socket SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost/" </FilesMatch> You can restart apache again and that's it. Good luck! A: Because 5.0 series is ended and 5.1 will be out next this will not be fixed. 5.1 has a new DI system and the classes mentioned in the output do not exist anymore. But you can download the latest version in development (phpMyAdmin 5.1+snapshot) and the DI errors should be gone :) https://github.com/phpmyadmin/phpmyadmin/issues/16268 A: I've got a WAMPSERVER installed and what cleared those notices for me was updating phpmyadmin to 5.1.3 that supported PHP 8
{ "language": "en", "url": "https://stackoverflow.com/questions/65745714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: I am not able to latch and read from an 8253 counter in mode 2 I am a beginner to proteus. I want to latch and read a constantly running counter in mode 2 to generate a random number between 1 and 5. this is the emulator code. When we latch it the output gets latched and the value in AL is 11111111. Can someone help please. this my code: mov ax,0100h mov ds,ax mov es,ax mov ss,ax mov sp,0FFFEH This is the main code: ;intialise porta & upper port C as input ,portb & lower portc as output mov al,00010100b out 0eh,al mov al,5 out 08h,al mov al,80h out 06h,al mov al,00001111b out 00h,al mov al,00000000b out 0eh,al in al,08h out 02h,al mov al,11111111b out 02h,al xi: jmp xi
{ "language": "en", "url": "https://stackoverflow.com/questions/55776074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NHibernate simple one-to-many mapping using NHibernate.Mapping.Attributes Can anyone provide me with a web-link which describes attribute-based simple one-to-many mapping very clearly? For example (A company can have only one country of origin. But there are many Companies in a Country): class Company { } class Country { IList<Company> Items; } A: For your example class, and using a bag for an unordered collection: using Map = NHibernate.Mapping.Attributes; [Map.Class( 0, Table = "country", NameType=typeof(Country) )] public class Country { [Map.Id( 1, Name = "Id" )] [Map.Generator( 2, Class = "identity" )] public virtual int Id { get; set; } [Map.Property] public virtual string Name { get; set; } [Map.Bag( 0, Table = "country_company" )] [Map.Key( 1, Column = "countryid" )] [Map.OneToMany( 2, ClassType = typeof( Company ) )] public virtual IList<Company> Items { get; set; } } [Map.Class( 0, Table = "country_company", NameType = typeof( Company ) )] public class Company { [Map.Id( 1, Name = "Id" )] [Map.Generator( 2, Class = "identity" )] public virtual Guid Id { get; set; } [Map.Property] public virtual string Name { get; set; } } produces the following hbm.xml: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="nh.Country, nh" table="country"> <id name="Id"> <generator class="identity" /> </id> <property name="Name" /> <bag name="Items" table="country_company"> <key column="countryid" /> <one-to-many class="nh.Company, nh" /> </bag> </class> <class name="nh.Company, nh" table="country_company"> <id name="Id"> <generator class="identity" /> </id> <property name="Name" /> </class> </hibernate-mapping>
{ "language": "en", "url": "https://stackoverflow.com/questions/1986472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to clone objects in Amazon S3 using RestS3Service so i'm trying to clone objects in a folder on my S3 (Amazon S3) account. But i was wondering if there a way to do it without having to write the file to my local system first, then uploading that file back up to S3? eventually i want it to be fully recursive cloning folders and objects in a given bucket, but for now i'm stuck on getting it to clone efficiently. say the bucket path is images.example.com/products/prodSku and in that prodSku folder i have a bunch of images i want to copy to a new folder here's what i have so far. (note: this is written in groovy, but if you know java, it's the same thing) try{ def s3os = restService.listObjects(bucket_name, sourcePrefix, null) def s3o for(def i in s3os){ s3o = get(bucket_name, i.key) // i want to be able to do something like this, just putting the input stream // back into s3. but i can't. from what i know now, i have to write the // dataInputStream into a file locally, then use that file to create a new S3Object // which is placed as the second argument in the putObject method restService.putObject(destinationBucketName, s3o.dataInputStream) } }catch(S3ServiceException e) { println e } Sorry the formatting is all messed up, first time posting a message. but any help would be greatly appreciated! Thanks! A: Not sure about JetS3t API but, the AWS SDK for Java does provide a simple copyObject method A: so i ended up figuring out how to do clone the asset in s3 using JetS3t. it was simpler than i expected. i'll post it up incase anyone ever googles this question. all do is first get the s3 object you want to clone. after you have it, call setKey(filename) on the s3 object. "filename" is the path for where you want the object to be followed by the file name itself i.e. yours3bucketname/products/assets/picture.png after your done with that, just call putObject(bucket_name, s3object), passing the s3object that you called setKey on as the second argument. good luck! happy programming!
{ "language": "en", "url": "https://stackoverflow.com/questions/5280030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Post Data to Webservice URL I have problem with my code for posting data to webservice. Can someone please, tell me where I am going wrong. I need to post three fields (doctorId-STRING, patientId. STRING, date-STRING) to this address: http://www.walter-dev.com/doctor/public/setTermin How to make this right? NSString *post = [NSString stringWithFormat:@"&id_doktor=%@&id_pacijent=%@&datum=%@",@"iddoktora",@"idpacijenta",@"ovojedatum"]; NSData* postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; //You need to send the actual length of your data. Calculate the length of the post string. NSString *postLength = [NSString stringWithFormat:@”%d”,[postData length]]; //Create URLRequest object and initialize it. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; //Set the Url for which your going to send the data to that request [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.walter-dev.com/doctor/public/setTermin"]]]; //set HTTP method (POST) [request setHTTPMethod:@"POST"]; //Set header field with lenght of the post data [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; //I dont understand this line of code [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; //Set httpbody of the urlrequest with string "post" [request setHTTPBody:postData]; //Initialize object with urlRequest NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; if(conn) { NSLog(@"Konekcija prema serveru je uspjela"); } else { NSLog(@"NIJE USPJELA "); }
{ "language": "en", "url": "https://stackoverflow.com/questions/26278156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Write struct to csv file What is an idiomatic golang way to dump the struct into a csv file provided? I am inside a func where my struct is passed as interface{}: func decode_and_csv(my_response *http.Response, my_struct interface{}) Why interface{}? - reading data from JSON and there could be a few different structs returned, so trying to write a generic enough function. an example of my types: type Location []struct { Name string `json: "Name"` Region string `json: "Region"` Type string `json: "Type"` } A: It would be a lot easier if you used a concrete type. You'll probably want to use the encoding/csv package, here is a relevant example; https://golang.org/pkg/encoding/csv/#example_Writer As you can see, the Write method is expecting a []string so in order to generate this, you'll have to either 1) provide a helper method or 2) reflect my_struct. Personally, I prefer the first method but it depends on your needs. If you want to go route two you can get all the fields on the struct an use them as the column headers, then iterate the fields getting the value for each, use append in that loop to add them to a []string and then pass it to Write out side of the loop. For the first option, I would define a ToSlice or something on each type and then I would make an interface call it CsvAble that requires the ToSlice method. Change the type in your method my_struct CsvAble instead of using the empty interface and then you can just call ToSlice on my_struct and pass the return value into Write. You could have that return the column headers as well (meaning you would get back a [][]string and need to iterate the outer dimension passing each []string into Write) or you could require another method to satisfy the interface like GetHeaders that returns a []string which is the column headers. If that were the case your code would look something like; w := csv.NewWriter(os.Stdout) headers := my_struct.GetHeaders() values := my_struct.ToSlice() if err := w.Write(headers); err != nil { //write failed do something } if err := w.Write(values); err != nil { //write failed do something } If that doesn't make sense let me know and I can follow up with a code sample for either of the two approaches.
{ "language": "en", "url": "https://stackoverflow.com/questions/33357156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Fastest way to apply function involving multiple dataframe I'm searching to improve my code, and I don't find any clue for my problem. I have 2 dataframes (let's say A and B) with same number of row & columns. I want to create a third dataframe C, which will transformed each A[x,y] element based on B[x,y] element. Actually I perform the operation with 2 loop, one for x and one for y dimension : import pandas A=pandas.DataFrame([["dataA1","dataA2","dataA3"],["dataA4","dataA5","dataA6"]]) B=pandas.DataFrame([["dataB1","dataB2","dataB3"],["dataB4","dataB5","dataB6"]]) Result=pandas.DataFrame([["","",""],["","",""]]) def mycomplexfunction(x,y): return str.upper(x)+str.lower(y) for indexLine in range(0,2): for indexColumn in range(0,3): Result.loc[indexLine,indexColumn]=mycomplexfunction(A.loc[indexLine,indexColumn],B.loc[indexLine,indexColumn]) print(Result) 0 1 2 0 DATAA1datab1 DATAA2datab2 DATAA3datab3 1 DATAA4datab4 DATAA5datab5 DATAA6datab6 but I'm searching for a more elegant and fastway to do it directly by using dataframe functions. Any idea ? Thanks,
{ "language": "en", "url": "https://stackoverflow.com/questions/42833607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Website/Files organisation for Ajax calls I am just getting started with Ajax, and I wonder how to organize my ajax scripts and php files (which process the ajax function). With Php it was easy, one functions library functions.php with all my classes and methods that I can call whenever I need them. My first reflex with Ajax was trying to call an already existing method inside a php class in order to process a contact form but I do believe this is impossible and I need a separate file to do this ? My question is, do I need to create a different file.js for each ajax script and a file.php for each ajax call ? It can get very messy with a few ajax functions compared to php. Is there a right way to organize this ? A: You definitely should use a php framework ! It will help you to organize your code and will bring to you some helpful features like routing which would solve your problem. You will define some roots, each linked to a specific controller and your code will be well organized. I can recommend you Symfony2 : but there are a lot of which are able to do the job : http://www.hongkiat.com/blog/best-php-frameworks/ If your application is small you can have a look to silex which is a light version of Symfony To define your urls, you can use a REST api which is a best practice. I can understand that you find the learning curve of the frameworks difficult but you will not regret it.
{ "language": "en", "url": "https://stackoverflow.com/questions/42102156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable antivirus and enable windows defender using powershell How to firstly disable antivirus from computer and enable windows defender using powershell command: Set-MpPreference -DisableRealtimeMonitoring $false I'm performing this command to enable the windows defender but due to inbuilt antivirus I'm not able to enable it and perform this operation: Start-MpScan -ScanType QuickScan -ScanPath C If there is having another scan command for powershell which is not conflicting of having another antivirus then suggest me or help me to get the solution of above problem. Thanks in advance A: If the AV software exposes an API/CLI facility to disable it, you will need to find that from the AV company as they are all generally different. You could uninstall the AV software, but it may not be silent about it, in other words the uninstall software may have prompts the user has to deal with before it uninstalls often requiring a reboot before you could run the windows defender scan, before you then have to reinstall the AV software. If it could uninstall/install silently, that might be a work around? Another possible way would be to get handles to the AV software, walk through (enumerate) the screen controls and post events to the controls to simulate a user, but this is getting more into coding than scripting, and you still may not be able to walk through the controls, for example some web browsers dont let you enumerate the address bar in order to post web addresses into them and hijack them that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/51665652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Skip multiple iterations in loop I have a list in a loop and I want to skip 3 elements after look has been reached. In this answer a couple of suggestions were made but I fail to make good use of them: song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] for sing in song: if sing == 'look': print sing continue continue continue continue print 'a' + sing print sing Four times continue is nonsense of course and using four times next() doesn't work. The output should look like: always look aside of life A: >>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] >>> count = 0 >>> while count < (len(song)): if song[count] == "look" : print song[count] count += 4 song[count] = 'a' + song[count] continue print song[count] count += 1 Output: always look aside of life A: for uses iter(song) to loop; you can do this in your own code and then advance the iterator inside the loop; calling iter() on the iterable again will only return the same iterable object so you can advance the iterable inside the loop with for following right along in the next iteration. Advance the iterator with the next() function; it works correctly in both Python 2 and 3 without having to adjust syntax: song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] song_iter = iter(song) for sing in song_iter: print sing if sing == 'look': next(song_iter) next(song_iter) next(song_iter) print 'a' + next(song_iter) By moving the print sing line up we can avoid repeating ourselves too. Using next() this way can raise a StopIteration exception, if the iterable is out of values. You could catch that exception, but it'd be easier to give next() a second argument, a default value to ignore the exception and return the default instead: song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] song_iter = iter(song) for sing in song_iter: print sing if sing == 'look': next(song_iter, None) next(song_iter, None) next(song_iter, None) print 'a' + next(song_iter, '') I'd use itertools.islice() to skip 3 elements instead; saves repeated next() calls: from itertools import islice song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] song_iter = iter(song) for sing in song_iter: print sing if sing == 'look': print 'a' + next(islice(song_iter, 3, 4), '') The islice(song_iter, 3, 4) iterable will skip 3 elements, then return the 4th, then be done. Calling next() on that object thus retrieves the 4th element from song_iter(). Demo: >>> from itertools import islice >>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] >>> song_iter = iter(song) >>> for sing in song_iter: ... print sing ... if sing == 'look': ... print 'a' + next(islice(song_iter, 3, 4), '') ... always look aside of life A: I think, it's just fine to use iterators and next here: song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] it = iter(song) while True: word = next(it, None) if not word: break print word if word == 'look': for _ in range(4): # skip 3 and take 4th word = next(it, None) if word: print 'a' + word or, with exception handling (which is shorter as well as more robust as @Steinar noticed): it = iter(song) while True: try: word = next(it) print word if word == 'look': for _ in range(4): word = next(it) print 'a' + word except StopIteration: break A: You can do this without an iter() as well simply using an extra variable: skipcount = -1 song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] for sing in song: if sing == 'look' and skipcount <= 0: print sing skipcount = 3 elif skipcount > 0: skipcount = skipcount - 1 continue elif skipcount == 0: print 'a' + sing skipcount = skipcount - 1 else: print sing skipcount = skipcount - 1 A: Actually, using .next() three times is not nonsense. When you want to skip n values, call next() n+1 times (don't forget to assign the value of the last call to something) and then "call" continue. To get an exact replica of the code you posted: song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] songiter = iter(song) for sing in songiter: if sing == 'look': print sing songiter.next() songiter.next() songiter.next() sing = songiter.next() print 'a' + sing continue print sing A: Of course you can use three time next (here I actually do it four time) song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] it = iter(song) for sing in it: if sing == 'look': print sing try: sing = it.next(); sing = it.next(); sing = it.next(); sing=it.next() except StopIteration: break print 'a'+sing else: print sing Then always look aside of life A: I believe the following code is the simplest for me. # data list song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] # this is one possible way for sing in song: if sing != 'look'\ and sing != 'always' \ and sing != 'side' \ and sing != 'of'\ and sing != 'life': continue if sing == 'side': sing = f'a{sing}' # or sing = 'aside' print(sing) # this is another possible way songs_to_keep = ['always', 'look', 'of', 'side', 'of', 'life'] songs_to_change = ['side'] for sing in song: if sing not in songs_to_keep: continue if sing in songs_to_change: sing = f'a{sing}' print(sing) This produces the results you are looking for. always look aside of life
{ "language": "en", "url": "https://stackoverflow.com/questions/22295901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: How does Netbeans keep track of the projects' locations? When you create a new Java project in Netbeans, you get to choose where it will be stored. My question is where does Netbeans keep a refrence to such created projects? I looked in /etc/netbeans.conf but I did not find any refrence to the location I choose in Netbeans GUI. The idea behind this is to be able to package the installed Netbean app and the created projects and be able to move it to another PC. If I know where such path is kept I can create an app that update it as necessary. The official wiki of Netbeans doesn't talk about this. Does anyone know about this? A: For me, the project groups appear under: C:\Users\aedison\AppData\Roaming\NetBeans\8.1\config\Preferences\org\netbeans \modules\projectui Replace aedison with your user name and replace 8.1 with your Netbeans version. Hopefully that gives you a pointer in the right direction. I would caution you against manually messing with these settings, though. NetBeans is very very touchy. (Take backups first!) A: I may be incorrect, but have you tried looking in your NetBeans userdir? According to this page on their site NetBeans stores some files in ~/.netbeans and ~/.cache/netbeans/7.2/ Maybe try searching there for a database or perhaps XML file describing project locations
{ "language": "en", "url": "https://stackoverflow.com/questions/41108057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Group Object based on ending Number Here is the sample object { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', } I want to group via the number they end with and wante the expected output to be { 0: {abc: 'a', bcd: 'b', cde: 'c'}, 1: {abc: 'a', bcd: 'b', cde: 'c', def : 'd'}, } A: You may try this solution: const data = { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', }; const result = Object.entries(data).reduce((acc, [combo, value]) => { const [key, index] = combo.split('_'); acc[index] = { ...acc[index], [key]: value }; return acc; }, {}); console.log(result); A: You can write something like this to achieve it const obj = { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', }; const groupByChar = () => { const res = {}; for (let k in obj){ const char = k.charAt(k.length-1); if (!res[char]){ res[char] = {}; } const key = k.substring(0, k.length - 2); res[char][key] = obj[k]; } return res; } const res = groupByChar(); console.log(res); A: I deliberately disrupted the data sequence to better meet your needs. const data = { abc_0: 'a', abc_1: 'a', bcd_0: 'b', bcd_1: 'b', cde_0: 'c', cde_1: 'c', def_0: 'd', def_1: 'd', }; const res = Object.keys(data) .map((key) => { const [char, num] = key.split('_'); return { [num]: { [char]: data[key], }, }; }) .reduce((acc, cur) => { const acc_keys = Object.keys(acc); const [cur_key] = Object.keys(cur); if (acc_keys.includes(cur_key)) { acc[cur_key] = { ...acc[cur_key], ...cur[cur_key] }; return { ...acc, }; } else { return { ...acc, ...cur }; } }, {}); console.log(res); A: Another way of writing it const obj= { abc_0: 'a', bcd_0: 'b', cde_0: 'c', abc_1: 'a', bcd_1: 'b', cde_1: 'c', def_1: 'd', } const filtered = Object.keys(obj).map((el)=>el.split('_')[1]).filter((el, i)=>Object.keys(obj).map((el)=>el.split('_')[1]).indexOf(el)===i); const res = Object.entries(obj).reduce((acc, curr, i)=>{ const left=curr[0].split('_')[0] const right=curr[0].split('_')[1] filtered.forEach((index)=>{ if(right==index){ !acc[index]? acc[index]={}:null !acc[index][left]?acc[index][left]=obj[`${left}_${right}`]:null } }) return acc },{}) console.log(res);
{ "language": "en", "url": "https://stackoverflow.com/questions/70272226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: malloc handling - identifier not found issue I'm using visual studio to write a c code. This is the malloc code line i was told to use: root = (Coor)malloc(sizeof(Coor)); It doesn't let me use it for the following error: identifier not found Can anyone tell me why it happens and how to fix it? Thanks, A: Please check if you have included <stdlib.h> and <malloc.h>.
{ "language": "en", "url": "https://stackoverflow.com/questions/17254127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Change default popup menu submenu arrow I'm using default PopupMenu. I've customized it in my XML style, and now it has a dark style. but I have a problem now: please look at this screenShot I've prepared: As you can see the arrow is kind of hard to see and I really wish to avoid using popup window now. Is there any way that I could change it to a white arrow? A: It's been a long time, but in case anyone else runs into this problem, you can leverage a style to fix this. it looks like the color of the arrow is controlled by android:textColorSecondary, so if you are programmatically generating a popup menu, you could do something like this (in Kotlin): val contextThemeWrapper = ContextThemeWrapper(context, R.style.PopupMenuStyle) val popupMenu = PopupMenu(contextThemeWrapper, view) val menu = popupMenu.menu menu.addSubMenu(groupId, itemId, order, groupTitle) menu.add(groupId, itemId, order, title1) menu.add(groupId, itemId, order, title2) etc... and define your PopupMenuStyle like this in your styles.xml: <style name="PopupMenuStyle" parent="@style/<some.parent.style>"> <!--this makes an the arrow for a menu's submenu white--> <item name="android:textColorSecondary">@android:color/white</item> </style> A: custom theme and set listMenuViewStyle <style name="AppTheme" parent="Theme.MaterialComponents.Light"> <item name="listMenuViewStyle">@style/listMenuViewStyle</item> </style> set subMenuArrow <style name="listMenuViewStyle" parent="Base.Widget.AppCompat.ListMenuView"> <item name="subMenuArrow">@drawable/icon_sub_menu</item> </style> apply custom theme to activity <activity android:name=".material.MyTopAppBarActivity" android:theme="@style/AppTheme"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/44221594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: move onclick function to other element with jquery - reading attr() returns function I have an <img src="blabla.png" onclick="someFunction();"> tag that I want to replace with an <a> tag (created dynamically). I want to move the onclick from the to the but when I read attr("onclick") it returns: function onclick(event) { someFunction(); } How can I extract only the someFunction(); call and set this to the onclick of the <a> tag? After the answer I used it like this: $(function(){ $(".content img[src*=images]").each(function(){ $(this).after("<a href=# class='button'></a>"); $(this).next().text($(this).attr("alt")); $(this).next().click(this.onclick); /* remove old img */ $(this).remove(); }); }); A: Use the this.onclick instead of $(this).attr('onclick'). It will be a function type and you can simply set the a.onclick = img.onclick. Ideally however the image would have a click handler and would be bound unobtrusively. var someFunction = function(){}; $('img').click(someFunction); Then you could use the same function on the a $('a').click(someFuncion);
{ "language": "en", "url": "https://stackoverflow.com/questions/4736492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Order by Value in Spark pairRDD from (Key,Value) where the value is from spark-sql I have created a map like this - val b = a.map(x => (x(0), x) ) Here b is of the type org.apache.spark.rdd.RDD[(Any, org.apache.spark.sql.Row)] * *How can I sort the PairRDD within each key using a field from the value row? *After that I want to run a function which processes all the values for each Key in isolation in the previously sorted order. Is that possible? If yes can you please give an example. *Is there any consideration needed for Partitioning the Pair RDD? A: Answering only your first question: val indexToSelect: Int = ??? //points to sortable type (has Ordering or is Ordered) sorted = rdd.sortBy(pair => pair._2(indexToSelect)) What this does, it just selects the second value in the pair (pair._2) and from that row it selects the appropriate value ((indexToSelect) or more verbosely: .apply(indexToSelect)).
{ "language": "en", "url": "https://stackoverflow.com/questions/30469864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: React Hooks - Retry Failed Async Requests Inside of useEffect that is Dependent on Props Does anybody know what patterns are considered best practice when it comes to retrying async network requests that fail within a useEffect hook? I have the following component: import React, {useEffect, useState, useCallback} from 'react' import styles from './_styles.module.scss' type Props = { itemIds: string[]; } function MyComponent({itemIds}: Props): JSX.Element { const [loading, setLoading] = useState<boolean>(true) const [error, setError] = useState<boolean>(true) const [itemsData, setItemsData] = useState<Record<string, Item>>({}) useEffect(() => { async function fetchItemsData() { setError(false) const {data, error: fetchError} = await getDataForItems(itemIds) // uses fetch API under the hood if (fetchError) { setError(true) setLoading(false) return } setItemsData(data) setLoading(false) } if (loading) { void fetchItemsData() } }, [itemIds, loading]) const retry = useCallback(() => { setLoading(true) }, []) return ( <div> {loading && ( <div className={styles.loadingSpinner} /> )} {(!loading && error) && ( <div> <div>Some error message with a try again button</div> <button onClick={retry}>Try Again</div> </div> )} {(!loading && !error) && ( <div>Success</div> )} </div> ) } The intent is for this component to be re-usable, and I have the useEffect hook configured to trigger in the event the itemIds prop changes or if the loading state changes. I have that loading state to help display loading-based visuals but also to serve as the retry request mechanism. The problem with this, however, is I have to guard the execution of the fetchItemsData function using that flag to prevent the effect from running that request again after every setLoading invocation. Furthermore, in the event the initial request succeeds (loading will be set to false), when the itemIds prop updates to a new set of ids, the effect will not fire off because loading is false which prevents the execution of the fetchItemsData function. Does anyone have a good pattern for handling request retries like this in React Hooks?
{ "language": "en", "url": "https://stackoverflow.com/questions/63605264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Duplicated rows on getting Categories of a Publication I have a table of Publications Id | Title | Content ... 1 | 'Ex title 1' | 'example content 1' 2 | 'Ex title 2' | 'example content 2' ... And a table of Categories CategoryId | PublicationId 1 | 1 2 | 1 2 | 2 3 | 2 ... So a Publication could have one or many categories. I am trying to get the first 10 publications and their categories on a single query, like that: SELECT [Publication].Id, [Publication].Title, [Publication].Content, [PublicationCategory].CategoryId FROM [Publication] LEFT JOIN [PublicationCategory] ON [Publication].Id = [PublicationCategory].Id ORDER BY [Publication].Id DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY But I am getting duplicated values because of diferents categories ids, which is the better way to get 10 publications and their categories and not getting duplicated rows (because of duplicated rows, i got duplicated publications) A: You can first pick the TOP 10 Publications and then put a JOIN with the Category table like following query to get all the categories. SELECT [Publication].*,[PublicationCategory].[categoryid] FROM ( SELECT TOP 10 [Publication].id, [Publication].title, [Publication].content FROM Publications [Publication] ORDER BY [Publication].Id DESC ) [Publication] INNER JOIN Categories [PublicationCategory] ON [Publication].id = [PublicationCategory].publicationid DEMO A: Use a CTE to number your publlication, and then JOIN onto your table PublicationCategory and filter on the value of ROW_NUMBER(): WITH RNs AS( SELECT P.Id, P.Title, P.Content, ROW_NUMBER() OVER (ORDER BY P.ID DESC) AS RN FROM Publication P) SELECT RNs.Id, Rns.Title, RNs.Content, PC.CategoryId FROM RNs LEFT JOIN PublicationCategory PC ON RNs.Id = PC.Id WHERE RNs.RN <= 10; A: I Think the best answer is the @PSK's but What if a publication is not categorized? (weird case but if is not validated maybe could happen) so you can add a left join and always get at least the 10 publications, if a publication has no category you still will get it but with a NULL category SELECT [Publication].*,[PublicationCategory].[categoryid] FROM ( SELECT TOP 10 [Publication].id, [Publication].title, [Publication].content FROM Publications [Publication] ORDER BY [Publication].Id DESC ) [Publication] LEFT JOIN Categories [PublicationCategory] ON [Publication].id = [PublicationCategory].publicationid
{ "language": "en", "url": "https://stackoverflow.com/questions/49795201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I typedef unnamed struct/class in c++? In C, I can typedef unnamed (no tag) struct: typedef struct { int val; } Foo_t; But when I tried to do the same in c++: typedef struct { A(int a) : a_var(a) {} int a_var; } A; typedef struct : public A { B(int a, int b) : A(a), b_var(b) {} int b_var; } B; B &getB() { static B b(1, 2); return b; } int main() {} output: error: ISO C++ forbids declaration of β€˜A’ with no type error: only constructors take member initializers error: class β€˜<unnamed struct>’ does not have any field named β€˜A’ I know I am using constructor A(int a) of "unnamed" struct, but right after it, it is typedefed. So constructors are only available to know types A: The problem for example with this typedef declaration typedef struct { A(int a) : a_var(a) {} int a_var; } A; is that within the unnamed structure there is used undeclared name A as a name of a constructor. So this declaration is invalid. By the way the same problem exists else in C. Consider for example a typedef declaration of a structure used to define a node of a linked list. typedef struct { int data; A *next; } A; Again the name A within the structure definition is undefined. Even if you will write like typedef struct A { int data; A *next; } A; nevertheless the name A is still undeclared within the structure in C. You have to write in C typedef struct A { int data; struct A *next; } A; On the other hand, in C++ such a typedef declaration is valid. A: Yes, you can, but it's not possible to make use of the type name inside the structure, as you said. // this is valid typedef struct{ int x; void set(int n){x=n;} } A; // this is not typedef struct{ int x; B(int n){x = n;} } B; // you can only have constructor with named structs typedef struct st_C{ int x; st_C(int n){x = n;} } C; // this is valid C *foo = new C(3); A: In C, you often have to write typdefs like this: typedef struct { int val; } Foo_t; to avoid having to write struct Foo_t f; every time, which soon becomes quite tedious. In C++, all structs unions and enums declarations act as though they are implicitly typedefed. So you can declare a struct like this: struct A { A(int a) : a_var(a) {} int a_var; }; However, structs in C++ are often aggregates (a simple collection of data), and you don't need the constructors. So the following is fine: struct A { int a_var; int b_var; }; The constructor is implicitly defined by the compiler, and when you use value initialisation with braces: A a{}; all the members of the struct will be zeroed out.
{ "language": "en", "url": "https://stackoverflow.com/questions/63425162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP connecting to SQL I want to connect to sql server with php. I have a table of users but I can't connect the server. Login.php <html> <form action='LoginAction.php' method='POST'> Username: <input type='text' name='username'/><br/> Password: <input type='password' name='password'/><br/> <input type='submit' value='Login'/> </form> </html> I tryed 2 codes to LoginAction.php The First: <?php $username = $_POST['username']; $password = $_POST['password']; if ($username&&$password) { $connect = mysql_connect("myphpadmin.net", $username, $password, "my_db") or die("Couldn't connect!"); mysql_select_db("users") or die("Coulnd't find db!"); } else { die("please fill in all fields."); } ?> The second: <?php $connection=mysqli_connect("example.com",$username, $password,"my_db"); // Check connection if (mysqli_connect_errno($connection)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_close($connection); ?> Also, I created a table "users.sql" and tryed to put it in my code, and it's stull not working. Can you help me? Thanks for helpers! Edit: I think I will try do it with PDO as aldanux said, thanks for all! A: Try this PHP <?php $username = $_POST['username']; $password = $_POST['password']; if (isset($username) && isset($password)) { try { $connection = new PDO('mysql:host=localhost;dbname=dbname', $username, $password); // to close connection $connection = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ?> A: Try this maybe.... <html> <form action='LoginAction.php' method='POST'> Username: <input type='text' name='username'/><br/> Password: <input type='password' name='password'/><br/> Database: <input type='text' name='database'/><br/> <input type='submit' value='Login'/> </form> </html> And the php.... <?php $username = $_POST['username']; $password = $_POST['password']; $database = $_POST['database']; if (isset($username) && isset($password) && isset($database)) { $connect = mysql_connect("myphpadmin.net", $username, $password, $database) or die("Couldn't connect!"); mysql_select_db("users") or die("Coulnd't find db!"); } else { die("please fill in all fields."); } ?> A: In your edit you mentioned PDO, here's an example ! <?php $config['db'] = array( 'host' => 'yourHost(i.e. localhost)', 'username' => 'yourUsername', 'password' => 'yourPassword', 'dbname' => 'yourDBName' ); $db = new PDO('mysql:host=' . $config['db']['host'] . '; dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']); ?> Your login situation would be something in the likes of this: <?php include '../connection_file.php'; $username= $_GET['username']; $password = $_GET['password']; $select_query = "SELECT username, password FROM user WHERE username = :username AND password = :password"; $get_user = $db->prepare($select_query); $get_user->execute(array(':username' => $username, ':password' => $password)); $countRows = $get_user->rowCount(); if($countRows >= 1){ //The user is logged in //echo "true" or header('yourLocation') }else{ //The user doesn't exist //echo "true" or header('yourLocation') } ?> I Hope this helped ! EDIT Stupid mistake, maybe you want to encrypt the password, you can do so by doing: $password = $_GET['password']; $encrypt_password = md5($password); //As you guessed "md5" encrypts the password ;) Of course don't forget to also replace "$password" in your $get_user->execute(array) with $encrypt_password ! A: Also you can try this: $connect = mysql_connect("myphpadmin.net", $username, $password) or die("Couldn't connect!"); mysql_select_db($database, $connect) or die("Coulnd't find db!");
{ "language": "en", "url": "https://stackoverflow.com/questions/18869306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is calling a constructor faster then setting a field Mono? I'm working on implementing Mono to my C++ project and I have a C# class that holds a single integer. Something like this: public class TestClass { int number; } And I have another Class that has a field of TestClass. Something like this: public class AnotherClass { TestClass test; } Now, I have an instance of AnotherClass called instance and I want to set it's test field. Since the field can be null by default I create an instance of TestClass called testInstance, set it's number field and then set instance.test field to testInstance. However I'm wondering if it wouldn't be faster to instead give TestClass a constructor that sets the number field to a parameter it takes and then initialize testInstance with that constructor and lastly set instance.test to testInstance. So my questions is that, Is it faster to call a constructor that just sets a field from withing C# or to set that field manually from within C++ A: Performance difference should be very small in your case, It may be big when your constructor has complex code inside it or multiple fields to be set. In general, it's good to practise keeping the constructor simple and doing the object initialization inside it. When you are setting the field directly not in the constructor you are escaping from doing the things which the constructor does apart from setting this particular field. your code should be readable, easily maintainable and scalable, so chose the approach accordingly. If you are really concerned about the performance then you could do a benchmark and compare the results.
{ "language": "en", "url": "https://stackoverflow.com/questions/75193182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Behavior of decltype Say I have an object of some of stl container classes obj. I can define other object of same type this way: decltype(obj) obj2; But I can't declare iterator for the container this way: decltype(obj)::iterator it = obj.begin(); Why? Am I doing something wrong? A: It's because of the way that the language is parsed. decltype(obj)::iterator it = obj.begin(); You want it to become (decltype(obj)::iterator) it; But in actual fact, it becomes decltype(obj) (::iterator) it; I have to admit, I was also surprised to see that this was the case, as I'm certain that I've done this before. However, in this case, you could just use auto, or even decltype(obj.begin()), but in addition, you can do typedef decltype(obj) objtype; objtype::iterator it; A: Yet another workaround until VC++'s parser is fixed to reflect the FDIS is to use the std::identity<> metafunction: std::identity<decltype(obj)>::type::iterator it = obj.begin(); A: Your code is well-formed according to the final C++0x draft (FDIS). This was a late change that's not yet been implemented by the Visual Studio compiler. In the meantime, a workaround is to use a typedef: typedef decltype(obj) obj_type; obj_type::iterator it = obj.begin(); EDIT: The relevant chapter and verse is 5.1.1/8: qualified-id: [...] nested-name-specifier templateopt unqualified-id nested-name-specifier: [...] decltype-specifier :: decltype-specifier: decltype ( expression ) And for completeness's sake: The original core issue Proposal for wording
{ "language": "en", "url": "https://stackoverflow.com/questions/6101728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: VB.NET: How to compare different generic lists I have a method where I'm taking a generic object and using TypeOf to check what has been passed through. Now I would like to pass it a List(Of T) (T being anything) and no matter what T is I'd like to do the same thing to this list. I tried the following: public sub foo(ByVal obj As Object) if TypeOf obj Is List(Of Object) Then 'do stuff end if end sub but this doesn't seem to work if I pass it List(Of String), say. I suppose that List(Of Object) and List(Of String) are being treated as different objects, but I thought that since String is an object, the comparision might work. Now I realise that this is as ugly as sin and I'm better off overloading the method to take List(Of T) as its parameter, but I'm mostly asking out of curiosity: is there a way of comparing the types List(Of Object1) and List(Of Object2) and getting a positive result, since they are both just List(Of T)? A: To check if an object is of type List(of T) no matter of what type T is, you can use Type.GetGenericTypeDefinition() as in the following example: Public Sub Foo(obj As Object) If IsGenericList(obj) Then ... End If End Sub ... Private Function IsGenericList(ByVal obj As Object) As Boolean Return obj.GetType().IsGenericType _ AndAlso _ obj.GetType().GetGenericTypeDefinition() = GetType(List(Of )) End Function Or alternatively as an extension method: Public Sub Foo(obj As Object) If obj.IsGenericList() Then ... End If End Sub ... Imports System.Runtime.CompilerServices Public Module ObjectExtensions <Extension()> _ Public Function IsGenericList(obj As Object) As Boolean Return obj.GetType().IsGenericType _ AndAlso _ obj.GetType().GetGenericTypeDefinition() = GetType(List(Of )) End Function End Module A: List(Of Object) and List(Of String) are different types. You can do different things with them - for example, you can't add a Button to a List(Of String). If you're using .NET 4, you might want to consider checking against IEnumerable(Of Object) instead - then generic covariance will help you. Do you have any reason not to just make Foo generic itself? A: It's difficult to tell exactly what you're trying to accomplish. I'm pretty bad at mind reading, so I thought I'd let a few others try answering this question first. It looks like their solutions haven't been the silver bullet you're looking for, so I thought I'd give it a whack. I suspect that this is actually the syntax you're looking for: Public Sub Foo(Of T)(ByVal myList As List(Of T)) ' Do stuff End Sub This makes Foo into a generic method, and ensures that the object you pass in as an argument (in this case, myList) is always a generic list (List(Of T)). You can call any method implemented by a List(Of T) on the myList parameter, because it's guaranteed to be the proper type. There's really no need for anything as complicated as Reflection.
{ "language": "en", "url": "https://stackoverflow.com/questions/5166748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle UITableView with different cell height? each cell in my table has a label, with maximum three lines, so the cell height depends on the label's height, I know the delegate method that returns height for a specific cell(NSIndexPath), but I need to get the actual cell in order to determine the height, and if I call cellForRow:atIndexPath: in heightForCell:, it loops infinitely, I guess cellForRow also calls heightForCell. So is there any way I can handle this? Thanks! A: You can use NSStrings size for string in the heightForRow: delegate method e.g. CGSize maxSize = CGSizeMake(300, 800); //max x width and y height NSString *cellTitle = @"Lorem ipsum"; UIFont *stringFont = [UIFont systemFontOfSize:14]; // use the same font your using on the cell CGSize cellStringSize = [myString sizeWithFont:stringFont constrainedToSize:maximumSize lineBreakMode: UILineBreakModeWordWrap]; This will give you a CGSize you can then use the height from here and add a little padding. You can find more information here: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html Tim A: Use – sizeWithFont:constrainedToSize:lineBreakMode: of NSString (you can find more on this on this portal) or use an array containing height for every indexPath as shown in this example (SectionInfo class) http://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html.
{ "language": "en", "url": "https://stackoverflow.com/questions/6853419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load large data from MySQL from R I have a large table in MySQL (about 3million rows with 15 columns) and I'm trying to use some of the data from the table in an R shiny app. I've been able to get the connection and write a query in R: library(DBI) library(dplyr) cn <- dbConnect(drv = RMySQL::MySQL(), username = "user", password = "my_password", host = "host", port = 3306 ) query = "SELECT * FROM dbo.locations" However, when I run dbGetQuery(cn, query) it takes really long (I ended up closing my RStudio program after it turned unresponsive. I also tried res <- DBI::dbSendQuery (cn, query) repeat { df <- DBI::dbFetch (res, n = 1000) if (nrow (df) == 0) { break } } dbClearResult(dbListResults(cn)[[1]]) since this is similar to reading the data in by chunks, but my resulting df has 0 rows for some reason. Any suggestions on how to get my table in R? Should I even try to read that table into R? From what I understand, R doesn't handle large data very well.
{ "language": "en", "url": "https://stackoverflow.com/questions/64379624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I use CASE in JOIN condition I am getting error while using CASE in JOIN statement. Below is the query. I have masked the contents. Please let me know where I am going wrong. As it looks fine to me. Pasted the error aswell. SELECT S1.NR AS "a", S1.ZTV AS "b", S1.RNR AS "c", S1.TW AS "d", S1.STV AS "e", S1.RTV "f", S1.DA AS "v", CASE WHEN S1.ZTV = '115' THEN 'T_RR' ELSE ' ' END AS "DT", ' ' AS "SiT", S1.S1JL AS "Ns", S1.S1JM AS "Vs", S1.S1JN AS "NSv", S1.S1JO AS "VSf", S1.S1JP AS "Vse", S1.S1JQ AS "Vde", S1.S1JR AS "Vds" FROM XXXX S1 JOIN YYYYY B ON S1.S1R1TW = B.BUKSCD AND ( CASE WHEN B1.BUSX != ' ' AND S1.S1TV = B1.BTX THEN 1 WHEN S1.S1TV = B1.B2TX THEN 1 ELSE 0 END ) I am getting the below error Message: [SQL0104] Token was not valid. Valid tokens: < > = <> <= !< !> != >= Β¬< Β¬> Β¬= IN. Cause . . . . . : A syntax error was detected at token . Token is not a valid token. A partial list of valid tokens is < > = <> <= !< !> != >= Β¬< Β¬> Β¬= IN. This list assumes that the statement is correct up to the token. The error may be earlier in the statement, but the syntax of the statement appears to be valid up to this point. Recovery . . . : Do one or more of the following and try the request again: -- Verify the SQL statement in the area of the token . Correct the statement. The error could be a missing comma or quotation mark, it could be a misspelled word, or it could be related to the order of clauses. -- If the error token is , correct the SQL statement because it does not end with a valid clause. A: This is not valid SQL: CASE WHEN B1.BUSX != ' ' AND S1.S1TV = B1.BTX THEN 1 WHEN S1.S1TV = B1.B2TX THEN 1 ELSE 0 (although some databases do support it). Instead, use OR: ( (B1.BUSX <> ' ' AND S1.S1TV = B1.BTX) OR (B1.BUSX = ' ') ) I should point out that you can use CASE, but you need some comparison afterwards: (CASE WHEN B1.BUSX != ' ' AND S1.S1TV = B1.BTX THEN 1 WHEN S1.S1TV = B1.B2TX THEN 1 ELSE 0) = 1 However, I think the basic boolean operations are simpler.
{ "language": "en", "url": "https://stackoverflow.com/questions/64065052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rows not displaying properly in Tkinter GUI I'm working on setting up a GUI using TKinter creating a basic program which allows me to add, update, remove and view books that I have in my personal library. I am struggling on 2 parts of the code: * *When I click on View Records, the textbox in the GUI should show records in a list, with each item appearing on its own line. *It should also not duplicate the listings every time the button is pressed. The View Button view_records = Button(root, text="View Records", width=12, command=view_command) view_records.grid(row=3,column=3,columnspan=2,sticky='w’) def view_command(): listings.delete(0,END) # does not duplicate entries for multiple clicks for row in personal_library_backend.view(): listings.insert(END,row) # this does not list rows per index And this is my Backend Script: def insert(title, author, genre, year): conn=sqlite3.connect("library.db") cur=conn.cursor() cur.execute("INSERT INTO books VALUES (NULL,?,?,?,?)",(title,author,genre,year)) conn.commit() conn.close() def view(): conn=sqlite3.connect("library.db") cur=conn.cursor() cur.execute("SELECT * FROM books") rows=cur.fetchall() conn.close() return rows When I run the program, I keep getting an error that says "bad text index 0" on the view_command function. I can't seem to figure it out. Can someone point me in the right direction? A: Index of text widget should be in one of these formats (i.e "line.column" or tk.END etc.) and your 0 doesn't fit in to any of those. You should change delete line to: listings.delete("1.0", "end") #you can use END instead of "end" to delete everything in text widget. And to make each row appear on new line, simply insert a new line manually after instering row. for row in personal_library_backend.view(): listings.insert("end", row) listings.insert("end","\n") #there is an extra new line at the end, you can remove it using txt.delete("end-1c", "end")
{ "language": "en", "url": "https://stackoverflow.com/questions/42265024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Partitioning a JSP page accessed through an ajax call I have a page in which I am making an ajax call, which in turn gets forwarded to a jsp page and returns a table constructed in this jsp. Till now this jsp used to return an html which the original page(table) used to append in a particular div. But now, we have a requirement that this jsp along with the table, returns some other info about the metadat of the query. With this change, I would ideally not like to change the existing behaviour of some clients where they are just appending the html. But then, is there a way, in which the new pages which make this call can have both the html table(which can be appended) as well as metadata returned (which can be processed). let me know if the question isn't clear enough. Thanks! A: The easiest and least destructive change would be to send it as response header. In the servlet you can use HttpServletResponse#setHeader() to set a response header: response.setHeader("X-Metadata", metadata); // ... (using a header name prefixed with X- is recommended for custom headers) In JS you can use XMLHttpRequest#getResponseHeader() to get a response header: var metadata = xhr.getResponseHeader('X-Metadata'); // ... You can even set some JSON string in there so that (de)serialization is easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/6249814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does greasemonkey on firefox support @match? I want to use the @match directive but do not want to break compatibility with greasemonkey. Also, as unbelievable as it may seem, I don't have firefox installed on my system and thus can't test this myself. A: Older versions of Greasemonkey will ignore the @match directive, but will not break. For maximum compatibility, use the @include and @exclude directives to control where/when a script runs. Update: As of Greasemonkey 0.9.8, GM fully supports the @match directive.
{ "language": "en", "url": "https://stackoverflow.com/questions/6786613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Split cell value into two columns in Excel In Column A I have values as follows: A1: 1234567890;1234567890;1234567890;1234567890;1234567890;1234567890; A2: 1234567890;1234567890 A3: 1234567890;1234567890;1234567890; Now I want to store value after 33rd character or third semi-colon into the separate B column. Result: Column A (Result should be) A1: 1234567890;1234567890;1234567890; A2: 1234567890;1234567890 A3: 1234567890;1234567890;1234567890; Column B (Result should be) A1: 1234567890;1234567890;1234567890; A2: A3: Note In Column B A2 & A3 are blank as they are less than 33 character. A: You can use Text_to_column tool in DATA tab of the excel sheet.. When the dialog box appears * *select the Fixed Width radio button and click next *Then select the range you want to split.. *Then next and Finish.. You will get the required output..
{ "language": "en", "url": "https://stackoverflow.com/questions/21574939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Hibernate problems with Postgres on TomEE i'm working on a WebApp, written in Java running on TomEE. As persistence layer i'm using Hibernate. Persistence.xml is configured, The entityManager is instantiated by TomEE using @PersistenceContext(name = "persistentUnitJndi", unitName = "docTracingPU") in a @Stateless(name = "utenteFacade", mappedName = IUtente.MAPPED_NAME) EJB. It seems to work fine, but all queries returns an empty result (empty list). The DB is PostrgeSQL, i tried 8.4 and also 9.2 but the result is always the same. I put on the logging on the postrges (postgresql.conf) where i read only Could not receive data from client: Unknown winsock error 10061. I tried switching off antivirus and/or firewall....nothing changes. What to do? EDIT: I tried the same project on a Win8.1 machine. Here i get user lacks privilege or object not found A: I found: * *hibernate.cfg.xml is not neede *only persistence.xml and tomee.xml are required I give you my example: <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="docTracingPU" transaction-type="JTA"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:comp/env/jdbc/docTracing</jta-data-source> <non-jta-data-source>java:comp/env/jdbc/docTracing</non-jta-data-source> <class>com.emaborsa.doctracing.core.persistentobject.UtentePO</class> <properties> <property name="hibernate.hbm2ddl.auto" value="validate" /> <property name="hibernate.transaction.flush_before_completion" value="true"/> <property name="hibernate.transaction.auto_close_session" value="true"/> <property name="hibernate.transaction.manager_lookup_class" value="org.apache.openejb.hibernate.TransactionManagerLookup" /> <property name="hibernate.transaction.flush_before_completion" value="true"/> <property name="hibernate.transaction.auto_close_session" value="true"/> <!-- Print SQL to stdout. --> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> </properties> </persistence-unit> <?xml version="1.0" encoding="UTF-8"?> <tomee> <Resource id="docTracingPU" type="DataSource"> JdbcDriver org.postgresql.Driver JdbcUrl jdbc:postgresql://127.0.0.1:5432/myDb UserName **** Password **** JtaManaged false TestWhileIdle true InitialSize 5 </Resource> <Resource id="docTracingPU" type="DataSource"> JdbcDriver org.postgresql.Driver JdbcUrl jdbc:postgresql://127.0.0.1:5432/myDb UserName ***** Password ***** JtaManaged true TestWhileIdle true InitialSize 5 </Resource> </tomee>
{ "language": "en", "url": "https://stackoverflow.com/questions/19051180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Procedural Approach into Set Based Approach in Sql-Server We are using procedural approach (while loop) for inserting records into a particular table. the insert syntax is like below, DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01', @FLAG INT CREATE TABLE #Tmpdata (officeId int,id smallint, weekDate date,startsOn varchar(10),endsOn varchar(10),flag bit); WHILE (@CNT <7) BEGIN SET @WEEK = DATEADD(D,@CNT,@WEEK ) IF EXISTS (SELECT 1 FROM YEARRANGE WHERE @WEEK BETWEEN CONVERT(DATE,taxseasonbegin) AND CONVERT (DATE,taxSeasonEnd) ) BEGIN SET @FLAG =1 END ELSE BEGIN SET @FLAG = 0 END INSERT INTO #Tmpdata ( officeId,id,weekDate,startsOn,endsOn,flag ) VALUES ( 5134,@lvCounter,@week,'09:00 AM','05:00 PM',@flag ); SET @cnt=@cnt+1; end (NOTE : TaxSeason is from january to august). Is it possible to re-write the above logic in set based approach? A: Please can you provide sample data? You can do something like: SELECT DateIncrement = SUM(DATEADD(D,@CNT,@WEEK)) OVER (ORDER BY officeID) FROM... This gets an incremented date value for each record which you can then check against your start and end dates. A: This is making a number of assumption because you didn't post ddl or any consumable sample data. Also, there is a variable @lvCounter not defined in your code. This is perfect opportunity to use a tally or numbers table instead of a loop. declare @lvCounter int = 42; DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01', @FLAG INT; WITH E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)) , cteTally(N) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1 ) select 5134 as officeId , @lvCounter as Id , DATEADD(DAY, N - 1, @WEEK) as weekDate , '09:00 AM' as startsOn , '05:00 PM' as EndOn , Flag from cteTally t cross apply ( select CAST(count(*) as bit) as Flag from YearRange where DATEADD(Day, t.N, @WEEK) > CONVERT(DATE,taxseasonbegin) AND DATEADD(Day, t.N, @WEEK) <= CONVERT (DATE,taxSeasonEnd) ) y where t.N <= 7; A: You could try some Kind of this one. This gives you the data I think you Need for your insert. I do not have a table named YEARRANGE so I couldn't test it completely DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01', @FLAG INT; CREATE TABLE #Tmpdata (officeId int,id smallint, weekDate date,startsOn varchar(10),endsOn varchar(10),flag bit); WITH CTE AS ( SELECT num AS cnt, DATEADD(D, SUM(num) OVER(ORDER BY num ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) , @WEEK) AS [week] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY nl) -1 AS num FROM (SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl UNION ALL SELECT NULL AS nl ) AS ni ) AS no ) INSERT INTO #Tmpdata (officeId,id,weekDate,startsOn,endsOn,flag) SELECT 5134 AS officeID, cnt AS id, [week],'09:00 AM' AS startsOn,'05:00 PM' AS endsOn, COALESCE(A1.flag,0) AS flag FROM CTE OUTER APPLY (SELECT 1 FROM YEARRANGE WHERE [week] BETWEEN CONVERT(DATE,taxseasonbegin) AND CONVERT (DATE,taxSeasonEnd) ) AS A1(flag);
{ "language": "en", "url": "https://stackoverflow.com/questions/33523186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: System.IO.EndOfStreamException when scaffolding Npgsql.EntityFrameworkCore.PostgreSQL database I am trying to scaffold an existing Postgres database with the following command dotnet ef dbcontext scaffold "<connection string>" Npgsql.EntityFrameworkCore.PostgreSQL -v Which results in the exception below: Npgsql.NpgsqlException (0x80004005): Exception while reading from stream ---> System.IO.EndOfStreamException: Attempted to read past the end of the stream. at Npgsql.Internal.NpgsqlReadBuffer.g__EnsureLong|41_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications) at Npgsql.Internal.NpgsqlReadBuffer.g__EnsureLong|41_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications) at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt) at Npgsql.Internal.NpgsqlConnector.g__OpenCore|191_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt) at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) at Npgsql.ConnectorPool.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) at Npgsql.ConnectorPool.g__RentAsync|28_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlConnection.g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlConnection.Open() at Npgsql.EntityFrameworkCore.PostgreSQL.Scaffolding.Internal.NpgsqlDatabaseModelFactory.Create(DbConnection dbConnection, DatabaseModelFactoryOptions options) at Npgsql.EntityFrameworkCore.PostgreSQL.Scaffolding.Internal.NpgsqlDatabaseModelFactory.Create(String connectionString, DatabaseModelFactoryOptions options) at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions) at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable1 schemas, IEnumerable1 tables, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable1 schemaFilters, IEnumerable1 tableFilters, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluarlize) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) I'm using Npgsql.EntityFrameworkCore.PostgreSQL on version 6.0.7 Can anyone help? I've searched and can't find a solution to this problem A: I had the same problem. I check my projects dependencies in my solution. I deleted extra and unused dependencies and then, I made the version used for each dependency the same in all projects and the problem solved! My be it works for you, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/73288745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Relational Database Can you do more than one clause in SQL without using aggregation and only: selection, join? Thanks. A: If you mean having multiple WHERE's (ands), then yes. SELECT user.id, post.title FROM user LEFT JOIN post ON (post.user = user.id) WHERE (post.title LIKE '%Monkeys%') AND (user.id > 3) AND (user.id < 20)
{ "language": "en", "url": "https://stackoverflow.com/questions/993660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking if my array of pointer string is an integer EDIT -> My problem with finding if was an integer got solved. My next problem is how to get the size of the array. Example: char **str = [hello][world] -> returns 2 char **str = [hello] -> return 1 char **str = [hello][world][yes] -> returns 3 The way I am doing right now. It's wrong int size = sizeof(str) / sizeof(str[0]); I also tried int size = sizeof(str) / sizeof(char *); ..... I have a program that gets a line from the user like "Hello World". Then I parse that into an array of pointers: so it's something like char **str = [Hello][World]. Then I want to check if the second index is an integer or not. So if the user types Hello 2, this function returns true (1), but if not returns false(0). I am a little confused how to work with pointers. So I think I will have something like this: int my_function(char** str) { // it's empty if (str[0] == NULL) return 0; // Just have one index int size = sizeof(str) / sizeof(str[0]); if (size < 1) { return 0; } // checking if data in second index is an integer int length = strlen(str[1]); for (int i = 0; i < length; i++) { // Here is my problem how do I go over each character for // only str[1] to check if is an integer??????? if (!isdigit(str)) { return 0; } } return 1; } A: You need a double dereference. The first dereference to get the relevant char pointer. The second dereference to get the relevant character. Try: isdigit(str) --> isdigit(str[1][i]) A: Try following, char *secondString = str[1]; int length = strlen(secondString ); for (int i = 0; i < length ; ++i) { if (!isdigit(secondString[i])) return 0; } return 1;
{ "language": "en", "url": "https://stackoverflow.com/questions/69378802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploy create-react-app-typescript on Google App Engine I am triying to deploy an application created using CRA with Typescript into the Google Cloud App Engine service, however, for some reason, the appspot link keeps loading forever until a 502 Bad Gateway appears (the error appears sometimes, normally it just keeps loading..) I've already checked several tutorials and questions without success. * *Deploy create-react-app on Google App Engine *https://medium.com/tech-tajawal/deploying-react-app-to-google-app-engine-a6ea0d5af132 The app.yaml is the following: env: flex runtime: nodejs handlers: - url: /static/js/(.*) static_files: build/static/js/\1 upload: build/static/js/(.*) - url: /static/css/(.*) static_files: build/static/css/\1 upload: build/static/css/(.*) - url: /static/media/(.*) static_files: build/static/media/\1 upload: build/static/media/(.*) - url: /(.*\.(json|ico))$ static_files: build/\1 upload: build/.*\.(json|ico)$ - url: / static_files: build/index.html upload: build/index.html - url: /.* static_files: build/index.html upload: build/index.html env_variables: REACT_APP_DEV_API_URL: "......" REACT_APP_MAP_API_KEY: "........" # [END app_yaml] Logs of the app engine (It seems it's calling the 'npm run start' command each time I open a page) Of course, my application works fine in dev mode and also it doesn't seem to be any problem in the deployment logs. If someone has experienced this problem before, please let me know how to solve it. Thanks in advance. package.json: { "name": "testing-app", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "@types/google-map-react": "^1.1.5", "@types/jest": "^24.0.0", "@types/lodash": "^4.14.149", "@types/node": "^12.0.0", "@types/react": "^16.9.0", "@types/react-dom": "^16.9.0", "@types/react-helmet": "^5.0.15", "@types/react-router-dom": "^5.1.3", "@types/styled-components": "^5.0.0", "@types/swiper": "^5.2.1", "axios": "^0.19.2", "google-map-react": "^1.1.6", "lodash.differenceby": "^4.8.0", "lodash.throttle": "^4.1.1", "prop-types": "^15.7.2", "react": "^16.12.0", "react-circular-progressbar": "^2.0.3", "react-dom": "^16.12.0", "react-id-swiper": "^3.0.0", "react-router-dom": "^5.1.2", "react-scripts": "3.3.0", "semantic-ui-react": "^0.88.2", "styled-components": "^5.0.1", "swiper": "^5.3.6", "typescript": "~3.7.2" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^2.14.0", "@typescript-eslint/parser": "^2.14.0", "cross-env": "^6.0.3", "eslint": "^6.8.0", "eslint-config-airbnb": "^18.0.1", "eslint-config-airbnb-base": "^14.0.0", "eslint-config-prettier": "^6.9.0", "eslint-config-react-app": "^5.1.0", "eslint-plugin-import": "^2.19.1", "eslint-plugin-jsx-a11y": "^6.2.3", "eslint-plugin-prettier": "^3.1.2", "eslint-plugin-react": "^7.17.0", "eslint-plugin-react-hooks": "^2.3.0", "gh-pages": "^2.2.0", "jest": "^24.9.0", "lint-staged": "^9.5.0", "pre-commit": "^1.2.2", "prettier": "^1.19.1" }, "lint-staged": { "*.js": [ "npm run lint:eslint:fix", "git add --force" ], "*.json": [ "prettier --write", "git add --force" ] }, "pre-commit": "lint:staged", "resolutions": { "serialize-javascript": "^2.1.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "build:clean": "rimraf ./build", "test": "react-scripts test", "eject": "react-scripts eject", "lint:staged": "lint-staged", "lint:eslint": "eslint --ignore-path .gitignore", "lint:eslint:fix": "eslint --ignore-path .gitignore --fix", "prettify": "prettier --write" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } The project structure is the typical CRA with containers-components (Ignore the nginx.conf and dockerfile which I was using for testing another way with Gcloud run at the time of the photo) Edit: Added project structure and package.json A: Solved (May 18, 2020) I changed my approach and go for a custom runtime and it worked out. Here is the configuration I used if anyone encounter this problem in the future. Change the runtime to custom in the App.yaml <!-- language: lang-html --> env: flex runtime: custom And include a Dockerfile with a nginx.conf for the runtime management Dockerfile: FROM node:8-alpine as react-build WORKDIR /app COPY . ./ RUN npm install RUN npm run build # server environment FROM nginx:alpine COPY nginx.conf /etc/nginx/conf.d/configfile.template ENV PORT 8080 ENV HOST 0.0.0.0 RUN sh -c "envsubst '\$PORT' < /etc/nginx/conf.d/configfile.template > /etc/nginx/conf.d/default.conf" COPY --from=react-build /app/build /usr/share/nginx/html EXPOSE 8080 CMD ["nginx", "-g", "daemon off;"] nginx.conf server { listen $PORT; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri /index.html; } gzip on; gzip_vary on; gzip_min_length 10240; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml; gzip_disable "MSIE [1-6]\."; } This configuration appears in one of the tutorials here: https://cloud.google.com/community/tutorials/deploy-react-nginx-cloud-run Thank you to @Nibrass H for suggesting some possible solutions.
{ "language": "en", "url": "https://stackoverflow.com/questions/61586978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Graph/Plots on ANDROID I am new to android and trying to learn creation or plotting of graphs in android. I've come across 2 libraries: * *GraphView *AndroidPlot. My intent would be to receive some sound file and plot it on a graph. So, for this purpose which library would be better. Also I wanna know, where I can see the complete implementation or definitions of these libraries i.e. the structure and code for the API's used in the above libraries. Also I have tried some sample codes available on net. But I'm looking for a more sophiticated code which I could develop on eclipse ADT and hence can learn something out of it. A: My intent would be to receive some sound file and plot it on a graph Neither library does this by default. The libraries are used to plot a graph given a set of data points. Getting the data points from the sound file is up to you. So, for this purpose which library would be better. Either library should be fine once you get the data points. Also I wanna know, where I can see the complete implementation or definitions of these libraries i.e. the structure and code for the API's used in the above libraries. Check out the sources for GraphView and AndroidPlot. A: I have used Achartengine some times and it works great. I modified it without difficulties. A: If You are drawing simple Line Graph using canvas to draw the graph. A: Use AndroidPlot. This code draw the content of Vector(in this case filled of zeros). You only have to pass the info of the wav file to the vector. And you can check this thread for the reading issue. Android: Reading wav file and displaying its values plot = (XYPlot) findViewById(R.id.Grafica); plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 0.5); plot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1); plot.getGraphWidget().getGridBackgroundPaint().setColor(Color.rgb(255, 255, 255)); plot.getGraphWidget().getDomainGridLinePaint().setColor(Color.rgb(255, 255, 255)); plot.getGraphWidget().getRangeGridLinePaint().setColor(Color.rgb(255, 255, 255)); plot.getGraphWidget().setDomainLabelPaint(null); plot.getGraphWidget().setRangeLabelPaint(null); plot.getGraphWidget().setDomainOriginLabelPaint(null); plot.getGraphWidget().setRangeOriginLabelPaint(null); plot.setBorderStyle(BorderStyle.NONE, null, null); plot.getLayoutManager().remove(plot.getLegendWidget()); plot.getLayoutManager().remove(plot.getDomainLabelWidget()); plot.getLayoutManager().remove(plot.getRangeLabelWidget()); plot.getLayoutManager().remove(plot.getTitleWidget()); //plot.getBackgroundPaint().setColor(Color.WHITE); //plot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE); plot.setRangeBoundaries(-25, 25, BoundaryMode.FIXED);// check that, these //boundaries wasn't for audio files InicializarLasVariables(); for(int i=0; i<min/11;i++){ DatoY=0; Vector.add(DatoY); } XYSeries series = new SimpleXYSeries(Vector, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,""); LineAndPointFormatter seriesFormat = new LineAndPointFormatter(Color.rgb(0, 0, 0), 0x000000, 0x000000, null); plot.clear(); plot.addSeries(series, seriesFormat);
{ "language": "en", "url": "https://stackoverflow.com/questions/17398247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Installing AppFabric in Windows 10 I have tried installing AppFabric multiple times on Windows 10 Pro as an administrator. I have read many posts related to it. Somewhere it is mentioned to delete AS_OBSERVER or delete PSModulePath. I have tried both but still I couldn't able to install. The error log is as follows: 2015-11-12 10:26:44, Information Setup ===== Logging started: 2015-11-12 10:26:44-08:00 ===== 2015-11-12 10:26:44, Information Setup File: c:\4edb67880c60dcfa5814780a9bd89e\setup.exe 2015-11-12 10:26:44, Information Setup InternalName: Setup.exe 2015-11-12 10:26:44, Information Setup OriginalFilename: Setup.exe 2015-11-12 10:26:44, Information Setup FileVersion: 1.1.2106.32 2015-11-12 10:26:44, Information Setup FileDescription: Setup.exe 2015-11-12 10:26:44, Information Setup Product: Microsoft(R) Windows(R) Server AppFabric 2015-11-12 10:26:44, Information Setup ProductVersion: 1.1.2106.32 2015-11-12 10:26:44, Information Setup Debug: False 2015-11-12 10:26:44, Information Setup Patched: False 2015-11-12 10:26:44, Information Setup PreRelease: False 2015-11-12 10:26:44, Information Setup PrivateBuild: False 2015-11-12 10:26:44, Information Setup SpecialBuild: False 2015-11-12 10:26:44, Information Setup Language: Language Neutral 2015-11-12 10:26:44, Information Setup 2015-11-12 10:26:44, Information Setup OS Name: Windows 10 Pro 2015-11-12 10:26:44, Information Setup OS Edition: Professional 2015-11-12 10:26:44, Information Setup OSVersion: Microsoft Windows NT 6.2.9200.0 2015-11-12 10:26:44, Information Setup CurrentCulture: en-US 2015-11-12 10:26:44, Information Setup Processor Architecture: AMD64 2015-11-12 10:26:44, Information Setup Event Registration Source : AppFabric_Setup 2015-11-12 10:26:44, Information Setup 2015-11-12 10:26:44, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : Initiating V1.0 Upgrade module. 2015-11-12 10:26:44, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : V1.0 is not installed. 2015-11-12 10:26:54, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : Initiating V1 Upgrade pre-install. 2015-11-12 10:26:54, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : V1.0 is not installed, not taking backup. 2015-11-12 10:26:54, Information Setup Executing C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe with commandline -iru. 2015-11-12 10:26:54, Information Setup Return code from aspnet_regiis.exe is 0 2015-11-12 10:26:54, Information Setup Process.Start: C:\WINDOWS\system32\msiexec.exe /quiet /norestart /i "c:\4edb67880c60dcfa5814780a9bd89e\Microsoft CCR and DSS Runtime 2008 R3.msi" /l*vx "C:\Users\MAshhad\AppData\Local\Temp\AppServerSetup1_1(2015-11-12 10-26-54).log" 2015-11-12 10:26:55, Information Setup Process.ExitCode: 0x00000000 2015-11-12 10:26:55, Information Setup Windows features successfully enabled. 2015-11-12 10:26:55, Information Setup Process.Start: C:\WINDOWS\system32\msiexec.exe /quiet /norestart /i "c:\4edb67880c60dcfa5814780a9bd89e\Packages\AppFabric-1.1-for-Windows-Server-64.msi" ADDDEFAULT=Worker,WorkerAdmin,CacheService,CacheClient,CacheAdmin,Setup /l*vx "C:\Users\MAshhad\AppData\Local\Temp\AppServerSetup1_1(2015-11-12 10-26-55).log" LOGFILE="C:\Users\MAshhad\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2015-11-12 10-26-55).log" INSTALLDIR="C:\Program Files\AppFabric 1.1 for Windows Server" LANGID=en-US 2015-11-12 10:27:18, Information Setup Process.ExitCode: 0x00000643 2015-11-12 10:27:18, Error Setup AppFabric installation failed because installer MSI returned with error code : 1603 2015-11-12 10:27:18, Error Setup 2015-11-12 10:27:18, Error Setup AppFabric installation failed because installer MSI returned with error code : 1603 2015-11-12 10:27:18, Error Setup 2015-11-12 10:27:19, Information Setup Microsoft.ApplicationServer.Setup.Core.SetupException: AppFabric installation failed because installer MSI returned with error code : 1603 2015-11-12 10:27:19, Information Setup at Microsoft.ApplicationServer.Setup.Installer.WindowsInstallerProxy.GenerateAndThrowSetupException(Int32 exitCode, LogEventSource logEventSource) 2015-11-12 10:27:19, Information Setup at Microsoft.ApplicationServer.Setup.Installer.WindowsInstallerProxy.Invoke(LogEventSource logEventSource, InstallMode installMode, String packageIdentity, List`1 updateList, List`1 customArguments) 2015-11-12 10:27:19, Information Setup at Microsoft.ApplicationServer.Setup.Installer.MsiInstaller.InstallSelectedFeatures() 2015-11-12 10:27:19, Information Setup at Microsoft.ApplicationServer.Setup.Installer.MsiInstaller.Install() 2015-11-12 10:27:19, Information Setup at Microsoft.ApplicationServer.Setup.Client.ProgressPage.StartAction() 2015-11-12 10:27:19, Information Setup 2015-11-12 10:27:19, Information Setup === Summary of Actions === 2015-11-12 10:27:19, Information Setup Required Windows components : Completed Successfully 2015-11-12 10:27:19, Information Setup IIS Management Console : Completed Successfully 2015-11-12 10:27:19, Information Setup Microsoft CCR and DSS Runtime 2008 R3 : Completed Successfully 2015-11-12 10:27:19, Information Setup AppFabric 1.1 for Windows Server : Failed 2015-11-12 10:27:19, Information Setup Hosting Services : Failed 2015-11-12 10:27:19, Information Setup Caching Services : Failed 2015-11-12 10:27:19, Information Setup Cache Client : Failed 2015-11-12 10:27:19, Information Setup Hosting Administration : Failed 2015-11-12 10:27:19, Information Setup Cache Administration : Failed 2015-11-12 10:27:19, Information Setup Microsoft Update : Skipped 2015-11-12 10:27:19, Information Setup Microsoft Update : Skipped 2015-11-12 10:27:19, Information Setup 2015-11-12 10:27:19, Information Setup ===== Logging stopped: 2015-11-12 10:27:19-08:00 ===== A: Windows 10 Installation * * * *Make sure you have both "remote registry" and "windows update service" installed. * *If you have previously attempted an install, you may have a couple of groups marked as AS_ in your user manager, make sure you delete these "AS_XXXX" -- delete these. I found that I would still get a 1603 after attempting again. * *Run your installation and you should get success.
{ "language": "en", "url": "https://stackoverflow.com/questions/33676265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python 2.7 Using a FOR Loop Hey guys basically Im trying to use a FOR loop to ask the username of the actor and actress to search for and printing out if that certain actor is in the movie as well as printing if they are not in the movie. Im very stuck so far and do not know how to ask my code for my actors print ("Which actor/actress you want to look for?") actors [] for actor in actors: If actor == actors: print ("Yes, %s is in the show breaking bad") (actors,) break else: print ( "NO , %s is not in the show breaking bad") (actors,) print actor A: Looks like you have the basic idea, but your code is all over the place. Try something like: search_name = raw_input('Please enter the actor to search for: ') actors = ['Idris Elba', 'Dwayne Johnson', 'Mel Brooks'] if search_name in actors: print search_name + 'is in the movie!' else: print search_name + 'is NOT in the movie!' If you want to continue asking until the input is a name in the list, use a loop: search_name = raw_input('Please enter the actor to search for: ') actors = ['Idris Elba', 'Dwayne Johnson', 'Mel Brooks'] while search_name not in actors: print search_name + 'is NOT in the movie!' search_name = raw_input('Please enter a different actor's name:') print search_name + 'is in the movie!'
{ "language": "en", "url": "https://stackoverflow.com/questions/40592407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CallbackFilterIterator and Prime numbers generation issue I'm trying to use the PHP \CallbackFilterIterator working in a script that prints Prime numbers. Basically what I'm trying to achieve is a very basic Sieve of Eratosthenes, see this nice video from Computerphile. Here's the simplified version of the code <?php /** * Run this code with: php -n to make sure no configuration will be used * so xdebug will not be used either. */ declare(strict_types=1); function llist($n = 2) { yield $n; return yield from llist($n + 1); } $callback = fn(int $p) => fn(int $a, int $b, Iterator $it): bool => $a % $p !== 0; $i = 0; $iterator = llist(); while (true) { $prime = $iterator->current(); $iterator->next(); var_dump($prime); if ($i++ > 100) { break; } $iterator = new CallbackFilterIterator( $iterator, $callback($prime) ); } (also available on Gist: https://gist.github.com/drupol/8a1ff3c4d5ccbb56a1e45823677a9b38) The script generate first an integer Iterator (from 2 to infinity), then, at each loop the iterator is overridden with a new \CallbackFilterIterator and a new filter callback. This script should print out Prime numbers, starting with 2, but after printing 2 for some unknown reasons yet, it end up with a Fatal error: $ php -n primes.php int(2) NULL PHP Fatal error: Uncaught TypeError: Argument 1 passed to {closure}() must be of the type int, null given, called in /home/pol/dev/git/primes.php on line 32 and defined in /home/pol/dev/git/primes.php:15 Stack trace: #0 /home/pol/dev/git/primes.php(32): {closure}() #1 {main} thrown in /home/pol/dev/git/primes.php on line 15 I don't know yet what I'm doing wrong, this is why I'm posting my message here, any clue is welcome. A: The answer is to move the call to next() under the new CallbackFilterIterator. Here's the final version: https://gist.github.com/drupol/8513c7bfdbe1ad7d66fa710f51a21b32 Thanks @jeto !
{ "language": "en", "url": "https://stackoverflow.com/questions/63672136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is Chrome issuing a "Confirm Form Resubmission" even when I'm using the PRG pattern? After processing a POST request I am doing the very standard thing of redirecting to the same page so that the user won't get a "Confirm Form Resubmission" (or equivalent) dialog if they reload the page. I am using a 303 response status code. Here's the code: header( "HTTP/1.1 303 See Other" ); header( "Location: " . $_SERVER['REQUEST_URI'] ); exit(); This works as expected in Safari and FF. Chrome pops up the "Confirm Form Resubmission" dialog. In Chrome I can use the network inspector to see that the 303 redirect is indeed issued and there is a GET following my initial POST. Yet if I try to reload the page at that point I get the "Confirm Form Resubmission". If I modify the URL by adding a spurious query param, this does not happen. That is... header( "HTTP/1.1 303 See Other" ); header( "Location: " . $_SERVER['REQUEST_URI'] . '?foo' ); exit(); ...works just fine. Is Chrome trying to be too clever and short-cutting the reload of the same page? Or is this a known issue? I've spent some time looking around, but aside from a million cases of people just needing to use the PRG pattern, nothing. A: This seems to be a bug in Chrome 25. I tested it in virtualbox with Chrome 24 and updated to Chrome 25. Chrome 24 => No dialog Chrome 25 => Dialog Maybe you should file a bug. :-) A: You can try proxy-redirect to script with different URI if ($_SERVER['REQUEST_METHOD'] == 'POST') { header('Location: proxy.php?uri='.$_SERVER['REQUEST_URI'], true, 303); } then come back # proxy.php if (!empty($_GET['uri'])) { // maybe some validation here header('Location: '.$_GET['uri'], true, 303); } A: When a user tries to restore the pages which have been unexpectedly shut down, then the browser will display this error 'err_cache_miss'. Watch the video proof for main source of the error https://www.youtube.com/watch?v=6c9ztzqlthE A: this will help you more better way just put this in any file that include all files header("Cache-Control: no-cache, must-revalidate"); if not then try this session_cache_limiter('private, must-revalidate'); session_cache_expire(60);
{ "language": "en", "url": "https://stackoverflow.com/questions/15036267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Troubles with Xdebug 2.1.0, XAMPP 1.7.3, Win7 32bit Looking for some help with getting xdebug to behave with my setup. My goal is to be able to debug Joomla code. First let me preface saying that about a year ago I was able to get a version xdebug to work with Eclipse PDT 2.1 with xampp under Vista 32bit. However, now I'm on a new machine, and I wanted to get everything working with the latest versions. I did so by following through this walk-through. Now, trying to do the same thing I can't get it to work. First, as per the walk-through, I downloaded php_xdebug-2.0.0-5.2.2.dll. Quickly realized that I needed an xdebug for php 5.3. So, I found the xdebugs Tailored Installation Instructions and followed that. My php.ini section looks as thus: [XDebug] ;; Only Zend OR (!) XDebug zend_extension = "D:\xampp\php\ext\php_xdebug-2.1.0-5.3-vc6.dll" xdebug.remote_enable=true xdebug.remote_host=localhost xdebug.remote_port=10000 xdebug.remote_handler=dbgp xdebug.profiler_enable=1 xdebug.profiler_output_dir="D:\xampp\tmp" So this got the xdebug to actually show up in the phpinfo(). But, in Eclipse when I Debug As Php Webpage, it at first appears to connect, however if I step to the next line of code the debugger just sits there saying it is stepping, indefinitely. Sometimes apache will crash. I tried ports 9000, and 10000 with no avail. What I did find out is, if I use the the php_xdebug.dll that comes with XAMPP 1.7.3, I actually can connect and step without any issues, EXCEPT, that version of xdebug apparently has a major bug in it that causes all my variables to be listed as 'Uninitialized'. So it is basically useless, however, it does give some hope that I have some of this stuff set up correctly. So, my current setup thus: Win7 32bit, XAMPP 1.7.3 (PHP 5.3.1, Apache 2.2.14), Eclipse PDT 2.2 I have very limited experience with basically all the tools here so I'm kinda at a loss of what to do. Any help would be greatly appreciated. I searched some of the other posts here with similar issue but most of them appear to be for older versions of these components. A: your report is somewhat confusing. As far as I understand you, your setup works as soon as you replace the XDebug-dll. Then your (primary) problem cannot be related to your settings, as far as you also adjusted zend_extension, of course. Though xdebug.remote_port=10000 seems odd. Std is 9000. If you use 9000, the you have to tell Eclipse in Window/Preferences/PHP/Debug/Debuggers to also listen to that port for XDebug. Best Raffael
{ "language": "en", "url": "https://stackoverflow.com/questions/4630327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net Core Razor Pages Post From _layout What i'm trying to do is change the theme of the application using a check box that is populated as dark or light from the server's session. I know the theme (Style Sheet) can be changed with JavaScript but that leads to loading the default Bootstrap Style Sheet then the dark one which causes the screen to flicker. What I need to do is return the css from the server thought a post method like below. <div> <form id="theme-switcher" method="post"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" asp-for="IsDark" id="theme" /> <label class="custom-control-label" for="theme">Theme</label> </div> <button id="change" type="submit" class="btn btn-primary">Change</button> </form> </div> The code above can be in a view component or a partial view but I can not seem to find a way to post the from. _Layout.cshtml @{ bool isDark = HttpContext.HttpContext.Session.GetBoolean("IsDark"); } <!-- Custom styles --> @if (CultureInfo.CurrentUICulture.Name == "ar-LB") { if (isDark) { <link rel="stylesheet" type="text/css" href="~/css/site-dark-rtl.css"> } else { <link rel="stylesheet" type="text/css" href="~/css/site-rtl.css"> } } else { if (isDark) { <link rel="stylesheet" type="text/css" href="~/css/site-dark.css"> } else { <link rel="stylesheet" type="text/css" href="~/css/site.css"> } } What I've tied so far is partial views and view components but as far as I've found partial views can not have code behind with OnPost (when adding @page to the partial view I get view data can not be null although the model and the view data are set) and view components can not call methods. What approach should I use ? A: You can post to different routes, regardless of where you currently are. So assuming you have a Razor page SwitchTheme.cshtml with a code-behind that switches the theme on POST, then you can adjust your <form> tag to post to that page: <form asp-page="/SwitchTheme" method="post"> <!-- … --> </form> Note the use of the asp-page tag helper to generate the action attribute with a link to the page. For changing things like the design, which doesn’t directly have some page content you want to display, you could also use a simple controller that makes the change and then redirects back. Then, you would use the asp-action and asp-controller tag helpers instead: <form asp-controller="Utility" asp-action="SwitchTheme" asp-route-returnUrl="@Context.Request.Path" method="post"> <!-- … --> </form> public class UtilityController : ControllerBase { [HttpPost] public IActionResult SwitchTheme([FromForm] bool isDark, string returnUrl) { // switch the theme // redirect back to where it came from return LocalRedirect(returnUrl); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/60157396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Class based components or anonymous components? From the docs you can make two types of components. I'm struggling to see why you would pick one over the other? As with anonymous components, you can declare data with @props. Why would you use one implementation over the other? A: Class base components can be thought of as being some sort of controller (invokable kind). When there's a need for accessing a service out of the service container and process the data received as props - class based components can handle it. In class based component, any service from Laravel's container can be injected via the constructor. For example: Say you are defining a component to show the total before tax, discount, tax and then the final grand total. A service can be defined to lookup the tax rates and perform tax and discount calculations with specific formulae and then this service can be injected via the components constructor - anonymous component won't be a good fit here. On the other hand say there's need to define a component for alert, the data required to be passed to the alert component would be message & type of alert. Then based on type of alert the colouring of alert component can be adjusted. Here there's no need to go for class based component as no complex processing is required. A: It is totally optional, but I may say that when your component relies on so many data variables and calculations or queries, you should consider using the class-based component to separate the logic behind the component and the rest of your application. As @Donkarnash said, class-based components are like Controllers. To give an example I have a class-based component like this: class Filters extends Component { public $post_caption; public $image_path; public $filter1 ="thePathToTheFilteredImage"; public $filter2 ="thePathToTheFilteredImage"; public $filter3 ="thePathToTheFilteredImage"; public $filter4 ="thePathToTheFilteredImage"; public $filter5 ="thePathToTheFilteredImage"; public $filter6 ="thePathToTheFilteredImage"; public $filter7 ="thePathToTheFilteredImage"; public $filter8 ="thePathToTheFilteredImage"; public $filter9 ="thePathToTheFilteredImage"; public $filter10 ="thePathToTheFilteredImage"; public $filter11 ="thePathToTheFilteredImage"; public $filter12 ="thePathToTheFilteredImage"; public $filter13 ="thePathToTheFilteredImage"; public function __construct($post_caption, $image_path) {} public function applyFilter($num) {} public function correctImageOrientation($imagepath, $effect, $newimagepath, $arg1, $arg2, $arg3, $arg4, $argnum) {} public function render() { return view('components.filters'); } } Then I have the blade template: <div class="max-w-4xl my-0 mx-auto"> <div class="grid grid-cols-3 gap-4 mx-0 mt-0 mb-10"> <div> <p class="text-center">{{__('original')}}</p> <img src="storage/{{$image_path}}" class="w-64 h-64 cursor-pointer" onClick=""> </div> <div> <p class="text-center">{{__('filter1')}}</p> <img src="{{$filter1}}" class="w-64 h-64 cursor-pointer" onClick=""> </div> <div> <p class="text-center">{{__('filter2')}}</p> <img src="{{$filter2}}" class="w-64 h-64 cursor-pointer" onClick=""> </div> <div> <p class="text-center">{{__('filter3')}}</p> <img src="{{$filter3}}" class="w-64 h-64 cursor-pointer" onClick=""> </div> <div> <p class="text-center">{{__('filter4')}}</p> <img src="{{$filter4}}" class="w-64 h-64 cursor-pointer" onClick=""> </div> ....**and so on**..... </div> </div> And that's the idea. Note: I have deleted the contents of functions and a lot of codes, this is just an example. I was already answering the question before you got your answer, but I decided that I will continue with my answer haha
{ "language": "en", "url": "https://stackoverflow.com/questions/65414225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The Type of one of the Expression in the join clause is incorrect.Type inference failed in the call to join Getting this error in GetDiseaseBySymptoms method below when trying to join two list of type DiseaseSymptomMapping & Symptom. Can anyhelp with better understanding suggest what went wrong with the code of GetDiseaseBySymptoms. Note: Don't worry about the return type of GetDiseaseBySymptoms method, that will be taken care later once this issue is resolved. class Program { static void Main(string[] args) { Disease malaria = new Disease { ID = 1, Name = "Malaria" }; Disease Cholera = new Disease { ID = 1, Name = "Cholera" }; Symptom Fever = new Symptom { ID = 1, Name = "Fever" }; Symptom Cough = new Symptom { ID = 2, Name = "Cough" }; Symptom Shevering = new Symptom { ID = 3, Name = "Shevering" }; List<DiseaseSymptomMapping> DiseaseDetails = new List<DiseaseSymptomMapping> { new DiseaseSymptomMapping{ ID=1,disease=malaria,symptom=Fever}, new DiseaseSymptomMapping{ ID=2,disease=malaria,symptom=Shevering}, new DiseaseSymptomMapping{ ID=3,disease=Cholera,symptom=Fever}, new DiseaseSymptomMapping{ ID=4,disease=Cholera,symptom=Cough} }; List<Symptom> symptoms = new List<Symptom> { Fever, Fever,Shevering }; List<Disease> diseases = GetDiseaseBySymptoms(symptoms, DiseaseDetails); foreach (Disease disease in diseases) { Console.WriteLine("Disease Name :{0}", disease.Name); } Console.ReadLine(); } class Disease { public int ID { get; set; } public string Name { get; set; } } class Symptom { public int ID { get; set; } public string Name { get; set; } } class DiseaseSymptomMapping { public int ID { get; set; } public Disease disease { get; set; } public Symptom symptom { get; set; } } static List<Disease> GetDiseaseBySymptoms(List<Symptom> symptoms,List<DiseaseSymptomMapping> DiseaseDetails) { var querytmp = from diseasedetails in DiseaseDetails join symp in symptoms on diseasedetails.symptom equals symp in symptomsgrp select new { DiseaseName= diseasedetails.Name, Symptoms=symptomsgrp }; foreach (var v in querytmp) { Console.WriteLine("{0}", v.DiseaseName); } return new List<Disease>(); } } A: Change in symptomsgrp to into symptomsgrp. And you get rid of the error by changing DiseaseName = diseasedetails.Name to DiseaseName = diseasedetails.disease.Name
{ "language": "en", "url": "https://stackoverflow.com/questions/16807173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bulk insert data using recordset and return new ID's quickly How can I bulk insert a number of records and obtain the last inserted ID of each quickly (classic asp/ado)? I have tried this but it only runs at about 3 rows per second which is a joke. rs.Open "myTable", cn,adOpenKeyset, adLockOptimistic do while NOT rs.EOF rs.AddNew rs("text") = myFunction() ' returns some text. rs.update lastid = rs("id") ' get new id and so something loop Using the normal adOpenForwardOnly (which doesn't return the last inserted ID) it runs about 1000x faster. Can anyone suggest either a fix to the above or an alternative solution? I have to do this in the code rather than straight sql insert into ... select() etc. because I need to run a processing function on the text. A: The way to do this quickly is to use a bulk-insert in a stored procedure. You end up running a query to get back all the IDs but it reduces the main bottleneck: the number of trips to the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/11689550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIImageView ignores widthAnchor inside UIStackView I'm trying to align and scale an image inside a UIStackView: class LogoLine: UIViewController { override func viewDidLoad() { let label = UILabel() label.text = "powered by" label.textColor = .label label.textAlignment = .center let logoToUse = UIImage(named: "Image") let imageView = UIImageView(image: logoToUse!) let stackView = UIStackView(arrangedSubviews: [label, imageView]) stackView.axis = .vertical stackView.distribution = .fillProportionally view.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.widthAnchor.constraint(equalToConstant: 50), // this gets ignored stackView.topAnchor.constraint(equalTo: self.view.topAnchor), stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), view.heightAnchor.constraint(equalTo: stackView.heightAnchor) ]) } } This is how it looks in the simulator (going from border to border): Question: Why is the UIImageView ignoring my widthAnchor constraint of 50pt, and why does the aspect ratio of the original image get changed? How can I constrain the UIImage (or the UIImageView) to e.g. half the screen width and maintain the aspect ratio? A: By default, a vertical stack view has .alignment = .fill ... so it will stretch the arranged subviews to "fill the width of the stack view." Change it to: stackView.alignment = .center As a side note, get rid of the stackView.distribution = .fillProportionally ... it almost certainly is not what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/66134698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# -> Roslyn -> DocumentEditor.ReplaceNode -> Code indentation and format I have a problem that when I use DocumentEditor.ReplaceNode everything works but the generated code is hard to read. Roslyn - replace node and fix the whitespaces Output looks like this with several strings on the same line: using System; using System.IO; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { string test5 = @"test symbols \r\n Β© @ {} [] <> | / \ $Β£@!\#Β€%&/()=?` hello"; string varTest1 = @"test var hello"; string varTest2 = @"test var hello"; string test1 = @"test string hello"; string test2 = @"test String hello"; string test3 = @"test const hello"; string test4 = @"test readonly hello"; int i = 0; var i2 = 0; } } } I can get a new line by adding {System.Environment.NewLine} to the end of the string and remove all formating but then the code is not indented. What I have tried: 1: var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";").WithAdditionalAnnotations(Formatter.Annotation); newVariable = newVariable.NormalizeWhitespace(); 2: var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";").WithAdditionalAnnotations(Formatter.Annotation); 3: var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";").WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); newVariable = newVariable.NormalizeWhitespace(); 4: var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";"); newVariable = newVariable.NormalizeWhitespace(); Code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace CodeAnalysisApp1 { class Program { static void Main(string[] args) { var workspace = new AdhocWorkspace(); var projectId = ProjectId.CreateNewId(); var versionStamp = VersionStamp.Create(); var projectInfo = ProjectInfo.Create(projectId, versionStamp, "NewProject", "projName", LanguageNames.CSharp); var newProject = workspace.AddProject(projectInfo); var sourceText = SourceText.From( @" using System; using System.IO; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { string test5 = ""test symbols \r\n Β© @ {} [] <> | / \ $Β£@!\#Β€%&/()=?`""; var varTest1 = ""test var""; var varTest2 = ""test var""; string test1 = ""test string""; String test2 = ""test String""; const string test3 = ""test const""; readonly string test4 = ""test readonly""; int i = 0; var i2 = 0; } } }"); var document = workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText); var syntaxRoot = document.GetSyntaxRootAsync().Result; var root = (CompilationUnitSyntax)syntaxRoot; var editor = DocumentEditor.CreateAsync(document).Result; var localDeclaration = new LocalDeclarationVirtualizationVisitor(); localDeclaration.Visit(root); var localDeclarations = localDeclaration.LocalDeclarations; foreach (var localDeclarationStatementSyntax in localDeclarations) { foreach (VariableDeclaratorSyntax variable in localDeclarationStatementSyntax.Declaration.Variables) { var stringKind = variable.Initializer.Value.Kind(); //Replace string variables if (stringKind == SyntaxKind.StringLiteralExpression) { //Remove " from string var value = variable.Initializer.Value.ToString().Remove(0, 1); value = value.Remove(value.Length - 1, 1); var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";").WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); newVariable = newVariable.NormalizeWhitespace(); editor.ReplaceNode(variable, newVariable); Console.WriteLine($"Key: {variable.Identifier.Value} Value:{variable.Initializer.Value}"); } } } var newDocument = editor.GetChangedDocument(); var text = newDocument.GetTextAsync().Result.ToString(); } } class LocalDeclarationVirtualizationVisitor : CSharpSyntaxRewriter { public LocalDeclarationVirtualizationVisitor() { LocalDeclarations = new List<LocalDeclarationStatementSyntax>(); } public List<LocalDeclarationStatementSyntax> LocalDeclarations { get; set; } public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node); LocalDeclarations.Add(node); return node; } } } A: Normalize Whitespace normalizes the whitespace for the current object - not the object contained within a SyntaxTree. If you would for instance call normalize whitespace on newVariable with the value string varTest2 = @"test var hello"; It does not matter that the variable declaration is also within a syntax tree - what matters is the current context. Normalizing the whitespace of the above statement does basically nothing as there are no BlockStatements, Declarations or other elements which would create an indentation. If you however call normalize whitespace on the containing scope, for instance the method, you would get something along these lines: static void Main(string[] args) { string test5 = @"test symbols \r\n Β© @ {} [] <> | / \ $Β£@!\#Β€%&/()=?` hello"; string varTest1 = @"test var hello"; string varTest2 = @"test var hello"; string test1 = @"test string hello"; string test2 = @"test String hello"; string test3 = @"test const hello"; string test4 = @"test readonly hello"; int i = 0; var i2 = 0; } As you can see this would provide you with a correctly indented method. So in order to get the correctly formatted document you would have to call NormalizeWhitespace on the SyntaxRoot after everything else is done: editor.GetChangedRoot().NormalizeWhitespace().ToFullString() This will of course prevent you from retaining your old formatting if you had some artifact you would like to keep (e.g. the additional line between the DeclarationStatements you have in your sample). If you want to keep this formatting and the comments you could just try to copy the Trivia(or parts of the Trivia) from the original statement: foreach (var localDeclarationStatementSyntax in localDeclarations) { foreach (VariableDeclaratorSyntax variable in localDeclarationStatementSyntax.Declaration.Variables) { var stringKind = variable.Initializer.Value.Kind(); //Replace string variables if (stringKind == SyntaxKind.StringLiteralExpression) { //Remove " from string var value = variable.Initializer.Value.ToString().Remove(0, 1); value = value.Remove(value.Length - 1, 1); var newVariable = SyntaxFactory.ParseStatement($"string {variable.Identifier.ValueText} = @\"{value + " hello"}\";").WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); newVariable = newVariable.NormalizeWhitespace(); // This is new, copies the trivia (indentations, comments, etc.) newVariable = newVariable.WithLeadingTrivia(localDeclarationStatementSyntax.GetLeadingTrivia()); newVariable = newVariable.WithTrailingTrivia(localDeclarationStatementSyntax.GetTrailingTrivia()); editor.ReplaceNode(variable, newVariable); Console.WriteLine($"Key: {variable.Identifier.Value} Value:{variable.Initializer.Value}"); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49424690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can I transclude child component template into its parent in Angular 6+? Back in AngularJS, I created a simple smart table component that could be used like this for our team: <smart-table items="vm.people"> <column field="name">{{row.firstname}} {{row.lastname}}</column> <column field="age">{{vm.getAge(row.birthday)}}</column> </smart-table> This is a contrived example, but it worked like this. it generated the table, with the headers and used the inner content of the <column> tag as the template for each cell (the <td> element) correctly. Now, I am trying to port this to Angular (6+). So far, using @ContentChildren I am able to easily extract the list of columns. import { Component, OnInit, Input, ContentChildren, QueryList } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-table [data]="data"> <app-column title="name">{{name}}</app-column> <app-column title="age">{{birthday}}</app-column> </app-table> `, }) export class AppComponent { data = [{ name: 'Lorem Ipsum', birthday: new Date(1980, 1, 23), }, { name: 'John Smith', birthday: new Date(1990, 4, 5), }, { name: 'Jane Doe', birthday: new Date(2000, 6, 7), }]; } @Component({ selector: 'app-column', template: ``, }) export class ColumnComponent implements OnInit { @Input() title: string; constructor() { } ngOnInit() { } } @Component({ selector: 'app-table', template: ` <table> <thead> <th *ngFor="let column of columns">{{column.title}}</th> </thead> <tbody> <tr *ngFor="let row of data"> <td *ngFor="let column of columns"> <!-- <ng-container *ngTemplateOutlet="column.title;context:row" ></ng-container> --> </td> </tr> </tbody> </table> `, }) export class TableComponent implements OnInit { @Input() data: any[]; @ContentChildren(ColumnComponent) columns: QueryList<ColumnComponent>; constructor() { } ngOnInit() { } } This renders the following HTML: <table> <thead> <!--bindings={"ng-reflect-ng-for-of": "[object Object],[object Object"}--> <th>name</th> <th>age</th> </thead> <tbody> <!--bindings={"ng-reflect-ng-for-of": "[object Object],[object Object"}--> <tr> <!--bindings={"ng-reflect-ng-for-of": "[object Object],[object Object"}--> <td></td> <td></td> </tr> <tr> <!--bindings={"ng-reflect-ng-for-of": "[object Object],[object Object"}--> <td></td> <td></td> </tr> <tr> <!--bindings={"ng-reflect-ng-for-of": "[object Object],[object Object"}--> <td></td> <td></td> </tr> </tbody> </table> But now I am stuck trying to insert the content of the <app-column> component into the <app-table> template. I have read several answers around here (this one and this one). But the issue I have with those is that either you have a static set of templates or you insert them in static places. In my case, I need to use that template inside an *ngFor at runtime. In AngularJS, I was using the following code: function compile(tElement) { const columnElements = tElement.find('column'); const columns = columnElements.toArray() .map(cEl => ({ field: cEl.attributes.field.value, header: cEl.attributes.header.value, })); const template = angular.element(require('./smart-table.directive.html')); tElement.append(template); // The core of the functionality here is that we generate <td> elements and set their // content to the exact content of the "smart column" element. // during the linking phase, we actually compile the whole template causing those <td> elements // to be compiled within the scope of the ng-repeat. const tr = template.find('tr[ng-repeat-start]'); columnElements.toArray() .forEach(cEl => { const td = angular.element('<td/>') .html(cEl.innerHTML); tr.append(td); }); const compile = $compile(template); // comment out originals columnElements.wrap(function () { return `<!-- ${this.outerHTML} -->`; }); return function smartTableLink($scope) { $scope.vm.columns = columns; compile($scope); }; } A: Here is what I ended up with, thanks to Meriton's pointers. As he suggested, I changed my app-column component to a directive instead. That directive must appear on a ng-template element: @Directive({ selector: 'ng-template[app-column]', }) export class ColumnDirective { @Input() title: string; @ContentChild(TemplateRef) template: TemplateRef<any>; } The app-table component became: @Component({ selector: 'app-table', template: ` <table> <thead> <th *ngFor="let column of columns">{{column.title}}</th> </thead> <tbody> <tr *ngFor="let row of data"> <td *ngFor="let column of columns"> <ng-container [ngTemplateOutlet]="column.template" [ngTemplateOutletContext]="{$implicit:row}"> </ng-container> </td> </tr> </tbody> </table> `, }) export class TableComponent { @Input() data: any[]; @ContentChildren(ColumnDirective) columns: QueryList<ColumnDirective>; } While at first I was a bit turned off by having to expose ng-template to some of my teammates (not very Angular savvy team yet...), I ended up loving this approach for several reasons. First, the code is still easy to read: <app-table [data]="data"> <ng-template app-column title="name" let-person>{{person.name}}</ng-template> <ng-template app-column title="age" let-person>{{person.birthday}}</ng-template> </app-table> Second, because we have to specify the variable name of the context of the template (the let-person) code above, it allows us to retain the business context. So, if we were to now talk about animals instead of people (on a different page), we can easily write: <app-table [data]="data"> <ng-template app-column title="name" let-animal>{{animal.name}}</ng-template> <ng-template app-column title="age" let-animal>{{animal.birthday}}</ng-template> </app-table> Finally, the implementation totally retains access to the parent component. So, let say we add a year() method that extracts the year from the birthday, on the app-root component, we can use it like: <app-table [data]="data"> <ng-template app-column title="name" let-person>{{person.name}}</ng-template> <ng-template app-column title="year" let-person>{{year(person.birthday)}}</ng-template> </app-table> A: In Angular, content projection and template instantiation are separate things. That is, content projection projects existing nodes, and you will need a structural directive to create nodes on demand. That is, column needs to become a structural directive, that passes its template to the parent smart-table, which can then add it to its ViewContainer as often as necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/52319099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: std::remove_reference clarification with code snippet I am trying to understand how to use the std::remove_reference functionality in type_traits. This is the piece of code that I made template <class T> class example { public: T some_int; example(T inty) : some_int(inty){std::cout << "constructor called!" << "\n";} ~example(){std::cout << "destructor called!" << "\n";} }; template <class T> // return a value, hence return a copy of the object auto function(T ptr_object) -> typename std::remove_reference<decltype(*ptr_object)>::type{ ptr_object -> some_int = 69; return *ptr_object; } int main(){ example<int> classy(20); example<int> *ptr = &classy; auto hello = function<decltype(ptr)>(ptr); std::cout << hello.some_int << std::endl; } so this code compiles successfully however this is the output constructor called! 69 destructor called! destructor called! My aim is to return a copy of the object (and not a reference) therefore in my calculations, once i call the return in the function it should call also the constructor of the object, but this does not happen. Plus it calls the destructor 2 times. Can someone help me understand what I am getting wrong? A: When you return a copy of the object, that creates a new object, which is what you want. So one destructor is the for the copy, and one is for the original. In other words your code works, but you can't see the copy constructor, add the line example(const example& cp) : some_int(cp.some_int){std::cout << "copy constructor called!" << "\n";} And the output is constructor called! copy constructor called! 69 destructor called! destructor called! By the way, your code looks a little clunky, but maybe that's the point? The alternative would be ... template <class T> T function(T* ptr_object) { ptr_object -> some_int = 69; return *ptr_object; } Which is more concise EDIT: I just noticed that @Jarod42 beat me to it (again)
{ "language": "en", "url": "https://stackoverflow.com/questions/70273948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }