id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23530100
Is there a way to install it with that zip?
doc_23530101
127.0.0.1 wheels.dev 127.0.0.1 property.dev 127.0.0.1 myproperty.dev and also change in http.conf <VirtualHost *:80> #ServerAdmin webmaster@dummy-host2.example.com DocumentRoot "C:/xampp/htdocs/wheel/" ServerName wheel.dev ServerAlias www.wheel.dev ##ErrorLog "logs/dummy-host2.example.com-error.log" ##CustomLog "logs/dummy-host2.example.com-access.log" common </VirtualHost> <VirtualHost *:80> #ServerAdmin webmaster@dummy-host2.example.com DocumentRoot "C:/xampp/htdocs/property/public" ServerName property.dev ServerAlias www.property.dev ##ErrorLog "logs/dummy-host2.example.com-error.log" ##CustomLog "logs/dummy-host2.example.com-access.log" common </VirtualHost> <VirtualHost *:80> #ServerAdmin webmaster@dummy-host2.example.com DocumentRoot "C:/xampp/htdocs/myproperty/public" ServerName myproperty.dev ServerAlias www.myproperty.dev ##ErrorLog "logs/dummy-host2.example.com-error.log" ##CustomLog "logs/dummy-host2.example.com-access.log" common </VirtualHost> when i try to access the whell.dev or my property.dev all the it only myproperty website not any other please help me out what should i have to change any more in my project Thank you A: When the vhosts only listens on 127.0.0.1 it will only host for the box itself. From any other IP (computer in LAN) it will host the default host. The vhost should be configured to also listen on the IP that the host has in the LAN (192.168.....)
doc_23530102
I have the byte[] stream as '10101011101010101010010' ... .. .. First is there a way that i can filter this binary stream to pixel values and detect LSB ? A: If you want to read / write the Least Significant Byte to use the bitmap to hide information you will need to load the bmp data into an image, then access the pixel-data using GetPixel(). The BMP File itself might use RLL or some other compression so you cannot access the pixel data directly. For detecting LSB in an image, it largely depends on the algorithm used, some are harder to detect as others. Do you have the description of the LSB-variant that might be in that image?
doc_23530103
How can I show all files with extensions that match any of my allowed file types? I don't want all files to be visible/openable, just the ones that I have designated. A: Just specify what you want to allow... Just an example... Dim dlg As New OpenFileDialog() 'Filter by Office Files dlg.Filter = "Office Files|*.doc;*.xls;*.ppt" dlg.ShowDialog() A: A small snippet of how it works Dim result As DialogResult = New DialogResult() OpenFileDialog1.Filter = "Word Documents|*.doc;*.docx|PowerPoint Slides|*.ppt|Video Files|*.MP4|PDF Files|*.pdf" OpenFileDialog1.InitialDirectory = "C:\" OpenFileDialog1.FileName = "" result = OpenFileDialog1.ShowDialog()
doc_23530104
I got the error QWebException: "'NoneType' object is not callable" while evaluating 'has_shortage_so_lines(data)==True' This is my report_view.xml <?xml version="1.0" encoding="utf-8"?> <openerp> <data> <!-- External Consumption Report --> <!-- Landscape Paper Format--> <record id="paperformat_LetterLandscape" model="report.paperformat"> <field name="name">US Letter Landscape</field> <field name="default" eval="True"/> <field name="format">Letter</field> <field name="page_height">0</field> <field name="page_width">0</field> <field name="orientation">Landscape</field> <field name="margin_top">15</field> <field name="margin_bottom">15</field> <field name="margin_left">2</field> <field name="margin_right">2</field> <field name="header_line" eval="False"/> <field name="header_spacing">7</field> <field name="dpi">100</field> </record> <!--Report XLS--> <report id="action_report_shortage_xls" model="sale.order" string="Shortage Report" report_type="qweb-html" name="sale.report_shortage_xls" file="sale.report_shortage_xls"/> <!--Paper Format to shortage report--> <record id="action_report_shortage_xls" model="ir.actions.report.xml"> <field name="paperformat_id" ref="stock.paperformat_LetterLandscape"/> </record> </data> </openerp> This is my report_xls.xml <?xml version="1.0" encoding="utf-8"?> <openerp> <data> <!-- Translatable template --> <template id="report_shortage_xls"> <div class="workbook"> <div class="worksheet" name="Shortage Report"> <table> <tbody> <tr> <td easyfx="font: height 200;align: horizontal left,vert center">Printed On :</td> <td><span t-usertime="%d-%m-%Y %H:%M" /></td> </tr> <tr> </tr> </tbody> </table> <table> <thead> <tr> <th colspan="17" easyfx="font: height 400, bold on;align: horizontal center,vert center">Shortage Report</th> </tr> <!--<tr> <th> <span t-esc="has_shortage_so_lines(o.id)"/> </th> </tr>--> </thead> </table> <t t-if="has_shortage_so_lines(data)==True"> <table> <thead> <tr> <th easyfx="font:height 200, bold on;align: horizontal center,vert center;">Date</th> <th easyfx="font:height 200, bold on;align: horizontal center,vert center;">SO No</th> <th easyfx="font:height 200, bold on;align: horizontal center,vert center;">Customer Ref No</th> </tr> </thead> </table> </t> </div> </div> </template> <!-- Main template --> <template id="xls_report_shortage"> <t t-call="report.html_container"> <t t-foreach="doc_ids" t-as="doc_id"> <t t-raw="translate_doc(doc_id, doc_model, 'partner_id.lang', 'sale.report_shortage_xls')"/> </t> </t> </template> </data> </openerp> This is my report.py class ShortageReport(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(ShortageReport, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'get_date_from': self.get_date_from, 'get_date_to': self.get_date_to, 'has_shortage_so_lines': self.has_shortage_so_lines, 'get_shortage_lines': self.get_shortage_lines, }) def has_shortage_so_lines(self, order_id): _logger.info("sale order id >>> : %r", order_id) lines_obj = self.get_shortage_so_lines(order_id) if lines_obj: return True return False class report_shortage_xls(osv.AbstractModel):#(models.AbstractModel): _name = 'report.stock.report_shortage_xls' _inherit = 'report.abstract_report' _template = 'stock.report_shortage_xls' _wrapped_report_class = ShortageReport Is there any way to export the xls from odoo. Thank you so much for your helping. A: Make sure here _template = 'stock.report_shortage_xls' it must be module name with report name, you have created report for sale.order and you have given stock module name, is it correct in your case ? For more information you should refer our blog on Qweb Report.
doc_23530105
Or any other way to connect with tfs? A: Get the software * *tee-clc (can be installed with HomeBrew), which depends on *Java 6, 7, or 8 (see How to install Java 8 on Mac -- as of this writing, Java 9 will not work.) Create a workspace using tee-clc ("tf") Tell tee-clc to remember your credentials (in OSX's Keychain) by adding this line to your .bash_profile. Then close and reopen your terminal or just paste the same command. export TF_AUTO_SAVE_CREDENTIALS=0 Accept the EULA. tf eula Create a workspace. tf workspace -new MyCoolWorkspace -collection:https://my-server.example.com/tfs/DefaultCollection Map a path on the server to a local folder. tf workfold -map '$/Path/To/Folder' /path/to/your/local/folder -collection:https://your-server.example.com/tfs/DefaultCollection -workspace:MyCoolWorkspace Get the code and store your password. Make sure you type your actual username; if you enter your_username here it may get stored in the OSX Keychain and tee-clc is really dumb about replacing it later. cd /path/to/your/local/folder tf get -login:your_username If it works, it will download your code to that folder. You can also use the other commands. Use the Azure Repos Extension on VS Code Get the Azure Repos extension. Add the following settings (CMD+,): { "tfvc.location": "/usr/local/bin/tf", "tfvc.restrictWorkspace": true } Type which tf in Terminal to find out what the value for location should be. I'm not sure if "restrictWorkspace" is necessary. I got it from a comment on Github while I was troubleshooting. Finally, open the folder containing your code. From the command palette (⌘+⇧+P) type Team: Signin. If that works, you can start using the other features in the plugin. A: This are the steps to effectively connect a TFS (TFVC) Repository to your VS Code on Mac: INSTALL THE SOFTWARE * *Install Visual Studio Code for Mac (currently here: https://code.visualstudio.com/download). *Install the TFS extension for VS Code: Go to the Extensions tab in VS Code, Search for TFS and install. *Install TEE-CLC. Follow this guide: https://www.youtube.com/watch?v=VPNaEIVZfr0&feature=youtu.be. CREATE A LOCAL TFVC WORKSPACE IN YOUR MAC Now you need to have a local TFVC Workspace on your machine. If you don't have one (as it was my case), you need to create it. The following steps are partially extracted from https://stackoverflow.com/a/21785438/2816119. * *Create a local folder where you are going to download and locally store the source code. *Open a Terminal window. *Create a local workspace from your terminal window with the following command: tf workspace -new MyWorkspace -collection:<<<http://full.URL.of/your/repository>>> *Map your repository folder to your local folder with the following command: tf workfold -map '$/your/repository/folder/path' /your/local/folder/path -collection:<<<http://full.URL.of/your/repository>>> -workspace:MyWorkspace *If everything went well, you'll see a new sub-folder ".tf" in your local folder. *Open your local folder with VS Code. If everything went well you'll se after a few seconds the TFVC icons in the bottom bar: GET THE SOURCE CODE To get the source code you'll need to go to the Source Control Tab -> Ellipsis (...) button -> Sync. Once you press it you'll see a progress bar moving in the Source Control Tab and you'll see how the source code is downloaded to your local folder. ENJOY Now you can use your TFVC repository as described in their guides. If something is not clear or you have questions please let me know. I'll try to help you :-) A: GIT VS Code ships with a Git source control manager (SCM) extension. Most of the source control UI and work flows are common across SCM extensions. More details please refer this tutorial:Using Version Control in VS Code Note: VS Code will leverage your machine's Git installation, so you need to install Git first before you get these features. Make sure you install at least version 2.0.0. TFVC You can connect to TFVC using the Visual Studio Team Services extension since version 1.116.0 (2017/04/12). Note: You need Team Foundation Server 2015 Update 2 or later. A: Check the below link. It is working fine for me How to use TFS on a Mac Steps to be followed: Step 1: Install Eclipse Step 2: Download and install the TFS everywhere plugin Step 3: Checkout your solution using the eclipse to a local folder Step 4: Open the solution in Visual studio and make the code changes Step 5: Open eclipse and commit your changes.
doc_23530106
http://i.stack.imgur.com/xXnXz.png How can I be able to analyse the test result? A: The graph tells that in first minute of your test response time was between 10 and 20 seconds, after that it settled down and was < 0.5 second. Consider 3 things: * *You have yellow exclamation sign with "1" at upper-right corner. Check jmeter.log file to determine the cause, it may be critical. *Set reasonable ramp-up time so both JMeter and application under test could "warm-up" *Don't use JMeter GUI to run load tests, use it only for tests development and debugging. Run JMeter tests in command-line mode and consider following other recommendations from 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure guide. *You have yellow exclamation sign A: * *If you want to export the data of your graph, it is just above the graph in Write results to file. You will have csv file of each point *If you want to have the statistics of every call, you should add the Listener View Results in Table where you could export the data in a file. *If you don't know how to read this graph, it is you're average response time every 10 seconds. You could also add the Listner Summary Report to have global stats of the whole test.
doc_23530107
public class SetPoint { private String tagName; //more fields //getters and setters } I'm getting SetPoints from a REST API, do something with them and then send them again. Problem is that I want deserialize a SetPoint from a JSON like: { "tagnameOpc" : "6GH783", //more fields } But when I send them, I want serialize a SetPoint as: { "tagName" : "6GH783" //more fields } I mean, I want the property tagName to be named different in each case. Is this possible? A: Try using a different JsonProperty annotation for the getter and the setter. E.g. @JsonProperty("tagnameOpc") void setTagName(String name) @JsonProperty("tagName") String getTagName() If that doesn't work try with an extra setter @JsonIgnore void setTagName(String name) @JsonProperty("tagnameOpc") void setTagNameOpc(String name) { setTagName(name); } @JsonProperty("tagName") String getTagName() A: Jackson mix-in annotations might help. You would use the SetPoint class twice, but write a different mix-in class for each serialisation/deserialisation format, and then configure the ObjectMapper separately for each case. A: Assuming jsonObject is a JSONObject containing your json: jsonObject.put("tagName", jsonObject.remove("tagnameOpc")); From JSonObject documentation: jsonObject.remove(key) returns the value that was associated with that key, or null if there was no value.
doc_23530108
* *imbricated SQL queries with no indentation *case is not respected *etc... I tried automatic SaS formatter but it do not format Proc SQL. Do you have any ideas ? We have many scripts and the Team is ready to do that manually, it seems prone to error and I am not sure we'll have the same syntax at the end. Any tips would be welcome! I can add code snippets if needed but I think that the problem is clear and I am not the first to encounter it. A: I would suggest ignoring the fact that you're in SAS for the moment, and instead focus on the SQL itself. Find a language you're comfortable with that has libraries that format code in other languages - Python for example can do this - and then: * *Open the .sas file as a text file *Find "PROC SQL" text and grab from there to the "QUIT" (case insensitive) *Pass that inner text to the SQL code formatter *Grab the result and insert it back into the text file Something along those lines is your best bet. SAS doesn't have anything built-in for this, so you're going to have to go outside here.
doc_23530109
create view vkb1 as select dept, AVG(salary), count(eid) from emp_sal group by dept But it is giving me below error:- Msg 4511, Level 16, State 1, Procedure vkb1, Line 17 Create View or Function failed because no column name was specified for column 2. Please help me in this.I am new to the sql. A: You have to name the two columns without any name: create view vkb1 (dept, avg_salary, eid_count) as select dept, AVG(salary), count(eid) from emp_sal group by dept Alternative solution: create view vkb1 as select dept, AVG(salary) as avg_salary, count(eid) as eid_count from emp_sal group by dept
doc_23530110
The doc for getRawRowMapper says it's experimental and to provide feedback, but I am only an egg, so if anyone else has succeeded with this configuration, I'll try harder before bugging Gray with it. My code as follows: @DatabaseField(dataType=DataType.LONG_STRING) @Getter @Setter private String formatted_message; @DatabaseField(id=true) @Getter @Setter private long event_id; public void getRowMapper() { RawRowMapper<DbLog> rowMapper = daol.getRawRowMapper(); final String[] rowmap = { DbLog.EVENTID_FIELD, DbLog.MESSAGE_FIELD, DbLog.LEVEL_FIELD }; // try { rowMapper.mapRow( rowmap, rowmap ); } catch (NumberFormatException e) { e.printStackTrace(); } } It returns the following stack trace: java.lang.NumberFormatException: For input string: "event_id" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:441) at java.lang.Long.parseLong(Long.java:483) at com.j256.ormlite.field.types.LongObjectType.parseDefaultString(LongObjectType.java:32) at com.j256.ormlite.field.types.BaseDataType.resultStringToJava(BaseDataType.java:161) at com.j256.ormlite.field.FieldType.convertStringToJavaField(FieldType.java:671) at com.j256.ormlite.stmt.RawRowMapperImpl.mapRow(RawRowMapperImpl.java:33) A: I'm trying to use queryRaw with a RawRowMapper on MySQL. It works great with string columns, but .mapRow() chokes on if I add a long field -- it attempts to convert the column name to numeric. getRawRowMapper() has been around a while and really isn't experimental. I'll change the comments. I'm not sure what you are expecting to happen but ORMLite is trying to convert the EVENTID_FIELD which is a string into a long. The mapRow(...) method definition is: T mapRow(String[] columnNames, String[] resultColumns) throws SQLException and you are trying to pass in the rowmap as the resultColumns. I assume that the first result column is supposed to be a long and it is trying to do a Long.parseLong("event_id") which throws. If you provide more details about what you are trying to accomplish, I can see if I can help. A: Here's the working example. It is an access class for the Logback DbAppender's logging_event table, which is an awfully nifty way to make Slf4j log to a database. The SQL is complicated substantially by my need to filter logging_event rows by the presence or absence of specific MDC rows (they're like optional tags for log events) in the companion table logging_event_property. The use of RawRowMapper, however, is perfectly standard. The issue was my lack of comprehension: * *You don't call mapRow() yourself. It is called by queryRaw, as is explained perfectly well in the docs. *The mapper you get from dao.getRawRowMapper() will just work, even if you're not doing a SELECT *. Trust it until you have a reason not to. Anyhow, here's the working access classes, along with my funky double-join filtering. Might be useful for anyone trying to use the DbAppender in an Ormlite project. @DatabaseTable(tableName = "logging_event") public class DbLog { public static String EVENTID_FIELD = "event_id"; public static String TIMESTAMP_FIELD = "timestmp"; public static String MESSAGE_FIELD = "formatted_message"; public static String LEVEL_FIELD = "level_string"; @DatabaseField @Getter @Setter private long timestmp; @DatabaseField(dataType=DataType.LONG_STRING) @Getter @Setter private String formatted_message; @DatabaseField @Getter @Setter private String logger_name; @DatabaseField @Getter @Setter private String level_string; @DatabaseField @Getter @Setter private String thread_name; @DatabaseField @Getter @Setter private byte reference_flag; @DatabaseField @Getter @Setter private String arg0; @DatabaseField @Getter @Setter private String arg1; @DatabaseField @Getter @Setter private String arg2; @DatabaseField @Getter @Setter private String arg3; @DatabaseField @Getter @Setter private String caller_filename; @DatabaseField @Getter @Setter private String caller_class; @DatabaseField @Getter @Setter private String caller_method; @DatabaseField @Getter @Setter private String caller_line; @DatabaseField(id=true) @Getter @Setter private long event_id; /** Gets server logs since timestamp. * Filters out logs which have NO MDC called "Client". * @param daol - Dao for DbLog. * @param timestamp - get only logs after this. * @param eventId - if not zero, filters out logs matching this event. * @return */ public static GenericRawResults<DbLog> getServerLogsSince(Dao<DbLog, Long> daol, long timestamp, int eventId ) { try { // NB: This is not tested on SQLite. String mySqlQuery = "SELECT "; mySqlQuery += "a.event_id, a.formatted_message, a.level_string "; mySqlQuery += "FROM logging_event a "; mySqlQuery += "LEFT JOIN logging_event_property b "; mySqlQuery += "ON ( a.event_id = b.event_id "; mySqlQuery += " and b.mapped_key = 'Event' "; if( eventId != 0) { mySqlQuery += " and b.mapped_value = ? "; } mySqlQuery += ") "; mySqlQuery += "LEFT JOIN logging_event_property c "; mySqlQuery += "ON ( a.event_id = c.event_id AND c.mapped_key = 'Client') "; mySqlQuery += "WHERE a.timestmp > ? "; mySqlQuery += "and c.event_id is null "; RawRowMapper<DbLog> rowMapper = daol.getRawRowMapper(); String evStr = Long.toString(db.getEvent().getId()); String timeStr = Long.toString(timestamp); GenericRawResults<DbLog> results; if( eventId == 0) results = daol.queryRaw(mySqlQuery, rowMapper, timeStr); else results = daol.queryRaw(mySqlQuery, rowMapper, evStr, timeStr); return results; } catch (SQLException e) { log.error("Exception {}",Helpers.stackTraceInfo(e,DbLog.class)); } return null; } } @DatabaseTable(tableName = "logging_event_property") public class DbLogProp { public static String EVENTID_FIELD = "event_id"; public static String MAPPEDKEY_FIELD = "mapped_key"; public static String MAPPEDVALUE_FIELD = "mapped_value"; @DatabaseField(columnName="event_id", foreign=true) @Getter @Setter //private Long event_id; DbLog event; @DatabaseField(columnName="mapped_key") @Getter @Setter private String mappedKey; @DatabaseField(columnName="mapped_value") @Getter @Setter private String mappedValue; }
doc_23530111
/usr/bin/convert +dither -negate -threshold 0 -negate ... I get a black-and-white sure but with jagged edges. /usr/bin/convert +dither -colorspace Gray -intensity ... yields cyan too light gray with all intensities i tested. Any ideas ?
doc_23530112
I want the output into the A,C,D columns of excel spreadsheet. I'm using the pyExcelerator, the biggest problem is when I rerun the program, it replaces the original program. I just want the results adding to the existing excel spreadsheet. Like a option in file.write. indexlist = list(); indexlist2 = list(); indexlist3 = list(); #keep adding new element at same speed indexlist.append(a); indexlist2.append(b); indexlist3.append(c); #create the new excel spreadsheet w = Workbook() ws = w.add_sheet('sheet') for i in range(len(indexlist)): ws.write(i+1,3,str(indexlist[i])) for j in range(len(indexlist2)): ws.write(j+1,2,str(indexlist2[j])) for k in range(len(indexlist3)): ws.write(k+1,0,str(indexlist3[k])) A: It rewrites the values in the rows since i, j and k are the row numbers you write to and they start at 0 each time you run the program. What you need to do is open the file for reading firs, see if the sheet exists, if not continue to write into it for the first time, if the sheet exists see what the last row number is (there is a nrows function available in xlrd), close the file and reopen it for writing. Then add that value to i+1, j+1 and k+1 in your ws.write statements.
doc_23530113
In the current design the Owner is stored in a basic Owner table and each of the 4 entities is joined to this same Owner table with the Owner ID being the FK in the entity tables. The owner table is basic; it is OwnerID and Name, where OwnerID is the PK, and the OwnerID is a FK in each of the entity tables. I have a sneaky feeling this is the wrong approach for a Transactional database and that the approach I am taking is as if I was designing a reporting database (star schema) with the Owner being a dimension of these entities. In the current design it looks like the Entity belongs to the Owner as opposed to the opposite way around. The alternative is that I either store the Owner on each entity table or create Owner specific table for each entity i.e. table EntityOne which then joins to EntityOneOwner where the EntityID is a FK in the EntityOneOwner table. Hope I am making sense here. Thoughts? A: Actually this is the correct approach for an OLTP database - sounds like a good normalized database. A reporting database (OLAP, for instance) would be denormalized with the owner Name being repeated in the different tables for ease of querying.
doc_23530114
create procedure Service_Status(@service_status varchar(15)) AS Begin IF (NOT EXISTS(SELECT * FROM ServiceStatus WHERE [status]=@service_status)) --Check ([status] in ('Pending','In-Progress','Closed')) BEGIN SELECT 'Status must be either Pending, In-Progress or Closed' END END A: If you insist on procedure then I don't think you can - how are you planning to bind that stored procedure to the insert & update events? You can encapsulate your check code in a user defined function, but then you need to call that functions in a constraint (you seem not to aim that), you can also create a trigger (probably not advisable), but I really don't see how will you enforce a stored procedure check on an insert / update event.
doc_23530115
Say I have this model class SomeClassA(models.Model): first = models.CharField(max_length=25, null=True, blank=False) last = models.CharField(max_length=25, null=True, blank=False) classChoice1 = models.ForeignKey(SomeClassB, related_name='choice1') classChoice2 = models.ForeignKey(SomeClassB, related_name='choice2') classChoice3 = models.ForeignKey(SomeClassB, related_name='choice3') What is the correct way to enforce / check that the three "classChoice#" choices are unique per instance of SomeClassA? In other words how do I prevent a entry from being made if any of the options selected for classChoice1, classChoice2, classChoice3 are not unique, among themselves? In pseudo classChoice1 != classChoice2 classChoice2 != classChoice3 classChoice3 != classChoice1 A: Read unique_together from django docs A: To perform a such custom validation you can use clean() method. You can use it to automatically provide a value for a field, or to do validation that requires access to more than a single field which is you case. You can do as follow: from django.core.exceptions import ValidationError from django.db import models class SomeClassA(models.Model): ... def clean(self): if len(set((classChoice1.id, classChoice2.id, classChoice3.id))) < 3: raise ValidationError('classChoice[1,2,3] should have different values')
doc_23530116
(declare-const t Int) (assert (and (or (>= t 0) (>= t 1) ) (or (>= t 2) (<= t 2) ) (>= t 0) (<= t 1) ) ) (apply (par-then (! simplify :elim-and true) tseitin-cnf)) However, the script doesn't work. A: The simplify tactic only perform "local simplifications". That is, when simplifying an expression t, it will ignore the context of t. For example, it can simplify a + 1 - a into 1, but it will not simplify a != 0 or b = a + 1 into a != 0 or b = 1. Contextual simplification is expensive, the simplify tactic is meant to be efficient and simple. Other tactics may be used to achieve what you want. The tactic propagate-ineqs will propagate inequalities. However, it will not process terms nested in the formula. The tactic split-clause can be used to break the formula in cases\goals. The tactic propagate-values will propagate the value of an assertion, example: a = 0 and b >= a is simplified to a = 0 and b >= 0. The command (help-tactic) will display all available tactics. Here is a strategy for simplifying your example into t >= 0 and t <= 1. (apply (then simplify propagate-values split-clause propagate-ineqs)) Note that the combinator par-then is only useful for combining tactics that produce many sub-goals. (par-then t1 t2) applies t1 to the input goal, and applies t2 (in parallel) to every subgoal produced by t1. The split-clause tactic produces more than one subgoal. Then (for bigger examples) it may be more efficient to use: (apply (then simplify propagate-values (par-then split-clause propagate-ineqs)))
doc_23530117
Is it \n or \r\n ? A: Emails conform to the MIME specification, but even with the original SMTP RFC the situation was the same: the specification clearly states that line breaks must be represented by a CR LF sequence. This is not platform dependent, email text is not the same as a text file. See https://www.rfc-editor.org/rfc/rfc2046#section-4.1.1 A: Unfortunately since you want it to be cross-platform, it depends on the email client. Almost all modern email clients can handle either format. I would stick with and confirm if all windoze based clients can handle those (they should be able to).
doc_23530118
(defun del (x l &optional l0) (cond ((null l) (reverse l0)) ((if (atom x) (eq x (car l)) (remove (car l) x)) (del x (cdr l) l0)) (T (del x (cdr l) (cons (if (not (atom (car l))) (del x (car l)) (car l)) l0))))) (defun _delete(a l) (format t "~a~%" (del a l))) (_delete 'nest '(nest (second nest level) (third (nest) level))) This returns ((SECOND LEVEL (THIRD NIL LEVEL)) And I need ((SECOND LEVEL (THIRD () LEVEL)) I've tried using the ~:S format but that apparently doesn't work with composite structures. I've also tried the substitute function to replace NIL, also with no results. A: Two possible solutions: I. You can use the format directives ~:A or ~:S (format t "~:a" '()) => () However, this directive works only on the top level elements of a list, i.e. (format t "~:a" '(a b () c)) will not print (A B () C) but (A B NIL C) So you need to loop through the list applying the ~:A to each element recursively if it is a cons. (defun print-parentheses (l) (cond ((consp l) (format t "(") (do ((x l (cdr x))) ((null x) (format t ")" )) (print-parentheses (car x)) (when (cdr x) (format t " ")))) (t (format t "~:a" l)) )) (print-parentheses '(a b (c () d))) => (A B (C () D)) II. Create a print-dispatch function for empty lists and add it to the pretty print dispatch table: (defun print-null (stream obj) (format stream "()") ) (set-pprint-dispatch 'null #'print-null) (print '(a () b)) => (A () B) The latter is simpler, but it affects all the environment, which might not be what you want. A: We can write an :around method for print-object, for the case when the object to be printed is NIL. (defvar *PRINT-NIL-AS-PARENS* nil "When T, NIL will print as ().") (defmethod print-object :around ((object (eql nil)) stream) (if *print-nil-as-parens* (write-string "()" stream) (call-next-method))) (defun write-with-nil-as-parens (list) (let ((*print-nil-as-parens* t)) (write list))) Example: CL-USER 73 > (write-with-nil-as-parens '(a b c nil (()) (nil))) (A B C () (()) (())) ; <- printed (A B C NIL (NIL) (NIL)) ; <- return value A: I've also tried the substitute function to replace NIL, also with no results. None of the standard substitution functions will work. substitute is a sequence processing function: it will not recurse into the tree structure. The sublis and subst functions will process the tree structure, but they treat the car and cdr fields of conses equally: if we replace nil throughout a tree structure with :whatever, that applies to all of the terminating atoms, so that (a nil b) becomes (a :whatever b . :whatever). We must make our out function which is like subst, but only affects car-s: (defun subcar (old new nested-list) (cond ((eq nested-list old) new) ((atom nested-list) nested-list) (t (mapcar (lambda (atom-or-sublist) (subcar old new atom-or-sublist)) nested-list)))) With this, we can replace nil-s with the character string "()": [1]> (subcar nil "()" '(a b c nil (e nil f (g nil)) nil)) (A B C "()" (E "()" F (G "()")) "()") If we pretty-print that, the character strings just print as the data rather than as machine-readable string literals: [2]> (format t "~a~%" *) ;; * in the REPL refers to result of previous evaluation (A B C () (E () F (G ())) ()) I hope you understand that nil and () mean exactly the same thing; they are the same object: [3]> (eq nil ()) T The only way the symbol token nil can denote an object other than () is if we we are in a package which hasn't imported the nil symbol from the common-lisp package (and nil is interned as a local symbol in that package, completely unrelated to cl:nil): [1]> (defpackage "FOO" (:use)) #<PACKAGE FOO> [2]> (in-package "FOO") #<PACKAGE FOO> Sanity test: from within package foo check that cl:nil is the same as the () object. We have to refer to the eq function as cl:eq because package foo doesn't import anything from cl: FOO[3]> (cl:eq cl:nil ()) COMMON-LISP:T Now let's see if nil in this package is (): FOO[4]> (cl:eq nil ()) *** - SYSTEM::READ-EVAL-PRINT: variable NIL has no value OOPS! This is not the standard nil anymore; it doesn't have special the behavior that it evaluates to itself. We must quote it: FOO[6]> (cl:eq 'nil ()) COMMON-LISP:NIL Nope, not the () object. Note how the return values of the cl:eq function are printed as COMMON-LISP:NIL or COMMON-LISP:T. Symbols are printed without a package prefix only if they are present in the current package.
doc_23530119
T := table(a = 13, c = 47) Doing so gives me the following error: Undefined function 'T' for input arguments of type 'char'. I have no idea what is going on. Does anybody know why it isn't working and how I can create a table using this function? A: If you look at the top of the page, you are reading about functions contained in the "Symbolic Math Toolbox." I believe you need to pay for that license to use functions from the toolbox. From Matlab's help for that error you either: * *Made a typographical error ... *Changed directories so that a function is no longer on the search path... *Used the wrong case for a function or variable name ... *Are trying to use a function for which you are not licensed. I got the same error as you, and I also do not have that Toolbox, so perhaps its the last reason. Is it time to switch to Python? A: This happens when you try to call a muPAD function from the MATLAB command line. Whenever you see :=, that's a clue that you're dealing with muPAD. You cannot use muPAD syntax directly in MATLAB (feval or evalin and symengine can be used in some cases to call muPAD functions and return a symbolic expression). To use table in muPAD: Call mupad at the command line to open up a muPAD notebook, then call your sample line. You do not need the latest MATLAB version, although I'm not sure exactly when it was brought in (works fine for me on 2011b with Symbolic toolbox). To use table in MATLAB: The muPAD table function should not be confused with the MATLAB table function/datatype, which is relatively new. The equivalent in MATLAB of that muPAD code would be something along the lines of (untested): T = table([13;47],'RowNames',{'a';'c'});
doc_23530120
It will run in editor manually, but when applying it to a rule in outlook based on the words in the subject body, it will only open a new excel workbook. Will not give an error as well. I have read and research through the forums to get it to this level to work ” thanks to the CODE GOD’S”. Any direction or advise on getting this to work under a rule(run a script) would be much appreciated. Code below: Public Sub SaveEmailBody(itm As Outlook.MailItem) Dim outlookApp As New Outlook.Application Dim olNs As Outlook.NameSpace Dim Fldr As Outlook.MAPIFolder Dim olMail As Variant Dim myTasks Dim xlApp As Object Dim myXLApp As Excel.Application Dim myXLWB As Excel.Workbook Dim aFile As String Dim TotalRows As Long, i As Long 'Delete yesterday's file aFile = "C:\Reporting\Input_files\Volume.xls" If Len(Dir$(aFile)) > 0 Then Kill aFile End If Set outlookApp = CreateObject("Outlook.Application") Set olNs = outlookApp.GetNamespace("MAPI") Set Fldr = olNs.GetDefaultFolder(olFolderInbox) Set myTasks = Fldr.Items Set myXLApp = New Excel.Application myXLApp.Visible = True Set myXLWB = myXLApp.Workbooks.Add 'Find today's volume email For Each olMail In myTasks If (InStr(1, olMail.Body, "ListVolume", vbTextCompare) > 0) Then TotalRows = Sheets(1).Range("A65536").End(xlUp).Row i = TotalRows + 1 - 1 With myXLWB.Worksheets(1) '.Cells(i, 1) = Format(myItem.SentOn, "mm/dd/yyyy") '.Cells(i, 2) = myItem.SenderName '.Cells(i, 3) = myItem.To .Cells(i, 1) = olMail.Body 'Save today's volume email ActiveWorkbook.SaveAs FileName:="C:\Reporting\Input_files\Volume.xls", FileFormat:= _ xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _ , CreateBackup:=False Set outlookApp = Nothing myXLApp.Quit Set myXLApp = Nothing End With Exit For End If Next End Sub A: There is no need to create a new Outlook Application instance in the VBA macro: Set outlookApp = CreateObject("Outlook.Application") Instead, you need to use the Application property available in the VBA module: Set outlookApp = Application Also I see that you iterate over all tasks: 'Find today's volume email For Each olMail In myTasks I suppose you want to get some information from the incoming email message instead. If so, you need to use the argument passed to the sub instead: Public Sub SaveEmailBody(itm As Outlook.MailItem) The itm object represents the incoming email message. Use it in the code instead.
doc_23530121
Here's my table structure: linkages ID table_name tag_id 1 subcategories 6 2 categories 9 music ID artwork 1 5 2 4 artwork ID url_path 1 /some/file/path 2 /some/file/path And here's my query: SELECT music.*, artwork.url_path AS artwork_url_path, GROUP_CONCAT( linkages.tag_id ) AS tag_ids, GROUP_CONCAT( linkages.table_name ) AS table_name FROM music LEFT JOIN artwork ON artwork.id = music.artwork LEFT JOIN linkages ON music.id = linkages.track_id WHERE music.id IN( '1356', '1357', '719', '169', '170', '171', '805' ) ORDER BY FIELD( music.id, 1356, 1357, 719, 169, 170, 171, 805 ) This is the result of the GROUP_CONCAT : [tag_ids] => 3, 6, 9, 17, 19, 20, 26, 49, 63, 64, 53, 57, 63, 65, 67, 73, 79, 80, 85, 96, 98, 11, 53, 67, 3, 6, 15, 17, 26, 38, 50, 63, 74, 53, 56, 57, 62, 63, 65, 66, 67, 72, 85, 88, 98, 24, 69, 71, 3, 6, 15, 17, 26, 38, 50 The first portion of the result is correct: [tag_ids] => 3, 6, 9, 17, 19, 20, 26, 49, 63, 64, 53, 57, 63, 65, 67, 73, 79, 80, 85, 96, 98, 11, 53, 67 Everything after the correct values seems random and most of the values don't exist in the result in the database, but it's still pulling it in. It seems to repeat a portion of the correct result (3, 6, 15, 17 - the 3, 6, 17 are correct, but 15 shouldn't be there, similar with a bunch of other numbers - 71, etc. I can't use DISTINCT because I need to match up the tag_ids and table_name results as a multidimensional array from the results. Any thoughts as to why? UPDATE: I ended up solving it with the initial push from Gordon. It needed a GROUP_BY clause, otherwise it was putting every results tag id's in each result. The final query ended up becoming this: SET SESSION group_concat_max_len = 1000000; SELECT music.*, artwork.url_path as artwork_url_path, GROUP_CONCAT(linkages.tag_id, ':', linkages.table_name) as tags FROM music LEFT JOIN artwork ON artwork.id = music.artwork LEFT JOIN linkages ON music.id = linkages.track_id WHERE music.id IN('1356', '1357', '719', '169', '170', '171', '805') GROUP BY music.id ORDER BY FIELD(music.id,1356,1357,719,169,170,171,805); A: Your join is generating duplicate rows. I would suggest that you fix the root cause of the problem. But, a quick-and-dirty solution is to use group_concat(distinct): GROUP_CONCAT(DISTINCT linkages.tag_id) as tag_ids, GROUP_CONCAT(DISTINCT linkages.table_name) as table_name You can put the columns in a single field using GROUP_CONCAT(): GROUP_CONCAT(DISTINCT linkages.tag_id, ':', linkages.table_name) as tags
doc_23530122
Edit I installed cygwin and for some reason objdump does not work: A: Consider installing cygwin and trying those linux examples...
doc_23530123
sample code: plugin modifier accessBaseObject name:"Access Details" classID:#(0x260e697e, 0x64b63822) replaceUI:true version:1 ( parameters main rollout:params ( enterValue type:#float animatable:true ui:spnEnterValue default:0.0 on spnEnterValue set val do (print $.name) ) rollout params "Modifier Parameters" ( spinner spnEnterValue "Enter Value : " ) on update do ( print ($CAMERA.pos.Z) ) ) Thanks in advance, Videep A: A modifier is not really aware of the base objects position in the world. Think of it in terms of information flow: Object->Modifier->World You don't receive information about the world (your Z position, same as the object doesn't recieve information about the modifier. Generally, if you find yourself requiring information that goes against the flow, you have a design issue that could be resolved in a better way. Generally that would be by implementing a world space modifier, but unfortunately I don't think thats possible in MaxScript. To hack around this, you could find your node and access it directly. theNode = refs.dependentNodes yourModifier firstOnly:on But this won't update when the node moves, and won't handle instancing. I'd consider refactoring your plugin to use a different class - try script controller, or make a script object that depends on the input object. A: Frozen Wiki pretty much summed it up. Custom Attributes typically do the trick for this sort of thing. You can store weak references, and handle them however you please. For more info check Paul Neale's website: http://www.paulneale.com/ For scripted controller: http://www.paulneale.com/tutorials/Scripting/weakReferences/weakReferences.htm A: "Scripted Modifier plug-ins can only extend existing Modifier plug-ins. " Please see the doc, this might be the reason for it and $.pos usually ok. However if you camera is moved by an other script animation you can still force update by changing some values and on some value change call your function inside your plugin.
doc_23530124
Say I have a table called Table1 with the columns order_id and general_notes (and a few others with more data). I am trying to write a query that 1) INSERT order_id and general_notes INTO my table if order_id does not exist yet 2) CONTACT UPDATE general_notes if column already contains text and 3)UPDATE general_notes column if order_id has been pushed to db already. Essentially I do not want order_id to be duplicated in my table so if it doesn't exist I want to push both columns, if it already exists without any general_notes added I want to add data and if general_notes does already exist I want to concat new text to the end. The script I currently have adds new entry to db and updates the general_notes column if additional notes are added but I can't figure out how to update the general_notes column for an order_id that is already in db aka general_notes is NULL. This is what I currently have: $query = "INSERT INTO table1 (order_id, general_notes) VALUES(:order_id, :general_notes) ON DUPLICATE KEY UPDATE general_notes = CONCAT(general_notes, '. ', :general_notes)"; A: I would recommend concat_ws(): it gracefully skips null values (and does not concatenates the separator to nulls): INSERT INTO table1 (order_id, general_notes) VALUES(:order_id, :general_notes) ON DUPLICATE KEY UPDATE general_notes = CONCAT_WS('. ', general_notes, VALUES(general_notes)) Note that you can use VALUES() in the ON DUPLICATE KEY clause to refer to the value that would have been otherwise inserted.
doc_23530125
When I run the exported file dealer.spec.js, my first 3 tests pass but the 4th one fails. I have tracked it down to when I click the FaceBook link. The error that I am receiving in the command prompt is: * *Dealer Dealership Overview: ReferenceError: waitForWindow is not defined at Context. (dealer.spec.js:68:23) at processTicksAndRejections (internal/process/task_queues.js:93:5) Here is a snippit of the offending code: vars["root"] = await driver.getWindowHandle() await driver.switchTo().window(vars["root"]) vars["windowHandles"] = await driver.getAllWindowHandles() await driver.findElement(By.id("FacebookLogo")).click() vars["win4361"] = await waitForWindow(2000) await driver.switchTo().window(vars["win4361"]) vars["fbURL"] = await driver.executeScript("return window.location.href.substring(0,24);") assert(vars["fbURL"].toString() == "https://www.facebook.com") await driver.close() await driver.switchTo().window(vars["root"]) vars["windowHandles"] = await driver.getAllWindowHandles() await driver.findElement(By.id("ctl00_TwitterLogo")).click() vars["win5590"] = await waitForWindow(2000) await driver.switchTo().window(vars["win5590"]) vars["twitterURL"] = await driver.executeScript("return window.location.href.substring(0,19);") assert(vars["twitterURL"].toString() == "https://twitter.com") await driver.close() await driver.switchTo().window(vars["root"]) vars["windowHandles"] = await driver.getAllWindowHandles() await driver.findElement(By.id("ctl00_LinkedInLogo")).click() vars["win877"] = await waitForWindow(2000) await driver.switchTo().window(vars["win877"]) vars["LinkedinURL"] = await driver.executeScript("return window.location.href.substring(0,24);") assert(vars["LinkedinURL"].toString() == "https://www.linkedin.com") await driver.close() await driver.switchTo().window(vars["root"]) I see that this is a function but is not defined. Anyone have a fix for this?
doc_23530126
Example 1: Input: s = "aba" Output: true Example 2: Input: s = "abca" Output: true Explanation: You could delete the character 'c'. Example 3: Input: s = "abc" Output: false For this problem in leetcode my code has passed 462/469 test cases: Following is the test case for which my code is failing the test. "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga" My code is: class Solution: def validPalindrome(self, s: str) -> bool: skip=0 l,r=0,len(s)-1 while l<r: if s[l]==s[r]: l+=1 r-=1 elif s[l]!=s[r] and skip<1 and s[l+1]==s[r]: l+=1 skip=1 elif s[l]!=s[r] and skip<1 and s[r-1]==s[l]: r-=1 skip=1 else: return False return True What is the problem with my code? Note: in this string the output should be true, mine returns false From left there are characters 'lcup' and from right there are characters 'lucup' My code is supposed to skip the letter u from right side and continue. "aguokepatgbnvfqmgm**lcup**uufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuu**pucul**mgmqfvnbgtapekouga" Another example: It returns true for the following string: s='adau' Skips letter 'u' as expected. However when I use the example according to the test case string that failed, it returns False. s= 'cuppucu' It should skip first u from the right side and return True but it doesn't. However as soon as I replace that last letter 'u' with letter 'a' it skips the letter 'a' and returns True. What's the problem here? A: Imagine the string 'abbab'. First you check index 0 and 4 with the values "a" and "b". They are not the same, but the "b" at index 1 matches the "b" at index 4. So you move forward to 1 and 4. Next is 2 and 3 and those are "b" and "a" and those don't match too. End of the story. abbab l r abbab l r abbab lr -> False Now let's switch around the elif blocks. Again you check index 0 and 4 first. They are not the same, so you now change the right index first and see that 0 and 3 are both "a". The next comparison is at indexes 1 and 2 with "b". Finished. Found a match. abbab l r abbab l r abbab lr -> True You didn't ask for it but here is a working solution with a different approach. class Solution: def generate_strings(self, s): yield s, s[::-1] for pos in range(len(s)): t = ''.join(c for i, c in enumerate(s) if i != pos) yield t, t[::-1] def validPalindrome(self, p): return any(x == y for x, y in self.generate_strings(p)) A: I over-complicated this in my first answer. I thought that you had to skip a particular character multiple times. As others have pointed out, that isn't true. So you have a solution from someone else, but you wanted to know how to change your code to always do the right thing. One way would be to run your algorithm twice. The first time, you only consider if you can skip a character on the left side of the input string as you're walking over it. For the second call, you only consider skipping a character on the right side. For cases like the one you ran into here where you could choose to skip either character, but only one will produce a positive result, well then if you try both cases, one or the other will always succeed when it should. So here's that simple change you can make...modifying your function only slightly, and then calling it twice. class Solution: def _validPalindrome(self, s: str, choose_first: bool) -> bool: skip = 0 l, r = 0, len(s) - 1 while l < r: if s[l] == s[r]: l += 1 r -= 1 elif choose_first and s[l] != s[r] and skip < 1 and s[r - 1] == s[l]: r -= 1 skip = 1 elif not choose_first and s[l] != s[r] and skip < 1 and s[l + 1] == s[r]: l += 1 skip = 1 else: return False return True def validPalindrome(self, s: str) -> bool: return self._validPalindrome(s, False) or self._validPalindrome(s, True) def main(): inp = "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga" print(Solution().validPalindrome(inp)) main() Result: True This should pass for all the cases for which your original code passed.
doc_23530127
When my server gets a lot of requests per second. I get the 307 response instead of 200 (because it is simple HTTP GET request, so I should get 200). Request: "host/api/..." is the simplest get. "Location" in header in response is the same url as was requested, I mean when "X" url was called, "X" url was included in Location in response. This is sample of my Log from azure {"RequestScheme":"http","AddressIp":"34.204.191.83","ResponseHeader":"[Location, https://onlinedoctor.azurewebsites.net/api/doctor/getdoctors]","RequestMethod":"GET","RequestPath":"/api/doctor/getdoctors","StatusCode":307,"Elapsed":0.0974,"SourceContext":"Serilog.AspNetCore.RequestLoggingMiddleware","RequestId":"0HM4D65VS83G8:00000001","SpanId":"|82de96cf-4cd9d83596f676e5.","TraceId":"82de96cf-4cd9d83596f676e5","ParentId":"","ConnectionId":"0HM4D65VS83G8","MachineName":"RD501AC5A97F1B","ProcessId":21264,"ThreadId":61} Is it some prebulid middleware in .net core to maintain the server traffic or how to set your own rules? A: HTTP 307 is Temporary redirect. It may be that when the load is too high for your service, Azure is trying to redirect the request to a different instance of the service. You need to implement security on your site. Using the url in the question it is possible to get a list of all doctors in your system. https://onlinedoctor.azurewebsites.net/api/doctor/getdoctors
doc_23530128
I cannot interpret the following error messages. How is the string incorrectly formatted? With Datetime .strptime() from datetime import datetime datetime.strptime("3/31/21 1:50PM", '%d/%m/%y %I:%M%p') Returns: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-41-8f0bfdfcb876> in <module> ----> 1 datetime.strptime("3/31/21 1:50PM", '%d/%m/%y %I:%M%p') ~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime_datetime(cls, data_string, format) 566 """Return a class cls instance based on the input string and the 567 format string.""" --> 568 tt, fraction, gmtoff_fraction = _strptime(data_string, format) 569 tzname, gmtoff = tt[-2:] 570 args = tt[:6] + (fraction,) ~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime(data_string, format) 347 found = format_regex.match(data_string) 348 if not found: --> 349 raise ValueError("time data %r does not match format %r" % 350 (data_string, format)) 351 if len(data_string) != found.end(): ValueError: time data '3/31/21 1:50PM' does not match format '%d/%m/%y %I:%M%p' With Pandas to_datetime() import pandas as pd pd.to_datetime("3/31/21 1:50PM", format='%d/%m/%y %I:%M%p') Returns --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact) 455 try: --> 456 values, tz = conversion.datetime_to_datetime64(arg) 457 dta = DatetimeArray(values, dtype=tz_to_dtype(tz)) pandas/_libs/tslibs/conversion.pyx in pandas._libs.tslibs.conversion.datetime_to_datetime64() TypeError: Unrecognized value type: <class 'str'> During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) <ipython-input-43-72b4542d7532> in <module> ----> 1 pd.to_datetime("3/31/21 1:50PM", format='%d/%m/%y %I:%M%p') ~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, infer_datetime_format, origin, cache) 830 result = convert_listlike(arg, format) 831 else: --> 832 result = convert_listlike(np.array([arg]), format)[0] 833 834 return result ~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact) 458 return DatetimeIndex._simple_new(dta, name=name) 459 except (ValueError, TypeError): --> 460 raise e 461 462 if result is None: ~/miniconda3/envs/metpy/lib/python3.9/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact) 421 if result is None: 422 try: --> 423 result, timezones = array_strptime( 424 arg, format, exact=exact, errors=errors 425 ) pandas/_libs/tslibs/strptime.pyx in pandas._libs.tslibs.strptime.array_strptime() ValueError: time data '3/31/21 1:50PM' does not match format '%d/%m/%y %I:%M%p' (match) Using strftime reference When I try using the non-zero padded information I get a bad directive in format error datetime.strptime("3/31/21 1:50PM", '%-d/%m/%y %-I:%M%p') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-44-84bcd95d0fd5> in <module> ----> 1 datetime.strptime("3/31/21 1:50PM", '%d/%m/%y %-I:%M%p') ~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime_datetime(cls, data_string, format) 566 """Return a class cls instance based on the input string and the 567 format string.""" --> 568 tt, fraction, gmtoff_fraction = _strptime(data_string, format) 569 tzname, gmtoff = tt[-2:] 570 args = tt[:6] + (fraction,) ~/miniconda3/envs/metpy/lib/python3.9/_strptime.py in _strptime(data_string, format) 339 bad_directive = "%" 340 del err --> 341 raise ValueError("'%s' is a bad directive in format '%s'" % 342 (bad_directive, format)) from None 343 # IndexError only occurs when the format string is "%" ValueError: '-' is a bad directive in format '%-d/%m/%y %-I:%M%p' A: You have day and month the wrong way round. This should work. from datetime import datetime datetime.strptime("3/31/21 1:50PM", '%m/%d/%y %I:%M%p')
doc_23530129
where domain.com/username/ is non-editable text (that doesn't get submitted as form data), but the user can type what they want at the end of it. I know I can use Javascript for this, but is there a clean, non-hacky way to do it with CSS alone? Of course the username will vary in size, so the editable text needs to start in the right place. A: If you don't need the default browser-style inputs and can edit the HTML, you can create your custom fields like this - http://jsfiddle.net/Aprillion/aJQ6M/: HTML: <label class="looks_like_input"> domain.com/username/ <input type="text" value="all-about-kitties"> </label> CSS: .looks_like_input { border: 1px inset; font-weight: bold; } .looks_like_input input { border: 0; font-weight: normal; } A: why not just label the domain.com/username/ and then put the input? put this in your CSS #page{float:left;} #box{border:1px inset; height:30px;} .text_field{border:none;} and this goes in HTML <div id="page"> <div id="box"> <input class="text_field" style="float:right; min-width:50px;width:50px;max-width:130px;text-align:left;" size="5" onkeyup="this.size=this.value.length+1;this.style.width='auto'" type="text"> <label class="prefix_for_input" style="float:right;">http://millerpath.tumblr.com/</label> </div> </div> you might wanna fix some things around here.
doc_23530130
Here is how I'm connecting to the tables. class CrmTable < ActiveRecord::Base self.abstract_class = true def self.table_name_prefix 'dbo_' end # establish_connection "crm_tables_#{Rails.env}" establish_connection "crm_tables" end class Address < CrmTable self.table_name = "Address" end class Opportunity < CrmTable self.table_name = "Opportunity" end That connects me to the Address and Opportunity tables with no issues. However, I want to be able to access the SQL view of database/views/dbo.vPerson. I tried variations on the following: class Vperson < CrmTable self.table_name = "Vperson" end However, I don't seem to be getting any records. I tried putting the following in my view but it was nil <% @view_name = CrmTable::Vperson.all %> <% @view_name.inspect %> Is it possible to establish an active record connection to a view? If so, what am I doing wrong? A: OK, I feel STUPID.. I forgot the = in the <% @view_name.inspect %> line.. It should be <%= @view_name.inspect %>. That explains why I wasn't seeing anything.. I did see another question that mentioned a need to add a primary key when you are connecting to views. How can I use SQL Server Table Views as Rails Models (Read Only)?
doc_23530131
when i type 75 in the textbox it gives me the results like below 7510- Synaptic 7512-Allied 7513-King when i select the particular row , the number in the seleted value should only be placed in the textbox. -- > 7513-King 7513 should be placed in textbox. A: Are you using the jQuery UI autocomplete ? If so, pass in an initial array of Json objects with both label and value properties. The label text will be displayed in the autocomplete dropdown, but the value is available on the select event. var data = [ { label: "7510-Synaptic", value: 7510 }, { label: "7512-Allied", value: 7512 }, { label: "7513-King", value: 7513 } ]; $( "#theAutocomplete" ).autocomplete({ delay: 0, source: data, select: function(event, ui) { // selected value is at ui.item.value; // label is at ui.item.label } }). A: This should do it, although a regex expression would be also usefull and maybe more accurate. parseInt('7513-King'); A: This can be done with the original standalone jQuery autocompleter plugin that is still around (and actively developed): http://code.google.com/p/jquery-autocomplete/ You will have to use the option onItemSelect There is an example that does just this in the demo (http://code.google.com/p/jquery-autocomplete/source/browse/demo/index.html)
doc_23530132
This append query has been around for the past few months and has been working perfectly until 2 weeks ago. It is something I do 1x a week and this first started by rejecting 1 record 2 weeks ago, then the next time I imported there were 2 records that got rejected 1 week ago, and finally this 3rd time I'm doing it there are 124 cases that are being rejected due to a key violation and I cant seem to pinpoint what is causing the rejection. When it happened the first few times there was only 1 or 2 records that were effected so I added their ID# (The primary key) to the main table and then re-did the import and after I did that it was able to update all of the information related to that record however this is not something I can do for 124 records. I've tried everything I can think of including, checking the ID# field in the original file to see if there were any spaces etc, checking the ID# field in the imported file before it tries to append, removing all of the other data outside of the ID field to see if it would just import the ID field but none of those things resolved the issue. In fact the only thing I've found that helps is if I manually add the ID # to the tblPI ID field and then re-run the append ( I get one less to append which makes sense) and once I run the update queries it imports the rest of the corresponding data. TblPI is the table I want to append the information to and the CCE Cohort is the file that i'm pulling the information from. The ID field in tblPI is the primary key and is set to "Indexed Yes (No Duplicates)" The only other indexed field is the Visit Date field which is set to "Indexed Yes (Duplicates OK)" This is the syntax that is used for the append query and literally before 2 weeks ago there wasn't any issues occurring which is also what is so puzzling to me: INSERT INTO tblPI ( ID, [911#], Deceased, DoB, Gender, [Hispanic/Latino], Race, [Employment Status], Occupation, [Marital Status], VisitDate, [Visit#] ) SELECT [CCE Cohort].ID, [CCE Cohort].[911#], [CCE Cohort].Deceased, [CCE Cohort].DoB, [CCE Cohort].Gender, [CCE Cohort].[Hispanic/Latino], [CCE Cohort].Race, [CCE Cohort].[Employment Status], [CCE Cohort].Occupation, [CCE Cohort].[Marital Status], [CCE Cohort].VisitDate, [CCE Cohort].[Visit#] FROM [CCE Cohort] LEFT JOIN tblPI ON [CCE Cohort].[ID] = tblPI.[ID] WHERE (((tblPI.ID) Is Null)); Thank you so much for any guidance! =)
doc_23530133
One of my CCK text fields has an unlimited number of values. However if more than 1 value is used, only the first value is included in the email. How can I include all values when their is more than 1? Thanks A: Token Array module fixes this problem: http://drupal.org/project/token_array
doc_23530134
As part of gitci.I have a docker file in gitlab. I am planning to create a docker image and push it to ECR and then use that image for batch processing. I have already completed batch processing part using existing image in ECR. But not able to create docker image n push using cloudformation. Please guide me. Should I use command in init. Thanks in advance gurus A: I had the same problem at work and sumbled across this already asked question that does not have a proper answer, so I'll give instructions of how I did. Baseline: you cannot do this with cloudformation, cloudformation is used to create infrastructure and automations. Although, you can accomplish this with codebuild and you can use cloudformation to create a codebuild project. This repository does that for a practical example. What you would do is: create a cloudformation template that creates a codebuild project and in your codebuild create a buildspec.yml (file that specifies the build) that will push your image to ECR. The codebuild project would look like this: CodeBuildProject: Type: AWS::CodeBuild::Project Properties: Artifacts: Type: CODEPIPELINE Description: "Codebuild project to push flask api image to ecr" Environment: ComputeType: !FindInMap [CodeBuildComputeTypeMap, !Ref GithubBranch, type] EnvironmentVariables: - Name: AWS_DEFAULT_REGION Value: !Ref AWS::Region - Name: AWS_ACCOUNT_ID Value: !Ref "AWS::AccountId" - Name: AWS_ECR_REPOSITORY_URI Value: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${EcrRepository} - Name: IMAGE_REPO_NAME Value: !Ref GithubRepository - Name: IMAGE_TAG Value: "latest" Image: "aws/codebuild/standard:5.0" PrivilegedMode: true Type: "LINUX_CONTAINER" ServiceRole: !GetAtt CodeBuildRole.Arn Source: Type: "CODEPIPELINE" BuildSpec: buildspec.yml EcrRepository: Type: AWS::ECR::Repository Properties: RepositoryName: !Ref GithubRepository CodeBuildRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: - codebuild.amazonaws.com Action: - "sts:AssumeRole" Policies: - PolicyName: "PushImageToEcr" PolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Action: - ecr:BatchGetImage - ecr:BatchCheckLayerAvailability - ecr:CompleteLayerUpload - ecr:GetDownloadUrlForLayer - ecr:InitiateLayerUpload - ecr:PutImage - ecr:UploadLayerPart - ecr:GetAuthorizationToken Resource: "*" - PolicyName: "CodeBuildLogsRole" PolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*" - PolicyName: "GetAndPutArtifacts" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: - s3:GetObject - s3:PutObject - s3:ListBucket Resource: - !GetAtt ArtifactBucket.Arn - !Sub ${ArtifactBucket.Arn}/* ArtifactBucket: Type: AWS::S3::Bucket This should go in the Resources section of the cloudformation and will create the codebuild project, the ecr repository, the codebuild service role and the s3 bucket for the artifacts. Then you need a buildspec.yml template to push your image, this would look like this: version: 0.2 phases: pre_build: commands: - echo Logging in to Amazon ECR... - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com build: commands: - echo Build started on `date` - echo Building the Docker image... - cd app/ - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG . - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG post_build: commands: - echo Build completed on `date` - echo Pushing the Docker image... - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG A: You won't be able to do it using CloudFormation as it's not intended to do this style of operation. However, you mentioned that you're using gitlab-ci. This means you could easily create a job that build your docker image and uploads it to ECR. In my opinion, it's even easier to create a CodeBuild project (using CloudFormation, IaC FTW!) that handle the building and uploading of your Docker image. The advantage of CodeBuild over GitLab-ci is that you'll be able to give the proper ECR access to the CodeBuild worker for it to upload the image to the repository.
doc_23530135
(ABC.*\.DAT) in perl. How to write a negation for the above regex? I already tried expressions like (?!ABC.*)\.DAT or (?!(ABC.*\.DAT)) Any help is appreciated. A: (?s:(?!ABC).)*\.DAT You can try this negation based regex. See demo. The above can be safely embedded into a larger pattern. For example, /^(?:(?!ABC).)*\.DAT\z/s If you are trying to match the whole input, and if ABC doesn't end with ., .D, .DA or .DAT, then the following will be faster: /^(?!.*ABC)\.DAT\z/s
doc_23530136
How can I get the foreign key fields normally? Here is my model class : @Table(name = "affecter") @Data @Entity public class Affecter implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", insertable = false, nullable = false) private Integer id; @Column(name = "dateEntree", nullable = false) private Date dateEntree; @Column(name = "dateSortie") private Date dateSortie; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="idAffaire", nullable = false) @JsonBackReference private Affaire affaire; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="idService", nullable = false) @JsonBackReference private Service service; Here is my repository : @CrossOrigin("*") @RepositoryRestResource public interface AffecterRepository extends JpaRepository<Affecter, Integer>, JpaSpecificationExecutor<Affecter>{ //Long countById(); @Query(value = "SELECT a FROM Affecter a WHERE a.service.id = ?1 AND a.dateSortie=null") @RestResource(path = "/byService") public List<Affecter> findAffecterByService(@Param("idS") Integer service); } And this is my JSON array returned by the link : http://localhost:8080/affecters id: 2, dateEntree: "2019-06-19T00:00:00.000+0000", dateSortie: null, _links: { self: { href: "http://localhost:8080/affecters/2" }, affecter: { href: "http://localhost:8080/affecters/2" }, affaire: { href: "http://localhost:8080/affecters/2/affaire" }, service: { href: "http://localhost:8080/affecters/2/service" } } A: You have to map the foreign key columns as attributes in the entity as well but as read only: @Column(name = "idAffaire", insertable = false, nullable = false) private Integer idAffaire; @Column(name = "idService", insertable = false, nullable = false) private Integer idService;
doc_23530137
public class MySampleWebServiceOutboundGateway extends SimpleWebServiceOutboundGateway { private String externalServiceName; @Override protected Object doHandle(String uri, final Message<?> requestMessage, final WebServiceMessageCallback requestCallback) { try { Message<?> responseMessage = (Message<?>) super.doHandle(uri, requestMessage, new MySampleWebServiceMessageCallback(requestCallback, session,mapHeaders)); } catch (RuntimeException t) { .. throw new MessageHandlingException(requestMessage, "Error Occurred at External Service: " + this.externalServiceName, t); } I want to add additional info to exception like external Service name so that when error-channel get the exception, I can parse the message to get external service name. However, I get generic MessageHandlingException in the error-channel like this: gateway.GatewayFacade - failure occurred in gateway sendAndReceive org.springframework.integration.MessageHandlingException: error occurred in message handler [(inner bean)#30] at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:79) Please let me know what I can do to add some additional details to exception, without having to wrap the exception with another exception. Full Stack Trace: 2015-11-30 15:19:12,445 WARN [main] {} org.springframework.integration.gateway.GatewayProxyFactoryBean$MethodInvocationGateway - failure occurred in gateway sendAndReceive org.springframework.integration.MessageHandlingException: Error Occurred for External Service: Retrieve at com.myPackage.ws.outbound.MySampleWebServiceOutboundGateway.doHandle(MySampleWebServiceOutboundGateway.java:161) at org.springframework.integration.ws.AbstractWebServiceOutboundGateway.handleRequestMessage(AbstractWebServiceOutboundGateway.java:164) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:142) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:148) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain.handleMessageInternal(MessageHandlerChain.java:131) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115) at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102) at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.doSendAndReceive(MessagingTemplate.java:361) at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:274) at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:234) at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceiveMessage(MessagingGatewaySupport.java:208) at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:323) at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:286) at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:277) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy34.exchange(Unknown Source) at org.springframework.integration.gateway.RequestReplyMessageHandlerAdapter.handleRequestMessage(RequestReplyMessageHandlerAdapter.java:47) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:142) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:148) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:148) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain.handleMessageInternal(MessageHandlerChain.java:131) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115) at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102) at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115) at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102) at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.doSendAndReceive(MessagingTemplate.java:361) at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:274) at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:234) at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceiveMessage(MessagingGatewaySupport.java:208) at com.myPackage.rest.gateway.GatewayFacade.process(GatewayFacade.java:67) at com.myPackage.rest.gateway.GatewayFacade.process(GatewayFacade.java:58) at com.myPackage.springIntegration.MySpringIntegrationTest.verifyErrorResponseWhenRetrieveFailsWithSoapFault(MySpringIntegrationTest.java:51) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.ws.soap.client.SoapFaultClientException: 1929|Application|This is an error message. at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37) at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774) at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600) at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537) at org.springframework.integration.ws.SimpleWebServiceOutboundGateway.doHandle(SimpleWebServiceOutboundGateway.java:89) at com.MyPack.ws.outbound.MySampleWebServiceOutboundGateway.doHandle(MySampleWebServiceOutboundGateway.java:141) ... 107 more 2015-11-30 15:19:12,445 WARN [main] {} com.myPack.rest.gateway.GatewayFacade - failure occurred in gateway sendAndReceive org.springframework.integration.MessageHandlingException: error occurred in message handler [(inner bean)#30] at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:79) at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:148) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:148) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain.handleMessageInternal(MessageHandlerChain.java:131) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115) at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102) at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115) at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102) at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.doSendAndReceive(MessagingTemplate.java:361) at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:274) at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:234) at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceiveMessage(MessagingGatewaySupport.java:208) at com.myPack.rest.gateway.GatewayFacade.process(GatewayFacade.java:67) at com.myPack.rest.gateway.GatewayFacade.process(GatewayFacade.java:58) at com.springIntegration.MySpringIntegrationTest.verifyErrorResponseWhenRetrieveFailsWithSoapFault(MySpringIntegrationTest.java:51) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.ws.soap.client.SoapFaultClientException: 1929|Application|This is an error message. at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37) at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774) at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600) at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537) at org.springframework.integration.ws.SimpleWebServiceOutboundGateway.doHandle(SimpleWebServiceOutboundGateway.java:89) at com.myPack.ws.outbound.MySampleWebServiceOutboundGateway.doHandle(MySampleWebServiceOutboundGateway.java:141) at org.springframework.integration.ws.AbstractWebServiceOutboundGateway.handleRequestMessage(AbstractWebServiceOutboundGateway.java:164) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:142) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain$1.send(MessageHandlerChain.java:148) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.send(MessagingTemplate.java:169) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendMessage(AbstractReplyProducingMessageHandler.java:228) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.sendReplyMessage(AbstractReplyProducingMessageHandler.java:212) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.produceReply(AbstractReplyProducingMessageHandler.java:177) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleResult(AbstractReplyProducingMessageHandler.java:171) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:149) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.handler.MessageHandlerChain.handleMessageInternal(MessageHandlerChain.java:131) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115) at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102) at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149) at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330) at org.springframework.integration.core.MessagingTemplate.doSendAndReceive(MessagingTemplate.java:361) at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:274) at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:234) at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceiveMessage(MessagingGatewaySupport.java:208) at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:323) at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:286) at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:277) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy34.exchange(Unknown Source) at org.springframework.integration.gateway.RequestReplyMessageHandlerAdapter.handleRequestMessage(RequestReplyMessageHandlerAdapter.java:47) at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:142) at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) ... 74 more Here is what I noticed. If the gateway has error-channel defined like below, I get the exception in the error-channel as I expect. <int:gateway request-channel="retrieve_external" error-channel="exception_errorChannel" /> However, I want to define error-channel at the top level. <bean id="gatewayAdapter" class="com.myPack.rest.gateway.GatewayFacade"> <property name="requestChannel" ref="my_Requests" /> <property name="replyChannel" ref="my_response" /> <property name="errorChannel" ref="exception_errorChannel" /> </bean> public class GatewayFacade extends MessagingGatewaySupport implements GatewayAdapter, BeanNameAware { .. } With this way, MessagingGatewaySupport class looks that error-channel is null, and rethrows the original cause, which again gets wrapped into generic MessageHandlingException, which is why I loose the original MessageHandlingException I throw. A: It should be working as you describe; the code concerned (in AbstractMessageHandler) is: if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageHandlingException(message, "error occurred in message handler [" + this + "]", e); i.e. since you are throwing a MessageHandlingException, it should just be re-thrown. So it looks like you might be throwing some other MessageHandlingException that's not in the MessagingException hierarchy. Can you show the complete stack trace?
doc_23530138
at first i succeed to convert the number but it was in a reversed order (the first mod needs to be the last number or letter). the code is a part (for cases of %x) from a big project that is kind of implementation of sprintf (so sprintf or printf are not allowed obviously). so the buffer is for composing a string without any placeholders. thank u in advance. here's my code: int num = *(int*)ptrs[counter]; int tempnum=num; int mod=0; int length =0; for(int i=0;tempnum !=0;i++) { length++; tempnum /= 16; } int array[length]; for(int i= length; i>0;i--) { mod = num%16; num = num/16; array[i] = mod; } for(int i=0;i<length;i++) { if(array[i]<10) *buffer = array[i]+ '0'; else *buffer = array[i] -10 + 'a'; buffer++; } A: The for loop of calculating array[i] should change to: for(int i = length-1; i>=0;i--) // i from (length - 1) to 0 instead of from length to 1. { mod = num%16; num = num/16; array[i] = mod; } You do not need to change the buffer pointer. You can use: for(int i=0;i<length;i++) { if(array[i]<10) buffer[i] = array[i]+ '0'; else buffer[i] = array[i] + 55; } then do not forget at the null character at the end of buffer: buffer[length] = '\0'; I do not see the declaration of buffer in your code, so i propose the solution above for the declaration: char buffer[length+1]; A: for(int i= length; i>0;i--) { mod = num%16; num = num/16; array[i] = mod; } mistakes at array[i] to array[i-1]. buffer = array[i] + '87'; I suggest you use: buffer = array[i]-10 + 'a'; A: printf("%i", (int)[any hexadecimal number]); would print the integer form of this '[any hexadecimal number]' number
doc_23530139
$("#new-job-form").validate({ focusCleanup: true, focusInvalid: false, ignore: [], rules: { jobServices: "required", file: { required: true, filesize: maxFileSize, extension: '.tsv|.txt|.csv|.psv|.xls|.xlsx|.zip|.7z|.rar' } } }); This works fine. However, a new requirement has come in to accept files that dob't have an extension at all, and I can't figure out how to do this via JQuery validate. I tried adding an empty partition: extension: '.txt|.csv|.xls|.xlsx|.zip|.7z|.rar||' But that still refuses files without an extension. Is there a way to configure the module to accept files with no extension ? A: I suggest to you to create your own rule ; a rule same as extention but add the check if the file name doesn't contain a dot , value.indexOf('.') == -1; see below snippet : //adding extensionempty rule $.validator.addMethod("extensionempty", function(value, element, param) { param = typeof param === "string" ? param.replace(/,/g, "|") : "png|jpe?g|gif"; console.log(value, param); return this.optional(element) || value.match(new RegExp("\\.(" + param + ")$", "i")) || value.indexOf('.') == -1; }, $.validator.format("Please enter a value with a valid extension.")); $("#new-job-form").validate({ focusCleanup: true, focusInvalid: false, ignore: [], rules: { file: { required: true, extensionempty: 'tsv|txt|csv|psv|xls|xlsx|zip|7z|rar' } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.js"></script> <form id="new-job-form"> <label for="file">.tsv|.txt|.csv|.psv|.xls|.xlsx|.zip|.7z|.rar files allowed: </label> <input type="file" id="file" name="file"> <br/> <input type="submit" value="Validate!"> </form>
doc_23530140
The final outcome should be various plots that describe our research question which is if there is any connection between district, job sector and more to uneployments percentage. I did a lot of searching and nothing comes up as far as it comes to characters columns. So, I need your help in understanding how can I make a conditional command to create a subset of this database which summarise it. Here's how the database looks like: Cdata <- structure( list( Month = c( "2020-01", "2020-01", "2020-01", "2020-01", "2020-01", "2020-01", "2020-01", "2020-01", "2020-01", "2020-01" ), District = c( "Center", "Center", "Center", "Center", "Center", "Center", "Center", "Center", "Center", "Center" ), Age = c( "Under 17", "Under 17", "Under 17", "18-24", "18-24", "18-24", "18-24", "18-24", "18-24", "18-24" ), Gender = c( "Male", "Male", "Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male" ), Education = c("0", "0", "0", "0", "0", "0", "0", "0", "0", "0"), MedicalDisability = c( "Without any", "Without any", "Without any", "Without any", "Without any", "Without any", "Without any", "Without any", "Without any", "Without any" ), Religion = c( "Jewish", "Muslims", "Other", "Jewish", "Jewish", "Jewish", "Jewish", "Jewish", "Jewish", "Jewish" ), UneploymentDays = c( "0-30", "Over 270", "Over 270", "0-30", "0-30", "0-30", "0-30", "0-30", "0-30", "31-180" ), Occupation = c( "Laboring class", "Sales \\ Costumer service", "Undefinded", "Laboring class", "Academic degree", "Practical engineers / Technicians", "Undefinded", "Sales \\ Costumer service", "Laboring class", "Practical engineers / Technicians" ), Jobseekers = c(2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 5L, 2L), GMI = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), ACU = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), NACU = c(2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 5L, 2L), NewSeekers = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L), NewFiredSeekers = c(0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L) ), row.names = c(NA, 10L), class = "data.frame" ) i need a new dataset that looks like this: District Jobseekers GMI ACU NACU North 1024 8710 3245 3256 Center 57691 12160 8710 14320 South 21516 9821 5289 18172 And than sort it all over again by age: Age Jobseekers GMI ACU NACU Under 17 1024 8710 3245 3256 18-24 57691 12160 8710 14320 25-34 21516 9821 5289 18172 45-54 4682 7142 2365 6128 55-64 1999 1991 2839 1927 Over 64 10918 4289 1378 5368 And than, finally, i need to make plots for each category that shows statistics and make statistic tests as i described. Hope i made my point clearly now. as for the codes, i've tried so many structures and examples, non of them really helped. Let me make it clear - I don't want you to do my work or write the whole code for me, but at the same time i'll mentioned i'm a newbie in R language, and i do this task as a part of a project in data science course. If anything else needed, please let me know. Here's a screenshot of the database: https://imgur.com/a/7fDGuuK Thanks, Moshe
doc_23530141
Here's the code: let varArray = []; let rufus1 = document.getElementById('rufus1'); let rufus2 = document.getElementById('rufus2'); // variables for easing syntax function arrayGiver() { varArray.push('<div>' + document.getElementById('rufus1').value + '</div>'); // I've used `<div>` instead of `<br>` for line breaking the elements, but when I'll be making bigger more complex projects I should probably use `<br>` shouldn't I? rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" + varArray); //this cleans the input after executing the function rufus1.value = ''; } //this makes the function execute on an enter key press document.addEventListener('keydown', function(enterKey) { if (enterKey.keyCode === 13) { arrayGiver(); } }) <input id="rufus1"> <br> <br> <button onclick="arrayGiver();">Bleh</button> <p id="rufus2"></p> A: Because array auto add commas as separator when converted to string. You can get rid of this by simply use join(' ') on varArray as below let varArray = []; let rufus1 = document.getElementById('rufus1'); let rufus2 = document.getElementById('rufus2'); // variables for easing syntax function arrayGiver() { varArray.push('<div>' + document.getElementById('rufus1').value + '</div>') // I've used `<div>` instead of `<br>` for line breaking the elements, but when I'll be making bigger more complex projects I should probably use `<br>` shouldn't I? rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" + varArray.join(' ')); //this cleans the input after executing the function rufus1.value = ''; } //this makes the function execute on an enter key press document.addEventListener('keydown', function (enterKey) { if (enterKey.keyCode === 13) { arrayGiver(); } }) <input id="rufus1" type="text"> <br> <br> <button onclick="arrayGiver();">Bleh</button> <p id="rufus2"></p> A: You can use forEach() or another loop to add the array elements to innerHTML For this answer I used: varArray.forEach(e => rufus2.innerHTML += e); which iterates over the array adding each element (e) to rufus2.innerHTML. let varArray = []; let rufus1 = document.getElementById('rufus1'); let rufus2 = document.getElementById('rufus2'); // variables for easing syntax function arrayGiver() { varArray.push('<div>' + document.getElementById('rufus1').value + '</div>'); // I've used `<div>` instead of `<br>` for line breaking the elements, but when I'll be making bigger more complex projects I should probably use `<br>` shouldn't I? rufus2.innerHTML = ("You have just added to your collection:" + "<br/>"); varArray.forEach(e => rufus2.innerHTML += e); //this cleans the input after executing the function rufus1.value = ''; } //this makes the function execute on an enter key press document.addEventListener('keydown', function(enterKey) { if (enterKey.keyCode === 13) { arrayGiver(); } }) <input id="rufus1"> <br> <br> <button onclick="arrayGiver();">Bleh</button> <p id="rufus2"></p> A: To achieve expected result, use string variable instead of array as below let varArray = []; var list =''; let rufus1 = document.getElementById('rufus1'); let rufus2 = document.getElementById('rufus2'); // variables for easing syntax function arrayGiver(){ list = list + '<div>' + document.getElementById('rufus1').value + '</div>' rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" + list); list.value = ''; } https://codepen.io/nagasai/pen/bvQKbX let varArray = []; var list =''; let rufus1 = document.getElementById('rufus1'); let rufus2 = document.getElementById('rufus2'); // variables for easing syntax function arrayGiver(){ list = list + '<div>' + document.getElementById('rufus1').value + '</div>' rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" + list); list.value = ''; } document.addEventListener('keydown', function(enterKey) { if(enterKey.keyCode === 13){ arrayGiver(); } }) body { font-family: Arial; font-size: 24px; } button { width: 100px; height: 25px; } <input id="rufus1"> <br> <br> <button onclick="arrayGiver();">Bleh</button> <p id="rufus2"></p>
doc_23530142
First, let me start with a simple example: Map<Integer, String> myMap = new HashMap<>(); //plain old hashmap myMap.put(9,"star"); //no problem myMap.put(10, 1.2); //Incompatible type, the compiler yells Map<Integer, Double> aMap = (Map<Integer, Double>) myMap; //Cannot cast, the compiler yells So far, everything is expected, as you should not be able to put an object of inconsistent type into an already constructed Map. Now let's consider this: public class NoRulesForMe { static Object theRing; public static void main(String[] args){ Map<Integer, String> myMap = new HashMap<>(); myMap.put(9,"star"); Map<Integer, Double> myMapMorphed = castWildly(myMap); myMapMorphed.put(99, 3.14); System.out.println(myMapMorphed.get(9)); //"star", as we put in System.out.println(myMapMorphed.get(99)); //3.14, as we put in } public static <T> T castWildly(Object value){ theRing = value; T morphed = (T) theRing; return morphed; } } I'm surprised that this didn't cause a run-time error - how does Map achieve this, and is this behavior specified in the JLS or API and thus can be depended upon? Reason I ask is that I saw a (more involved) version of this in production code, and I wonder, even if this may be befuddling and smelly, can it be guaranteed to work functionality-wise. Any input would be appreciated. A: This type of coding is very risky!! Although it will compile, you will notice that the compiler complains with a warning: Note: NoRulesForMe.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. These warnings, especially since you are using generics, should never be ignored nor just suppressed. You must absolutely be sure (logically following the code) that the cast is safe and won't be causing some problems later on. It is best to always code in such a way that errors are discovered and picked up at compiler time instead of run time. The warning given by the compiler here is telling you that things may go wrong. You are passing your myMap as an Object to the method castWildly, and when you are casting you are casting from Object to a Map. The compiler can infer that T in your code has type target of Map<String, Double>, and thus can infer this. However, when casting, it has no information about what (sub)type the Object value (or Object theRing) is. So it has no way in checking that the cast is safe (specifically type safe). The problem with this code comes in when you retrieve values out of your map. The following code has one extra added line, and the code compiles (with the same warning as above). This is because when retrieving a value as a Double out of a map that is declared as Map<String, Double> is absolutely valid when the compiler does type checking... at run time however, your code will crash (run time crash error shown below). This is very dangerous way to code, especially in production code. You'd rather have your compiler give you errors than deploying production code that compiles and have your product crash when live. public class NoRulesForMe { static Object theRing; public static void main(String[] args){ Map<Integer, String> myMap = new HashMap<>(); myMap.put(9,"star"); Map<Integer, Double> myMapMorphed = castWildly(myMap); myMapMorphed.put(99, 3.14); System.out.println(myMapMorphed.get(9)); //"star", as we put in System.out.println(myMapMorphed.get(99)); //3.14, as we put in // added to show why this style of coding causes problems Double testValue1 = myMapMorphed.get(9); } public static <T> T castWildly(Object value){ theRing = value; T morphed = (T) theRing; return morphed; } } Run time error when running the above code: star 3.14 Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double at NoRulesForMe.main(NoRulesForMe.java:19) For further information, read Effective Java, by Joshua Bloch; Item 24: Eliminate unchecked warnings. (This item is under the heading Generics).
doc_23530143
for example: http://torcache.com/torrent/63ABC1435AA5CD48DCD866C6F7D5E80766034391.torrent responded HTTP/1.1 200 OK Server: nginx Date: Wed, 09 Jun 2010 01:11:26 GMT Content-Type: application/x-bittorrent Content-Length: 52712 Last-Modified: Tue, 08 Jun 2010 15:09:58 GMT Connection: keep-alive Expires: Fri, 09 Jul 2010 01:11:26 GMT Cache-Control: max-age=2592000 Content-Encoding: gzip Accept-Ranges: bytes then the compressed gzip, i tried gzdecode but doesn't work , gzeflate as well doesn't they simply don't get any response, and the contents of the files are no more than 2k A: Just tell cURL to decode the response automatically whenever it's gzipped curl_setopt($ch,CURLOPT_ENCODING, ''); A: Use gzdecode: <?php $c = file_get_contents("http://torcache.com/" . "torrent/63ABC1435AA5CD48DCD866C6F7D5E80766034391.torrent"); echo gzdecode($c); gives d8:announce42:http://tracker.openbittorrent.com/announce13:announce-listll42 ... A: libcurl offers a feature that makes it decompress the contents automatically (if built with zlib). See the CURLOPT_ACCEPT_ENCODING option: https://curl.haxx.se/libcurl/c/CURLOPT_ACCEPT_ENCODING.html A: Have you tried setting the header stating that you accept gzip encoding as follows?: curl_setopt($rCurl, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip,deflate')); A: With a zlib Stream Wrapper: file_get_contents("compress.zlib://http://torcache.com/" . "torrent/63ABC1435AA5CD48DCD866C6F7D5E80766034391.torrent"); A: Have you tried gzuncompress or gzinflate? gzdeflate compresses, the opposite of what you want. To be honest, I can't figure out how gzdecode differs from normal uncompressing. There's also the cURL option CURLOPT_ENCODING: The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. It seems to mean it'll automatically decompress the response, but I haven't tested that. A: You can do it with gzinflate (pretending that $headers contains all your HTTP headers, and $buffer contains your data): if (isset($headers['Content-Encoding']) && ($headers['Content-Encoding'] === 'gzip' || $headers['Content-Encoding'] === 'deflate')) { if ($headers['Content-Encoding'] === 'gzip') { $buffer = substr($buffer, 10); } $contents = @gzinflate($buffer); if ($contents === false) { return false; } }
doc_23530144
Here is the countdown: <HTML> <HEAD> <TITLE>Countdown</TITLE> <SCRIPT LANGUAGE="JavaScript"> var eventdate = new Date("May 19, 2013 21:00:00"); function toSt(n) { s="" if(n<10) s+="0" return s+n.toString(); } function countdown() { cl=document.clock; d=new Date(); count=Math.floor((eventdate.getTime()-d.getTime())/1000); if(count<=0) {cl.hours.value="--"; cl.mins.value="--"; cl.secs.value="--"; return; } cl.secs.value=toSt(count%60); count=Math.floor(count/60); cl.mins.value=toSt(count%60); count=Math.floor(count/60); cl.hours.value=count; setTimeout("countdown()",500); } // end hiding script--> </SCRIPT> </HEAD> <BODY onLoad="countdown()"> <FONT FACE="arial, helvetica" SIZE="-1"> <CENTER> <P> <FORM name="clock"> <TD ALIGN=CENTER><INPUT name="hours" size=0></TD> : <TD ALIGN=CENTER><INPUT name="mins" size=0></TD> : <TD ALIGN=CENTER><INPUT name="secs" size=0></TD> <TD ALIGN=CENTER><B>Hours</B></TD> </FORM> </CENTER> </BODY> </HTML> I have tried somehing like this: if(count=0){<META HTTP-EQUIV="refresh" CONTENT="0;URL=http://www.example.com/">} but it needs to be inserted in the HEAD, and it just redirects Please help me... You can do this in php, html or any language where this will work. A: For example i want to send a mail every 7 days. i have the page that does it. it just need to be clicked. so when countdown finishes it clicks that and resets the countdown back to 7 days. I would use Cron Jobs to do that instead of a Jquery code. But, anyways, in regards of what you were asking, the redirecting stuff, you could use the following code which doesn't need to be placed in <head> if(count == 0){ window.location.href="http://example.com"; }
doc_23530145
It mostly works well, but sometimes, there is a small glitch at a random place in the video that I important and I don't know why since the source video does not have any glitches. Can someone help me resolve this? A: It is rare, but this can happen since AE does not have the same import modules as Premiere. I've seen cases when AE would not read properly some mp4 files, and Premiere could read them nicely. How are you importing in AE ? Do you import the Premiere Pro project and have the entire timeline recreated? This means that AE will import the same video sources as Premiere. If AE has an issue with this specific format, that might be the issue. A workaround would be to render out your video in Premiere Pro, and then import this video in AE. You can use a lossless output format, but something like ProRes422HQ will most likely do the job without taking too much disk space. It is also a format that AE will surely understand. In short, the safe bet is to "bake" what you see correctly in Premiere Pro by rendering your timeline, then importing this render in AE, rather than the original sources.
doc_23530146
A: I'd suggest XAMPP, which is PHP, MySQL, Apache and Perl packed together with very easy installation and almost no configuration needed. For development, I suggest using NetBeans as IDE, it has very nice PHP support. A: Get a prepackaged distribution. There are quite a few of these around. Personally I use XAMPP but others are fine too. This gives you Apache, PHP and MySQL with an easy-to-use installer. Other than that you don't really need much. Just an editor of some kind (which could be anything from Notepad to a full-blown IDE) and something to connect to MySQL. Possibly phpMyAdmin but I personally prefer a desktop app for this. DBVisualizer is pretty decent. There are others. As far as editors go, of course don't use Windows Notepad. :) Notepad++ is a better free alternative. As far as IDE goes, I kinda like phped but it's commercial. Netbeans is OK. Eclipse can be used too. A: I'd second the notepad++ requirement. I'd also seriously advise installing xdebug on the webserver as it'll give a full stack trace if something goes wrong. Without this debugging can be really difficult. I'd also advise developing with notices on (rather than just warnings). It's a bit more work to code but it's caught stupid errors for me countless times and is invaluable. Wamp server is good, and contains MySQL, which is probably what you want to target if you ever plan on putting anything live on the web as other databases may not be as well supported. A: Make sure you have a real, step-by-step, debugger, and teach them how to use it. “var_dump debugging” is okay in a pinch, but not a good habit to get into. As suggested above, Xdebug is a good choice, especially when paired with a nice front-end. The Komodo IDE as well as NetBeans work with Xdebug. Beginners often are concerned about “optimizing” their code to make it faster. You can show them—using profiling—that optimizing for speed is pointless unless (1) it really is slow and (2) what you’re optimizing really is the bottleneck. You can configure Xdebug so that simply adding ?XDEBUG_PROFILE to the end of a URL generates profiling statistics. You can then analyze those statistics with the beautiful and easy-to-use webgrind. Choosing an editor or IDE is a personal decision. Let them use whatever they are comfortable with. If they’ve never programmed before, teach them about your favorite editor or IDE. A: XAMPP give you an out-of-the-box installation with PHP, MySQL, Perl and Apache, so you can focus on learning HTML and PHP: http://www.apachefriends.org/en/xampp.html A: Apache-based local web-server, and a comfortable IDE. You may use whatever IDE you like, but it should: - highlight PHP - have embedded FTP client (for working with non-local files) A: I recommend XAMPPLite with PHP 5.3.0 if possible. Regarding databases, I suggest SQLite - it's a great database engine embedded in a single file that supports standard SQL and IMHO it's easier to set up and maintain, otherwise MySQL with InnoDB. Editors, I would go with Notepad++ or Intype for TextMate-like bundles. If you're looking for IDEs, pick either Komodo or Aptana.
doc_23530147
Sub Find() Dim I As Long, temp As String Dim WS_Count As Integer Dim A As Integer WS_Count = ActiveWorkbook.Worksheets.Count For I = 1 To Range("A" & Rows.Count).End(xlUp).Row temp = Cells(I, "A").Value For A = 1 To WS_Count ' Search current value in sheets. Next A Next I End Sub A: What I have done is create a sub that searches for similar IDs in other sheets. I have tested this by adding a bit of code which can be replaced with whatever you intend to do with the matched IDs. Sub Find() Dim findVal As String, IDLocation As String Dim IDSheet As Worksheet Set IDSheet = Worksheets("IDSheet") Dim N As Long, i As Long, j As Long, k As Long k = 1 'loop through each cell in the first column and store its value in the "findVal" variable N = IDSheet.Cells(Rows.Count, "A").End(xlUp).Row For i = 1 To N findVal = Cells(i, 1).Value j = 2 'Loop each sheet in the workbook For Each ws In ThisWorkbook.Worksheets 'Do not search through IDSheet If ws.Name = IDSheet.Name Then 'do nothing Else 'Loop each cell in the sheet for the "findVal" variable For Each c In ws.UsedRange If c.Value = findVal Then 'Stores the location of the like ID IDLocation = ws.Name & ": (" & c.Row & ", " & c.Column & ")" IDSheet.Cells(k, j) = IDLocation j = j + 1 Else 'Do nothing End If Next End If Next k = k + 1 Next i End Sub
doc_23530148
I've researched the various mappings and have tried many of them. I haven't found one that does what I need and I think my need is a rather basic one (there are several of these questions on SO and each seems to get a different answer, which is fine.). I've really tried to do my due diligence on this. I've googled and trolled CodePlex and downloaded the ProDinner application (got it up and running and stepped through the code in debug). I'm at a point where I have my own ValueInjection class to handle the injecton. I'm about to paste my code and objects in a pretty friendly way so you can grab and run them. Mind you I have a solution that uses the base LoopValueInjection, but I don't like it because it'd require manual plumbing for injections going from entity to mapping and then mapping to entity. The ProDinner example had a more templated approach, which I liked, but I couldn't adapt it to my needs. I think where my code is messing up logic wise is that I don't understand how to force a recursive injection to occur if the source property type is not a simple object. In this example, the Person.Address.* properties will match by name and type those on the PersonViewModel class; however, the injection loops over the properties on Person and tries to match on the name and type of the Person.Address property. I thought the line Object result = Activator.CreateInstance(c.SourceProp.Type) .InjectFrom<CloneInjection>(c.SourceProp.Value); Would perform this recursion, but I don't think it does. So...Can anyone give me any direction on how to fix this? ////// ENTITY MODELS public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual Address Address { get; set; } } public class Address { public int Id { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } ////// VIEW MODEL public class PersonViewModel { public string FirstName { get; set; } public string LastName { get; set; } public int PersonId { get; set; } public int AddressId { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } ////// CUSTOM INJECTOR public class EntityToViewModel : ConventionInjection { protected override bool Match(ConventionInfo c) { //ignore int = 0 and DateTime = to 1/01/0001 if (c.SourceProp.Type == typeof(DateTime) && (DateTime)c.SourceProp.Value == default(DateTime) || (c.SourceProp.Type == typeof(int) && (int)c.SourceProp.Value == default(int))) return false; if (c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Value != null) return true; if (c.SourceProp.Type == typeof(int) && c.TargetProp.Type == typeof(int) ) { if( "id".Equals(c.SourceProp.Name.ToLower()) && c.TargetProp.Name.ToLower().EndsWith("id") && c.TargetProp.Name.StartsWith(c.Source.Type.Name)) return true; } //Transition logic to SetValue for value types. This should //allow Address values on Person to be set. if (!c.SourceProp.Type.IsPrimitive || c.SourceProp.Type.Equals(typeof(string))) return true; return false; //put id logic matching here //return c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Value != null; } protected override object SetValue(ConventionInfo c) { //If type is primative or string return the value as is if (c.SourceProp.Type.IsPrimitive || c.SourceProp.Type.Equals(typeof(string))) return c.SourceProp.Value; Object result = Activator.CreateInstance(c.SourceProp.Type) .InjectFrom<CloneInjection>(c.SourceProp.Value); //for simple object types create a new instace and apply the clone injection on it return result; } } ////// Program.cs public class Program { public static void Main(string[] args) { Person defaultPerson = getDefaultPerson(); //Throws an error. I'm not sure where in the pipeline this occurs, but //it seems to happen somewhere other than the Match & SetValue method of //my EntityToViewModel injection PersonViewModel pvm = CreateFromEntity(defaultPerson); //Works, but want it more generic & without having to //include hardcoded prefix for every non-simple object on my EF Model pvm = CreateFromEntityWorking(defaultPerson); Console.ReadLine(); } private static PersonViewModel CreateFromEntity(Person person) { PersonViewModel pvm = new PersonViewModel(); pvm.InjectFrom<EntityToViewModel>(person); return pvm; } ///WORKING MAPPING BUT SEEMS TOO HARDCODED private static PersonViewModel CreateFromEntityWorking(Person person) { PersonViewModel personvm = new PersonViewModel(); //Fill out view model properties with the same name as those on Person personvm.InjectFrom(new LoopValueInjection().TargetPrefix("Person"), person); if (person != null && person.Address != null) { //Fill out view model properties for the Address personvm.InjectFrom(new LoopValueInjection().TargetPrefix("Address"), person.Address); } return personvm; } public static Person getDefaultPerson() { Person p = new Person(); Address a = new Address(); p.Id = 1; p.FirstName = "John"; p.LastName = "McClain"; a.City = "New York"; a.State = "New York"; a.Zip = "55555"; a.Id = 2; p.Address = a; return p; } } A: Finally found the examples I needed. Sadly,despite all my searching I've only just now landed on these. That's no one's fault by my own; however, my foot is sore from how much I've been kicking it. Pertinent URLS: The documentation (RTFM) http://valueinjecter.codeplex.com/documentation Flattening Example & Convention http://valueinjecter.codeplex.com/wikipage?title=flattening&referringTitle=Documentation Unflattening Example & Convention http://valueinjecter.codeplex.com/wikipage?title=unflattening&referringTitle=Documentation Solution to my issue: The convention that must be used on the view model is that top level properties are not prefixed by their property name as it would exist on the Entity. So, in my class below where FirstName, LastName, and Id all exist as top level properties on my Person entity, they don't get prefixed in my view model class. The City, State, Zip, and Id for the Person.Address property do get prefixed. Oddly enough, I thought of this solution while I was trying to implement my own injection. I got one working that went from Entity to ViewModel....just not the other way around. public class PersonViewModelPrefixed { public string FirstName { get; set; } public string LastName { get; set; } public int Id { get; set; } public int AddressId { get; set; } public string AddressCity { get; set; } public string AddressState { get; set; } public string AddressZip { get; set; } } public static void Main(string[] args) { Person defaultPerson = getDefaultPerson(); PersonViewModelPrefixed defaultPrefixedVm = getDefaultPrefixedViewModel(); //flatten - Entity to View Model PersonViewModelPrefixed pvm = Flatten(defaultPerson); //unflatten - View Model to Entity Person person2 = Unflatten(defaultPrefixedVm); Console.ReadLine(); } //unflatten - View Model to Entity private static Person Unflatten(PersonViewModelPrefixed personViewModel) { Person p = new Person(); p.InjectFrom<UnflatLoopValueInjection>(personViewModel); return p; } //flatten - Entity to View Model private static PersonViewModelPrefixed Flatten(Person person) { PersonViewModelPrefixed pvm = new PersonViewModelPrefixed(); pvm.InjectFrom<FlatLoopValueInjection>(person); return pvm; } So, given these details, does any one have some suggestions on how to make the Flatten & Unflatten methods more generic? That's what I'll be working on next.
doc_23530149
int main(int argc, char* argv[]) { cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE ); CvCapture* capture = cvCreateFileCapture( argv[1] ); IplImage* frame; while(1) { frame = cvQueryFrame( capture ); if( !frame ) break; cvShowImage( "Example2", frame ); char c = cvWaitKey(33); if( c == 27 ) break; } cvReleaseCapture( &capture ); cvDestroyWindow( "Example2" ); } A: Well, since your code lacks error checking, maybe there was a problem with cvCreateFileCapture() and you'll never know until you check the return of the function. Anyway, you should either remove, or add a debug for this statement here: if( !frame ) break; Becouse if there was a problem retrieving the first frame of the file, your application would simply give up and quit silently, giving you the "nothing happened" feeling. Changed it to something like: if (!frame) { printf("Uow, huge fail!\n"); break;} But most importantly: why are you not using cvCaptureFromAVI() ? Check this out: http://nashruddin.com/How_to_Play_AVI_Files_with_OpenCV
doc_23530150
However, the social media section is set off from the rest. It should be aligned to the right following the programming section. Any ideas? A: Add a (fixed) height to your .grid_6-Container. .grid_6 {height:250px; /*or something else*/} Your Problem occurs on floated elements with different height. Nice reading about floatings: http://coding.smashingmagazine.com/2007/05/01/css-float-theory-things-you-should-know/ Edit: Otherwise you could add a wrapper element to clear your floats: <div class="wrapper"> <div class="grid_6"></div> <div class="grid_6"></div> </div> <div class="wrapper"> <div class="grid_6"></div> <div class="grid_6"></div> </div> You can clear your floats with .wrapper {overflow:hidden;} OR you can use the clearfix method: http://perishablepress.com/press/2009/12/06/new-clearfix-hack/
doc_23530151
Highcharts.chart('container', { chart: { marginTop: 50, events: { load: function() { this.bread = { '': makeNode('', this.series[0].name, this.series[0]) } } } }, series: [{ type: 'treemap', layoutAlgorithm: 'squarified', allowDrillToNode: true, animationLimit: 1000, dataLabels: { enabled: false }, levelIsConstant: false, levels: [{ level: 1, dataLabels: { enabled: true, align:'left', verticalAlign:'Top' }, borderWidth: 1 }, { level: 2, colorByPoint: true, dataLabels: { enabled: true, }, borderWidth: 1 } ], data: points }], credits:false, plotOptions: { series: { dataLabels: { color: '#fff', textOutline:0, style: { fontWeight: 'bold' } }, point: { events: { click: function(e) { const hasChildren = !!this.node.childrenTotal if (hasChildren) { const bread = this.series.chart.bread bread[this.id] = makeNode(this.id, this.name, this.series, bread[this.node.parent]) } } } } } }, title: { text: '' } }); Here is my js fiddle. https://jsfiddle.net/irfanbsse/8djawts9/ But I dont want show second level color on first level.Same for second level and so on. how i can do it ? Thanks A: Here's a demo that shows how to change color of child nodes on point.click.event: click: function() { var points = this.series.points; this.node.children.forEach(function(child, i) { var point = points.find(function(point_) { return child.id === point_.id }); point.update({ color: color[i % (color.length - 1)] }); }); Live demo: https://jsfiddle.net/BlackLabel/sgkah0fq/ The next thing to implement is reverting the original colors while clicking on the previous level in navigation (label with callout shape).
doc_23530152
A self-contained, compilable example of what I have done follows. Note that I have set the Stage modality to Modality.APPLICATION_MODAL, and have set its owner to the Window of the Scene within the JFXPanel. How do I make the Stage modal within the Swing application? import javafx.application.Platform; import javafx.embed.swing.JFXPanel; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; import java.awt.BorderLayout; import java.awt.Dimension; public class App { public static void main(String[] args) { new App().run(); } public void run() { JFrame applicationFrame = new JFrame("JavaFX Mucking"); applicationFrame.setSize(new Dimension(300, 300)); JPanel content = new JPanel(new BorderLayout()); applicationFrame.setContentPane(content); JFXPanel jfxPanel = new JFXPanel(); content.add(jfxPanel); Platform.runLater(() -> jfxPanel.setScene(this.generateScene())); applicationFrame.setVisible(true); applicationFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } private Scene generateScene() { Button button = new Button("Show Dialog"); Scene scene = new Scene(new BorderPane(button)); button.setOnAction(actionEvent -> { Stage stage = new Stage(StageStyle.UTILITY); stage.initOwner(scene.getWindow()); stage.initModality(Modality.APPLICATION_MODAL); stage.setScene(new Scene(new Label("Hello World!"))); stage.sizeToScene(); stage.show(); }); return scene; } } A: You generated a scene object, placed it inside the JFXPanel which was placed inside the JFrame. At the same time you have placed the same Scene as the main Scene object in your Stage. You cannot have the same Scene be placed in two different places at the same time. To create the modal dialog just use the Stage object, because Stage and JFrame are both top level containers from two different gui libraries. Do not add the scene to the JFXPanel and the Stage, do one or the other.
doc_23530153
Logo in system theme. Logo in dark theme I had read all the manifest element but there is nothing any description about this issue. Can we remain same logo using changes in manifest? or There is any way to remain same logo in any theme?
doc_23530154
My efforts to solve this: todayVariable = Date.Now() Taking the datepart of this variable, if it is 1 or 7, that means it's a weekend, so I will leave it alone. However, what I don't know is how to determine if the week days are not holidays. How can I get a list of, for instance, all the official holidays for the next two years? A: Use this to answer if tomorrow is a holiday: Dim todayVariable As Date = Today Debug.Print(isHoliday(todayVariable.AddDays(1))) Function isHoliday(ByVal dt As Date) Return getHolidayList(dt.Year).Any(Function(x) x = dt) End Function The code below will calculate the dates for US Federal Holidays. A weakness of this method is that since the rules are hard coded I would need to change the code in the rare event that congress changed the rules. For my in-house software that is not a problem but it might be for others. Also I don't calculate Easter since that is not a US federal holiday. See Nature (1876) Algorithm for Calculating the Date of Easter Public Function getHolidayList(ByVal vYear As Integer) As List(Of Date) Dim FirstWeek As Integer = 1 Dim SecondWeek As Integer = 2 Dim ThirdWeek As Integer = 3 Dim FourthWeek As Integer = 4 Dim LastWeek As Integer = 5 Dim HolidayList As New List(Of Date) ' http://www.usa.gov/citizens/holidays.shtml ' http://archive.opm.gov/operating_status_schedules/fedhol/2013.asp ' New Year's Day Jan 1 HolidayList.Add(DateSerial(vYear, 1, 1)) ' Martin Luther King, Jr. third Mon in Jan HolidayList.Add(GetNthDayOfNthWeek(DateSerial(vYear, 1, 1), DayOfWeek.Monday, ThirdWeek)) ' Washington's Birthday third Mon in Feb HolidayList.Add(GetNthDayOfNthWeek(DateSerial(vYear, 2, 1), DayOfWeek.Monday, ThirdWeek)) ' Memorial Day last Mon in May HolidayList.Add(GetNthDayOfNthWeek(DateSerial(vYear, 5, 1), DayOfWeek.Monday, LastWeek)) ' Independence Day July 4 HolidayList.Add(DateSerial(vYear, 7, 4)) ' Labor Day first Mon in Sept HolidayList.Add(GetNthDayOfNthWeek(DateSerial(vYear, 9, 1), DayOfWeek.Monday, FirstWeek)) ' Columbus Day second Mon in Oct HolidayList.Add(GetNthDayOfNthWeek(DateSerial(vYear, 10, 1), DayOfWeek.Monday, SecondWeek)) ' Veterans Day Nov 11 HolidayList.Add(DateSerial(vYear, 11, 11)) ' Thanksgiving Day fourth Thur in Nov HolidayList.Add(GetNthDayOfNthWeek(DateSerial(vYear, 11, 1), DayOfWeek.Thursday, FourthWeek)) ' Christmas Day Dec 25 HolidayList.Add(DateSerial(vYear, 12, 25)) 'saturday holidays are moved to Fri; Sun to Mon For i As Integer = 0 To HolidayList.Count - 1 Dim dt As Date = HolidayList(i) If dt.DayOfWeek = DayOfWeek.Saturday Then HolidayList(i) = dt.AddDays(-1) End If If dt.DayOfWeek = DayOfWeek.Sunday Then HolidayList(i) = dt.AddDays(1) End If Next 'return Return HolidayList End Function Private Function GetNthDayOfNthWeek(ByVal dt As Date, ByVal DayofWeek As Integer, ByVal WhichWeek As Integer) As Date 'specify which day of which week of a month and this function will get the date 'this function uses the month and year of the date provided 'get first day of the given date Dim dtFirst As Date = DateSerial(dt.Year, dt.Month, 1) 'get first DayOfWeek of the month Dim dtRet As Date = dtFirst.AddDays(6 - dtFirst.AddDays(-(DayofWeek + 1)).DayOfWeek) 'get which week dtRet = dtRet.AddDays((WhichWeek - 1) * 7) 'if day is past end of month then adjust backwards a week If dtRet >= dtFirst.AddMonths(1) Then dtRet = dtRet.AddDays(-7) End If 'return Return dtRet End Function A: There isn't a commonly agreed upon list of official U.S. holidays. Probably the closest thing is the federal holiday calendar, but that includes days that most businesses remain open, such as Washington's Birthday and Columbus Day. Many businesses opt to put their holidays in a database table or combine into a calendar table. A: As others have pointed out already, there doesn't seem to be a list of holidays that you can "compute" or simply "get-somewhere". You'll have to hard-code the applicable list of dates. A few remarks on your description, to help you avoid any other issues: Date.Now gives the Date AND the Time of "now". You may use Date.Today if you wish to compare dates without regarding times. dateValue.DatePart gives you, indeed, the Date-part (Year, Month, Day). You presumably want to know the day-of-week (Sunday, Monday, ...). This goes as: Dim dayValue As System.DayOfWeek = dateValue.DayOfWeek The result is an integer Enum with values Sunday(=0), Monday(=1) etcetera. To avoid confusion: the Day property of a dateValue (dateValue.Day) gives you the day-number in a month (1..31).
doc_23530155
I want to enqueue tasks with the scheduleTime parameter to run in the future, but I must be able to cancel those tasks. I expected it would be possible to do something like this pseudo code: const task = await queue.enqueue({ foo: true }) // Then... await queue.cancel(task.id) I'm using Node.js. In case it's not possible to cancel a scheduled task with firebase-admin, can I somehow work around it by using @google-cloud/tasks directly? PS: I've also created a feature request: https://github.com/firebase/firebase-admin-node/issues/1753 A: The Firebase SDK doesn't return the task name/ID right now as in the code. If you need this functionality, I'd recommend filing a feature request and meanwhile use Cloud Tasks directly. You can simply create a HTTP Callable Function and then use the Cloud Tasks SDK to create a HTTP Target tasks that call this Cloud Function instead of using the onDispatch. // Instead of onDispatch() export const handleQueueEvent = functions.https.onRequest((req, res) => { // ... }); Adding a Cloud Task: async function createHttpTask() { const parent = client.queuePath(project, location, queue); const task = { httpRequest: { httpMethod: 'POST', // change method if required url, // Use URL of handleQueueEvent function here }, }; const request = { parent: parent, task: task }; const [response] = await client.createTask(request); return; } Checkout the documentation for more information.
doc_23530156
assetpath String: final String assetPath = 'lib/asset/textfile/cs_one.txt'; class one( sending assetpath as a string ): Navigator.push( context, MaterialPageRoute(builder: (context) => cs_one( assetPath : assetPath) ), ); class two ( receiving assetpath from class one and loading data ) : class cs_one extends StatefulWidget { final String assetPath; const cs_one({Key? key, required this.assetPath}) : super(key: key); @override _cs_oneState createState() => _cs_oneState( ); } class _cs_oneState extends State<cs_one> { String? data; static String? get assetPath => assetPath; void _loadData() async { final _loadedData = await rootBundle.loadString(assetPath!); setState(() { data = _loadedData; }); } @override void initState() { super.initState(); _loadData(); } Showing text in widget: body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Container( margin: EdgeInsets.all(15), width: 360, child: Text(data ?? 'empty'), ))), A: The Problem is solved. I solved it this way: class cs_one extends StatefulWidget { final String assetPath; const cs_one({Key? key, required this.assetPath}) : super(key: key); @override _cs_oneState createState() => _cs_oneState(assetPath ); } class _cs_oneState extends State<cs_one> { String? data; String path=''; _cs_oneState(String assetPath){ this.path=assetPath; } void _loadData() async { final _loadedData = await rootBundle.loadString(path); setState(() { data = _loadedData; }); }
doc_23530157
html/Javascript content makes HTTPS requests to our remote server. Because I am using an in-app server, the server sees the origin for these requests as coming from localhost. And it's a different port number each time. Is there a way to specify what the origin string should be for these requests, instead of letting StageWebView/iOS determine it?
doc_23530158
private bool speedBallForward = false; private bool firstTouchControl = false; public void Start() { rb = GetComponent<Rigidbody>(); } public void Update() { if (Variables.firstTouch == 1 && speedBallForward == false) { transform.position += new Vector3(0, 0, forwardSpeed * Time.deltaTime); cameraFollow.transform.position += new Vector3(0, 0, forwardSpeed * Time.deltaTime); vectorBack.transform.position += new Vector3(0, 0, forwardSpeed * Time.deltaTime); vectorUp.transform.position += new Vector3(0, 0, forwardSpeed * Time.deltaTime); } if (Input.touchCount > 0) { touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { if (firstTouchControl == false) { Variables.firstTouch = 1; UIManager.DeactiveAfterGameStart(); firstTouchControl = true; } } } else if (touch.phase == TouchPhase.Moved) { rb.velocity = new Vector3(touch.deltaPosition.x * speedModifier * Time.deltaTime, transform.position.y, touch.deltaPosition.y * speedModifier * Time.deltaTime); } else if (touch.phase == TouchPhase.Ended) { rb.velocity = Vector3.zero; } } }
doc_23530159
I've seen that whatsapp web allows certain kind of drag and drop integration. If I select several files from my file browser and drag and drop them into whatsapp web, I can send multiple images. It doesn't work using ctrl+c and ctrl+v. How could I display images in my website so that a user could drag and drop them into whatsapp web? Is there a way to do this programatically? Like copying base64 encoded images to the clipboard using javascript?
doc_23530160
Not a big thing, but I reckon it should be relatively easy to address. A: Try to use On Enter and On Exit subform events for set focus on required field in main form
doc_23530161
I have seen Start exe after msi install but using current user privileges but it seems overly complicated and shows no code. I haven't got the time to experiment with an unknown API. Are there any easy ways? Can I use VS Setup to define a non-elevated custom action or do something from the elevated custom action? A: If you just want to test your code, it wouldn't be hard to update your built msi file with Orca. It'll let you add the dll with your code to the binary table, add a corresponding row to the customaction table, and add the action to a sequence. If you need this to happen as part of your build process, you could accomplish the same thing with vbscript. The SDK comes with good sample vbscript code for interacting with an msi database, as described here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa372865%28v=vs.85%29.aspx A: Visual Studio setup projects do not support immediate custom actions. They are all deferred by default. So either you use custom code to impersonate the current user or you switch to another setup authoring tool which supports immediate actions.
doc_23530162
def reportWithOutComma = params.summaryReportDataTable.split(",") def inst = Institution.get(session.institutionid.toLong()) def result = [:] result.data = [] for(int i = 0;i<reportWithOutComma.size();i+=7){ def spaceReplacedData = reportWithOutComma.toString().replace('&nbsp;',' ') def name = reportWithOutComma[i].decodeHTML().toString() def index1 = name.indexOf("(") def stdNames = name.substring(0,index1) result.data << [StudentName:stdNames, TotalDays:reportWithOutComma[i+1].decodeHTML(), Holidays:reportWithOutComma[i+2].decodeHTML(), LeaveDays:reportWithOutComma[i+3].decodeHTML(), AbsentDays:reportWithOutComma[i+4].decodeHTML(), LateMins:reportWithOutComma[i+5].decodeHTML(), EarlyMins:reportWithOutComma[i+6].decodeHTML()] } params.InstitutionName = inst.name params._format = "PDF" params._file = "summaryReport" // filename of xml file def report = jasperService.buildReportDefinition(params, request.getLocale(),result) generateReport(report) } where generateReport contains: def generateReport = { reportDef -> if (!reportDef.fileFormat.inline && !reportDef.parameters._inline) { response.setHeader("Content-Disposition", "inline; filename=\"${reportDef.parameters._name ?: reportDef.name}.${reportDef.fileFormat.extension}\""); response.setHeader("Content-Type", "${reportDef.fileFormat.mimeTyp}"); response.contentType = reportDef.fileFormat.mimeTyp response.characterEncoding = "UTF-8" response.outputStream << reportDef.contentStream.toByteArray() } else {} } and i have xml file as created by iReport is: <?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="summaryReport" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="2b498a22-3b8e-44c4-a599-d41d0feae942"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <parameter name="InstitutionName" class="java.lang.String"/> <field name="StudentName" class="java.lang.String"/> <field name="TotalDays" class="java.lang.String"/> <field name="Holidays" class="java.lang.String"/> <field name="LeaveDays" class="java.lang.String"/> <field name="AbsentDays" class="java.lang.String"/> <field name="LateMins" class="java.lang.String"/> <field name="EarlyMins" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <pageHeader> <band height="108" splitType="Stretch"> <staticText> <reportElement x="34" y="87" width="100" height="20" uuid="0c063040-4acd-4e8f-8982-c87e1dca696a"/> <textElement textAlignment="Justified"/> <text><![CDATA[StudentName]]></text> </staticText> <line> <reportElement x="34" y="107" width="757" height="1" uuid="2f5845c8-dfa9-43f3-881f-ef34149351c3"/> </line> <staticText> <reportElement x="134" y="87" width="100" height="20" uuid="f999ecfb-3068-4fc4-bd7a-2f5c80dcf303"/> <text><![CDATA[TotalDays]]></text> </staticText> <staticText> <reportElement x="234" y="87" width="100" height="20" uuid="955a5328-7b84-4ba2-abae-7de90394bca3"/> <text><![CDATA[Holidays]]></text> </staticText> <textField> <reportElement x="671" y="40" width="80" height="20" uuid="d1bf7379-8c77-463c-aa74-c905c2ed9cc8"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression> </textField> <textField evaluationTime="Report"> <reportElement x="751" y="40" width="40" height="20" uuid="80df4247-690c-49a3-9dbc-85734480b67c"/> <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression> </textField> <textField> <reportElement x="150" y="20" width="404" height="20" uuid="4efbab64-a7d9-4c48-9e9c-ef9d8c5c390d"/> <textElement textAlignment="Center"/> <textFieldExpression><![CDATA[$P{InstitutionName}]]></textFieldExpression> </textField> <staticText> <reportElement x="334" y="87" width="100" height="20" uuid="14b757f8-522c-40f7-8b41-7aad0970c7ee"/> <text><![CDATA[LeaveDays]]></text> </staticText> <staticText> <reportElement x="534" y="88" width="100" height="20" uuid="b198e76e-30bb-432f-a083-c17afa5c5482"/> <text><![CDATA[LateMins]]></text> </staticText> <staticText> <reportElement x="634" y="87" width="100" height="20" uuid="757bc097-1e2c-4ba2-9aa1-7a15f9177413"/> <text><![CDATA[EarlyMins]]></text> </staticText> <staticText> <reportElement x="434" y="87" width="100" height="20" uuid="90a0e43a-9c4f-4475-b101-aef659b726a4"/> <text><![CDATA[AbsentDays]]></text> </staticText> </band> </pageHeader> <detail> <band height="125" splitType="Stretch"> <textField> <reportElement x="134" y="0" width="100" height="20" uuid="8d5ef54f-328e-42fd-ae87-2ef27f71562a"/> <textFieldExpression><![CDATA[$F{TotalDays}]]></textFieldExpression> </textField> <textField> <reportElement x="234" y="0" width="100" height="20" uuid="8e5b85b5-8071-48ab-b41c-95b22c5cd8f3"/> <textFieldExpression><![CDATA[$F{Holidays}]]></textFieldExpression> </textField> <textField> <reportElement x="34" y="0" width="100" height="20" uuid="691f19c5-9995-45cf-8aa7-bf6d1f953b23"/> <textFieldExpression><![CDATA[$F{StudentName}]]></textFieldExpression> </textField> <textField> <reportElement x="334" y="0" width="100" height="20" uuid="d45e1645-93fa-4b00-9d69-a3b079306027"/> <textFieldExpression><![CDATA[$F{LeaveDays}]]></textFieldExpression> </textField> <textField> <reportElement x="534" y="0" width="100" height="20" uuid="bf4dd507-7d72-4baf-ac9d-7d5c96a5e51c"/> <textFieldExpression><![CDATA[$F{LateMins}]]></textFieldExpression> </textField> <textField> <reportElement x="434" y="0" width="100" height="20" uuid="9a6e330f-f377-427f-969a-29d58a88de3b"/> <textFieldExpression><![CDATA[$F{AbsentDays}]]></textFieldExpression> </textField> <textField> <reportElement x="634" y="0" width="100" height="20" uuid="7a5cb204-41c3-4215-9c23-b5ec9310b06e"/> <textFieldExpression><![CDATA[$F{EarlyMins}]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band height="45" splitType="Stretch"/> </columnFooter> <pageFooter> <band height="54" splitType="Stretch"/> </pageFooter> <summary> <band height="42" splitType="Stretch"/> </summary> </jasperReport> and during pdf export it shows following error: URI /sAttend/report/summaryReport Class java.lang.NoSuchMethodError Message com.lowagie.text.pdf.PdfWriter.setRgbTransparencyBlending(Z)V how can i solve this problem please help. A: If you run grails dependency-report you will probably see that there are 2 versions of itext in the report. The one that Grails uses to generate documentation is probably conflicting. Try and exclude it by modifying your BuildConfig to exlclude the one used by Grails: inherits("global") { excludes "itext" } A: I tried both but it did not work so i added build "com.lowagie:itext:2.1.7" in BuildConfig.groovy including inherits("global") { excludes "itext" } and updated iText 2.0.8 to 2.1.7
doc_23530163
JavaScript: Show project image. _showProjectImage(e) { const btn = e.target.closest('.projects__maximize-btn'); if (!btn) return; const { id } = btn.dataset; const { image } = this._data.find(image => image.id === +id); this._projectBox = e.target.closest('.projects__box'); const markup = this._generateProjectImage(image); this._projectBox.insertAdjacentHTML('afterbegin', markup); } Hide project image. _hideProjectImage(e) { const btnClose = e.target.closest('.btn__close-window'); if (!btnClose) return; this._projectBox.removeChild(this._projectBox.firstElementChild); } HTML Element: _generateProjectImage(image) { return ` <div class="projects__window"> <div class="projects__window-content"> <button class="projects__window-close btn__close-window"> <svg class="projects__window-icon"> <use xlink:href="${icon}#icon-close" ></use> </svg> </button> <div class="projects__window-box"> <img src="${image}" alt="" class="projects__window-image"> </div> </div> </div> `; } CSS: .projects { &__window { position: fixed; inset: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.7); z-index: 1000; animation: window-animate 300ms linear; } } @keyframes window-animate { from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; } }
doc_23530164
<form id="MyForm" runat="server"> <asp:UpdatePanel ID="UpdatePanel" runat="server"> <ContentTemplate> <asp:Panel ID="FormPanel" runat="server"> ... <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClientClick="Clicked(event)" OnClick="SubmitButton_Click" UseSubmitBehavior="false" /> </asp:Panel> </ContentTemplate> </asp:UpdatePanel> <asp:UpdateProgress ID="UpdateProgress" DynamicLayout="true" runat="server" AssociatedUpdatePanelID="UpdatePanel"> <ProgressTemplate> ... </ProgressTemplate> </asp:UpdateProgress> </form> <script> function Clicked(event) { alert('hello'); //this works! event.preventDefault(); //don't think this works... $('#<%= SubmitButton.ClientID %>').disabled = true; //this didn't even work! } </script>
doc_23530165
I know Watir is using Ruby as it's main language, so should I study Ruby first?(I only have experience on Java, C++, and a little bit of Scala so far.) Or should I go straight to the documentations? We're using Eclipse as our default terminal for the web app. A: Yes, you need to know Ruby to work in WATIR, but it's very easy language, more closely put, it's syntax is neat and clean. And also WATIR is very easy to use and having very lesser code compared to selenium, I write code below using both WATIR and Selenium so that you could see the difference. To select a select_list in WATIR, you need to write the following code b.select_list(:id,'country').select 'India' The same equivalent in Selenium element=driver.findElement(By.id("country"); Select var=new Select(element); var.selectByVisibleText("India"); So you might have understand the difficulty level when you write code in Java using selenium. Ruby has a very rich Library so most of the functions would be readily available to you which you don't have code from your level. A: This question is ill-suited for SO because it will yield opinion-based answers. But I can't help doing some watir cheerleading: Consider this example from https://github.com/watir/watir: require 'watir' browser = Watir::Browser.new browser.goto 'google.com' browser.text_field(title: 'Search').set 'Hello World!' browser.button(type: 'submit').click puts browser.title # => 'Hello World! - Google Search' browser.close There are a bunch of programming concepts here: requiring external libraries, instantiating an object, local variables, symbol-based locators, method-chaining, printing to console, etc. But who cares? It's fairly clear that the script is creating a browser and going to google to perform a search. So dive in and start writing watir code and refer to the documentation--watiror ruby--when you get stuck or need clarification.
doc_23530166
Here's the code... ul { list-style-type: none; margin: 0; padding: 0; width: 15%; position: fixed; background-color: yellow; } li a { display: block; height: 50px; color: red; text-decoration: none; text-align: center; text-transform: uppercase; line-height: 50px; transition: .2s all linear; } li a:hover { color: white; border-bottom: 50px solid lightskyblue; box-sizing: border-box; } <ul class="nav"> <li><a href="#peace">peace</a></li> <li><a href="#love">love</a></li> </ul> A: I would change a bit the structure to use an overlay instead of borders. And without the need to use fixed heights. From what I see the border-top issue is actually the expected behaviour. Both border-top and border-bottom push content downwards, but since you are using box-sizing: border-box and the bottom border is already underneath the text you won't see the content go down. ul { list-style-type: none; margin: 0; padding: 0; width: auto; position: fixed; background-color: yellow; } li a{ display: block; position: relative; color: red; text-decoration: none; text-align: center; text-transform: uppercase; padding: 20px; line-height: 1; } li a .overlay{ position:absolute; left: 0; right: 0; top: 0; bottom: 100%; transition: .2s all linear; background-color: rgba(0,0,0,0.3); } li a:hover .overlay { bottom: 0; } <ul class="nav"> <li> <a href="#peace"> <div class="overlay"></div> peace </a> </li> <li> <a href="#love"> <div class="overlay"></div> love </a> </li> </ul> A: See border-top adds the height in the element from top to downward direction and border-bottom add height from bottom also in downward direction...so applying the border-top will always push your text to down Actually you have applied box-sizing: border-box with height: 50px to that element...it means element's border will not affect the height of that element if any height value is specified... As MDN web docs says border-box tells the browser to account for any border and padding in the values you specify for width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements If you remove height from the element you will see that border-bottom will add below text because no height value is defined... ul { list-style-type: none; margin: 0; padding: 0; width: 15%; position: fixed; background-color: yellow; } li a { display: block; color: red; /* height: 50px; */ text-decoration: none; text-align: center; text-transform: uppercase; line-height: 50px; transition: .2s all linear; box-sizing: border-box; } li a:hover { color: white; border-bottom: 50px solid lightskyblue; } <ul class="nav"> <li><a href="#peace">peace</a></li> </ul>
doc_23530167
<StackLayout Orientation="Horizontal"> <Label Text="Your Ingredient is:" /> <Label Text="{Binding IngredientName}" /> </StackLayout> <Button x:Name="IngrediantsButton" Text="Add Ingredient" Command="{Binding Path=NewIngredientCommand, Source={StaticResource viewModel}}"/> <ListView x:Name="IngredientsListView" ItemsSource="{Binding Ingredients, Source={StaticResource viewModel}}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Orientation="Horizontal"> <Label Text="{Binding IngredientsName}"/> <Label Text="{Binding Ammount}"/> <Label Text="{Binding Units}"/> <Label Text="{Binding RecipeId}"/> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> ViewModel private string _ingredientName { get; set; } public string IngredientName { get { return _ingredientName; } set { if (_ingredientName != value) { _ingredientName = value; OnPropertyChanged("IngredientName"); } } } public Command NewIngredientCommand { get { return new Command(() => { Ingredients ingredients = new Ingredients() { IngredientsName = IngredientName, Ammount = 0, Units = "g", RecipeId = Recipe1.RecipeID, Recipe = Recipe1 }; Ingredients.Add(ingredients); }); } } protected virtual void OnPropertyChanged(string propertyName) { var changed = PropertyChanged; if (changed != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } A: private ICommand _saveIngredientCommand; public ICommand SaveIngredientCommand => _saveIngredientCommand ?? (_saveIngredientCommand = new Command(() => { Ingredients ingredient = new Ingredients(); App.RecipeDbcontroller.SaveIngredients(ingredient); if (Ingredient.IngredientsName != null && Ingredient.Ammount != 0) { ingredient.IngredientsName = Ingredient.IngredientsName; ingredient.Ammount = Ingredient.Ammount; ingredient.Units = Ingredient.Units; ingredient.Recipe = Recipe; ingredient.RecipeID = Recipe.RecipeID; App.RecipeDbcontroller.SaveIngredients(ingredient); IngredientsList.Add(ingredient); Recipe.Ingredients.Add(ingredient); IngredientMessage = "Your ingredient has been added"; } else { IngredientMessage = "Please add at least one ingredient"; App.RecipeDbcontroller.DeleteIngredients(ingredient.IngredientsId); }
doc_23530168
List<ClassA> oldlist; ClassA has 20 different properties, I want to * *compare and remove exact matching items from newlist *however the comparison has to exclude few properties from ClassA as the values will not be relavant *Record set I am dealing with is huge (300 thousand to 400 thousand). So it has to be efficient Linq Except or Intersect doesnt seem to support the above requirement, plus it seems to be slow as well. Any suggestions to achieve this? A: You can implement your own custom comparer public class MyEqualityComparer: IEqualityComparer<ClassA> { public bool Equals(ClassA x, ClassA y) { if (Object.ReferenceEquals(x, y)) return true; else if ((null == x) || (null == y)) return false; // Your custom comparison here (...has to exclude few properties from ClassA) ... } public int GetHashCode(ClassA obj) { if (null == obj) return 0; // Your custom hash code based on the included properties ... } } and use HashSet<ClassA> then (we want to exclude oldlist from newlist): HashSet<ClassA> toExclude = new HashSet<ClassA>( oldlist, new MyEqualityComparer()); newList.RemoveAll(item => toExclude.Conytains(item)); A: A while back, I found the following function which will allow you to distinct on a particular attribute. public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) if (seenKeys.Add(keySelector(element))) yield return element; } I couldn't find the author for this, so thank you unnamed programmer! I hope this is what you're looking for. A: As described here: .Distinct() clause not working c# MVC you can use GroupBy() and Distinct() to archieve your Task.
doc_23530169
Our classes retrieve their loggers via private static readonly ILog Logger = LoggerUtil.GetLogger(); public static class LoggerUtil { public static ILog GetLogger() { var type = ReflectionUtil.GetCallingMethod().DeclaringType; return LogManager.GetLogger(type); } } UPDATE: For now, I created a Decorator around LogManager.GetLogger(type).Logger and a ThreadStatic IsDebugEnabled variable. This way two threads can leverage the same utility class, and one will debug and one will not. This is problematic because it messes with Calling Class and Line Number... public void Debug(object message) { if (_decorated.IsDebugEnabled && LoggerUtil.IsDebugEnabled) { _decorated.Log(typeof (MyLoggerDecorator), Level.Debug, message, null); } } A: You could write your own custom IFilter implementation which looked at a ThreadStatic variable. (I'd probably also create an IDisposable implementation that sets the variable to true in the constructor and sets it back to false in the Dispose() method, so you wrap your code in a using block with that, so you re-enable it automatically when you pop out of that using context, e.g. if there's an exception.)
doc_23530170
error is : file_get_contents(https://api.linkedin.com/v1/groups/group_id/posts?oauth2_access_token=xxxxxxx&format=json&content=%7B%22title%22%3A%22my+title+%22%2C%22summary%22%3A%22my+Summery++%22%7D) : failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /var/www/html/linkedin_update/xyz.php on line 161 kindly guide me how to fix this thing ... Thanks & Regards
doc_23530171
I want to reset my SwitchNavigator (root), which would reset all my nested navigators, and then go to SignInScreen. I lost a lot of hours and tried a lot of things. It seems that before, we could use NavigationActions.reset({ key: null, index: 0, actions: [NavigationActions.navigate({ routeName: 'SignIn' })], }) But in the actual version of react-navigation, reset is not available from NavigationActions but only from StackActions. I mean, I want to reset my root navigator, not only my nested StackNavigator. In the issues from react-navigation I saw that if the key was null the root navigator was reset. So I tried like this : this.props.navigation.dispatch(StackActions.reset({ key: null, index: 0, actions: [ NavigationActions.navigate({ routeName: 'SignIn', }), ], })); I don't know if it works, because I can't go from my ProfileScreen (the screen from which I want to logout) to SignInScreen, I have this Error: Error: There is no route defined for key SignIn. Must be one of: 'ProfileScreen' So, my question is the following : How to unmount all the screens of my app (while logging out) ? A: From the documentation of createSwitchNavigator: By default, it does not handle back actions and it resets routes to their default state when you switch away. So, all you really need to do is navigate to your SignIn screen. this.props.navigation.navigate('SignIn') However, since it says there's no route defined for that key, then you should make sure that that is the correct route name defined in AuthStack.js.
doc_23530172
A: There is no API in WP7 for rendering text to a bitmap image. The WP7 API for manipulating bitmap images is WriteableBitmap, which gives you an array of pixels and nothing more! There is a good codeplex project WriteableBitmapEx, which adds various drawing extension methods, but not text rendering. You can however place text above an image, for example ... <Grid> <Image Source="myImage.png"/> <TextBlock Text="Overlay text"/> <Grid> This will render the text above the image. You can also use a WriteableBitmap to 'capture' part of the visual tree into a bitmap, see my blog post for examples. The route you take really depends on your requirements. A: I found a way of doing this by adding a Textblock onto the WriteableBitmap. This link gives you an example of how it can be achieved. How can i write string on WriteableBitmap?
doc_23530173
object Test extends App { def compare[T1, T2](a: T1, b: T2)(implicit ev: T1 => T2) = compareImpl[T2](ev(a), b) def compare[T1, T2](a: T1, b: T2)(implicit ev: T2 => T1) = compareImpl[T1](a, ev(b)) def compareImpl[T](a: T, b: T) = a == b case class Foo(s: String) case class Bar(s: String) implicit def foo2bar(f: Foo): Bar = Bar(f.s) println(compare(Foo("hello"), Bar("hello"))) } However this snippet gives me error: error: ambiguous reference to overloaded definition, both method compare in object Test of type [T1, T2](a: T1, b: T2)(implicit ev: T2 => T1)Boolean and method compare in object Test of type [T1, T2](a: T1, b: T2)(implicit ev: T1 => T2)Boolean match argument types (Test.Foo,Test.Bar) and expected result type Any implicit def foo2bar(f: Foo): Bar = Bar(f.s) If I remove the second compare, it works, but then if I do compare(Bar("hello), Foo("hello")) it won't compile. How can I have these two versions without ambiguity? A: I ended up using macro because currently Scala does not have type lambda and it does generic type erasure, so no such thing will be supported out of the box. Macro definition: import scala.reflect.runtime.universe._ import scala.reflect.macros.blackbox.Context import scala.language.experimental.macros import scala.language.implicitConversions def compare[T1, T2](a: T1, b: T2): Boolean = macro compareImpl[T1,T2] def compareImpl[T1: c.WeakTypeTag, T2: c.WeakTypeTag](c: Context)(a: c.Expr[T1], b: c.Expr[T2]): c.Expr[Boolean] = { import c.universe._ // Search for T1=>T2 first. If not found, search T2=>T1 val f1 = c.inferImplicitValue(c.weakTypeOf[T1 => T2]) if (f1.isEmpty) { val f2 = c.inferImplicitValue(c.weakTypeOf[T2 => T1]) if(f2.isEmpty) { c.abort(c.enclosingPosition, s"Cannot find ${weakTypeOf[T1]}=> ${weakTypeOf[T2]}") } else { c.Expr(q"$f2.apply($b) == $a") } } else { c.Expr(q"$f1.apply($a) == $b") } } Test: case class Foo(s: String) case class Bar(s: String) implicit def foo2bar(f: Foo): Bar = Bar(f.s) println(compare(Foo("hello"), Bar("hello"))) println(compare(Bar("hello"), Foo("hello"))) A: The problem here is because both of your compare functions are having exactly the same type parameter which is ambiguous for Scala compiler to figure out which one to use. For example when you do a compare of compare[Foo, Bar] it is not clear for Scala compiler whether it should use the compare function with (implicit ev: T1 => T2) or the second one with (implicit ev: T2 => T1) , because both of Foo and Bar could be placed as T1 or T2. In fact this is the reason when you remove one of the compare functions, it works. Because there is no overloaded version of compare function and Foo and Bar can be placed as T1 and T2 in your one and only compare function. Here is an answer to another Stackoverflow question which is somehow related to your problem and it describes the problem in details: https://stackoverflow.com/a/16865745/2508492 A: Solution without macros (it's based on type classes) def compare[T1, T2](a: T1, b: T2)(implicit cmp: Compare[T1, T2]) = (compareImpl[cmp.T] _).tupled(cmp(a, b)) def compareImpl[T](a: T, b: T) = a == b trait Compare[T1, T2] { type T type Out = (T, T) def apply(a: T1, b: T2): Out } object Compare { type Aux[T1, T2, T0] = Compare[T1, T2] { type T = T0 } def instance[T1, T2, T0](f: (T1, T2) => (T0, T0)): Aux[T1, T2, T0] = new Compare[T1, T2] { override type T = T0 override def apply(a: T1, b: T2): Out = f(a, b) } implicit def directCompare[T1, T2](implicit ev: T1 => T2): Aux[T1, T2, T2] = instance((a, b) => (ev(a), b)) implicit def reverseCompare[T1, T2](implicit ev: T2 => T1): Aux[T1, T2, T1] = instance((a, b) => (a, ev(b))) } case class Foo(s: String) case class Bar(s: String) implicit def foo2bar(f: Foo): Bar = Bar(f.s) println(compare(Foo("hello"), Bar("hello"))) // true Or you can even prioritize direct and reverse directions if you want def compare[T1, T2](a: T1, b: T2)(implicit cmp: Compare[T1, T2]) = (compareImpl[cmp.T] _).tupled(cmp(a, b)) def compareImpl[T](a: T, b: T) = a == b trait Compare[T1, T2] { type T type Out = (T, T) def apply(a: T1, b: T2): Out } trait LowPriorityCompare { type Aux[T1, T2, T0] = Compare[T1, T2] { type T = T0 } def instance[T1, T2, T0](f: (T1, T2) => (T0, T0)): Aux[T1, T2, T0] = new Compare[T1, T2] { override type T = T0 override def apply(a: T1, b: T2): Out = f(a, b) } implicit def reverseCompare[T1, T2](implicit ev: T2 => T1): Aux[T1, T2, T1] = instance((a, b) => (a, ev(b))) } object Compare extends LowPriorityCompare { implicit def directCompare[T1, T2](implicit ev: T1 => T2): Aux[T1, T2, T2] = instance((a, b) => (ev(a), b)) } case class Foo(s: String) case class Bar(s: String) implicit def foo2bar(f: Foo): Bar = Bar(f.s) implicit def bar2foo(f: Bar): Foo = Foo(f.s) println(compare(Foo("hello"), Bar("hello"))) // true
doc_23530174
>Location.get_info ...... >Location.get_info --help outputs info on the location; lazily loads hours where the output is embedded as maybe an rdoc style comment? I am looking to be able to have quick documentation for a set of seed commands for our rails app thx A: you can build nearly everything in ruby... i don't think that there is any library out there doing what you want. guessing from the IRB tag that you put on your post, you want to help people using your code. in that case you could tell them to use pry and use the show-doc functionality [2] pry(main)> show-doc User#url From: /Users/paule/Documents/rails/on_ruby/app/models/user.rb @ line 39: Owner: User Visibility: public Signature: url() Number of lines: 1 generates a homepage url for a user A: Methods aren't objects, therefore you cannot store anything in them. You can obtain a proxy object for a bound method using the Object#method method and for an unbound method using the Module#instance_method method, but that proxy object is, well, just a proxy object. In particular, it is not guaranteed that you will always get the same proxy object when you ask for one. So, if you obtain a proxy object for a method, then store some documentation in it, then later obtain another proxy object for the same method, this might be a different proxy object which doesn't have your documentation in it. Example: class UnboundMethod attr_accessor :doc end map = Array.instance_method(:map) map.doc = '`map` maps a block over all elements' map_again = Array.instance_method(:map) map_again.doc # => nil map.doc # => '`map` maps a block over all elements' map.object_id == map_again.object_id # => false So, you cannot store your documentation in the method, because methods aren't objects and you cannot store it in the proxy object, because Ruby doesn't guarantee the identity of those proxy objects. You need to store it somewhere else. Maybe in the Module the method is defined in, indexed by the method name.
doc_23530175
It seems the only way to set whether a tab is enabled or disabled is to pass setEnabledAt an int for the tab index and the boolean. The only way I can find to pass the index of a tab to something is to use indexOfTabComponent and pass in the panel to swap to....This seems horrible, and doesn't work. I'm getting java.lang.ArrayIndexOutOfBoundsException: -1 when I try and swap to the tab at index 1. Is there a better way than this? public void swapView(JPanel paneToSelect) { myContainerPane.getMyPaneTab().setSelectedComponent(paneToSelect); myContainerPane.getMyPaneTab().setEnabledAt(myContainerPane.getMyPaneTab().indexOfTabComponent(paneToSelect), true); } The only solution I can think of is to add 2 to the index number...but it feels there should be a better way to do this. A: The correct code to use is: public void swapView(JPanel paneToSelect) { int index = myContainerPane.getMyPaneTab().indexOfComponent(paneToSelect); myContainerPane.getMyPaneTab().setSelectedIndex(index); myContainerPane.getMyPaneTab().setEnabledAt(index, true); } The difference being is that, for whatever reason indexOfTabComponent, does not work with my set up. A: ordering started from zero :-) ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, for example :-) import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class TabbedPane { private static final long serialVersionUID = 1L; public TabbedPane() { JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); final JTabbedPane tb = new JTabbedPane(); //tb.setUI(new CustomTabbedPaneUI()); JButton btn = new JButton("push me !!!"); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tb.setEnabledAt(1, true); tb.setEnabledAt(2, true); tb.setEnabledAt(3, true); tb.setEnabledAt(4, true); } }); JPanel pnl = new JPanel(); pnl.add(btn); tb.add("Tab1", pnl); tb.add("Tab2", new JTextArea(10, 20)); tb.add("Tab3", new JTextArea(10, 20)); tb.add("Tab4", new JTextArea(10, 20)); tb.add("Tab5", new JTextArea(10, 20)); jp.add(tb, BorderLayout.CENTER); //add(jp, BorderLayout.CENTER); tb.setEnabledAt(1, false); tb.setEnabledAt(2, false); tb.setEnabledAt(3, false); tb.setEnabledAt(4, false); JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.add(jp, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { try { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception system) { system.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TabbedPane tP = new TabbedPane(); } }); } } A: Once selected, you coud use getSelectedIndex instead. Or you could use the tabs title, but that would mean you know it & ties you into the naming. int index = myContainerPane.getMyPaneTab().indexOfTabComponent(paneToSelect); myContainerPane.getMyPaneTab().setSelectedIndex(index); myContainerPane.getMyPaneTab().setEnabledAt(index, true); The only other choice that comes to mind is extending the base class & implementing your methods to achieve the ensured results
doc_23530176
I have a class that use guzzle to call to an existing api it look like this. class HttpCall { public static function request($method, $endpoint, $payload) { $client = new Client(); $response = $client->request(...); return $response; } } Then I have a service class that use the HttpCall to fetch some data on another server The flow is like this Search Name (Request to another endpoint) > Update Data (Request to another endpoint) so this two flow search name and update data each request a token to the server Authenticate (Request to login and get token) > Search Name Authenticate (Request to login and get token) > Update data My service class is like this class MyService { public function searchName($name) { $request = HttpCall::request(...); return $request; } public function updateData($payload) { $request = HttpCall::request(...); return $request; } } then in my Class that actually interact with the events class MyClass { public function __construct(MyService $service) { $this->service = $service; } public function update() { // When I remove this, It's working and hardcoded some data $data = $this->service->searchName('test'); $updateData = [...]; $this->service->updateData($updateData); } } I'm not quite sure what's happening why the request seem's to fail (sometimes) Thanks for help guys
doc_23530177
However, my code doesn't contain any of these charecters. <string name="scientists_descrption">(26 December 1791 18 October 1871) was an English polymath.He was a mathematician, philosopher, inventor and mechanical engineer, who is best remembered now for originating the concept of a programmable computer.\n Considered a "father of the computer", Babbage is credited with inventing the first mechanical computer that eventually led to more complex designs. His varied work in other fields has led him to be described as "pre-eminent" among the many polymaths of his century.\n Parts of Babbage's uncompleted mechanisms are on display in the London Science Museum. In 1991, a perfectly functioning difference engine was constructed from Babbage's original plans. Built to tolerances achievable in the 19th century, the success of the finished engine indicated that Babbage's machine would have worked.</string> but I still got error in this string. any help please? A: You have to escape ' with backslash, so just replace all occurrences of ' with \'. <string name="scientists_descrption">(26 December 1791 18 October 1871) was an English polymath.He was a mathematician, philosopher, inventor and mechanical engineer, who is best remembered now for originating the concept of a programmable computer.\n Considered a "father of the computer", Babbage is credited with inventing the first mechanical computer that eventually led to more complex designs. His varied work in other fields has led him to be described as "pre-eminent" among the many polymaths of his century.\n Parts of Babbage\'s uncompleted mechanisms are on display in the London Science Museum. In 1991, a perfectly functioning difference engine was constructed from Babbage\'s original plans. Built to tolerances achievable in the 19th century, the success of the finished engine indicated that Babbage\'s machine would have worked.</string> A: Your are having an error because you haven't backslashed your double quotes inside the string. ..."father of the computer"... must be ...\"father of the computer\".... Although you might have the same problem with single quotes.
doc_23530178
Ex: 2013-11-01 to 41579 This is the way to do it in Excel A: I found a way to convert a Unix timestamp to an Excel date. $date_time = "2013-11-01 00:00:00"; $date_time_plus_one = strtotime($date_time . ' +1 day'); $str_date = strtotime(date('Y-m-d', $date_time_plus_one)); $excel_date = intval(25569 + $str_date / 86400); echo 'php actual date time : ' . $date_time . '<br>'; echo 'add one day : ' . $date_time_plus_one . '<br>'; echo 'excel Number DATEVALUE : ' . $excel_date . '<br>'; seconds in a day: 86400 , 25569 days between 30 Dec 1899 and 01 Jan 1970. So This is the output. php actual date time : 2013-11-01 00:00:00 add one day : 1383330600 excel Number DATEVALUE : 41579 A: You can change time into string like this. Every date is unique and you can also arrange them in order $month = date("F"); $date = date("d"); $year = date("Y"); $timestamp = strtotime($month . " " . $date . " " . $year);
doc_23530179
We're developing a Spring Boot service to upload data to different back end databases. The idea is that, in one multipart/form-data request a user will send a "model" (basically a file) and "modelMetadata" (which is JSON that defines an object of the same name in our code). We got the below to work in the WebFlux annotated controller syntax, when the user sends the "modelMetadata" in the multipart form with the content-type of "application/json": @PostMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE], produces = [MediaType.APPLICATION_JSON_VALUE]) fun saveModel(@RequestPart("modelMetadata") monoModelMetadata: Mono<ModelMetadata>, @RequestPart("model") monoModel: Mono<FilePart>, @RequestHeader headers: HttpHeaders) : Mono<ResponseEntity<ModelMetadata>> { return modelService.saveModel(monoModelMetadata, monoModel, headers) } But we can't seem to figure out how to do the same thing in Webflux's functional router definition. Below are the relevant code snippets we have: @Bean fun modelRouter() = router { accept(MediaType.MULTIPART_FORM_DATA).nest { POST(ROOT, handler::saveModel) } } fun saveModel(r: ServerRequest): Mono<ServerResponse> { val headers = r.headers().asHttpHeaders() val monoModelPart = r.multipartData().map { multiValueMap -> it["model"] // What do we do with this List<Part!> to get a Mono<FilePart> it["modelMetadata"] // What do we do with this List<Part!> to get a Mono<ModelMetadata> } From everything we've read, we should be able to replicate the same functionality found in the annotation controller syntax with the router functional syntax, but this particular aspect doesn't seem to be well documented. Our goal was to move over to use the new functional router syntax since this is a new application we're developing and there are some nice forward thinking features/benefits as described here. What we've tried * *Googling to the ends of the Earth for a relevant example * *this is a similar question, but hasn't gained any traction and doesn't relate to our need to create an object from one piece of the multipart request data *this may be close to what we need for uploading the file component of our multipart request data, but doesn't handle the object creation from JSON *Tried looking at the @RequestPart annotation code to see how things are done on that side, there's a nice comment that seems to hint at how they are converting the parts to objects, but we weren't able to figure out where that code lives or any relevant example of how to use an HttpMessageConverter on the `` the content of the part is passed through an {@link HttpMessageConverter} taking into consideration the 'Content-Type' header of the request part. Any and all help would be appreciated! Even just some links for us to better understand Part/FilePart types and there role in multipart requests would be helpful! A: I was able to come up with a solution to this issue using an autowired ObjectMapper. From the below solution I could turn the modelMetadata and modelPart into Monos to mirror the @RequestPart return types, but that seems ridiculous. I was also able to solve this by creating a MappingJackson2HttpMessageConverter and turning the metadataDataBuffer into a MappingJacksonInputMessage, but this solution seemed better for our needs. fun saveModel(r: ServerRequest): Mono<ServerResponse> { val headers = r.headers().asHttpHeaders() return r.multipartData().flatMap { // We're only expecting one Part of each to come through...assuming we understand what these Parts are if (it.getOrDefault("modelMetadata", listOf()).size == 1 && it.getOrDefault("model", listOf()).size == 1) { val modelMetadataPart = it["modelMetadata"]!![0] val modelPart = it["model"]!![0] as FilePart modelMetadataPart .content() .map { metadataDataBuffer -> // TODO: Only do this if the content is JSON? objectMapper.readValue(metadataDataBuffer.asInputStream(), ModelMetadata::class.java) } .next() // We're only expecting one object to be serialized from the buffer .flatMap { modelMetadata -> // Function was updated to work without needing the Mono's of each type // since we're mapping here modelService.saveModel(modelMetadata, modelPart, headers) } } else { // Send bad request response message } } Although this solution works, I feel like it's not as elegant as the one alluded to in the @RequestPart annotation comments. Thus I will accept this as the solution for now, but if someone has a better solution please let us know and I will accept it!
doc_23530180
I don't think Windows 10 will find shortcuts to anything other than .exe, .bat and .chm. I can create a .bat file that will launch the pdf / html documents but this doesn't seem like the cleanest solution to me. Does anyone have any other suggestions or opinions?
doc_23530181
Chart chart = new Chart() { LegendVisibility = Visibility.Hidden, LeftTitle = YaxisName[i], BottomTitle = "Carrier i [-]", }; chart.Content = getChart(graphIndex, GraphYvalues, GraphXvalues, GraphListOfNames[graphIndex]); chartView.Children.Add(chart); Could someone please help me out? Thank you A: Eventually I was able to scramble something up. It's actually so damn easy. I gave up on setting the range of y-axis and instead of that I added padding to the plot itself like this: LineGraph lineGraphFar = new LineGraph() { Stroke = new SolidColorBrush(Colors.Red), Padding = new System.Windows.Thickness(0, 30, 0, 0) }; It's surely not the greatest option but it will do the job.
doc_23530182
App.js: import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { MapView, Permissions, Location } from 'expo'; export default class App extends React.Component { constructor(props){ super(props); this.state = { region: { latitude: 37.7885, longitude: -122.4324, latitudeDelta: 0.922, longitudeDelta: 0.0421, } } } _getLocationAsync = async () => { let {status} = await Permissions.askAsync(Permissions.LOCATION); if(status !== 'granted') console.log('No se tienen permisos para acceder al gps'); let location = await Location.getCurrentPositionAsync({enableHighAccuracy: true}); let region={ latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0045, longitudeDelta: 0.0045, } this.setState({region: region}) } render() { return ( <View style={styles.container}> <MapView initialRegion ={this.state.region} showUserLocation={true} showCompass={true} rotateEnabled={false} style={{flex: 1}} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, }); A: The import for MapView comes from a separate package: import MapView from 'react-native-maps';
doc_23530183
A: As @MariyamMohammedJalil said you can use an EventEmitter to trigger the update of your first component. See following sample: first.component.ts @Component({ selector: 'first-component', template: '<div>{{label}}</label> }) export class FirstComponent { @Input() update: EventEmitter<string>; label = 'First Component'; constructor() {} ngOnInit() { if (this.update) { // Subscribe to the event emitter to receive an update event this.update.subscribe((value: string) => { this.refresh(value); }) } } refresh(value: string) { // Do your stuff here this.label = value; } } second.component.ts @Component({ selector: 'second-component', template: '<button (click)="updateFirstCmp()">Update First Component</button>' }) export class SecondComponent { @Input() update: EventEmitter<string>; constructor(){} updateFirstCmp() { // Emit an event to update your first component this.update.emit('Updated First Component'); } } And for example you should add following to your app.component.ts: updateEventEmitter: EventEmitter<string>; constructor() { ... this.updateEventEmitter = new EventEmitter(); } And in your app.component.html: <first-component [update]="updateEventEmitter"></first-component> <second-component [update]="updateEventEmitter" Another way do solve your problem can be to enter the first.component as input parameter to the second.component to call the refresh function directly without EventEmitter. See following sample: app.component.html <first-component #firstComponent></first-component> <second-component [firstCmp]="firstComponent"></second-component> second.component.ts @Component({ selector: 'second-component', template: '<button (click)="updateFirstCmp()">Update First Component</button>' }) export class SecondComponent { @Input() firstCmp: FirstComponent; constructor(){} updateFirstCmp() { // Update the first component directly this.firstCmp.refresh('Updated First Component'); } } With this sample you don't need to subscribe to an update event, because you're not using an EventEmitter.
doc_23530184
It looks really nice, but if I need to catch any change/addition to the files in a directory, is there a way for me to catch any files that were changed since the script was last run? ie. is there any way to have Listen work with persistence? A: If directory change events order matters, then you probably cannot get that order after your script has stopped working, as it lost and cannot be retrieved from the filesystem. Otherwise I would utilize git repo to collect changes after previous commit, making commits before script stops working. A: Try on console with below command to fix the issue echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
doc_23530185
WireShark tells that conn.recv() don't send ACK after client socket close. (According to Wireshark, Here is packet after client socket close. client >> server : FIN/ACK server >> clinet : FIN/ACK ) The cause is that conn.close() is executed before conn.recv() sends ACK. You can check it by uncommenting time.sleep(1). (According to Wireshark, Here is packet after client socket close on the above condition client >> server : FIN/ACK server >> client : ACK server >> clinet : FIN/ACK ) Could you tell me how to set socket that surely send conn.recv() ACK before the next code (conn.close) is executed? class PLC_Server: def __init__(self, ip_address="localhost", port=5000): self.ip = ip_address self.port = port self.comm = {"address": self.ip + ":" + str(self.port)} self.buffer_size = 4096 self.client = None def _init_socket(self, listen_num=1): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind((self.ip, int(self.port))) self.sock.listen(listen_num) def run(self): self._init_socket() while True: conn, address = self.sock.accept() while True: recv_data = conn.recv(4096) if recv_data == b"": # FIN is convered to lenght 0 message by the conn.recv print("Detect Client's socket close") # time.sleep(1) conn.close() break else: conn.send("OK") if __name__ == '__main__': test = PLC_Server() test.run()
doc_23530186
I tried: 1) Making the div fixed. The problem with that is that id destroys my bootstrap attributes and also because the height is generated dynamically. <div id="timelineContainer"> <p class="mes">{{mes1}}</p> <div id='chart_div' class="chart"></div> <div class="row fixedcontrols"> <div class="fixed col-md-1 col-lg-1 col-xs-1 form-group-lg"> <button type="button" id="next1" class="btn btn-primary btn-block transback " ng-click="timeline.getPreviousData();"class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Load previous 100 records..."> <span id="nextdata1" class="glyphicon glyphicon-arrow-left"></span></button> </div> <div class="col-md-3 col-lg-3 col-xs-3 "> <button type="button" class="btn btn-warning btn-block" class="tt" id="btn_ZoomIn" name="btn_ZoomIn" ng-click="timeline.zoomIn()"><span id="zoomin" class="glyphicon glyphicon-zoom-in"></span> </button> </div> <div class="col-md-3 col-lg-3 col-xs-3 form-group-lg"> <button type="button" class="btn btn-primary btn-block" id="btn_ZoomOut" name ="btn_ZoomOut" ng-click="timeline.zoomOut()"> <span id="zoomout" class="glyphicon glyphicon-zoom-out"></span></button> </div> <div class="col-md-4 col-lg-4 col-xs-4 col-sm-4 form-group-md ff"> <button type="button" id="advanced1" ng-click="timeline.searchclick()" class="btn btn-default btn-block">Show Search</button> </div> <div class="col-md-1 col-lg-1 col-xs-1 form-group-lg pull-right"> <button type="button" id="next" class="btn btn-primary btn-block " ng-click="timeline.getNextData();"class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Load next 100 records..."> <span id="nextdata" class="glyphicon glyphicon-arrow-right"></span> </button> </div> </div> </div> #timelineContainer { overflow-x: scroll; overflow-y: scroll; white-space: nowrap; border: 13px solid #bed5cd; width: 100%; margin: 0 auto; position: relative; background-color: #5bc0de; } Thank you. Update: The controls move when user scrolls as shown below. I want them to be fixed. update: said picture A: What i can understand from your question is you want your div at the lower part of page to be fixed in position, i hope a small change in css will solve your issue position: fixed !important; if its not what you meant then can you please explain more !! A: set position of controls to absolute and make sure their ancestor is div with id timelineContainer. absolute will position the elements relative to its ancestor. no matter where you move they will be fixed to div.
doc_23530187
I am using tbl_summary and trying to modify my header to have n(%) instead of the standard format of N = 57. I would normally use modify_header(stat_by) but can't when by isn't included. Example: trial %>% select(trt, marker, stage) %>% tbl_summary() %>% modify_header(stat_by = "**{level}**, n(%)") Any ideas most appreciated! A: To edit the text of your header, you can use the update argument in modify_header(). stat_0 refers to the statistic column, so this is the one you need to change: library(gtsummary) trial %>% select(trt, marker, stage) %>% tbl_summary() %>% modify_header(update = stat_0 ~ "**n(%)**") You can use {glue} syntax if you want to insert a statistic as well: trial %>% select(trt, marker, stage) %>% tbl_summary() %>% modify_header(update = stat_0 ~ "**n(%), N = {N}**") Good luck!
doc_23530188
The problem is I dont understand what is meant by initialized with the upper case letters of the alphabet Does this mean that she wants the alphabet to be in all capitals? A: Basically it just refers to all characters are all capitals. No programming meaning. A: reading the data from a one-dimensional array that is initialized with the upper case letters of the alphabet This means the array you're going to be working with is already constructed/created with all the letters in uppercase. in other words as suggested in the comments: char[] chars = new char[]{'A', 'B', .... , 'Z'}
doc_23530189
Redcarpet.new(@post.content).to_html A: Okay, it looks like Redcarpet 2 has completely changed the API. The following works: markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true) raw markdown.render(@post_content.content)
doc_23530190
var a = new List{ 1, 2, 3, 1 }; var duplicated = a.GroupBy(x=> x).Any(b => b.Count > 1); A: Here is how I understand you issue. You have a class (call it table) that has a property List<string> with column labels called X, and a List<List<object>> property called Y that represents the data rows. class table { public List<string> X { get; set; } // headers public List<List<object>> Y { get; set; } // rows } You have two tables (call them t1 and t2) and you want to left join them on one or more columns and create a new table object containing the data from the join. The left hand side will be duplicated for multiple matches on the right hand side. The right hand side for unmatched rows will be a List<object> of nulls. The result will be filtered to only have desired columns on the right hand side. (My sample t1 table is like yours, my sample t2 table adds a new column "f" that is an integer to match up with t1 column "c".) Create an empty right hand side for when there is no matching rhs: var emptyT2 = Enumerable.Repeat((object)null, t2.X.Count).ToList(); Create an IEqualityComparer<object> to compare the join columns: var jec = new IEnumerableSequenceEqualityComparer<object>(); Find the column indices of the columns you want to join on: var t1JoinCols = new List<string> { "a", "c" }; var t1JoinIndices = t1JoinCols.Select(c => t1.X.IndexOf(c)).ToList(); var t2JoinCols = new List<string> { "c", "f" }; var t2JoinIndices = t2JoinCols.Select(c => t2.X.IndexOf(c)).ToList(); Create a filter for the right hand side columns you want in the output: var t2wanted = new List<string> { "d", "e", "f" }; var t2wantedIndices = t2.X.Select((x, n) => (x, n)).Where(xn => t2wanted.Contains(xn.x)).Select(xn => xn.n).ToHashSet(); Create an intermediate query to do the left join and pull the matching data (switch to fluent syntax to pass the IEqualityComparer<object>): var t3r = t1.Y.GroupJoin(t2.Y, t1r => t1JoinIndices.Select(n1 => t1r[n1]), t2r => t2JoinIndices.Select(n2 => t2r[n2]), (t1r, t2rg) => (t1r,t2rg), jec) .SelectMany(t1rt2rg => t1rt2rg.t2rg.DefaultIfEmpty() .Select(t2r => t1rt2rg.t1r.Concat(Enumerable.Range(0, t2.X.Count) .Where(n => t2wantedIndices.Contains(n)) .Select(n => t2r?[n])) .ToList())); Convert the intermediate query into a table object by building the new headers and the List<List<object>> for the rows: var ans = new table { X = t1.X.Concat(Enumerable.Range(0, t2.X.Count) .Where(n => t2wantedIndices.Contains(n)) .Select(n => t2.X[n])) .ToList(), Y = t3r.ToList() }; NOTE: the GroupJoin operation in the t3r query creates a Lookup for the second (in this case t2.Y) argument which uses hashcode based O(1) lookup, so there is not much efficiency to be gained by not using LINQ. If you are doing millions of rows in each object, you may want to consider re-writing the whole thing in procedural code to gain a few milliseconds per row. Here is the IEnumerableSequenceEqualityComparer definition: public class IEnumerableSequenceEqualityComparer<T> : IEqualityComparer<IEnumerable<T>> { public bool Equals(IEnumerable<T> x, IEnumerable<T> y) => Object.ReferenceEquals(x, y) || (x != null && y != null && (x.SequenceEqual(y))); public int GetHashCode(IEnumerable<T> obj) { // Will not throw an OverflowException unchecked { return obj.Where(e => e != null).Select(e => e.GetHashCode()).Aggregate(17, (a, b) => 23 * a + b); } } }
doc_23530191
while (reader.Read()) { ListViewItem item = new ListViewItem(reader["item_ID"].ToString()); Item.SubItems.Add(reader["item_Desc"].ToString()); listView1.Items.Add(item); if(action == "add") { txtitemid.Text = ""; txtitem.Text = ""; } else { //this is the part i am taking about txtitemid.Text = reader.GetValue(0).ToString(); txtitemdesc.Text = reader.GetValue(1).ToString(); } } Suppose the last record in the table has an item_ID of 15 and item_Desc is dress then the textboxes will show the following according to code above txtitemid.Text = 15; txtitemdesc.Text = "dress"; I want to be able to determine which Item_ID details get displayed in the textboxes A: Assign the text box values after your while loop: if (listView1.Items.Count > 0) { var displayedItem = listView1.Items[listView1.Items.Count - 1]; txtitemid.Text = displayedItem.SubItems[0].Text; txtitemdesc.Text = displayedItem.SubItems[1].Text; } else { txtitemid.Text = ""; txtitemdesc.Text = ""; } EDIT: Similarly, you could display the first item by changing the line in the code above to: var displayedItem = listView1.Items[0]; A: if (reader.Read()) { var readMore = true; while (readMore) { var val = reader.GetValue(0).ToString(); readMore = reader.Read(); if (!readMore) { //Last record. Use val . txtitemid.Text = val; } else { //Not last record. Process val differently. } } }
doc_23530192
In the IDE the result is 143260 words, but from the command line the result is 1397. What am I doing wrong here? Code: import java.io.File; import java.util.Scanner; public class WordCount { public static void main(String [] args) throws Exception{ File file = new File("taleoftwocities.txt"); Scanner scanner = new Scanner(file); int words = 0; while(scanner.hasNextLine()){ String line = scanner.nextLine(); words += line.split(" ").length; } System.out.println("The file contains: " + words + " words."); } }
doc_23530193
There are N jugs on a table and each jug has a capacity C[i]. Each jug will be filled with water such that the amount of water from Jug 1 to Jug N will be in non-increasing order. i.e. if Jug i has A[i] amount of water in it the A[i] >= A[i+1] for 1 <= i < N. What is the maximum amount of water in total that can be poured in all the jugs? Input format: The first line contains T, number of test cases. For each test case, First line contains N, number of Jugs. Second line contains N space separated integers, C[i]. Output format: For each test case print the maximum amount of water that can be poured in the jugs in a new line. My Code: #include<bits/stdc++.h> using namespace std; int main() { int testCases; cin>>testCases; while(testCases--) { int jugs, answer = 0, minCapacity = 0, inputCapacity; cin >> jugs; cin >> inputCapacity; minCapacity = inputCapacity; answer = inputCapacity; for(int i = 1; i < jugs; i++) { cin >> inputCapacity; if(inputCapacity < minCapacity ) { minCapacity = inputCapacity; } answer = answer + minCapacity; } cout << answer << "\n"; } return 0; } A: The algorithm can't be better than O(N) as you will have to at least take the complete input. N is the number of elements in the input array. So, no way to further optimize the algorithm. Now, try optimizing the code. Make the I/O faster by adding the two lines as shown below: int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ... //rest of the code as is You can read more about the significance of the two lines here. A: Here's a simple solution in Javascript, function fillingJugs(n, arr) { if (arr.length === 1) { return arr[0] } // console.log(n, arr) let maxSum = 0 let maxValue = arr[0] // console.log(maxSum) for (let i in arr) { // console.log('index', i) if (arr[i] < maxValue) maxValue = arr[i] if (arr[i] <= maxValue) { maxSum += arr[i] } else { maxSum += maxValue } // console.log('maxSum', maxSum) } return maxSum } Hope this helps someone out there!
doc_23530194
doc_23530195
I have the following code that I use with the intention of reuse a couple of nodes to construct a simple yes/no dialog: var myDialog = function(e) { if(myDialog.dialog === undefined){ var container = $('<div><h2>Are you sure you want to delete this Item?</h2></div>'), yesBtn = $('<input type="button" value="Yes" id="yesBtn"/>').appendTo(div), noBtn = $('<input type="button" value="No" id="noBtn"/>').appendTo(div); myDialog.dialog = container; $('#yesBtn').on({ click: function(e) { console.log('Yes'); } } ); $('#noBtn').live('click', function(e) { console.log('No'); }); } //I am using a third party lib called facebox to create the showbox $.facebox(myDialog.dialog); }; Then this function is used by an button that, when clicked, displays the dialog box (correctly every time) and, when clicked the first time, the yes/no buttons fires correctly, but when the dialog is shown again, none of the two events fires. This problem gets fixed if I use live insted of on but I have been reading that the good practice is to start using the latter instead of the former. Any comments will be of great help! Thanks in advance. A: i dont think it works when you send an options hash to on() instead of $('#yesBtn').on({ click: function(e) { console.log('Yes'); } } ); try $('#yesBtn').on("click", function(e) { console.log('Yes'); } ); A: This depends on the jQuery version you are using. Check what your jQuery version is. As of jQuery 1.7 you should use on use live is deprecated. You cant use on if you are using 1.4. $(selector).live(events, data, handler); // jQuery 1.3+ $(document).delegate(selector, events, data, handler); // jQuery 1.4.3+ $(document).on(events, selector, data, handler); // jQuery 1.7+ And you are also using on the wrong way. * *You passed in the wrong parameters. *You can only pass in object on the third parameter on on. You pass it in as object data. *Using on means that you put a listener and then wait until that event bubbles up to that listener from the DOM element you select, thus, this is the right way doing it: $(document).on("click", "#yesBtn", function(e) { console.log("Yes"); } ); In that case it bubbles to document. you may want to make it so that the event gets bubbled up to only the container of #yesBtn. you can Wrap #yesBtn inside a div or something
doc_23530196
if arg[1] == "write" then local output = assert(io.open(arg[2], "wb")) output:write(arg[3]) --3rd argument is written to the file. assert(output:close()) elseif arg[1] == "read" then local input = assert(io.open(arg[2], "rb")) print(input:read(1)) --Should read one byte, not one char/int. Right? end A: If you only write ASCII characters to a file, it will be possible to open it in Notepad or any other text editor just fine: local out = io.open("file.bin", "wb") local str = string.char(72,101,108,108,111,10) -- "Hello\n" out:write(str) out:close() The resulting file will contain: Hello On the other hand if you write real binary data (for instance random bytes) you will get garbage: local out = io.open("file.bin", "wb") local t = {} for i=1,1000 do t[i] = math.random(0,255) end local str = string.char(unpack(t)) out:write(str) out:close() This is similar to those video game save files you have seen. If you still don't get it, try to write all possible octets to a file: local out = io.open("file.bin", "wb") local t = {} for i=0,255 do t[i+1] = i end local str = string.char(unpack(t)) out:write(str) out:close() and then open it with a hexadecimal editor (here I used Hex Fiend on Mac OS) to see the correspondences: Here, on the left, you have the bytes in hexadecimal and on the right you have their text representation. I have selected uppercase H which, as you can see on the left, corresponds to 0x48. 0x48 is 4*16 + 8 = 72 in base 10 (look at the bottom bar of the screenshot which tells you that). Now look at my first code example and guess what the code for lowercase e is... And finally look at the 4 last rows of the screenshot (bytes 128 to 255). This is the garbage you were seeing. A: I dont understand how to write binary files My levels created on old computer and my new game can reads it 2200 bytes every level of 129 I still don't understand how i can xdata (level data) table can write to file. function xdatatoline (levelnumber,xdata) local out = io.open("file.bin", "wb") local t = xdata --for i=1,1000 do t[i] = math.random(0,255) end local str = string.char(unpack(t)) out:write(str) out:close() end BAD ARGUMENT #1 to CHAR number expected , got string)
doc_23530197
{ "count": 29, "result": [ // removed for brevity { "confirmed": 6443, "date": "2020-04-04", "deaths": 373, "recovered": 205 }, { "confirmed": 6830, "date": "2020-04-05", "deaths": 401, "recovered": 205 }, { "confirmed": 7206, "date": "2020-04-06", "deaths": 477, "recovered": 205 }, { "confirmed": 7693, "date": "2020-04-07", "deaths": 591, "recovered": 205 }, { "confirmed": 8419, "date": "2020-04-08", "deaths": 687, "recovered": 205 }, { "confirmed": 9141, "date": "2020-04-09", "deaths": 793, "recovered": 205 }, { "confirmed": 9685, "date": "2020-04-10", "deaths": 870, "recovered": 381 } ] } I am plotting a graph for several countries As each country has different populations, how would I normalise the data to plot a better graph to better compare the rates in different countries. A: * *Pick a number that will define your unit, e.g. 100,000. *Divide every number (except the dates) by the population size of the given country, and multiply with 100,000. *Now your unit is confirmed cases (or deaths or recovered persons) per 100,000 residents.
doc_23530198
OS is RHEL6.9 64 bit Thanks in advance. A: This happens when you download and install xz from sources on a RHEL (or CentOS) 7 system. Update 2022-11-14: As of xz-5.2.7, the xz maintainers have kindly added compatibility support for this ill-conceived RHEL7 modification, obviating the rest of this answer. I am leaving it here for history. ... The problem is that the XZ_5.1.2alpha label is not present in the released versions of xz, but it is present in the version RedHat ships and compiles against. A small patch to the xz sources will fix the problem: https://github.com/easybuilders/easybuild-easyconfigs/issues/4036 The patch is small enough to copy&paste here. I have used it on xz-5.2.4 successfully. --- src/liblzma/liblzma.map.orig 2015-09-29 12:57:36.000000000 +0200 +++ src/liblzma/liblzma.map 2017-02-22 11:10:33.432868185 +0100 @@ -95,7 +95,13 @@ lzma_vli_size; }; -XZ_5.2 { +XZ_5.1.2alpha { +global: + lzma_stream_encoder_mt; + lzma_stream_encoder_mt_memusage; +} XZ_5.0; + +XZ_5.2.2 { global: lzma_block_uncomp_encode; lzma_cputhreads; @@ -105,4 +111,4 @@ local: *; -} XZ_5.0; +} XZ_5.1.2alpha; (update) If you try to use this .so on CentOS 8, you will get unresolved symbols for XZ_5.2 (e.g. librpmio.so.8 wants lzma_stream_encoder_mt@XZ_5.2). Here is a revised patch to create an liblzma.so.5 library that will work on both CentOS 7 and 8: diff -u -r xz-5.2.5/src/liblzma/common/stream_encoder_mt.c xz-5.2.5-rhel7/src/liblzma/common/stream_encoder_mt.c --- xz-5.2.5/src/liblzma/common/stream_encoder_mt.c 2020-03-17 07:28:50.000000000 -0700 +++ xz-5.2.5-rhel7/src/liblzma/common/stream_encoder_mt.c 2021-12-06 16:18:14.976457229 -0800 @@ -1141,3 +1141,9 @@ return total_memusage + outq_memusage; } + +/* http://peeterjoot.com/2019/09/20/an-example-of-linux-glibc-symbol-versioning/ */ +__asm__(".symver lzma_stream_encoder_mt,lzma_stream_encoder_mt@XZ_5.1.2alpha"); +__asm__(".symver lzma_stream_encoder_mt,lzma_stream_encoder_mt@@XZ_5.2"); +__asm__(".symver lzma_stream_encoder_mt_memusage,lzma_stream_encoder_mt_memusage@XZ_5.1.2alpha"); +__asm__(".symver lzma_stream_encoder_mt_memusage,lzma_stream_encoder_mt_memusage@@XZ_5.2"); diff -u -r xz-5.2.5/src/liblzma/liblzma.map xz-5.2.5-rhel7/src/liblzma/liblzma.map --- xz-5.2.5/src/liblzma/liblzma.map 2020-03-17 07:28:54.000000000 -0700 +++ xz-5.2.5-rhel7/src/liblzma/liblzma.map 2021-12-06 15:48:05.650672828 -0800 @@ -95,6 +95,12 @@ lzma_vli_size; }; +XZ_5.1.2alpha { +global: + lzma_stream_encoder_mt; + lzma_stream_encoder_mt_memusage; +} XZ_5.0; + XZ_5.2 { global: lzma_block_uncomp_encode; @@ -105,4 +111,4 @@ local: *; -} XZ_5.0; +} XZ_5.1.2alpha; A: I was stuck with similar problem since Nov 27, 2017 when I installed XZ Utils 5.2.3 from sources on CentOS 7.4 and copied liblzma.so.5.2.3 from /usr/local/lib/ to /lib64/. Cause of this problem is library librpmio.so.3 which requires symbol XZ_5.1.2alpha to be defined in lzma shared library. liblzma.so.5.2.2 defines this symbol but liblzma.so.5.2.3 doesn't. Without XZ update the most recent version of lzma library was 5.2.2 and I had symbolic link /lib64/liblzma.so.5 -> /lib64/liblzma.so.5.2.2. After copying liblzma.so.5.2.3 and some further updates the link was changed to the most recent file i.e. /lib64/liblzma.so.5 -> /lib64/liblzma.so.5.2.3. And that broke rpm and yum commands. So, solution is: * *Link /lib64/liblzma.so.5 back to /lib64/liblzma.so.5.2.2: cd /lib64 sudo ln -s -f liblzma.so.5.2.2 liblzma.so.5 *Delete file /lib64/liblzma.so.5.2.3 Second possible cause might be environment variable LD_LIBRARY_PATH. Check if it contains unwanted paths and clear it. A: In my case: mark as comments the lines that contain an export to the variable "LD_LIBRARY_PATH", in /etc/bashr and ~/.bashrc A: Just remove liblzma.so.5.2.3 and yum will work again. It broke because of source psxevars.sh in https://software.intel.com/en-us/cluster-checker-user-guide-getting-started. A: Halo team. Am also experiencing the same problem when launching nautilus. Am in centos 8 that comes with xz 5.2.4 nautilus: /lib64/liblzma.so.5: version `XZ_5.2.2' not found (required by /lib/libarchive.so.13) nautilus: /lib64/liblzma.so.5: version `XZ_5.1.2alpha' not found (required by /lib/libarchive.so.13) Downloaded xz-5.2.5.tar.gz and applied patch by Nemo. I compiled it into /usr/local/lib and did a sim link. ln -s /usr/local/lib/liblzma.so.5.2.5 /usr/lib64/liblzma.so.5 That sorts out nautilus but breaks the system. dnf and almost every thing else breaks. # dnf list installed kernel Traceback (most recent call last): File "/usr/lib64/python3.6/site-packages/libdnf/error.py", line 14, in swig_import_helper return importlib.import_module(mname) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 658, in _load_unlocked File "<frozen importlib._bootstrap>", line 571, in module_from_spec File "<frozen importlib._bootstrap_external>", line 922, in create_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed ImportError: /lib64/liblzma.so.5: version `XZ_5.2' not found (required by /lib64/librpmio.so.8) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/dnf", line 57, in <module> from dnf.cli import main File "/usr/lib/python3.6/site-packages/dnf/__init__.py", line 30, in <module> import dnf.base File "/usr/lib/python3.6/site-packages/dnf/base.py", line 29, in <module> import libdnf.transaction File "/usr/lib64/python3.6/site-packages/libdnf/__init__.py", line 8, in <module> from . import error File "/usr/lib64/python3.6/site-packages/libdnf/error.py", line 17, in <module> _error = swig_import_helper() File "/usr/lib64/python3.6/site-packages/libdnf/error.py", line 16, in swig_import_helper return importlib.import_module('_error') File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named '_error' When i do ldconfig it returns the sim link to point back to 5.2.4. To survive i have to loop that procedure for the time being on every log on. That is create a sim link launch nautilus then do ldconfig. But if ther be a permanent solution kindly share. centos8 needs that XZ_5.2 not XZ_5.2.2 Here is my patched xz-5.2.5/src/libzma.map XZ_5.0 { global: lzma_alone_decoder; lzma_alone_encoder; lzma_auto_decoder; lzma_block_buffer_bound; lzma_block_buffer_decode; lzma_block_buffer_encode; lzma_block_compressed_size; lzma_block_decoder; lzma_block_encoder; lzma_block_header_decode; lzma_block_header_encode; lzma_block_header_size; lzma_block_total_size; lzma_block_unpadded_size; lzma_check_is_supported; lzma_check_size; lzma_code; lzma_crc32; lzma_crc64; lzma_easy_buffer_encode; lzma_easy_decoder_memusage; lzma_easy_encoder; lzma_easy_encoder_memusage; lzma_end; lzma_filter_decoder_is_supported; lzma_filter_encoder_is_supported; lzma_filter_flags_decode; lzma_filter_flags_encode; lzma_filter_flags_size; lzma_filters_copy; lzma_filters_update; lzma_get_check; lzma_index_append; lzma_index_block_count; lzma_index_buffer_decode; lzma_index_buffer_encode; lzma_index_cat; lzma_index_checks; lzma_index_decoder; lzma_index_dup; lzma_index_encoder; lzma_index_end; lzma_index_file_size; lzma_index_hash_append; lzma_index_hash_decode; lzma_index_hash_end; lzma_index_hash_init; lzma_index_hash_size; lzma_index_init; lzma_index_iter_init; lzma_index_iter_locate; lzma_index_iter_next; lzma_index_iter_rewind; lzma_index_memusage; lzma_index_memused; lzma_index_size; lzma_index_stream_count; lzma_index_stream_flags; lzma_index_stream_padding; lzma_index_stream_size; lzma_index_total_size; lzma_index_uncompressed_size; lzma_lzma_preset; lzma_memlimit_get; lzma_memlimit_set; lzma_memusage; lzma_mf_is_supported; lzma_mode_is_supported; lzma_physmem; lzma_properties_decode; lzma_properties_encode; lzma_properties_size; lzma_raw_buffer_decode; lzma_raw_buffer_encode; lzma_raw_decoder; lzma_raw_decoder_memusage; lzma_raw_encoder; lzma_raw_encoder_memusage; lzma_stream_buffer_bound; lzma_stream_buffer_decode; lzma_stream_buffer_encode; lzma_stream_decoder; lzma_stream_encoder; lzma_stream_flags_compare; lzma_stream_footer_decode; lzma_stream_footer_encode; lzma_stream_header_decode; lzma_stream_header_encode; lzma_version_number; lzma_version_string; lzma_vli_decode; lzma_vli_encode; lzma_vli_size; }; XZ_5.1.2alpha { global: lzma_stream_encoder_mt; lzma_stream_encoder_mt_memusage; } XZ_5.0; XZ_5.2.2 { global: lzma_block_uncomp_encode; lzma_cputhreads; lzma_get_progress; lzma_stream_encoder_mt; lzma_stream_encoder_mt_memusage; local: *; } XZ_5.1.2alpha; How do i ammend XZ_5.2 in this file or in any other src file within 5.2.5 src tree? A: Simply removing the newest liblzma.so.%.% (in my case 5.2.5)from the lib folder worked for me.
doc_23530199
At this point, I'm too far in the project to switch to anything else. A: When you create the message you do something like: email = TMail::Mail.new To attach your file you do something like: attachment = TMail::Mail.new attachment.body = Base64.encode64(attachment_content.to_s) attachment.transfer_encoding = "Base64" attachment['Content-Disposition'] = "attachment; filename=#{attachment_filename}" email.parts << attachment It's the next to last line that should do the trick.