_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d8201
train
To be able to use read in your case, you need something like this using a special file descriptor : while read crontab_entry; do ... read -u3 -p 'question' yn ... done 3<&0 < crontab.out because STDIN is already fed by the crontab output A: I used a special file descriptor for the cat command instead and done some modifications to the sed command to work correctly. function cron_check() { crontab -l result=$? if [[ $result -eq 0 ]]; then crontab -l > crontab.out exec 3< crontab.out while read -u 3 cron_entry do # ignore commented cron entries [ "${cron_entry#\#}" = "$cron_entry" ] || continue # skip comment read -p "Do you want to remove this cron entry: $cron_entry, Please enter [Y/N]" yn case $yn in [yY] | [yY][Ee][Ss] ) cron_entry_esc=$(sed 's/[\*\.&/]/\\&/g' <<<"$cron_entry");crontab -l | sed "/$cron_entry_esc/d" | crontab -;; [nN] | [n|N][O|o] ) continue;; * ) echo "Please answer Y or N.";; esac done fi } cron_check
unknown
d8202
train
Quite simply 1.) Create app on Facebook, get the app_id that you will subsequently use to attach to your app. 2.) Define your applicationId in the AndroidManifest.xml like this: <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/> under <application android:label="@string/app_name".... tag where app_id is a string within your strings.xml. Example (Facebook Sample application): <application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name=".HelloFacebookSampleActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/> </application> Note the value added under the <application> tag and in strings.xml (MAKE SURE TO DO THIS) <string name="app_id">xxxxxxxxxxxx</string> 3.) Set permissions in manifest <uses-permission android:name="android.permission.INTERNET"/> This is an android requirement, so the app can access the internet. So with permissions the above manifest will look like <uses-permission android:name="android.permission.INTERNET" /> <application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name=".HelloFacebookSampleActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/> </application> A: I had the same problem. And here is how I solved it — I think. At least after doing these things, the problem went away. in strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> …. <string name="com.facebook.sdk.ApplicationId">facebook_app_id</string> <string name="facebook_app_id">111111111</string> …. </resources> in manifest <application … > <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" /> </application> </manifest> Notice there are two entries in the strings.xml file.
unknown
d8203
train
You need to convert the image to data imagesArray.indices.forEach { multipartFormData.append(imagesArray[$0].jpegData(compressionQuality:0.8)!, withName: "photo[\($0)]", fileName: "photo\($0).jpeg", mimeType: "image/jpeg") }
unknown
d8204
train
you can either use map.on('layeradd') and or try the layeradd event on your layer1 object. leaflet's documentation link: http://leafletjs.com/reference-1.0.3.html#layerevent EDIT... add the following code to js-fiddle code. layer1.on('add',(e)=>{ layer2.addTo(mymap); }); layer1.addTo(mymap); if that doesn't remove the addTo line from above and paste the following setTimeout(()=>{ layer1.addTo(mymap); },500); EDIT 2 : var controlObj = L.control.layers(basemaps,overlays,{collapsed:false}).addTo(mymap); layer1.on("add",function(){ console.log(controlObj._form[2].click()) }); this code works... but its not how it should be dont... will have to figureout a better way to do this, but this will work temporarily.
unknown
d8205
train
You have to define the fields before using it. In your jrxml, you have three field defined students in the subDataSet, id and students. But you haven't defined name and using it in your jrxml and that's why you are getting this exception. Try defining name, like <field name="name" class="java.lang.String"/> A: Try with a subreport. I launched your example in my local database without any problem. This is my list of student objects: private List<Student> getList(){ List<Student> students = new ArrayList<Student>(); Connection con = ....; //Retrieve your connection the way you want ResultSet rs = con.createStatement().executeQuery("select name, id from students order by id"); while (rs.next()){ students.add(new Student(rs.getString(1), rs.getInt(2))); } con.close(); return students; } This is how I passed my JRBeanCollectionDataSource object from my Java program: Map<String, Object> params = new HashMap<String, Object>(); params.put("SUBREPORT_DATASOURCE", new JRBeanCollectionDataSource(getList())); String jasperPath = "....."; //where you have your compiled jasper report file JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, params, new JREmptyDataSource(1)); This is the xlm main report "reportStudent.jrxml": <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reportStudent" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <parameter name="SUBREPORT_DATASOURCE" class="net.sf.jasperreports.engine.JRDataSource" isForPrompting="false"> <defaultValueExpression><![CDATA[]]></defaultValueExpression> </parameter> <background> <band splitType="Stretch"/> </background> <detail> <band height="125" splitType="Stretch"> <subreport> <reportElement x="0" y="0" width="555" height="125"/> <dataSourceExpression><![CDATA[$P{SUBREPORT_DATASOURCE}]]></dataSourceExpression> <subreportExpression><![CDATA["./reportStudent_subreport1.jasper"]]></subreportExpression> </subreport> </band> </detail> </jasperReport> And this is the one for the subreport "reportStudent_subreport1.jrxml": <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reportStudent_subreport1" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0"> <property name="ireport.zoom" value="1.771561000000001"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <field name="id" class="java.lang.String"/> <field name="name" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <columnHeader> <band height="20" splitType="Stretch"> <staticText> <reportElement x="66" y="0" width="100" height="20"/> <textElement/> <text><![CDATA[id]]></text> </staticText> <staticText> <reportElement x="212" y="0" width="100" height="20"/> <textElement/> <text><![CDATA[name]]></text> </staticText> </band> </columnHeader> <detail> <band height="20" splitType="Stretch"> <textField> <reportElement x="66" y="0" width="100" height="20"/> <textElement/> <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression> </textField> <textField> <reportElement x="212" y="0" width="100" height="20"/> <textElement/> <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression> </textField> </band> </detail> </jasperReport> This is for just one list of students. You can iterate inside the main report and print your course id and students subreport in the detail band with just a little changes. Hope it helps to start with. A: Fount out the issue. name attribute should defined inside the subdataset. Otherwise it wont work <subDataset name="dataset1" uuid="09015d96-ad5a-4fed-aa9e-19d25e02e205"> <field name="name" class="java.lang.String"/> </subDataset>
unknown
d8206
train
In this case, the underlying data source does not support editing since the properties of anonymous types are read only. Per the C# language spec: The members of an anonymous type are a sequence of read-only properties inferred from the anonymous object initializer used to create an instance of the type. Instead, you might want to define a display class with editable properties for the values you want to display and create instances of that class. A: I had this problem with an unbound DGV. I fixed it by setting the ReadOnly property of each ROW. Both the DGV and the Columns were not ReadOnly, but the Rows were somehow being set R/O perhaps when I set them using a collection. So: foreach (var r in Lst) { ... dgv.Rows[dgv.Rows.Count - 1].ReadOnly = false; }
unknown
d8207
train
You are probably best off writing your own session invalidation logic. You cant manually control the tomcat access time behaviour without a lot of hack work. You could write a servlet filter that tracks the last time a page(other than the whitelisted pages) was accessed and invalidates sessions that exceed the threshold. public class AccessTimeFilter implements Filter { private static final long ACCESS_TIME_WINDOW = 30 * 60 * 1000;//30 Mins private static final Set<String> IGNORED_URLS = new HashSet<>(Arrays.asList("/myurl", "/someOtherUrl")); @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpSession session = request.getSession(); Long realLastAccessedTime = (Long) session.getAttribute("realLastAccessedTime"); if(realLastAccessedTime != null && realLastAccessedTime < (System.currentTimeMillis() - ACCESS_TIME_WINDOW)){ session.invalidate(); } doFilter(req, res, chain); String url = request.getServletPath(); if(!IGNORED_URLS.contains(url)){ session.setAttribute("realLastAccessedTime", System.currentTimeMillis()); } }
unknown
d8208
train
You can take the datatable you need to move, Remove it from the first dataset and Add it to the other var dt = ds1.Tables[0]; ds1.Tables.Remove(dt); ds2.Tables.Add(dt); A: Use this function public DataTable CopyDataTable(DataTable dtSource) { // cloned to get the structure of source DataTable dtDestination = dtSource.Clone(); for (int i = 0; i < dtSource.Rows.Count; i++) { dtDestination.ImportRow(dtSource.Rows[i]); } return dtDestination; } Suppose you want to copy first table of sourceSet to destinationSet. Call it like DataTable destinationTable = CopyDataTable(ds1.Tables[0]); DataSet destinationSet = new DataSet(); ds2.Tables.Add(destinationTable);
unknown
d8209
train
You can do it using explicit function call syntax. For your case, the call should be os.operator<<(b ? 10 : -10), because the corresponding operator<< is a member function. However, with your operator<<, you will no longer be able to use expressions such as std::cout << true in namespace Foo, because this will trigger an ambiguity between your Foo::operator<<(std::ostream&, bool) and std::ostream's member function std::ostream::operator<<(bool): both accept an lvalue of type std::ostream as its left operand, and both accept a value of type bool as its right operand, neither is better than the other.
unknown
d8210
train
Based on your description and further comments, the following should hopefully meet your requirements - updating the row for the specified User where the values are currently NULL and the user has a qualifying existing order: update s set s.Discounted_Price = 1, Price = 10 from submitted_Orders s where s.userId=2 and s.Level_Name = 'Birmingham Blues' and s.discounted_Price is null and s.Price is null and exists ( select * from submitted_orders so where so.userId = s.userId and so.Level_name = 'Eldorado' and so.Order_Date < s.OrderDate );
unknown
d8211
train
try this one: audioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); A: I faced the same issue in which audio that recorded from Samsung's device is not working on all IOS devices and not even on safari browser. But they working fine in all android devices. I have fixed this issue by adding below lines in AudioRecordingUtil class: recorder?.let{ it.setAudioSource(MediaRecorder.AudioSource.MIC) it.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS) it.setAudioEncoder(MediaRecorder.AudioEncoder.AAC) } Hope this can help! A: It is codec issue , the format recorded by iOS is not able decode by android media player , in order to make it work just decode the audio file on IOS side in to android supported format like mp3 or mp4 or 3Gp etc. A: I also suffered issues with MediaRecorder. At the time of Audio Record, Mime Types are different like Mac chrome - Mime Type:audio/webm;codecs=opus Mac Safari - Mime Type:audio/mp4 Windows/Android - Mime Type:audio/webm;codecs=opus Iphone Chrome - Mime Type:audio/mp4 I was saving the file as M4a but Audio was not running in IOS. After some analysis and Testing. I decided to convert the file after Upload in Server and used ffmpeg and It worked like a charm. <!-- https://mvnrepository.com/artifact/org.bytedeco/ffmpeg-platform --> <dependency> <groupId>org.bytedeco</groupId> <artifactId>ffmpeg-platform</artifactId> <version>4.3.2-1.5.5</version> </dependency> /** * Convert the file into MP4 using H264 Codac in order to make it work in IOS Mobile Device * @param file * @param outputFile */ private void convertToM4A(File file, File outputFile) { try { String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class); ProcessBuilder pb = new ProcessBuilder(ffmpeg, "-i", file.getPath(), "-vcodec", "h264", outputFile.getPath()); pb.inheritIO().start().waitFor(); }catch (Exception e ){ e.printStackTrace(); } }
unknown
d8212
train
If you are scraping a web page that shows dynamic content then you basically have 2 options: * *Use something to render the page first. The simplest in C# would be to have a WebBrowser control, and listen for the DocumentCompleted event. Note that there is some nuance to this when it fires for multiple documents on one page *Figure out what service the page is calling to get the extra data, and see if you can access that directly. It may well be the case that the Canadapost website is accessing an API that you can also call directly.
unknown
d8213
train
I understand you want to replace fileSizes with the values from your fileSizesMap: const fileSizes = Array.from(fileSizesMap.values()) A: You could try to return an iterable for values and do your assertions: const fileSizesMap = new Map([ ["excelFileSize", "17.19 KB"], ["docxFileSize", "12.06 KB"], ["pdfFileSize", "67.75 KB"] ]); it('attaches many documents', () => { cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath]) for (const value of fileSizesMap.values()) { cy.get('div.table-body>.table-row').then(() => { expect($el.find('.col-upload-size')).to.contain.text(value) }) } })
unknown
d8214
train
If you are using angular cli . Then place these scripts in angular-cli.json file under scripts array scripts:[ ..... ] Please refer this [link] (https://rahulrsingh09.github.io/AngularConcepts/faq) It has a question on how to refer third party js or scripts in Angular with or without typings.
unknown
d8215
train
Just use divmod. It does a division and modulo at the same time. It's more convenient than doing that separately. seconds = 1.05 # or whatever (hours, seconds) = divmod(seconds, 3600) (minutes, seconds) = divmod(seconds, 60) formatted = f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}" # >>> formatted # '00:00:01.05' And if you need the fraction of seconds to be separated by :, which nobody will understand, you can use (seconds, fraction) = divmod(seconds, 1) and multiply fraction * 100 to get hundredth of a second.
unknown
d8216
train
Apparently, on my Macbook, I see /etc directory having symlinks with the /private/etc directory which is owned by the wheel group & root is part of that group. So, you would need to use sudo to copy to that directory. With that said on a Linux machine, you can work around this by adding your group to a new file in the /etc/sudoers.d/<group-name> path. <grp-name> ALL=(ALL) NOPASSWD:ALL I've just tried this on my mac, I could copy files onto /private/etc directory without entering the sudo password prompt. Unfortunately, this comes up with some risks as users of your group get privileged access without entering any password prompt. You might accidentally delete important system files etc., A more niche approach could be to allow selectively like <group> ALL = (ALL) NOPASSWD: /usr/local/bin/copy-script. This way, they can't run all scripts/commands with sudo privileges.
unknown
d8217
train
Python classes have three attributes that help here: * *class.__subclasses__(); a method that returns all subclasses of the class. *class.__bases__, a tuple of the direct parent classes of the current class. *class.__mro__, a tuple with all classes in the current class hierarchy. Find the current class object in that tuple and everything following is a parent class, directly or indirectly. Using these that gives: class SuperClass(object): def print(self): print('my sub classes are:', ', '.join([ cls.__name__ for cls in type(self).__subclasses__()])) class Sub1(SuperClass): def print(self): print('My direct parents are:', ', '.join([ cls.__name__ for cls in type(self).__bases__])) all_parents = type(self).__mro__ all_parents = all_parents[all_parents.index(Sub1) + 1:] print('All my parents are:', ', '.join([ cls.__name__ for cls in all_parents])) Demo: >>> SuperClass().print() my sub classes are: Sub1 >>> Sub1().print() My direct parents are: SuperClass All my parents are: SuperClass, object
unknown
d8218
train
No, at least not natively. What are you trying to achieve? Try compiling the program before doing anything else. If that is what it looks like (something to do with an industrial camera feed), then you're better off just using Javascript, PHP, NGINX and HTML. That would also be uncomparable to your approach in terms of reliability.
unknown
d8219
train
I ended up using this import 'dart:async'; import 'package:geolocator/geolocator.dart'; class LocationBloc { final Geolocator _geolocator = Geolocator(); final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10); StreamController<double> _streamController = StreamController<double>(); Stream<double> get stream => _streamController.stream; LocationBloc() { _streamController.addStream(_geolocator.getPositionStream(_locationOptions).map((position) => position.speed ?? 0.0)); } void dispose() { _streamController.close(); } } With a stream builder widget.
unknown
d8220
train
Look at GROUP_CONCAT but it may be easier to retrieve the data in multiple rows (you can sort to put repeats adjacent to each other) and process in code. A: This is similar to Aggregating results from SPARQL query, but the problem is actually a bit more complex, because there are multiple variables that have more than one result. ?name, ?office, and ?birthPlace have the same issue. You can work around this using group_concat, but you'll need to use distinct as well, to keep from getting, e.g., the same ?year repeated multiple times in your concatenated string. group by reduces the number of rows that you have in a solution, but in each of those rows, you have a set of values for the variables that you didn't group by. E.g., since ?year isn't in the group by, you have a set of values for ?year, and you have to do something with them. You could, e.g., select (sample(?year) as ?aYear) to grab just one from the set, or you could do as we've done here, and select (group_concat(distinct ?year;separator=", ") as ?years) to concatenate the distinct values into a string. You'll want a query like the following, which produces one row: SELECT ?x (group_concat(distinct ?name;separator="; ") as ?names) ?abs ?birthDate (group_concat(distinct ?birthplace;separator=", ") as ?birthPlaces) (group_concat(distinct ?year;separator=", ") as ?years) ?party (group_concat(distinct ?office;separator=", ") as ?offices) ?wiki WHERE { ?x owl:sameAs? dbpedia:Manmohan_Singh. ?x dbpprop:name ?name. ?x dbpedia-owl:birthDate ?birthDate. ?x dbpedia-owl:birthPlace ?birthplace. ?x dbpprop:years ?year. ?x dbpprop:party ?party. ?x dbpedia-owl:office ?office. ?x foaf:isPrimaryTopicOf ?wiki. ?x rdfs:comment ?abs. FILTER(langMatches(lang(?abs),"en")) } group by ?x ?abs ?birthDate ?party ?wiki SPARQL results
unknown
d8221
train
Try like below , It will help you... $("#tab2 tbody").append("<tr><td>"+selectval[i]+"</td><td><input type='text' id='text" + i + "' /></td></tr>"); It will generate Id like text0, text1, text2... To Get the value from the Text box add the below codes and try it... Fiddle Example : http://jsfiddle.net/RDz5M/4/ HTML : <button id="Get" value="Get">Get</button> JQuery : $("#Get").click(function(){ $('#tab2 tr').each(function(){ $("#divResult").html($("#divResult").html() + ($(this).find("input[id^='text']").val()) + "<br>") }); });
unknown
d8222
train
It seems generating such dependency is not possible directly with gfortran. Use of cmake (e.g.) seems to automatically account for that, even if I did not check the resulting makefile, and I wouldn't know how does cmake parse the contents of src1.f90 and mod_mymods.f90 to be able to tell the dependency.
unknown
d8223
train
Selenium-webdrivers #move_to accepts right and down offsets for the element you're moving to. When using capybara with selenium-webdriver, assuming you have found the element you want to move the mouse to, you should be able to do page.driver.browser.action.move_to(element.native, 1, 1).perform Note: this will only work with the selenium driver, not with Poltergeist, etc.
unknown
d8224
train
Fixed this issue by installing aceapi and setting the path of the vendor lib to the syswow path of ace32.dll in FDDrivers.ini
unknown
d8225
train
Authy developer evangelist here. With Authy, the secret key is not exposed to you, the developer, for security reasons. It is only shared with the user directly via the application, without them having to do anything, as you described. Authy, in fact, manages the keys between the app and the user more than just on the first occasion, as keys can be rotated regularly without your or the user's intervention. If a user is finding that they have signed up to your site but your application isn't appearing in their Authy app then a couple of things might have happened. * *Their phone may not be on a network at the time they signed up, leading to them not being able to receive the secret key from Authy This should resolve itself over time as the user will eventually get their phone back on a network. You might consider suggesting they install Authy Desktop to use their desktop computer to authorise. Alternatively, you could ensure they get a token and finish registering with your site by giving them the option to receive the token over SMS and forcing the token to be sent over SMS, using the force parameter when requesting a token. * *They may have signed up to your 2FA using a different phone number than the one they initially signed up to Authy with. For this, again, you may want to give them the option to receive a token by SMS. Or get the user to check their Authy account settings in the application and perhaps re-enter their phone number. Overall, you won't get access to the secret or a QR code as that is not how Authy manages the secrets. Instead, either give the option to receive an SMS or get them to install an application on a device that has a connection. Let me know if that helps at all.
unknown
d8226
train
Read https://reactnavigation.org/docs/en/headers.html#overriding-shared-navigationoptions within your ProfileScreen and MessageScreen override the header color by doing static navigationOptions = ({ navigation, navigationOptions }) => { return { headerStyle: { backgroundColor: theme.themeColor, }, }; };
unknown
d8227
train
in views.py use the annotate function to generate the result video_views=Video.objects.all().annotate(vote_count=Count('viewers', distinct=True)) .annotate(likes_count=Count('viewers_by_ip', distinct=True)) context={'video_views':video_views} return render(request, template_to_display.html, context) A: I just convert this video_views = video_viewers_ip + video_viewers to video_views = len(list(chain(video_viewers_ip, video_viewers))) and it's worked with me fine.
unknown
d8228
train
No temporary copies are created during the construction of matrixU and matrixV. Eigen::JacobiSVD inherits from Eigen::SVDBase, which defines the member functions matrixU() and matrixV() which just return a reference to the protected member variables of Eigen::SVDBase that hold the actual matrices. However, you are still copying data, but explicitly: you copy the two matrices from the local variable svd into member variables of Foo. If you do not need to modify the U and V matrices in-place, you could store the whole svd in Foo, like so: class Foo { public: JacobiSVD svd; Foo(const Ref<const MatrixXcd>& mat); }; Foo::Foo(const Ref<const MatrixXcd>& mat): svd(mat, Eigen::ComputeFullU | Eigen::ComputeFullV) { // proceed to do other things } Unfortunately, you can't modify the member variables of svd. So if you really need to modify them, and don't need the original values, then your code is fine as it is.
unknown
d8229
train
If your password must have at least one capital letter and at least one number your logic is wrong. You should have two booleans. boolean hasCapitalLetter = false; boolean hasNumber = false; for (int i = 0;i<Password.getText().length(); i++) { char i1 = Password.getText().charAt(i); if (!hasCapitalLetter) { hasCapitalLetter = Character.isUpperCase(i1); } if (!hasNumber) { hasNumber = Character.isDigit(i1); } if (hasCapitalLetter && hasNumber) { return true; } } return false;
unknown
d8230
train
First, I would suggest creating a function for the purpose of opening each dat-file. Please replace the read.table function by the function you use for opening the dat-files. In this case, the function contains both coordinates and the months to which respect it filters the dataframe as arguments. Arguments could however be extended by year and days for instance. To keep it simple I only included months. open_dat <- function(X, Y, left, right) { dat <- read.table(paste("hourly", X, Y, "2005.dat", sep = "_"), header=TRUE) %>% as.tibble() dat$X <- X dat$Y <- Y dat %>% filter(between(Month, left, right)) } Then, we can apply the function to the dataframe that contains X and Y for the days that are between May and July (numbers 5 and 7): full_df <- map2_dfr(df$X, df$Y, open_dat, left = 5, right =7)
unknown
d8231
train
The only way to do that would be to ask the Widget developer to do something like this: $cat_args_depth = 1; $cat_args_depth = apply_filters('woocommerce_cat_args_depth', $cat_args_depth ); $cat_args['depth'] = $cat_args_depth; and then you could just use add_filter( 'woocommerce_cat_args_depth', function( $cat_args_depth ) { $cat_args_depth = 2; // your value return $cat_args_depth ; });
unknown
d8232
train
First of all you said Can't drop table. But in post you mentioned ALTER TABLE table ENGINE=INFINIDB. But DROP != ALTER it is two different things. So you can do following: * *CREATE new table with same structure but engine you need. *copy(UPDATE) data from old table to the one you just created. *DROP old table. *RENAMErename new one to old name A: It turned out that another process (a website) was using this database and had a couple of queries that got 'stuck' in the SQL server and caused the table to hang due to the database using the wrong engine, which I'm assuming was InnoDB since I didn't specify an engine when I initially used the "CREATE TABLE table1 AS SELECT * FROM table2" command. We finally managed to wipe the database and start over. Thanks for your help.
unknown
d8233
train
@Named annotaion expects some name and in name is not set - it generate default name, but, name generates in accoartinatly to camel case name of bean. You need to try specify name or either use camel case for bean name.
unknown
d8234
train
Here are some links to get started provided from people working on Appium. Some documentation is not up to date since this is still pre Appium 1.0 but should be updated by May 1st. http://appium.github.io/training/ https://github.com/appium/appium/tree/master/docs
unknown
d8235
train
If you have an array of image urls, you can use setInterval to periodically update your header/footer images. Something like this: var imgUrls = [ 'assets/img/bg1.jpg', 'assets/img/bg2.jpg', 'assets/img/bg3.jpg', 'assets/img/bg4.jpg', // ... etc. ]; var currentImageIndex = 0; // Create a callback that will be invoked every 10 seconds setInterval(function() { var imgUrl = imgUrls[currentImageIndex++]; $('header').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover'); $('footer').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover'); // Make sure the currentImageIndex doesn't get too big if (currentImageIndex >= imgUrls.length) { currentImageIndex = 0; } }, 10000); A: Another solution : $(function() { let pictures = ["bg3.jpg", "bg2.jpg", "bg1.jpg"]; $.each(pictures, function(i,e) { setTimeout(function() { changeHeaderImg(e); }, i*10000); }); } function changeHeaderImg(pictureName: string) { $('header').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover'); } A: This will work for any number of images as long as you keep following your 'assets/img/bg' + num + '.jpg' format. Just set the number of headers you have at the top and you're good to go. $(function() { var numHeaders = 4; var header = 0; setInterval(function() { header++; if (header > numHeaders) { header = 1; } $('header').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover'); }, 10000); });
unknown
d8236
train
You just need to add margin-top: -2px; to .boxBody. Live example: http://jsfiddle.net/tw16/eBnUt/2/ .boxBody{ border: 2px solid #343434; background: #fff; /*width: 100%;*/ min-height: 70px; padding: 20px; margin-top: -2px; /* add this */ -webkit-border-bottom-right-radius: 10px; -webkit-border-bottom-left-radius: 10px; -moz-border-radius-bottomright: 10px; -moz-border-radius-bottomleft: 10px; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; }
unknown
d8237
train
Here's a vectorized approach based on sparse matrices: array01 = [0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0].'; % example data sample_period = 0.005; % example data t = sparse(1:numel(array01), cumsum([true; diff(array01(:))>0]).', array01); timearray = sample_period*full(max(cumsum(t, 1).*t, [], 2));
unknown
d8238
train
You can use AND/OR logic to simulate the If-else condition in where clause. Try something like this select * from users where parentid= @id and ( (@Type = 1 and UserType <> 0) or (@Type = 2 and UserType = 0) or (@Type = 3) ) or you can also use Dynamic sql to do this declare @Id uniqueidentifier = 'some parent guid' declare @Type int = 1 -- can be 1, 2 or 3 Declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once Declare @sql nvarchar(max) if(@Type = 1) set @UserType = ' and UserType <> 0' if(@Type = 2) set @UserType = ' and UserType = 0' if(@Type = 3) set @UserType = '' set @sql = 'select * from users where parentId ='''+ cast(@Id as varchar(25))+''''+ @UserType --Print @sql Exec sp_executesql @sql A: Different select statements would be most efficient since each is a fundamentally different query. If static SQL becomes unwieldly, use dynamic SQL. Below is a parameterized example using techniques from http://www.sommarskog.se/dyn-search.html. declare @sql nvarchar(MAX) = N'select * from users where parentId = @Id'; declare @Id uniqueidentifier = 'some parent guid'; declare @Type int = 1; -- can be 1, 2 or 3 declare @UserType varchar(max); --can be 0, anything else than 0, or all users at once SET @sql = @sql + CASE @Type WHEN 1 THEN N' and UserType <> 0' WHEN 2 THEN N' and UserType = 0' WHEN 3 THEN N'' END; EXEC sp_executesql @sql , N'@Id uniqueidentifier' , @Id = @Id;
unknown
d8239
train
I couldn't solve question completely But I found something useful for default template of controls in Windows 8.1. Windows 8.1 default XAML templates and styles
unknown
d8240
train
VNC and SSH are different beasts so your VNC viewer (ssh connection) stanza doesn't make a lot of sense, VNC is a separate protocol and JMeter doesn't support it either via its samplers or via plugins If you still want to use JMeter for load testing your VNC server you will need to implement the client login and getting initial image using some form of VNC Java client library like Vernacular VNC from JSR223 Sampler or come up with your own JMeter plugin
unknown
d8241
train
You're comparing current time to each of sunrise / sunset independently meaning you'll get some odd results. This should work for determining which one to show $now = date("H:i"); $sunrise = date_sunrise(time(), SUNFUNCS_RET_STRING, 51.29, 4.49, 90.7, 2) $sunset = date_sunset(time(), SUNFUNCS_RET_STRING, 51.29, 4.49, $icon = ($now > $sunrise && $now < $sunset) ? 'icon_day' : icon_night' // Will echo icon_day or icon_night echo $icon; Displaying an actual icon instead of text is a very different question. If that's what you're trying to get at more information is required (do you have icons? where are you showing them? what have you tried)
unknown
d8242
train
Looks like you are returning false as default and only returning true inside your future, not the actual FutureProvider. Try something like this and it should work: final adminCheckProvider = FutureProvider<bool>((ref) async { User? _uid = ref.watch(authStateChangesProvider).value; if (_uid != null) { print(_uid.uid); // Check for Admin Document final _fireStore = FirebaseFirestore.instance; final doc = await _fireStore.doc(FireStorePath.admin(_uid.uid)).get(); return doc.exists; } else { return false; } });
unknown
d8243
train
Query * *you need to refer to a field to compute the difference so you need $expr and aggregate operators *the bellow keeps red wines, with years difference>=20, and then sorts by rating. Playmongo aggregate( [{"$match": {"$expr": {"$and": [{"$eq": ["$wineType", "Red"]}, {"$gte": [{"$subtract": ["$endYear", "$startYear"]}, 20]}]}}}, {"$sort": {"rating": -1}}]) A: In MongoDB, the $where query operator is used for comparing the fields or documents that satisfy the JavaScript expression. We can also pass a string.
unknown
d8244
train
If you only need the ID to be unique for nodes within a single document, you could use <xsl:number count="*" level="any" from="/*" format="a"/> A: You'd have much more than 1296 possibilities with 2 characters if you wanted to use all the unicode characters that are allowed in an XML name! Unfortunately, XSLT processors are free to decide how that create IDs for the generate-id() function (meaning that depending on the processor you are using you can get more or less then 8 characters). That being said, if that's really important to you, you should be able to write your own generate-id() based on the number of preceding siblings and ancestor node nodes (count(ancestor::node()|preceding::node()))... You could convert this number into a two character id using lookup tables or any other mechanism and that would probably not be very efficient but that should work...
unknown
d8245
train
try something like this HTML CODE <select name="source_type" id="source_type" onchange="populateLocation(this.value)"> <option value="">Source Type</option> <option value="Internal">Internal</option> <option value="External">External</option> </select> <select name="location" id="location"> <option value="">Select</option> </select> JAVASCRIPT CODE USING JQUERY function populateLocation(source_type_value){ if(source_type_value !=''){ /* Pass your source type value to controller function which will return you json for your loaction dropdown */ var url = 'controller/function/'+ source_type_value; // $.get(url, function(data) { var $select = $('location'); // removing all previously filled option $select.empty(); for (var propt in data) { $select.append($('<option />', { value: propt, text: data[propt] })); } } } JSON FORMAT to be returned from controller {"":"Select","1":"New york","2":"London","3":"Mumbai"} A: Put an AJAX Function like this, $("#source_type").change(function(){ $.ajax({ type : 'POST', data : 'source_id='+ $(this).val(), url : 'controller/method', success : function(data){ $('#location').val(data); } }); }); In controller, put a method to get the values, public function getLocations() { $source_id = $this->input->post('source_id'); // Call the model function and get all the locations based on the source type id // Populate the dropdown options here echo $result; } A: attach a change event handler to your first DD and send an ajax call to the server to fetch data. In the success callback of the ajax call populate the second DD. Below is a simple proof of concept $("#source_type").change(function(e) { $.ajax({ url:'/echo/json', success:function(data){ console.log("success"); $("<option/>",{text:'google',value:'google'}).appendTo("#location"); } }); DEMO
unknown
d8246
train
Just use color as transparent like this for making it fully transparent border:10px solid transparent; My fiddle And if you want to add opacity, than this approach of your's is correct, it does make the border opaque border-color:rgba(17,17,17,0.7); You can use this too border-color:rgba(244,244,244,0.4); My fiddle
unknown
d8247
train
You must configure lazy for collections In your case is for tasks.
unknown
d8248
train
Right out of head, a dumb method: a binary search in C:\Windows\System32 for GetProcessDpiAwareness, then studying each occurrence with Dependency Walker for exports. This produces the result: GetProcessDpiAwareness is exported by SHCore.dll. One may also search the Windows SDK headers and libs, but in my case I haven't found GetProcessDpiAwareness, to my surprise. Another idea, run the following from the command line prompt: for %f in (%windir%\system32\*.dll) do dumpbin.exe /exports %f >>%temp%\__exports Then search %temp%\__exports for the API. A: I know it's been asked a while back. (Every time I Google it, this question comes up. So let me share my method.) If anyone wants to search for functions in DLLs, there's this tool that will do it for you. In case of the GetProcessDpiAwareness on my Windows 10 (64-bit) it is exported from shcore.dll like someone had already mentioned above. Here's the screenshot: Although I need to preface it by saying that it would be always prudent to refer to the function's documentation on MSDN instead. Currently you can find it at the bottom of each page: If you play around with the search that I showed above, you will notice that many of the system functions are exported from multiple DLLs (some of which are undocumented.) So if you just blindly go with whatever you find in a search app, you may run a risk of breaking your program in the future if Microsoft changes one of those undocumented functions. So use it only for your own research or curiosity. A: Usually functions that work with the same resources are in the same dll's. Look at another dpi function like GetDpiForMonitor and you will see it is in Shcore.dll Edit: After you find the dll this way you can double check using dependency walker to see what functions are exported from that dll.
unknown
d8249
train
you can have extra subquery to count the values for each parent_cat_id SELECT c.id AS id, pc.parent_cat_id, pc.cat_name, d.totalCount FROM db.category c INNER JOIN db.parent_category pc ON pc.id = c.parent_cat_id INNER JOIN ( SELECT parent_cat_id, COUNT(*) totalCount FROM db.parent_category GROUP BY parent_cat_id ) d ON c.parent_cat_id = d.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order
unknown
d8250
train
Yes of course, you can use the `<jsp:include page="content.jsp">` or `<%@include file="content.jsp"%>` If your content is static(copy and paste), you can use `<%@include file="content.jsp"%>` The `<%@include file="content.jsp">` directive is similiar to "#include" in C programming, including the all contents of the included file and then compiling it like it is part of the including file. Also the included file can be any type (including HTML or text).
unknown
d8251
train
If anyone stumbles over the same problem: the combination of ServiceLoader.load(MyFactoryInterface.class, Thread.currentThread().getContextClassLoader()) in MyClient and Thread.currentThread().setContextClassLoader(MyWorld.class.getClassLoader()); in the second test did the job.
unknown
d8252
train
Had same issue, I don't want a pipeline launch on pipeline creation (which is the default beahviour). Best solution I fount is : * *Create an EventBridge rule which catch the pipelineExecution on pipeline creation *Stop the pipeline execution from the lambda triggered Rule looks like this : { "source": ["aws.codepipeline"], "detail-type": ["CodePipeline Pipeline Execution State Change"], "detail": { "state": ["STARTED"], "execution-trigger": { "trigger-type": ["CreatePipeline"] } } } It works fine A: Sadly, there seem to be no way of this this. Docs clearly states that a newly created pipeline immediately starts running: Now that you've created your pipeline, you can view it in the console. The pipeline starts to run after you create it. The initial run will always happen. Subsequent runs depend on your source action. For example, if you use CodeCommit as your source, you can disable CloudWatch Event that triggers the pipeline. Thus if you want to use CodePipeline in your project, you have to design it so that it does not causes any issues due to immediate start. A: You can disable the Event rule from automatically starting your pipeline. Go to Amazon EventBridge -> Rules and disable the rule that notifies the CodePipeline. A: Further to Marcin's comment, it would seem there are 2 approaches you can take which would limit the run of the pipeline. * *Create a disabled StageTransition or Manual Approval stage directly after the Source stage. This would prevent the pipeline executing any other action aside from getting the source which would have no impact or capability to re-write anything. *Alternatively if your source stage is from a repository, you can opt to handle the pipeline triggers yourself by disabling the PollForSourceChanges parameter in your cloudformation template. Pipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: *NAME* RoleArn: *IAMROLE* Stages: - Name: Source Actions: - Name: CodeCommitSourceAction RunOrder: 1 ActionTypeId: Category: Source Provider: CodeCommit Owner: AWS Version: '1' OutputArtifacts: - Name: Source Configuration: RepositoryName: *REPOSITORYNAME* BranchName: *BRANCH* PollForSourceChanges: "false" #prevents codepipeline polling repository for changes. A: So the correct answer is... * *Commit your code before you deploy for the first time *Deploy only the pipeline *Let Code Pipeline do its thing 99% of cases it will finish sooner than your machine.
unknown
d8253
train
Assuming that this uses Meteor-Blaze templates you need to include the conditionals for DOM element attributes inside quotes/double quotes: <a-gltf-model id='playerone' class="{{#if myplayer playerone}}entitymove{{/if}}" src="#myMixBun"> </a-gltf-model> Readings: http://blazejs.org/guide/spacebars.html A: SOLVED This is my original, which doesn’t work. In main.js: player = "player not active"; Template.hello.helpers( counter() {...... // if player one player = "playerone"; // if player two player = "playertwo"; return { myplayer: player }; } In main.html: // This statement works {{counter.myplayer}}.... <a-gltf-model id='playerone' class="{{#if counter.myplayer playerone}}entitymove{{/if}}" src="#myMixBun"> </a-gltf-model> <a-gltf-model id='playertwo' class="{{#if counter.myplayer playertwo}}entitymove{{/if}}" src="#myMixBun"> </a-gltf-model> I think there are 2 problems with this: 1) spacebars doesn’t seem to like the if statement with a comparison?: {{#if counter.myplayer playertwo}} It only allows true or false if statements?, such as: {{#if counter.player1}} 2) My aframe custom component isn’t actually a class, so I can’t put the meteor #if statement inside the entity. I changed the code to the following and it now works: Changed main.js to: playerone =""; playertwo =""; // if player one playerone = "true"; playertwo = ""; // if player two playerone = ""; playertwo = "true"; return { player1: playerone, player2: playertwo}; } Changed main.html to: // These statements work {{#if counter.player1}}player1 is true{{/if}} {{#if counter.player2}}player2 is true{{/if}}.... {{#if counter.player1}} <a-gltf-model id='playerone' entitymove src="#myMixBun" ></a-gltf-model> <a-gltf-model id='playertwo' src="#myMixBun" ></a-gltf-model> {{/if}} {{#if counter.player2}} <a-gltf-model id='playerone' src="#myMixBun" ></a-gltf-model> <a-gltf-model id='playertwo' entitymove src="#myMixBun" ></a-gltf-model> {{/if}}
unknown
d8254
train
Lets call your host as HOST_BASE. You are having two containers, one is exposing 5000 on host. Its HOST_BASE:5000. Other is your python-app container. Now, you are running another python-app in container on host HOST_BASE. And try to hit: http://0.0.0.0:5000, which is not accessible. Note: its 0.0.0.0 is localhost of the container itself. You want to connect to HOST_BASE:5000, which is not localhost or 0.0.0.0 You need to configure networking between your two containers. Or, for simplicity, use --network host while running both of your container. Hope that helps. A: There is an acceptable answer for this question on stackoverflow which solves the problem: Python requests in Docker Compose containers
unknown
d8255
train
When setting up your CNAME, you need to end its value with a dot. to be absolute CNAME: webapp-*****.pythonanywhere.com. Otherwise it will be relative to your custom domain and end up like this : webapp-*****.pythonanywhere.com.$DOMAIN See Domain names with dots at the end
unknown
d8256
train
I found the solution. This query does approximately what i want to do var query = from b in db.BrandTbls.AsQueryable() join m in db.ShoeModelTbls on b.BrandID equals m.BrandID join s in db.ShoeTbls on m.ModelID equals s.ModelID join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.ShoeID,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g select new {g.Key.ShoeID,g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price}; A: Remove price from the output and use Distinct() like this: var query = (from b in db.BrandTbls.AsQueryable() join m in db.ShoeModelTbls on b.BrandID equals m.BrandID join s in db.ShoeTbls on m.ModelID equals s.ModelID join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID where s.Quantity > 0 orderby m.ModelName select new { s.ShoeID, m.ModelName, b.BrandName, i.ImagePath }).Distinct();
unknown
d8257
train
It's very simple. You can call it from anywhere in APP. $out = new \Symfony\Component\Console\Output\ConsoleOutput(); $out->writeln("Hello from Terminal"); A: You've to config where laravel to store the logs. Default Log::info() put the log in the log file not the console. you can use tail -f logpath to see the log. A: Try with error_log('message here.'); Read More If You ant add LOG Log::info('message'); If LOG with an array Log::info(json_encode($array)); Import Illuminate\Support\Facades\Log; A: Laravel 5.6 simplified this because you now have a logging.php config file you could leverage. The key thing to know is that you want to output to stdout and php has a stream wrapper built-in called php://stdout. Given that, you could add channel for that wrapper. You would add the stdout "channel" to your channels that you will be logging to. Here's how the config will basically look: <?php return [ 'default' => env('LOG_CHANNEL', 'stack'), 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single','stdout'], ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ], 'stdout' => [ 'driver' => 'monolog', 'handler' => StreamHandler::class, 'with' => [ 'stream' => 'php://stdout', ], ], ]; I have more information here - Laravel 5.6 - Write to the Console A: You can call info() method $this->info("Your Message");
unknown
d8258
train
It is safe. Accessing weak pointer and Zeroing weak pointer is in between spinlock_lock and spinlock_unlock. Take a look at the runtime source code http://opensource.apple.com/source/objc4/objc4-646/runtime/NSObject.mm Accessing weak pointer id objc_loadWeakRetained(id *location) { id result; SideTable *table; spinlock_t *lock; retry: result = *location; if (!result) return nil; table = SideTable::tableForPointer(result); lock = &table->slock; spinlock_lock(lock); if (*location != result) { spinlock_unlock(lock); goto retry; } result = weak_read_no_lock(&table->weak_table, location); spinlock_unlock(lock); return result; } Zeroing weak pointer void objc_object::sidetable_clearDeallocating() { SideTable *table = SideTable::tableForPointer(this); // clear any weak table items // clear extra retain count and deallocating bit // (fixme warn or abort if extra retain count == 0 ?) spinlock_lock(&table->slock); RefcountMap::iterator it = table->refcnts.find(this); if (it != table->refcnts.end()) { if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) { weak_clear_no_lock(&table->weak_table, (id)this); } table->refcnts.erase(it); } spinlock_unlock(&table->slock); } And the Object deallocating flow https://stackoverflow.com/a/14854977/629118
unknown
d8259
train
Considering the Type of MaxRequestLength is a Int, at the moment there is no way to parse a value higher than Int.Max correctly. I heard they might be increasing IIS8 but nothing concrete from Microsoft as of yet. The only way I've seen in .Net 4.5 is to use HttpRequest.GetBufferlessInputStream which Gets a Stream object that can be used to read the incoming HTTP entity body, optionally disabling the request-length limit that is set in the MaxRequestLength property. A: In my case these were the changes I needed to apply: <system.web> <httpRuntime targetFramework="4.6.1" maxRequestLength="2147483647" /> </system.web> <system.webServer> <serverRuntime uploadReadAheadSize="2147483647" /> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer> In order to add the serverRuntime follow the intructions in the first answer of this question A: You should be able to override the settings inside machine.config by adding the same node into your application's web.config like so. Microsoft has some information about ASP.NET Configuration File Hierarchy and Inheritance. NOTE: Erik Philips is right and the max size of maxRequestLength is 2,147,483,647 (Int32.MaxValue). This answer is to illustrate how to override a setting defined in machine.config (or any .config) from within your application's web.config/ <configuration> ... <system.web> <httpRuntime maxRequestLength="2147483647"/> ... ... </system.web> ... </configuration> In doing this though, you might also want to increase your timeout or it might, well, time out.
unknown
d8260
train
Even if you can have more then a single http block you should not do it. But having an http block in another http block IS NOT ALLOWED and will raise an error on startup. Just tested this on my instance. So you should check the output of nginx -T and check the configuration. The NGINX configuration works in an hierarchical order. Means a directive you set in the http context can be overwritten in the server or location context if supported.
unknown
d8261
train
Based on the code you've provided, it looks like listObjects is a function that accepts an object and a callback, and at some point calls that callback, so probably the simplest way to mock it would be like this: listObjects: (_, c) => c() The function you're testing only seems to care whether listObjects is passing an error to the callback or not, so this should seemingly be sufficient. Side note: you have return resolve in two places in your isS3Healthy function, but using return here almost certainly serves no purpose. To resolve a promise, just call resolve(...) without returning it.
unknown
d8262
train
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" />
unknown
d8263
train
As JDro04 pointed out, you can use Thread.Sleep to do delay. But your app will hang if you do it from main thread. So you can do delay in separate thread and invoke MessageBox.Show in the main one, here's the snippet: private void Button1_Click(object sender, RoutedEventArgs e) { Task.Factory .StartNew(() => Thread.Sleep(4000)) .ContinueWith( continuationAction: _ => { MessageBox.Show("My message!"); /* put rest of your code here */ }, cancellationToken: CancellationToken.None, continuationOptions: TaskContinuationOptions.None, scheduler: TaskScheduler.FromCurrentSynchronizationContext()); }
unknown
d8264
train
Absolutely not, in so many ways that it would be hard to count them all. First and foremost, the memory layout of arguments is simply not specified by the C language. Full stop. It is not specified. Thus the answer is "no" immediately. va_list exists because there was a need to be able to navigate a list of varadic arguments because it wasn't specified other than that. va_list is intentionally very limited, so that it works on platforms where the shape of the stack does not match your intuition. Other reasons it can't always be 4: * *What if you pass an object of length 8? *What if the compiler optimizes a reference to actually point at the object in another frame? *What if the compiler adds padding, perhaps to align a 64-bit number on a 64-bit boundary? *What if the stack is built in the opposite direction (such that the difference would be -4 instead of +4) The list goes on and on. C does not specify the relative addresses between arguments. A: As the other answers correctly say: No. Furthermore, even trying to determine whether the addresses differ by 4 bytes, depending on how you do it, probably has undefined behavior, which means the C standard says nothing about what your program does. void func(long a, long b) { printf("%d\n", (int)&b - (int)&a); } &a and &b are expression of type long*. Converting a pointer to int is legal, but the result is implementation-defined, and "If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type." It's very likely that pointers are 64 bits and int is 32 bits, so the conversions could lose information. Most likely the conversions will give you values of type int, but they don't necessarily have any meaning, nor does their difference. Now you can subtract pointer values directly, with a result of the signed integer type ptrdiff_t (which, unlike int, is probably big enough to hold the result). printf("%td\n", &b - &a); But "When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements." Pointers to distinct object cannot be meaningfully compared or subtracted. Having said all that, it's likely that the implementation you're using has a memory model that's reasonably straightforward, and that pointer values are in effect represented as indices into a monolithic memory space. Comparing &b vs. &a is not permitted by the C language, but examining the values can provide some insight about what's going on behind the curtain -- which can be especially useful if you're tracking down a bug. Here's something you can do portably to examine the addresses: printf("&a = %p\n", (void*)&a); printf("&b = %p\n", (void*)&b); The result you're seeing for the subtraction (4) suggests that type long is probably 4 bytes (32 bits) on your system. I'd guess you're on Windows. It also suggests something about the way function parameters are allocated -- something that you as a programmer should almost never have to care about, but is worth understanding anyway. A: [...] I was just curious if the addresses of a function's parameters are always in a difference of 4 bytes from one another." The greatest error in your reasoning is to think that the parameters exist in memory at all. I am running this program on x86-64: #include <stdio.h> #include <stdint.h> void func(long a, long b) { printf("%d\n", (int)((intptr_t)&b - (intptr_t)&a)); } int main(void) { func(1, 2); } and compile it with gcc -O3 it prints 8, proving that your guess is absolutely wrong. Except... when I compile it without optimization it prints out -8. X86-64 SYSV calling convention says that the arguments are passed in registers instead of being passed in memory. a and b do not have an address until you take their address with & - then the compiler is caught with its pants down from cheating the as-if rule and it quickly pulls up its pants and stuffs them into some memory location so that they can have their address taken, but it is in no way consistent in where they're stored.
unknown
d8265
train
* *Create a private variable, eg private $count = 0; *Increment it each time your function is run *Don't hide the comments if it's the first time you're running it :) A: If you need to target the "main" WP_Query_Comments() within the comments_template() core function, then the comments_template_query_args filter is available since WordPress 4.5: $comment_args = apply_filters( 'comments_template_query_args', $comment_args ); $comment_query = new WP_Comment_Query( $comment_args ); See ticket #34442 for more info and a simple example here.
unknown
d8266
train
If you need see Output Values, please add the Outputs code as below output "signed_url" { value = "${data.google_storage_object_signed_url.get_url.signed_url}" }
unknown
d8267
train
With: window.innerHeight You can know the height of the browser window and style your elements accordingly. I am assuming that by fold you mean what you see without scrolling. If you need a more backwards compatible (<I.E9) height and you can use jquery: $( window ).height(); A: You might try using the css unit of measurement vh. Say you have a div that you only want to take up half the screen (viewport) you would do something like this: div{ height: 50vh; } vh stands for "Viewport Height" and is used like a percentage. So to have the div always take up 100% of the view-able area (viewport), regardless of the screen size or resolution you would do this: div { height: 100vh; } A: I would use document.documentElement.clientHeight and document.documentElement.clientWidth which are essentially the width and height of the html element: $('div').css({'height':document.documentElement.clientHeight+'px', 'width':document.documentElement.clientWidth+'px'}); http://jsfiddle.net/L1wsLc2c/1/ You would have to re-execute this code every time the window is resized to keep the bottom of the box flush with the page fold.
unknown
d8268
train
To add to andyhasit's answer, using a service account is the correct and easiest way to do this. The problem with using the JSON key file is it becomes hard to deploy code anywhere else, because you don't want the file in version control. An easier solution is to use an environment variable like so: https://benjames.io/2020/09/13/authorise-your-python-google-drive-api-the-easy-way/ A: You can do this, but need to use a Service Account, which is (or rather can be used as) an account for an application, and doesn't require a browser to open. The documentation is here: https://developers.google.com/api-client-library/python/auth/service-accounts And an example (without PyDrive, which is just a wrapper around all this, but makes service account a bit trickier): from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials from httplib2 import Http scopes = ['https://www.googleapis.com/auth/drive.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name('YourDownloadedFile-5ahjaosi2df2d.json', scopes) http_auth = credentials.authorize(Http()) drive = build('drive', 'v3', http=http_auth) request = drive.files().list().execute() files = request.get('items', []) for f in files: print(f) A: I know it's quite late for answer but this worked for me: Use the same API you were using, this time in your computer, it will generate a Storage.json which using it along with your scripts will solve the issue (specially in read-ony platforms like heroku) A: Checkout the Using OAuth 2.0 for Web Server Applications. It seems that's what you're looking for. Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project. Open the Credentials page in the API Console. Click Create credentials OAuth client ID. Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses. For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080. We recommend that you design your app's auth endpoints so that your application does not expose authorization codes to other resources on the page. A: Might be a bit late but I've been working with gdrive over python, js and .net and here's one proposed solution (REST API) once you get the authorization code on authorization code How to refresh token in .net google api v3? Please let me know if you have any questions
unknown
d8269
train
This bit: vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names vars.put("old_date_succeeded", "succeededDate"); vars.put("old_date_running", "runningDate"); seems odd to me. Given: submittedDate, succeeddedDate and runningDates are regular expr. reference names My expectation is that you should be using JMeter Variables instead of hardcoded strings there, so you should change your code to look like: vars.put("old_date_submitted", vars.get("submittedDate")); // submittedDate, succeeddedDate and runningDates are regular expr. reference names vars.put("old_date_succeeded", vars.get("succeededDate")); vars.put("old_date_running", vars.get("runningDate")); So most likely your code is failing at DatatypeConverter.parseDateTime. Next time you face any problem with your Beanshell scripts consider the following troubleshooting techniques: * *Check jmeter.log file - in case of Beanshell script failure the error will be printed there *Add debug(); directive to the very beginning of your Beanshell script - it will trigger debugging output to stdout *Put your Beanshell code in try/catch block like: try { //your code here } catch (Throwable ex) { log.error("Something went wrong", ex); throw ex; } This way you get more "human-friendly" stacktrace printed to jmeter.log file. See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell in JMeter tests.
unknown
d8270
train
This can be done using purrr::pmap, which passes a list of arguments to a function that accepts "dots". Since most functions like mean, sd, etc. work with vectors, you need to pair the call with a domain lifter: df_1 %>% select(-y) %>% mutate( var = pmap(., lift_vd(mean)) ) # x.1 x.2 x.3 x.4 var # 1 70.12072 62.99024 54.00672 86.81358 68.48282 # 2 49.40462 47.00752 21.99248 78.87789 49.32063 df_1 %>% select(-y) %>% mutate( var = pmap(., lift_vd(sd)) ) # x.1 x.2 x.3 x.4 var # 1 70.12072 62.99024 54.00672 86.81358 13.88555 # 2 49.40462 47.00752 21.99248 78.87789 23.27958 The function sum accepts dots directly, so you don't need to lift its domain: df_1 %>% select(-y) %>% mutate( var = pmap(., sum) ) # x.1 x.2 x.3 x.4 var # 1 70.12072 62.99024 54.00672 86.81358 273.9313 # 2 49.40462 47.00752 21.99248 78.87789 197.2825 Everything conforms to the standard dplyr data processing, so all three can be combined as separate arguments to mutate: df_1 %>% select(-y) %>% mutate( v1 = pmap(., lift_vd(mean)), v2 = pmap(., lift_vd(sd)), v3 = pmap(., sum) ) # x.1 x.2 x.3 x.4 v1 v2 v3 # 1 70.12072 62.99024 54.00672 86.81358 68.48282 13.88555 273.9313 # 2 49.40462 47.00752 21.99248 78.87789 49.32063 23.27958 197.2825 A: A few approaches I've taken in the past: * *use a pre-existing row-wise function (e.g. rowSums) *using reduce (which doesn't apply to all functions) *complicated transposing *custom function with pmap Using pre-existing row-wise functions set.seed(1) df_1 <- data.frame( x = replicate(4, runif(30, 20, 100)), y = sample(1:3, 30, replace = TRUE) ) library(tidyverse) # rowSums df_1 %>% mutate(var = rowSums(select(., -y))) %>% head() #> x.1 x.2 x.3 x.4 y var #> 1 41.24069 58.56641 93.03007 39.17035 3 232.0075 #> 2 49.76991 67.96527 43.48827 24.71475 2 185.9382 #> 3 65.82827 59.48330 56.72526 71.38306 2 253.4199 #> 4 92.65662 34.89741 46.59157 90.10154 1 264.2471 #> 5 36.13455 86.18987 72.06964 82.31317 3 276.7072 #> 6 91.87117 73.47734 40.64134 83.78471 2 289.7746 Using Reduce df_1 %>% mutate(var = reduce(select(., -y),`+`)) %>% head() #> x.1 x.2 x.3 x.4 y var #> 1 41.24069 58.56641 93.03007 39.17035 3 232.0075 #> 2 49.76991 67.96527 43.48827 24.71475 2 185.9382 #> 3 65.82827 59.48330 56.72526 71.38306 2 253.4199 #> 4 92.65662 34.89741 46.59157 90.10154 1 264.2471 #> 5 36.13455 86.18987 72.06964 82.31317 3 276.7072 #> 6 91.87117 73.47734 40.64134 83.78471 2 289.7746 ugly transposing and matrix / data.frame conversion df_1 %>% mutate(var = select(., -y) %>% as.matrix %>% t %>% as.data.frame %>% map_dbl(var)) %>% head() #> x.1 x.2 x.3 x.4 y var #> 1 41.24069 58.56641 93.03007 39.17035 3 620.95228 #> 2 49.76991 67.96527 43.48827 24.71475 2 318.37221 #> 3 65.82827 59.48330 56.72526 71.38306 2 43.17011 #> 4 92.65662 34.89741 46.59157 90.10154 1 878.50087 #> 5 36.13455 86.18987 72.06964 82.31317 3 520.72241 #> 6 91.87117 73.47734 40.64134 83.78471 2 506.16785 Custom function with pmap my_var <- function(...){ vec <- c(...) var(vec) } df_1 %>% mutate(var = select(., -y) %>% pmap(my_var)) %>% head() #> x.1 x.2 x.3 x.4 y var #> 1 41.24069 58.56641 93.03007 39.17035 3 620.9523 #> 2 49.76991 67.96527 43.48827 24.71475 2 318.3722 #> 3 65.82827 59.48330 56.72526 71.38306 2 43.17011 #> 4 92.65662 34.89741 46.59157 90.10154 1 878.5009 #> 5 36.13455 86.18987 72.06964 82.31317 3 520.7224 #> 6 91.87117 73.47734 40.64134 83.78471 2 506.1679 Created on 2019-04-30 by the reprex package (v0.2.1) A: I think this is tricky because the scoped variants of mutate (mutate_at, mutate_all, mutate_if) are generally aimed at executing a function on a specific column, instead of creating an operation that uses all columns. The simplest solution I can come up with basically amounts to creating a vector (cols) that is then used to execute the summary operation: library(dplyr) library(purrr) df_1 <- data.frame( x = replicate(4, runif(30, 20, 100)), y = sample(1:3, 30, replace = TRUE) ) # create vector of columns to operate on cols <- names(df_1) cols <- cols[map_lgl(df_1, is.numeric)] cols <- cols[! cols %in% c("y")] cols #> [1] "x.1" "x.2" "x.3" "x.4" df_1 %>% select(-y) %>% rowwise() %>% mutate( var = sum(!!!map(cols, as.name), na.rm = TRUE) ) #> Source: local data frame [30 x 5] #> Groups: <by row> #> #> # A tibble: 30 x 5 #> x.1 x.2 x.3 x.4 var #> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 46.1 28.9 28.9 50.7 155. #> 2 26.8 68.0 67.1 26.5 188. #> 3 35.2 63.8 62.5 28.5 190. #> 4 31.3 44.9 67.3 68.2 212. #> 5 52.6 23.9 83.2 43.4 203. #> 6 55.7 92.8 86.3 57.2 292. #> 7 56.9 50.0 77.6 25.6 210. #> 8 95.0 82.6 86.1 22.7 286. #> 9 62.7 26.5 61.0 88.9 239. #> 10 65.2 23.1 25.5 51.0 165. #> # … with 20 more rows Created on 2019-04-30 by the reprex package (v0.2.1) NOTE: if you are unfamiliar with purrr, you can also use something like lapply, etc. You can read more about these types of more tricky dplyr operations (!!, !!!, etc.) here: https://dplyr.tidyverse.org/articles/programming.html A: This is a tricky problem since dplyr operates column-wise for many operations. I originally used apply from base R to apply over rows, but apply is problematic when handling character and numeric types. Instead we can use (the aging) plyr and adply to do this simply, since plyr lets us treat a one-row data frame as a vector: df_1 %>% select(-y) %>% adply(1, function(df) c(v1 = sd(df[1, ]))) Note some functions like var won't work on a one-row data frame so we need to convert to vector using as.numeric.
unknown
d8271
train
Short answer: No, it's not equivalent. When you use synchronized around that return ao;, the ArrayList is only synchronized during the return instruction. This means that 2 threads cannot get the object at the exact same time, but once they have got it, they can modify it at the same time. If 2 threads execute this code, the add() is not thread safe: ArrayList<?> list = getAo(); // cannot be executed concurrently list.add(something); // CAN be executed concurrently Side note: don't use Vectors, take a look at this post to know why. A: They aren't equivalent. What you're looking for is Collections.synchronizedList which can "wrap around" any list, including ArrayList. A: to do the equivalent of Vector you should protect any access to any element in the collection, the method getAo simply sychronize the access to the array list. If two threads call getAo and after each thread call "add" method over this arraylist then you could have a multi thread problem (because "add" is not synch"). I recommend you to check the atomic classes like CopyOnWriteArrayList: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
unknown
d8272
train
You could replace }{ with a },{, parse it and take Object.assign for getting an object with indices as properties from an array. const data = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}'; result = Object.assign({}, JSON.parse(`[${data.replace(/\}\{/g, '},{')}]`)); console.log(result); .as-console-wrapper { max-height: 100% !important; top: auto; } A: If they're in an array, it's fairly simple - just use reduce: const data = [{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}},{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}]; const res = data.reduce((a, c, i) => (a[i] = c, a), {}); console.log(res); .as-console-wrapper { max-height: 100% !important; top: auto; } A: You can use Array.protoype.match to separate each object then Array.protoype.reduce to get expected oject. let a = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}'; let objects = a.match(/({"device_type".*?}}}})/g).map(e => JSON.parse(e)); console.log('Array of objects',objects) const out = {...[objects]}; console.log('\ndesired output',out) Also, it seems to be useless to convert the array into an object when the keys are just the indexes.
unknown
d8273
train
Use the .one binding instead. This will attach it to fire on the first click and remove itself. A: In case you need only part of your event handler to run once : $("div").on("click",function(){ if (!$(this).data("fired")) { console.log("Running once"); $(this).data("fired",true); } console.log("Things as usual"); }); Demo A: Use: var isalreadyclicked=false; $('#navi a').bind('click',function(e){ var $this = $(this); var prevButton = current; $this.closest('ul').find('li').removeClass('selected'); if ( $(this).attr('id') == 'tab2') { if(!isalreadyclicked){ //fire function only once isalreadyclicked=true; } } });
unknown
d8274
train
You can get ids of courses associated with a given skill name, and then get a list of courses with ids that don't match the previous found. You can even make it as one composite SQL query. Course.where.not(id: Course.ransack({user_assigned_content_skills_skill_name_cont: 'ruby'}).result) This will generate an SQL like this: SELECT courses.* FROM courses WHERE courses.id NOT IN ( SELECT courses.id FROM courses LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user' LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id WHERE (skills.name ILIKE '%ruby%') )
unknown
d8275
train
From the documentation NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001). Since sqlite does not support NSDate directly, the date is persisted as the underlying value. 530963469.705571 represents the number of seconds between 00:00:00 UTC on 1 January 2001 and the time when you created the NSDate You can use the NSDate initialiser init(timeIntervalSinceReferenceDate:) to create an NSDate from the time interval value.
unknown
d8276
train
Solved it, apparently this code needed to be removed: OutputStream outputStream = conn.getOutputStream(); outputStream.close(); I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues. I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed... Anyway that is my solution, thanks a lot for your help guys ! A: HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working. A: For anyone still reaching here from a search engine, my solution was similar - I removed the line "conn.setDoOutput(true);" (or set it to false)
unknown
d8277
train
If i am not wrong you just want to read a text from remote file, so here it is. NSString * result = NULL; NSError *err = nil; NSURL * urlToRequest = [NSURL URLWithString:@"YOUR_REMOTE_FILE_URL"];//like "http://www.example.org/abc.txt" if(urlToRequest) { result = [NSString stringWithContentsOfURL: urlToRequest encoding:NSUTF8StringEncoding error:&err]; } if(!err){ NSLog(@"Result::%@",result); } A: To load the remote txt file, you should take a look at NSURLConnection or AFNetworking (there are other possibilities, these two are probably the most common). You will then get the content of the file. Depending on what you intend to do with it, you may have to parse it, either with something as simple as -[NSString componentsSeparatedByString:] or with something a bit more powerful like NSScanner. A: There are three steps involved in loading a file * *create the object that specifies the location of the file *call the appropriate NSString class method to load the file into a string *handle the error if the file is not found In step 1, you need to either create an NSString with the full path to the file in the file system, or you need to create an NSURL with the network location of the file. In the example below, the code creates an NSURL since your file is on the network. In step 2, use the stringWithContentsOfFile method to load a file from the file system, or the stringWithContentsOfURL method to load a file from the network. In either case, you can specify the file encoding, or ask iOS to auto-detect the file encoding. The code below auto detects while loading from the network. In step 3, the code below dumps the file to the debug console if successful or dumps the error object to the console on failure. Missing from this code is multithreading. The code will block until the file is loaded. Running the code on a background thread, and properly notifying the main thread when the download is complete, is left as an exercise for the reader. NSURL *url = [NSURL URLWithString:@"www.example.com/somefile.txt"]; NSStringEncoding encoding; NSError *error; NSString *str = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]; if ( str ) NSLog( @"%@", str ); else NSLog( @"%@", error );
unknown
d8278
train
var current = 0; $(".kunde-logo-listing").each(function() { $(this).data("wow-delay", current+"00ms"); current++; }); A: You can use this as follows: var current = 0; $(".kunde-logo-listing").each(function () { $(this).data("wow-delay", current++ * 100 + "ms"); // ^^^^^^^^^^^^^^^^^^^^^^^ });
unknown
d8279
train
There are a couple of guidelines that I follow when writing complex data structures in C++: * *Avoid raw pointers; use smart pointers. *Try to figure out early on if your data structure is cyclic or acyclic. If there are cycles in your data structure you won't be able to used share_ptr everywhere without creating a leak. At some point in your cyclic structure you want to break the cycle with a weak_ptr, so that objects can be released. *If my object holds onto other objects, and I want it to be a container, I implement the appropriate iterators when I need them, and not one second before. I usually need iterator support when I want to use one of the STL algorithms on my container. I could, of course, implement iterators that don't match the STL (in terms of naming or semantics) for my own use, but then I've added yet another way to do things in my code. I try to avoid that. *If my class is intended to hold different types, then I use templates to express that. There are ways to do this in C (using memcpy, etc), but while the code you'll end up with will be more understandable to C coders, you will lose most of the benefits of C++ (type safety, assignment operators, etc).
unknown
d8280
train
If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation. changeActiveLink is defined in JS (ex:init.js) file which you include to each page function changeActiveLink() { var currentLocation = window.location.href; currentLocation = currentLocation.replace('//', '/').split('/'); var page = currentLocation[currentLocation.length - 1]; if (page == "") { page = 'index.html'; } $('#leftNav1 a[href*="'+ page +'"]').addClass('active'); } This line is called from each file when "init.js" is included. $('#leftNav1').load('navigation.html', changeActiveLink); A: Or you can use any HTML or even HTML5 tag to specify li item. <li class="some"> or <li title="some"> or <li attr-specify="some-specific-in-url"> and jQuery with window.location object $('li[title="' + window.location.path + '"]').addClass("active"); A: You could set up some jquery script to get the url and then find the href of the li that matches that. This will allow you to addClass() to that li of active. This of course will only work if your href matches the url
unknown
d8281
train
Use FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer") in the back bean, you can have the request url. This bothers me for a long long time, hope this will help someone.
unknown
d8282
train
Banshee does not expose rating functions via DBus. You can quickly view all functions that it exposes, using applications like d-feet[1]. Make sure that an instance of the application you are interested in (like Banshee in this case) is running. There is a bug report already requesting to add rating functionality[2] to DBus interface. You might want to subscribe to it. * *https://fedorahosted.org/d-feet/ *https://bugzilla.gnome.org/show_bug.cgi?id=579754 A: Banshee does support rating via commandline since last year. banshee --set-rating={1;2;3;4;5} See the bug report for more options: Add item rating to DBus interface A: Sadly the developer have not implemented a GET method, so there is no common way to execute "rate current track 1 star up/down"-command, much less than a specific track. Does anyone has written a script which provide this feature? Yet, I haven't found any solution to modify the D-Bus Property via command line. Finally here is my Workaround for rate the current played Track. #!/bin/bash #read current TrackRating R=$(qdbus org.mpris.MediaPlayer2.banshee /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadata | grep 'userRating' | tr -d '/xesam:userRating: ') case $R in '' ) R=0 ;; '0.2' ) R=1 ;; '0.4' ) R=2 ;; '0.6' ) R=3 ;; '0.8' ) R=4 ;; '1' ) R=5 ;; esac case $1 in 'inc' ) [ $R -lt 5 ] banshee --set-rating=$(($R+1)) ;; 'dec' ) [ $R -gt 0 ] banshee --set-rating=$(($R-1)) ;; 'res' ) banshee --set-rating=3 ;; 'min' ) banshee --set-rating=0 ;; 'max' ) banshee --set-rating=5 ;; esac Options: * *inc -> increase rating by one if possible *dec -> decrease rating by one if possible *res -> reset rating to three stars *min -> set rating to zero stars *max -> set rating to five stars As far Banshee will not provide manipulating data of a specific Track this is my best bet.
unknown
d8283
train
Assuming the select statement is part of a login form, then most likely it's generated something like this: $user = $_POST['username']; $pwd = $_POST['password']; $query = "SELECT .... WHERE user_username='$user' AND user_password=md5('$pwd')"; which means, you could hack in by entering: noob') or ('a'='a for the password, giving you SELECT .... AND user_password=md5('noob') or ('a'='a') ^^^^^^^^^^^^^^^^^-- your contribution The actual password might not match, but 'a' will always equal itself, so the where clause will succeed and match a record based purely on the username and return the admin user's user_id. A: As others had mentioned the escaping that you see is not the OS, but some form of encoding done in PHP (likely magic quotes, but could be a straight call to addslashes()). Basically what you need to do is send in a form of quote that will not be escaped. You should research why one would use mysql_escape_string() rather than addslashes() and/or check this out: http://forums.hackthissite.org/viewtopic.php?f=37&t=4295&p=30747 A: Try ' OR 1; -- as user name. Imagine what the SQL query from such a user name looks like. A: This has nothing to do with the operating system. The operating system simply runs the PHP package. PHP is what does sanitization, etc. Have you tried submitting the following string for user_username?: admin' OR 1=1-- #assuming mysql Would yield a query: select user_id from user where user_username = 'admin' OR 1=1 --' AND user_password = md5('noob') In mysql (assuming the database type), -- is a comment, so everything after 1=1 is ignored. As a result, you've successfully gained access. If php magic quotes are on, however, this will be slightly more difficult. You will need to submit characters outside of utf-8 or attempt overflows or submitting null bytes. A: You could also try a bit of googling after entering a string that will error out the admin and use part of message that comes back as the key words. You could also use the http://gray.cs.uni.edu/moodle/mod/forum/discuss.php?d=106 fourm to ask questions so the whole class can benifit! if you can figure out how to upload files that would be great! I want to get c99.php up to really do some damage! you could also try some "hash" verse "dash dash"
unknown
d8284
train
[record.seq for record in pSeq] edit: You'll want str(pSeq[0].seq)
unknown
d8285
train
The output is 0x10. I.e., it's 0x2000 which means FILE_ATTRIBUTE_NOT_CONTENT_INDEXED and it's also 0x10 which means FILE_ATTRIBUTE_DIRECTORY. The values are bitwise-or'ed together. You can test them like this: if (file_attr & 0x10) puts("FILE_ATTRIBUTE_DIRECTORY");
unknown
d8286
train
I finally remembered that the term for this is "chunking", and then I was able to track it down, in the itertools recipes no less. Boiled down, it's this head-spinning little trick with zip (actually zip_longest, but who's counting): def chunk(source, n): return zip_longest(*([iter(source)] * n)) First you take n references to the same iterator and bundle them into a list; then you unpack this list (with *) as arguments to zip_longest. When it's used, each tuple returned by zip_longest is filled from n successive calls to the iterator. >>> for row in chunk(range(10), 3): ... print(row) (0, 1, 2) (3, 4, 5) (6, 7, 8) (9, None, None) See the itertools recipes (look for grouper) and this SO answer for variations on the corner cases. A: My suggestions is that, if you need such a function regularly, why not write it yourself. Here is an example how I would code it: def slice_into_lists(iterable, groupsize): rv = [] count = 0 for i in iterable: rv.append(i) count += 1 if count % groupsize == 0: yield rv rv = [] if rv: yield rv Of course instead of returning a list, you could also return something different. A: The problem got me interested, so I worked on a solution that would not copy anything but only use the original iterator. Posting it here as it relates directly to the question. class ichunk: ''' An iterable wrapper that raises StopIteration every chunksize+1'th call to __next__ ''' def __init__(self, iterable, chunksize, fill_last_chunk, fill_value): self.it = iter(iterable) self.stopinterval = chunksize+1 self.counter = 0 self.has_ended = False self.fill_last = fill_last_chunk self.fill_value = fill_value def __iter__(self): return self def __next__(self): if self.counter > 0 and self.counter % self.stopinterval == 0: self.counter += 1 raise StopIteration try: self.counter += 1 nexti = next(self.it) return nexti except StopIteration as e: self.has_ended = True if (not self.fill_last) or (self.counter % self.stopinterval == 0): raise e else: return self.fill_value def ichunker(iterable, chunksize, *, fill_last_chunk=False, fill_value=None): c = ichunk(iterable, chunksize, fill_last_chunk, fill_value) while not c.has_ended: yield c So rather then using the returned value from ichunker, you iterate over it again like: with open("filename") as fp: for chunk in ichunker(fp, 10): print("------ start of Chunk -------") for line in chunk: print("--> "+line.strip()) print("------ End of Chunk -------") print("End of iteration") A: Welcome to more_itertools. Straight from the documentation: >>> from more_itertools import ichunk >>> from itertools import count >>> all_chunks = ichunked(count(), 4) >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks) >>> list(c_2) # c_1's elements have been cached; c_3's haven't been [4, 5, 6, 7] >>> list(c_1) [0, 1, 2, 3] >>> list(c_3) [8, 9, 10, 11] You can choose between ichunk, which breaks an iterable into n sub-iterables, or chunk, which returns n sub-lists. A: Use itertools.islice with enumerate like this import itertools some_long_string = "ajbsjabdabdkabda" for n in itertools.islice(enumerate(some_long_string), 0, None ,10): print(some_long_string[n[0]:n[0]+10]) # output ajbsjabdab dkabda If you are dealing with file then you can use chunk while file.read() like this # for file with open("file1.txt", ) as f: for n in itertools.islice(enumerate(f.read(10000)), 0, 1000 ,5): print(n[1])
unknown
d8287
train
It will help you to get list of running application : for (NSRunningApplication *app in [[NSWorkspace sharedWorkspace] runningApplications]) { NSLog(@"%@",[app localizedName]); } A: You may get the cpu usage as: - (NSString*) get_process_usage:(int) pid { NSTask *task; task = [[NSTask alloc] init]; [task setLaunchPath:@"/bin/ps"]; NSArray *arguments; arguments = [NSArray arrayWithObjects: @"-O",@"%cpu",@"-p",[NSString stringWithFormat:@"%d",pid], nil]; [task setArguments: arguments]; NSPipe *pipe; pipe = [NSPipe pipe]; [task setStandardOutput: pipe]; NSFileHandle *file; file = [pipe fileHandleForReading]; [task launch]; NSData *data; data = [file readDataToEndOfFile]; NSString *string; string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSString* temp = [string stringByReplacingOccurrencesOfString:@"PID %CPU TT STAT TIME COMMAND" withString:@""]; NSMutableArray* arr =(NSMutableArray*) [temp componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [arr removeObject:@""]; [string release]; [task release]; if([arr count]>=2) return [arr objectAtIndex:1]; else return @"unknown"; }
unknown
d8288
train
"I've tried inserting "_blank" in various places" -- the correct place is in the a element: <a href="..." target="_blank"...> The code of your template should read: <?php foreach (glob("*.pdf") as $file) { echo '<li name="'.$file.'"><a href="'.$file.'" target="_blank">'.$file.'</a></li>'; } ?>
unknown
d8289
train
Oh lord how many times do I answer my own question right after posting it!!! I did attempt to delete some modules from the list that is the AzureRM ones, I didn't think it let me do it so I ended up just leaving them, I have no idea whether that is relevant or not but thought I'd mention it. On the Automation Account blad within the Azure portal I clicked on the "Run as accounts" option and it said it was incomplete, I deleted and recreated it and now everything works OK. Might help someone else so thought I'd post the answer. A: There are quite a few things to consider while the Az module in Azure Automation. This doc talks about these in greater detail. There is also a note that is worth quoting, from the same doc: Hope this helps.
unknown
d8290
train
* /{language}/MyController Application.MyController should allow you to access both languages, and you then have access to the language passed in, in the controller, if you wish.
unknown
d8291
train
It's not the slider which is messing up. Rather, IE isn't displaying the right border of #slider. I think moving the border to #overview would provide the style you're looking for. I have no idea why IE is messing up the border.
unknown
d8292
train
I'm not sure if I understand your question right, but to reduce boilerplate I would map your array to generate input fields: render:function(){ var inputs = []; this.props.form.fields.map(function(elem){ inputs.push(<Input data-fieldname={elem.fieldkey} type="text" label="Date Of Event" onChange={this.handleOnChange} value={elem.value} />); }); return (<div className="row"> {inputs} </div>) } This will always display your data in props. So when handleOnChange gets triggered the component will rerender with the new value. In my opinion this way is better than accessing a DOM node directly. A: If you want to use dynamic information on the input, you need to pass it through the array, and make a loop. Here is a little example based on Dustin code: var fieldArray = [ //replace by this.props.form.fields { fieldkey: 'Signs and Symptoms', value: 'fever, rash', type: 'text', label: 'Notes' }, { fieldkey: 'NotFeelingWell', value: 'false', type: 'checkbox', label: 'Not Feeling Well' }, ]; var Fields = React.createClass({ handleOnChange:function(e){ var fieldKey = e.target.attributes['data-fieldname'].value; Actions.updateField({ key: fieldKey, value: e.target.value }) }, render() { var inputs = []; fieldArray.map(function(field) { //replace by this.props.form.fields inputs.push( <Input data-fieldname={field.fieldkey} value={field.value} type={field.type} label={field.label} onChange={this.handleOnChange} /> ); }.bind(this)); return ( <div className="row"> {inputs} </div> ); } });
unknown
d8293
train
And take a look at ConstrainsLayout It will help you out build more complex layouts easily.Also your list of teams is completely hardcoded you should definetely switch to RecyclerView. A: you should follow Constraint layout, for your desired output I have attached some code. I hope, it helps. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto"> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="@id/ivPic" app:layout_constraintRight_toRightOf="@id/ivPic" app:layout_constraintBottom_toTopOf="@id/ivPic" android:text="Your desired text" android:textColor="@color/black" android:textSize="15sp" android:singleLine="true" android:marqueeRepeatLimit="marquee_forever" /> <ImageView android:id="@+id/ivPic" android:layout_width="100dp" android:layout_height="100dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/tvTitle" android:src="@drawable/yourImage" android:scaleType="centerCrop" android:padding="2dp" /> <TextView android:id="@+id/tvClubName" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="@id/ivPic" app:layout_constraintRight_toRightOf="@id/ivPic" app:layout_constraintTop_toBottomOf="@id/ivPic" android:text="Liverpool" android:textColor="@color/black" android:textSize="15sp" android:singleLine="true" android:padding="3dp" android:gravity="center_vertical|center" android:marqueeRepeatLimit="marquee_forever" /> </androidx.constraintlayout.widget.ConstraintLayout>
unknown
d8294
train
Here is an example of how you can get the previous RETENTION using a subquery, assuming that the period numbers are all consecutive: SELECT N_CUSTOMERS, PERIOD_NUMBER, CUSTOMER_WHEN_0, RETENTION, (SELECT st_inner.RETENTION FROM sourcetable st_inner WHERE st_inner.PERIOD_NUMBER = st_outer.PERIOD_NUMBER - 1 ) as PREVIOUS_RETENTION FROM sourcetable st_outer I left out the calculation for readability's sake, but I think it should be clear how to do this.
unknown
d8295
train
The site does a redirect, so you need to add CURLOPT_FOLLOWLOCATION => 1 to your options array. When in doubt with cURL, try $status = curl_getinfo($curl); echo json_encode($status, JSON_PRETTY_PRINT); giving : { "url": "http:\/\/www.mca.gov.in\/mcafoportal\/loginValidateUser.do?userNamedenc=hGJfsdnk%601t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=-825374456", "content_type": "text\/plain", "http_code": 302, "header_size": 1560, "request_size": 245, "filetime": -1, "ssl_verify_result": 0, "redirect_count": 0, "total_time": 1.298891, "namelookup_time": 0.526375, "connect_time": 0.999786, "pretransfer_time": 0.999844, "size_upload": 0, "size_download": 0, "speed_download": 0, "speed_upload": 0, "download_content_length": 0, "upload_content_length": -1, "starttransfer_time": 1.298875, "redirect_time": 0, "redirect_url": "http:\/\/www.mca.gov.in\/mcafoportal\/login.do", "primary_ip": "115.114.108.120", "certinfo": [], "primary_port": 80, "local_ip": "192.168.1.54", "local_port": 62524 } As you can see, you got a 302 redirect status, but a redirect_count was 0. After adding the option, i get: { "url": "http:\/\/www.mca.gov.in\/mcafoportal\/login.do", "content_type": "text\/html;charset=ISO-8859-1", "http_code": 200, "header_size": 3131, "request_size": 376, "filetime": -1, "ssl_verify_result": 0, "redirect_count": 1, "total_time": 2.383609, "namelookup_time": 1.7e-5, "connect_time": 1.7e-5, "pretransfer_time": 4.4e-5, "size_upload": 0, "size_download": 42380, "speed_download": 17779, "speed_upload": 0, "download_content_length": 42380, "upload_content_length": -1, "starttransfer_time": 0.30734, "redirect_time": 0.915858, "redirect_url": "", "primary_ip": "14.140.191.120", "certinfo": [], "primary_port": 80, "local_ip": "192.168.1.54", "local_port": 62642 } EDIT url encode the request parameters , and follow redirects $str = urlencode("userNamedenc=hGJfsdnk%601t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=-825374456"); curl_setopt_array( $curl , array ( CURLOPT_URL => "http://www.mca.gov.in/mcafoportal/loginValidateUser.do" , // <- removed parameters here CURLOPT_RETURNTRANSFER => true , CURLOPT_ENCODING => "" , CURLOPT_FOLLOWLOCATION => 1 , CURLOPT_MAXREDIRS => 10 , CURLOPT_TIMEOUT => 30 , CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1 , CURLOPT_CUSTOMREQUEST => "POST" , CURLOPT_POSTFIELDS => $str, // <- added this here CURLOPT_HTTPHEADER => array ( "cache-control: no-cache" ) , ) ); A: The simplest thing you can do, since you already have it working in POSTMAN, is to render out the PHP code in POSTMAN. Here is link about to get PHP code from POSTMAN. Then you can compare the POSTMAN example to your code. <?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://www.mca.gov.in/mcafoportal/loginValidateUser.do?userNamedenc=hGJfsdnk%601t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "postman-token: b54abdc0-17be-f38f-9aba-dbf8f007de99" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } What is immediately popping out to me is this 'hGJfsdnk`1t'. The backward quote can be an escape character '`'. This could very well be throwing an error where error handling redirects back to the login page. POSTMAN likely has something built in to render out the escape character to 'hGJfsdnk%601t'. Thus, this works in POSTMAN, but not in your code. Here is the status of this request: { "url": "http:\/\/www.mca.gov.in\/mcafoportal\/login.do", "content_type": "text\/html;charset=ISO-8859-1", "http_code": 200, "header_size": 3020, "request_size": 821, "filetime": -1, "ssl_verify_result": 0, "redirect_count": 1, "total_time": 2.920125, "namelookup_time": 8.2e-5, "connect_time": 8.7e-5, "pretransfer_time": 0.000181, "size_upload": 0, "size_download": 42381, "speed_download": 14513, "speed_upload": 0, "download_content_length": -1, "upload_content_length": -1, "starttransfer_time": 0.320995, "redirect_time": 2.084554, "redirect_url": "", "primary_ip": "115.114.108.120", "certinfo": [], "primary_port": 80, "local_ip": "192.168.1.3", "local_port": 45086 } Here is shows the successful login. A: This is honestly one of weird sites I have seen in a long time. First thing was to know how it works. So I decided to use chrome and see what happens when we login with wrong data Observations: * *Blanks username and passwords fields *Generates SHA1 hashes of username and password fields and sets then in userNamedenc and respectively *We can override username and password directly in JavaScript and login to your account just by overriding the details from console. *There are lot of different request which generates cookies but none of them look any useful So the approach to solve the issue was to follow below steps * *Get the login url login.do *Fetch the form details from the response for the access code *Submit the form to loginValidateUser.do The form sends below parameters Now one interesting part of the same is below post data displayCaptcha:true userEnteredCaptcha:strrty If we override the displayCaptcha to false then captcha is no more needed. So a wonderful bypass displayCaptcha: false Next was to code all of the above in PHP, but the site seemed so weird that many of the attempts failed. So finally I realized that we need to take it a bit closer to the browser login and also I felt delays between calls are needed <?php require_once("curl.php"); $curl = new CURL(); $default_headers = Array( "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding" => "deflate", "Accept-Language" => "en-US,en;q=0.8", "Cache-Control" => "no-cache", "Connection" => "keep-alive", "DNT" => "1", "Pragma" => "no-cache", "Referer" => "http://www.mca.gov.in/mcafoportal/login.do", "Upgrade-Insecure-Requests" => "1" ); // Get the login page $curl ->followlocation(0) ->cookieejar("") ->verbose(1) ->get("http://www.mca.gov.in/mcafoportal/login.do") ->header($default_headers) ->useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36") ->execute(); // Save the postfileds and access code as we would need them later for the POST field $post = $curl->loadInputFieldsFromResponse() ->updatePostParameter(array( "displayCaptcha" => "false", "userNamedenc" => "hGJfsdnk`1t", "passwordenc" => "675894242fa9c66939d9fcf4d5c39d1830f4ddb9", "userName" => "", "Cert" => "")) ->referrer("http://www.mca.gov.in/mcafoportal/login.do") ->removePostParameters( Array("dscBasedLoginFlag", "maxresults", "fe", "query", "SelectCert", "newUserRegistration") ); $postfields = $curl->getPostFields(); var_dump($postfields); // Access some dummy URLs to make it look like browser $curl ->get("http://www.mca.gov.in/mcafoportal/js/global.js")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/js/loginValidations.js")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/css/layout.css")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/img/bullet.png")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/getCapchaImage.do")->header($default_headers)->execute()->sleep(2); // POST to the login form the postfields saved earlier $curl ->sleep(20) ->header($default_headers) ->postfield($postfields) ->referrer("http://www.mca.gov.in/mcafoportal/login.do") ->post("http://www.mca.gov.in/mcafoportal/loginValidateUser.do") ->execute(false) ->sleep(3) ->get("http://www.mca.gov.in/mcafoportal/login.do") ->header($default_headers) ->execute(true); // Get the response from last GET of login.do $curl->getResponseText($output); //Check if user name is present in the output or not if (stripos($output, "Kiran") > 0) { echo "Hurray!!!! Login succeeded"; } else { echo "Login failed please retry after sometime"; } After running the code it works few times and few times it doesn't. My observations * *Only one login is allowed at a time. So not sure if others were using the login when I was testing *Without delays it would fail most of the time *There is no obvious reason when it fails to login except the site doing something on server side to block the request The reusable curl.php I created and used for chaining methods is below <?php class CURL { protected $ch; protected $postfields; public function getPostFields() { return $this->postfields; } public function newpost() { $this->postfields = array(); return $this; } public function addPostFields($key, $value) { $this->postfields[$key]=$value; return $this; } public function __construct() { $ch = curl_init(); $this->ch = $ch; $this->get()->followlocation()->retuntransfer(); //->connectiontimeout(20)->timeout(10); } function url($url) { curl_setopt($this->ch, CURLOPT_URL, $url); return $this; } function verbose($value = true) { curl_setopt($this->ch, CURLOPT_VERBOSE, $value); return $this; } function post($url='') { if ($url !== '') $this->url($url); curl_setopt($this->ch, CURLOPT_POST, count($this->postfields)); curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($this->postfields)); return $this; } function postfield($fields) { if (is_array($fields)){ $this->postfields = $fields; } return $this; } function close() { curl_close($this->ch); return $this; } function cookieejar($cjar) { curl_setopt($this->ch, CURLOPT_COOKIEJAR, $cjar); return $this; } function cookieefile($cfile) { curl_setopt($this->ch, CURLOPT_COOKIEFILE, $cfile); return $this; } function followlocation($follow = 1) { curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, $follow); return $this; } function loadInputFieldsFromResponse($response ='') { if ($response) $doc = $response; else $doc = $this->lastCurlRes; /* @var $doc DOMDocument */ //simplexml_load_string($data) $this->getResponseDoc($doc); $this->postfields = array(); foreach ($doc->getElementsByTagName('input') as $elem) { /* @var $elem DomNode */ $name = $elem->getAttribute('name'); // if (!$name) // $name = $elem->getAttribute('id'); if ($name) $this->postfields[$name] = $elem->getAttribute("value"); } return $this; } function retuntransfer($transfer=1) { curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, $transfer); return $this; } function connectiontimeout($connectiontimeout) { curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $connectiontimeout); return $this; } function timeout($timeout) { curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout); return $this; } function useragent($useragent) { curl_setopt($this->ch, CURLOPT_USERAGENT, $useragent); return $this; } function referrer($referrer) { curl_setopt($this->ch, CURLOPT_REFERER, $referrer); return $this; } function getCURL() { return $this->ch; } protected $lastCurlRes; protected $lastCurlResInfo; function get($url = '') { if ($url !== '') $this->url($url); curl_setopt($this->ch, CURLOPT_POST, 0); curl_setopt($this->ch, CURLOPT_HTTPGET, true); return $this; } function sleep($seconds){ sleep($seconds); return $this; } function execute($output=false) { $this->lastCurlRes = curl_exec($this->ch); if ($output == true) { echo "Response is \n " . $this->lastCurlRes; file_put_contents("out.html", $this->lastCurlRes); } $this->lastCurlResInfo = curl_getinfo($this->ch); $this->postfields = array(); return $this; } function header($headers) { //curl_setopt($this->ch, CURLOPT_HEADER, true); curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers); return $this; } function getResponseText(&$text){ $text = $this->lastCurlRes; return $this; } /* * * @param DOMDocument $doc * * */ function getResponseDoc(&$doc){ $doc = new DOMDocument(); libxml_use_internal_errors(false); libxml_disable_entity_loader(); @$doc->loadHTML($this->lastCurlRes); return $this; } function removePostParameters($keys) { if (!is_array($keys)) $keys = Array($keys); foreach ($keys as $key){ if (array_key_exists($key, $this->postfields)) unset($this->postfields[$key]); } return $this; } function keepPostParameters($keys) { $delete = Array(); foreach ($this->postfields as $key=>$value){ if (!in_array($key, $keys)){ array_push($delete, $key); } } foreach ($delete as $key) { unset($this->postfields[$key]); } return $this; } function updatePostParameter($postarray, $encoded=false) { if (is_array($postarray)) { foreach ($postarray as $key => $value) { if (is_null($value)) unset($this->postfields[$key]); else $this->postfields[$key] = $value; }} elseif (is_string($postarray)) { $parr = preg_split("/&/",$postarray); foreach ($parr as $postvalue) { if (($index = strpos($postvalue, "=")) != false) { $key = substr($postvalue, 0,$index); $value = substr($postvalue, $index + 1); if ($encoded) $this->postfields[$key]=urldecode($value); else $this->postfields[$key]=$value; } else $this->postfields[$postvalue] = ""; } } return $this; } function getResponseXml(){ //SimpleXMLElement('<INPUT/>')->asXML(); } function SSLVerifyPeer($verify=false) { curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $verify); return $this; } } ?> A: @yvesleborg and @tarun-lalwani gave the right hints. You need to take care of the cookies and the redirects. But nevertheless it was not working always for me. I guess the site operator requires some timeout between the two requests. I rewrote your code a little bit to play around with it. mycurl.php: function my_curl_init() { $url="http://www.mca.gov.in/mcafoportal/loginValidateUser.do"; $user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"; $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return $ch; } /* * first call in order to get accessCode and sessionCookie */ $ch = my_curl_init(); curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . "/cookie.txt"); // else cookielist is empty $output = curl_exec($ch); file_put_contents(__DIR__ . '/loginValidateUser.html', $output); // save cookie info $cookielist = curl_getinfo($ch, CURLINFO_COOKIELIST); //print_r($cookielist); curl_close($ch); // parse accessCode from output $re = '/\<input.*name="accessCode".*value="([-0-9]+)"/'; preg_match_all($re, $output, $matches, PREG_SET_ORDER, 0); if ($matches) { $accessCode = $matches[0][1]; // debug echo "accessCode: $accessCode" . PHP_EOL; /* * second call in order to login */ $post_fields = array( 'userNamedenc' => 'hGJfsdnk`1t', 'passwordenc' => '675894242fa9c66939d9fcf4d5c39d1830f4ddb9', 'accessCode' => $accessCode ); $cookiedata = preg_split('/\s+/', $cookielist[0]); $session_cookie = $cookiedata[5] . '=' . $cookiedata[6]; // debug echo "sessionCookie: $session_cookie" . PHP_EOL; file_put_contents(__DIR__ . '/cookie2.txt', $session_cookie); /* * !!! pause !!! */ sleep(20); // debug echo "curl -v -L -X POST -b '$session_cookie;' --data 'userNamedenc=hGJfsdnk`1t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=$accessCode' http://www.mca.gov.in/mcafoportal/loginValidateUser.do > loginValidateUser2.html"; $ch = my_curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); curl_setopt($ch, CURLOPT_COOKIE, $session_cookie); $output = curl_exec($ch); file_put_contents(__DIR__ . '/loginValidateUser2.html', $output); curl_close($ch); } The script issues two request to the website. The output of the first one is used to read the accessCode and to store the session cookie. Then after a little break the second one is issued using the accessCode and session information together with the login credentials. I tested it with PHP5.6 from a terminal (php -f mycurl.php). The script debugs all necessary information, outputs a curl command you could use in a terminal and logs the HTML and cookie information to some files in the same folder like the script. Running the script too often doesn't work. The login won't work. So take your time and wait some minutes between your tries. Or change your IP ;) Hope it helps. A: Replication of the Problem I did the same thing in Postman as you did your screenshot but was not able to log in: The only difference I can see is that your request had cookies, which I suspect is why you were able to log in without all the other input fields. And it seems like there are quite a number of input fields: Using Postman So, I used postman intercept to capture all the fields used during a login, including the captcha and access code and I was able to login: Update 1 I've found out that once you've solved a captcha to login, after you've logged out you may login again without displayCaptcha and userEnteredCaptcha in your form data, provided that you use the same cookie as the one you've used to login successfully. You just need to get a valid accessCode from the login page. A: it doesnt work either in PHP/Python that is (as others have already pointed out) because you were using your browser's existing cookie session, which had already solved the captcha. clear your browser cookies, get a fresh cookie session, and DO NOT SOLVE THE CAPTCHA, and Postman won't be able to log in either. Any idea what is missing ? several things, among them, several post login parameters (browserFlag, loginType,__checkbox_dscBasedLoginFlag, and many more), also your encoding loop here is bugged $str = $str . "$key=$value" . "&"; , it pretty much only works as long as both keys and values only contain [a-zA-Z0-9] characters, and since your userNamedenc contains a grave accent character, your encoding loop is insufficient. a fixed loop would be foreach($params as $key=>$value){ $str = $str . urlencode($key)."=".urlencode($value) . "&"; } $str=substr($str,0,-1); , but this is exactly why we have the http_build_query function, that entire loop and the following trim can be replaced with this single line: $str=http_build_query($params); , also, seems you're trying to login without a pre-existing cookie session, that's not going to work. when you do a GET request to the login page, you get a cookie, and a unique captcha, the captcha answer is tied to your cookie session, and needs to be solved before you attempt to login, you also provide no code to deal with the captcha. also, when parsing the "userName" input element, it will default to "Enter Username", which is emtied with javascript and replaced with userNamedenc, you must replicate this in PHP, also, it will have an input element named "dscBasedLoginFlag", which is removed with javascript, you must also do this part in php, also it has an input element named "Cert", which has a default value, but this value is cleared with javascript, do the same in php, and an input element named "newUserRegistration", which is removed with javascript, do that, here's what you should do: make a GET request to the login page, save the cookie session and make sure to provide it for all further requests, and parse out all the login form's elements and add them to your login request (but be careful, there is 2x form inputs, 1 belong to the search bar, only parse the children of the login form, don't mix the 2), and remember to clear/remove the special input tags to emulate the javascript, as described above, then make a GET request to the captcha url, make sure to provide the session cookie, solve the captcha, then make the final login request, with the captcha answer, and userNamedenc and passwordenc and all the other elements parsed out from the login page... that should work. now, solving the captcha programmatically, the captha doesn't look too hard, cracking it probably can be automated, but until someone actually does that, you can use Deathbycaptcha to do it for you, however note that it isn't a free service. here's a fully tested, working example implementation, using my hhb_curl library (from https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php ), and the Deathbycaptcha api: <?php declare(strict_types = 1); header ( "content-type: text/plain;charset=utf8" ); require_once ('hhb_.inc.php'); const DEATHBYCATPCHA_USERNAME = '?'; const DEATHBYCAPTCHA_PASSWORD = '?'; $hc = new hhb_curl ( '', true ); $hc->setopt(CURLOPT_TIMEOUT,20);// im on a really slow net atm :( $html = $hc->exec ( 'http://www.mca.gov.in/mcafoportal/login.do' )->getResponseBody (); // cookie session etc $domd = @DOMDocument::loadHTML ( $html ); $inputs = getDOMDocumentFormInputs ( $domd, true ) ['login']; $params = [ ]; foreach ( $inputs as $tmp ) { $params [$tmp->getAttribute ( "name" )] = $tmp->getAttribute ( "value" ); } assert ( isset ( $params ['userNamedenc'] ), 'username input not found??' ); assert ( isset ( $params ['passwordenc'] ), 'passwordenc input not found??' ); $params ['userName'] = ''; // defaults to "Enter Username", cleared with javascript unset ( $params ['dscBasedLoginFlag'] ); // removed with javascript $params ['Cert'] = ''; // cleared to emptystring with javascript unset ( $params ['newUserRegistration'] ); // removed with javascript unset ( $params ['SelectCert'] ); // removed with javascript $params ['userNamedenc'] = 'hGJfsdnk`1t'; $params ['passwordenc'] = '675894242fa9c66939d9fcf4d5c39d1830f4ddb9'; echo 'parsed login parameters: '; var_dump ( $params ); $captchaRaw = $hc->exec ( 'http://www.mca.gov.in/mcafoportal/getCapchaImage.do' )->getResponseBody (); $params ['userEnteredCaptcha'] = solve_captcha2 ( $captchaRaw ); // now actually logging in. $html = $hc->setopt_array ( array ( CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query ( $params ) ) )->exec ( 'http://www.mca.gov.in/mcafoportal/loginValidateUser.do' )->getResponseBody (); var_dump ( $hc->getStdErr (), $hc->getStdOut () ); // printing debug data $domd = @DOMDocument::loadHTML ( $html ); $xp = new DOMXPath ( $domd ); $loginErrors = $xp->query ( '//ul[@class="errorMessage"]' ); if ($loginErrors->length > 0) { echo 'encountered following error(s) logging in: '; foreach ( $loginErrors as $err ) { echo $err->textContent, PHP_EOL; } die (); } echo "logged in successfully!"; /** * solves the captcha manually, by doing: echo ANSWER>captcha.txt * * @param string $raw_image * raw image bytes * @return string answer */ function solve_captcha2(string $raw_image): string { $imagepath = getcwd () . DIRECTORY_SEPARATOR . 'captcha.png'; $answerpath = getcwd () . DIRECTORY_SEPARATOR . 'captcha.txt'; @unlink ( $imagepath ); @unlink ( 'captcha.txt' ); file_put_contents ( $imagepath, $raw_image ); echo 'the captcha is saved in ' . $imagepath . PHP_EOL; echo ' waiting for you to solve it by doing: echo ANSWER>' . $answerpath, PHP_EOL; while ( true ) { sleep ( 1 ); if (file_exists ( $answerpath )) { $answer = trim ( file_get_contents ( $answerpath ) ); echo 'solved: ' . $answer, PHP_EOL; return $answer; } } } function solve_captcha(string $raw_image): string { echo 'solving captcha, hang on, with DEATBYCAPTCHA this usually takes between 10 and 20 seconds.'; { // unfortunately, CURLFile requires a filename, it wont accept a string, so make a file of it $tmpfileh = tmpfile (); fwrite ( $tmpfileh, $raw_image ); // TODO: error checking (incomplete write or whatever) $tmpfile = stream_get_meta_data ( $tmpfileh ) ['uri']; } $hc = new hhb_curl ( '', true ); $hc->setopt_array ( array ( CURLOPT_URL => 'http://api.dbcapi.me/api/captcha', CURLOPT_POSTFIELDS => array ( 'username' => DEATHBYCATPCHA_USERNAME, 'password' => DEATHBYCAPTCHA_PASSWORD, 'captchafile' => new CURLFile ( $tmpfile, 'image/png', 'captcha.png' ) ) ) )->exec (); fclose ( $tmpfileh ); // when tmpfile() is fclosed(), its also implicitly deleted. $statusurl = $hc->getinfo ( CURLINFO_EFFECTIVE_URL ); // status url is given in a http 300x redirect, which hhb_curl auto-follows while ( true ) { // wait for captcha to be solved. sleep ( 10 ); echo '.'; $json = $hc->setopt_array ( array ( CURLOPT_HTTPHEADER => array ( 'Accept: application/json' ), CURLOPT_HTTPGET => true ) )->exec ()->getResponseBody (); $parsed = json_decode ( $json, false ); if (! empty ( $parsed->captcha )) { echo 'captcha solved!: ' . $parsed->captcha, PHP_EOL; return $parsed->captcha; } } } function getDOMDocumentFormInputs(\DOMDocument $domd, bool $getOnlyFirstMatches = false): array { // :DOMNodeList? $forms = $domd->getElementsByTagName ( 'form' ); $parsedForms = array (); $isDescendantOf = function (\DOMNode $decendant, \DOMNode $ele): bool { $parent = $decendant; while ( NULL !== ($parent = $parent->parentNode) ) { if ($parent === $ele) { return true; } } return false; }; // i can't use array_merge on DOMNodeLists :( $merged = function () use (&$domd): array { $ret = array (); foreach ( $domd->getElementsByTagName ( "input" ) as $input ) { $ret [] = $input; } foreach ( $domd->getElementsByTagName ( "textarea" ) as $textarea ) { $ret [] = $textarea; } foreach ( $domd->getElementsByTagName ( "button" ) as $button ) { $ret [] = $button; } return $ret; }; $merged = $merged (); foreach ( $forms as $form ) { $inputs = function () use (&$domd, &$form, &$isDescendantOf, &$merged): array { $ret = array (); foreach ( $merged as $input ) { // hhb_var_dump ( $input->getAttribute ( "name" ), $input->getAttribute ( "id" ) ); if ($input->hasAttribute ( "disabled" )) { // ignore disabled elements? continue; } $name = $input->getAttribute ( "name" ); if ($name === '') { // echo "inputs with no name are ignored when submitted by mainstream browsers (presumably because of specs)... follow suite?", PHP_EOL; continue; } if (! $isDescendantOf ( $input, $form ) && $form->getAttribute ( "id" ) !== '' && $input->getAttribute ( "form" ) !== $form->getAttribute ( "id" )) { // echo "this input does not belong to this form.", PHP_EOL; continue; } if (! array_key_exists ( $name, $ret )) { $ret [$name] = array ( $input ); } else { $ret [$name] [] = $input; } } return $ret; }; $inputs = $inputs (); // sorry about that, Eclipse gets unstable on IIFE syntax. $hasName = true; $name = $form->getAttribute ( "id" ); if ($name === '') { $name = $form->getAttribute ( "name" ); if ($name === '') { $hasName = false; } } if (! $hasName) { $parsedForms [] = array ( $inputs ); } else { if (! array_key_exists ( $name, $parsedForms )) { $parsedForms [$name] = array ( $inputs ); } else { $parsedForms [$name] [] = $tmp; } } } unset ( $form, $tmp, $hasName, $name, $i, $input ); if ($getOnlyFirstMatches) { foreach ( $parsedForms as $key => $val ) { $parsedForms [$key] = $val [0]; } unset ( $key, $val ); foreach ( $parsedForms as $key1 => $val1 ) { foreach ( $val1 as $key2 => $val2 ) { $parsedForms [$key1] [$key2] = $val2 [0]; } } } return $parsedForms; } example usage: in terminal, write php foo.php | tee test.html, after a few seconds it will say something like: the captcha is saved in /home/captcha.png waiting for you to solve it by doing: echo ANSWER>/home/captcha.txt then look at the captcha in /home/captcha.png , solve it, and write in another terminal: echo ANSWER>/home/captcha.txt, now the script will log in, and dump the logged in html in test.html, which you can open in your browser, to confirm that it actually logged in, screenshot when i run it: https://image.prntscr.com/image/_AsB_0J6TLOFSZuvQdjyNg.png also note that i made 2 captcha solver functions, 1 use the deathbycaptcha api, and wont work until you provide a valid and credited deathbycaptcha account on line 5 and 6, which is not free, the other 1, solve_captcha2, asks you to solve the captcha yourself, and tells you where the captcha image is saved (so you can go have a look at it), and what command line argument to write, to provide it with the answer. just replace solve_captcha with solve_captcha2 on line 28, to solve it manually, and vise-versa. the script is fully tested with solve_captcha2, but the deathbycaptcha solver is untested, as my deathbycatpcha account is empty (if you would like to make a donation so i can actually test it, send 7 dollars to paypal account [email protected] with a link to this thread, and i will buy the cheapest deathbycaptcha credit pack and actually test it) * *disclaimer: i am not associated with deathbycaptcha in any way (except that i was a customer of theirs a couple of years back), and this post was not sponsored.
unknown
d8296
train
your question is a little vague as to what the answer could be, did you want a value to return true if this is the case? did you want to gauruntee a way to fill the dictionary in a way where your condition is true? if you want to check that your condition is true, try: bool_dict = {} for key, val in dict.items(): if max(val)-min(val)>x: bool_list[key]=False else: bool_dict[key]=True print(bool_dict) A: Here's my implementation: def missions_to_dict(arr, x): curr_key = 1 last_mission = arr[0] dict = {"key1": [last_mission]} # Loop through all missions for curr_mission in arr[1:]: # Check to see if current mission is x away from last mission if abs(curr_mission - last_mission) <= x: # Add it to same key as last mission dict[f"key{curr_key}"].append(curr_mission) # Otherwise, need to create new key else: curr_key += 1 dict[f"key{curr_key}"] = [curr_mission] # Set current mission to last mission last_mission = curr_mission return dict
unknown
d8297
train
To get the browser name, you can use browser.getCapabilities(): browser.getCapabilities().then(function(capabilities) { // Outputs 'chrome' when on Chrome console.log(capabilities.caps_.browserName); }); If waiting until a promise is resolved isn't good for your use case, then a hackier way that works on my system is to access the resolved/fulfilled session object directly: // Outputs 'chrome' when on Chrome console.log(browser.driver.session_.value_.caps_.caps_.browserName);
unknown
d8298
train
You can add a with_items loop taking a list to every task in the imported file, and call import_tasks with a variable which you pass to the inner with_items loop. This moves the handling of the loops to the imported file, and requires duplication of the loop on all tasks. Given your example, this would change the files to: playbook.yml --- - hosts: 192.168.33.100 gather_facts: no tasks: - import_tasks: msg.yml vars: messages: - 1 - 2 msg.yml --- - name: Message 1 debug: msg: "Message 1: {{ item }}" with_items: - "{{ messages }}" - name: Message 2 debug: msg: "Message 2: {{ item }}" with_items: - "{{ messages }}" A: It is not possible. include/import statements operate with task files as a whole. So with loops you'll have: Task 1 with Item 1 Task 2 with Item 1 Task 3 with Item 1 Task 1 with Item 2 Task 2 with Item 2 Task 3 with Item 2 Task 1 with Item 3 Task 2 with Item 3 Task 3 with Item 3
unknown
d8299
train
The error message says you have a byte 0x92 in your file somewhere, which is not valid in utf-8, but in other encodings it may be, for example: >>> b'\x92'.decode('windows-1252') '`' That means that your file encoding is not utf-8, but probably windows-1252, and problematic character is the backtick, not the dot, even if that character is found only in a comment. So either change your file encoding to utf-8 in your editor, or the encoding line to # -*- coding: windows-1252 -*- The error message doesn't mention the file the interpreter choked on, but it may be your "main" file, not socket.py. Also, don't name your file socket.py, that will shadow the builtin socket module and lead to further errors. Setting an encoding line only affects that one file, you need to do this for every file, only setting it in your "main" file would not be enough. A: Your error says 'utf8' codec can't decode byte 0x92". In the Windows codepage 1252, this character maps to U+2019 the right quotation mark ’. It is likely that the editor you use for your Python script is configured to replace the single quote ('\x27' or ') by the right quotation mark. It may be nicer for text, but is terrible in source code. You must fix it in your editor, or use another editor. A: Thank you ! Indeed, this character doesn't exist in utf-8. However, I didn't send the character "`", corresponding to 0x92 with windows-1252 and to nothing in utf-8. Futhermore this error appears when a character "." is in controlAddr and it is the same hexadecimal code for both encoding, i.e, 0x2e. The complete error message is given above : Traceback (most recent call last): File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\pythonshell.py", line 566, in write_error self.shell.write_error(self.get_stderr()) File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 272, in get_stderr return self.transcode(qba) File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 258, in transcode return to_text_string(qba.data(), 'utf8') File "C:\Python27\Lib\site-packages\spyderlib\py3compat.py", line 134, in to_text_string return unicode(obj, encoding) File "C:\Python27\Lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 736: invalid start byte For this code : controlPort = 9051 controlAddr = unicode("127.0.0.1") import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((controlAddr, controlPort))
unknown
d8300
train
After try and fails finally, solved this issue. Rethink the code for FrameDelimiterDecoder and found the way how to do it with an array of bytes and at the end convert to ByteBuf. I believe it could be done with the buffer directly or to use ByteBuffer from NIO package and then convert. The simplest for me was: @Slf4j public class FrameDelimiterDecoder extends DelimiterBasedFrameDecoder { public FrameDelimiterDecoder(int maxFrameLength, ByteBuf delimiter) { super(maxFrameLength, delimiter); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) { boolean inMessage = false; int size = buffer.readableBytes(); ByteBuffer byteBuffer = ByteBuffer.allocate(size); buffer.readBytes(byteBuffer); byte[] byteArray = new byte[size - 2]; byte[] data = byteBuffer.array(); int index = 0; for (byte b : data) { if (b == FrameConstant.START_OF_TEXT) { if (!inMessage) { inMessage = true; } else { log.warn("Unexpected STX received!"); } } else if (b == FrameConstant.END_OF_TEXT) { if (inMessage) { inMessage = false; } else { log.warn("Unexpected ETX received!"); } } else { if (inMessage) { byteArray[index] = b; index += 1; } } } return Unpooled.wrappedBuffer(byteArray); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof InterruptedException) { log.warn("interrupted exception occurred"); Thread.currentThread().interrupt(); } else { log.error("FrameDelimiterEncoder exception occurred:", cause); } } } Where FrameConstant look like: @UtilityClass public class FrameConstant { public final int START_OF_TEXT = 0x02; public final int END_OF_TEXT = 0x03; public final int MAX_FRAME_LENGTH = 1024 * 1024; } Then initialize it: @Slf4j @Component @RequiredArgsConstructor public class QrReaderChannelInitializer extends ChannelInitializer<SocketChannel> { private final StringEncoder stringEncoder = new StringEncoder(); private final StringDecoder stringDecoder = new StringDecoder(); private final QrReaderProcessingHandler readerServerHandler; private final NettyProperties nettyProperties; @Override protected void initChannel(SocketChannel socketChannel) { ChannelPipeline pipeline = socketChannel.pipeline(); // Add the delimiter first pipeline.addLast(getDelimiterDecoder()); if (nettyProperties.isEnableTimeout()) { pipeline.addLast(new ReadTimeoutHandler(nettyProperties.getClientTimeout())); } pipeline.addLast(stringDecoder); pipeline.addLast(stringEncoder); pipeline.addLast(readerServerHandler); } private FrameDelimiterDecoder getDelimiterDecoder() { ByteBuf delimiter = Unpooled.wrappedBuffer(new byte[]{FrameConstant.END_OF_TEXT}); return new FrameDelimiterDecoder(FrameConstant.MAX_FRAME_LENGTH, delimiter); } } And some modification for handler: @Slf4j @Component @RequiredArgsConstructor @ChannelHandler.Sharable public class QrReaderProcessingHandler extends ChannelInboundHandlerAdapter { private final PermissionService permissionService; private final EntranceService entranceService; private final Gson gson; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { String remoteAddress = ctx.channel().remoteAddress().toString(); String stringMsg = (String) msg; if (log.isDebugEnabled()) { log.debug("CLIENT_IP: {}", remoteAddress); log.debug("CLIENT_REQUEST: {}", stringMsg); } if (HEARTBEAT.containsName(stringMsg)) { HeartbeatResponse heartbeatResponse = buildHeartbeatResponse(); sendResponse(ctx, heartbeatResponse); } } private <T> void sendResponse(ChannelHandlerContext ctx, T response) { ctx.writeAndFlush(formatResponse(response)); } private <T> String formatResponse(T response) { String realResponse = String.format("%s%s%s", (char) FrameConstant.START_OF_TEXT, gson.toJson(response), (char) FrameConstant.END_OF_TEXT); log.debug("response: {}", realResponse); return realResponse; } And finally, it sends correctly formed response back:
unknown