text
stringlengths
15
59.8k
meta
dict
Q: stuck threads in weblogic while trying to communicate over RMI Our application is running in an 8 node Weblogic cluster and is trying to communicate to an RMI server. The threads doing so get stuck due to an error in the RMI server. We're trying to solve that, but the problem is that until then, the stuck threads slow down the application eventually bringing the whole cluster on its knees. My question is 'how can we from the client side make sure that the threads get released ?' Any help is greatly appreciated. Implementation details: - Weblogic 10.0MP2, cluster with 8 nodes - Java 1.5 Thread dump snippet: "[STUCK] ExecuteThread: '15' for queue: 'weblogic.kernel.Default (self-tuning)'" daemon prio=3 tid=0x03808610 nid=0x1c9 runnable [0 x3ed4e000..0x3ed4faf0] at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:129) at java.io.BufferedInputStream.fill(BufferedInputStream.java:218) at java.io.BufferedInputStream.read(BufferedInputStream.java:235) - locked <0xa0a515a0> (a java.io.BufferedInputStream) at java.io.DataInputStream.readByte(DataInputStream.java:241) at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:126) at com.kpno.in.iac.CustomerBridge.CustomerBridge.RemoteDecorator_Stub.sendMessage(Unknown Source) at com.kpno.in.iac.CustomerBridge.RMIServer.CustomerBridgeProxy.sendMessage(Unknown Source) Application snippet (decompiled): public final class RemoteDecorator_Stub extends RemoteStub implements ... { ... public Map sendMessage(String paramString1, String paramString2, Map paramMap) throws InvalidActionException, ProcessingException, PropagationException, ResponseException, TimeoutException, RemoteException { try { Object localObject = this.ref.invoke(this, $method_sendMessage_2, new Object[] { paramString1, paramString2, paramMap }, 6494150482049562645L); return (Map)localObject; } catch ... UPDATE I've tried to make it work with the JNDI lookup as Tolis proposed, but until now I was not successful. I am wondering what the url should be. Retrieving from RMI naming is done as follows: java.rmi.Naming.lookup("//host:port/FactoryObject") How do I translate this to a JNDI url? I've tried with t3 as the protocol and with iiop. Nothing worked. I always get a naming exception. In case of t3 I get this exception: [Root exception is java.net.ConnectException: t3://host:port: Destination unreachable; nested exception is: java.io.IOException: Empty server reply; No available router to destination] In case of iiop I get this exception: javax.naming.CommunicationException: Cannot connect to ORB [Root exception is org.omg.CORBA.COMM_FAILURE: vmcid: SUN minor code: 201 completed: No] Any ideas ? A: You could use the weblogic.rmi.clientTimeout setting in order to avoid thread stuck situations when the target server is experiencing problems. EDITED: Another solution which is useful when you are trying to read from a socket and you are not getting any response from the server is the following: An RMISocketFactory instance is used by the RMI runtime in order to obtain client and server sockets for RMI calls. An application may use the setSocketFactory method to request that the RMI runtime use its socket factory instance instead of the default implementation. Implementation example: RMISocketFactory.setSocketFactory(new RMISocketFactory() { public Socket createSocket(String host, int port) throws IOException { Socket s = new Socket(); s.setSoTimeout(timeoutInMilliseconds); s.setSoLinger(false, 0); s.connect(new InetSocketAddress(host, port), timeoutInMilliseconds); return s; } public ServerSocket createServerSocket(int port) throws IOException { return new ServerSocket(port); } }); The setSocketFactory sets the global socket factory from which RMI gets sockets.
{ "language": "en", "url": "https://stackoverflow.com/questions/12038574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Limit Options in a Select Dropdown using CSS I am in need of limiting dropdown option items in a <select> element. I am working within a CMS system, so I can't alter the HTML and can only use CSS to achieve this. I currently am using: select option:not([value="1"]){display:none;} This works for most cases, except Edge (the dropdown box is still the size of 10 options) and on Mobile (my phone is still displaying all 10 options). Any suggestions? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/59398784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extract data from nested JSON and convert to TSV I'm looking at parsing nested json. For the example below, I know that it appears on Github - however due to sensitivity I cannot post my actual data on here. I've Been looking at jq for formatting, and can pull each component out, but cannot merge them together such that it looks like the below. BEcuase of software restrictions, I cannot use 3rd party code. input: { "asgs": [ { "name": "test1", "instances": [ {"id": "i-9fb75dc", "az": "us-east-1a", "state": "InService"}, {"id": "i-95393ba", "az": "us-east-1a", "state": "Terminating:Wait"}, {"id": "i-241fd0b", "az": "us-east-1b", "state": "InService"} ] }, { "name": "test2", "instances": [ {"id": "i-4bbab16", "az": "us-east-1a", "state": "InService"}, {"id": "i-417c312", "az": "us-east-1b", "state": "InService"} ] } ] } output: test1 i-9fb75dc us-east-1a InService test1 i-95393ba us-east-1a Terminating:Wait test1 i-241fd0b us-east-1b InService test2 i-4bbab16 us-east-1a InService test2 i-417c312 us-east-1b InService EDIT: Current code is such that I loop through all the instances of instances using and then append the names. For example: cat sampleData.json | jq -c '.' | while read i; do echo $i, & jq '.instances' sampleData.json done A: A slight shorter (though marginally more complex) version of @anubhava's answer: jq -r '.asgs[] | .name as $n | (.instances[] | [$n, .id, .az, .state] | @tsv)' file.json This "remembers" each name before producing a tab-separated line for each instance, inserting the correct name in each row. A: You may use this jq: jq -r '.asgs[] | .name + "\t" + (.instances[] | .id + "\t" + .az + "\t" + .state)' file.json test1 i-9fb75dc us-east-1a InService test1 i-95393ba us-east-1a Terminating:Wait test1 i-241fd0b us-east-1b InService test2 i-4bbab16 us-east-1a InService test2 i-417c312 us-east-1b InService A: You can use a generic map to create an extra entry per-instance: jq -r '.asgs[] | [.name] + (.instances[] | map(.)) | @tsv'
{ "language": "en", "url": "https://stackoverflow.com/questions/61139142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I find the first occurrence of "&" in a string using regex? I have a set of data and each row has different number of &. How do I find and match the first & in each row using regex? Sample data: * *Document & saved (faulty authorization) *Document & cannot be processed in this transaction with billing type & *Revenue of leading WBS element & determined by substitution from & I am working on a RPA system and when I put & as regex, it matches all & occurrences instead of the first. So wonder if you guys have any alternatives. Thanks! A: Since the regex engine you are using is .NET, you may use a positive lookbehind based solution: (?<=\A[^&]*)& See the regex demo. Details * *(?<=\A[^&]*) - a location in the string that is immediately preceded with * *\A - start of string *[^&]* - 0 or more chars other than & *& - a & char.
{ "language": "en", "url": "https://stackoverflow.com/questions/60965004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Make requests on chromecast receiver shutdown event I'm developing a chromecast custom receiver, and I need to send a request to the server once the sender disconnects from receiver. When I use ios or android senders, I can see that the 'sender disconnect' event is triggered, but when I use the browser, that event is not triggered. Because of that, I'm trying to use the 'shutdown' event, to send that request, once the sender is disconnected. I tried to pass an 'async/await' function as callback to the shutdown event, and tried to force an 'await' on the request, but I get the ' Application should not send requests before the system is ready (they will be ignored)' I also tried to use the window 'beforeunload' event, but with no success. Is there any way to send a request, once the 'shutdown' event is triggered? Cheers A: For us the Dispatching Shutdown event occurred in both cases. Web and Mobile senders. So I'm not sure what's happening on your end but will definitely need more information regarding what you're doing in order to look further into it. Anyhow, if you are setting addEventListeners on your end like this: context.addEventListener(cast.framework.system.ShutdownEvent, ()=>{ console.log("ShutdownEvent Called"); }); context.addEventListener(cast.framework.system.SenderDisconnectedEvent, ()=>{ console.log("SenderDisconnectedEvent called"); }); Which will result in your calls not firing. You should instead be doing: context.addEventListener(cast.framework.system.EventType.SHUTDOWN, ()=>{ console.log("ShutdownEvent Called"); }); context.addEventListener(cast.framework.system.EventType.SENDER_DISCONNECTED, ()=>{ console.log("SenderDisconnectedEvent called"); }); Here's the docs for their reference: https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.EventType
{ "language": "en", "url": "https://stackoverflow.com/questions/65250660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: After jQuery Ajax invocation call , the application Fails to navigate to the ASP.NET MVC view that I want to show I'm using jquery DataTables to show some tabular data, and I also placed an edit link for each row in said jquery DataTables so that the user can edit data associated with a particular row if needed. ( Also, I have No clue how to use ASP.NET MVC Html helpers within jQuery DataTables so that is why I am using the html link in the following code ) jquery DataTable javascript: $("#resultCodeTable").dataTable({ "processing": true, "serverSide": false, "destroy": shouldDestroy, "ajax": { "url": "../Admin/LoadResultCodes", "type": "GET", "datatype": "json", "data": function (data) { data.actionCodeIDArg = actionCodeIDInQuestion; } }, .................................... ............................ .............. columnDefs: [ { { targets: 1, searchable: false, orderable: false, name: "EditResultCodeInQuestionReasonForArrears", "data": "ID", render: function (data, type, full, meta) { if (type === 'display') { data = '<a class="editResultCodeInQuestionReasonForArrears" href="javascript:void(0)" data-id="' + full.ID + '">Edit RFAs</a>' } return data; } }, .................................... ............................ .............. Clicking on the aforementioned link will ensure that the point of execution reaches the following jQuery Event Handler method: jQuery Event handler method/ function Javascript $('#resultCodeTable').on('click', '.editResultCodeInQuestionReasonForArrears', function () { console.log(this.value); navigateToAParticularResultCodeAssociatedReasonForArrearsList($(this).data('id')); }); The jQuery Ajax call successfully invokes the C# Controller's action because I see the Visual Studio's Debugger's point of execution reach said Controller's action, however, it fail to navigate to the view that I want to show. jquery / javascript: function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) { console.log(resultCodeTable_ID); $.ajax({ url: '../Admin/NavigateToAParticularResultCodeAssociatedReasonForArrearsList', type: 'POST', dataType: 'json', contentType: "application/json;charset=utf-8", data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}", cache: false, }).done(function (response, status, jqxhr) { }) .fail(function (jqxhr, status, error) { // this is the ""error"" callback }); } C#: ( in my AdminController.cs ) public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg) { AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel(); aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg; return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel); } Razor / Html: (In my \Areas\Admin\Views\Admin\AdminModules\Auxiliaries\AParticularResultCodeAssociatedReasonForArrearsList.cshtml view ) @model Trilogy.Areas.Admin.ViewModels.Auxiliaries.AParticularResultCodeAssociatedReasonForArrearsListViewModel @{ ViewBag.Title = "AParticularResultCodeAssociatedReasonForArrearsList"; } <h2>AParticularResultCodeAssociatedReasonForArrearsList</h2> Could someone please tell me how I can change the code so that the view shows up after the jquery Ajax invocation? A: May be on .done function you will get the view in the response, you need to take that response and bind it to your control A: You call the controller via AJAX, and sure it hits the controller action method, and the controller returns a view but this is your code that deals with whatever is returned from the AJAX call (from the controller): .done(function (response, status, jqxhr) {}) You are doing absolutely nothing, so why would it navigate anywhere. A better question you need to ask yourself, instead of fixing this, is why would you use AJAX and then navigate to another page. If you are navigating to a whole new page, new URL, then simply submit a form regularly (without AJAX) or do it via a link (which the user will click). Use AJAX post if you want to stay on the same page and refresh the page's contents. A: @yas-ikeda , @codingyoshi , @code-first Thank you for your suggestions. Here are the modifications that I had to make to resolve the problem(please feel free to suggest improvements): Basically, I had to end up creating 2 separate Action methods to resolve the problem. In the jquery/Javascript code below, it is important to note the first action method '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) { console.log(resultCodeTable_ID); $.ajax({ url: '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList', type: 'POST', dataType: 'json', contentType: "application/json;charset=utf-8", data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}", cache: false, }).done(function (response, status, jqxhr) { window.location.href = response.Url; }) .fail(function (jqxhr, status, error) { // this is the ""error"" callback }); } The purpose of the 1st action method called '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' is to retrieve a url within a Json object. [HttpPost] public ActionResult RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg) { var redirectUrl = new UrlHelper(Request.RequestContext).Action("NavigateToAParticularResultCodeAssociatedReasonForArrearsList", "Admin", new { resultCodeTable_IDArg = resultCodeTable_IDArg }); return Json(new { Url = redirectUrl }); } The purpose of the 2nd action method is to ultimately navigate to the ASP.NET MVC View that I want to show. public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg) { AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel(); aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg; aParticularResultCodeAssociatedReasonForArrearsListViewModel.RFACodeList = actionCodeResultCodeBusinessService.GetSpecificResultCodeRFACodeList(resultCodeTable_IDArg); return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel); } However, I Dislike the fact that I have to use 2 action methods to navigate to the desired asp.net mvc view, therefore, please feel free to suggest improvements or even a totally different better solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/52768163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Objects/types Javascript I'm working on a simple 2d game in JS using canvs. The game consists of a knight who runs around to kill goblins, the goblin once touched, resets to a rangom location. I want to leave bloodsplatters for every goblin killed. Currently, before I redraw the canvas, I use the previous X and Y co-ordinates from where the goblin died to paint my blood splatter image. I want to do it for all goblins though. In a traditional language like Java, I would define a type, for example "blood" with two properties, X and Y. I'd then create a new instance of this type each round using the goblins current co-ords and then add this type to an array, I'd loop and print all the objects in this array then. I'm quite new to JS and since it's a functional language, things are a bit different. How exactly would I define a type like this that I could "new" into an array every iteration of the game? var blood = { x: 0, y: 0 }; Here's the current blood object I have A: You create "classes" in Javascript as functions. Using this.x inside the function is like creating a member variable named x: var Blood = function() { this.x = 0; this.y = 0; } var blood = new Blood() console.log(blood.x); These aren't classes or types in the sense of OO languages like Java, just a way of mimicking them by using Javascript's scoping rules. So far there isn't really much useful here -- a simple object map would work just as well. But this approach may be useful if you need more logic in the Blood "class", like member functions, etc. You create those by modifying the object's prototype: Blood.prototype.createSplatter = function() { return [this.x-1, this.y+1]; // (idk, however you create a splatter) }; blood.createSplatter(); (Fiddle) For more details on Javascript classes, I suggest taking a look at CoffeeScript syntax (scroll down to "Classes, Inheritance, and Super"). They have some side-by-side examples of classes in the simplified CS syntax, and the JS translation.
{ "language": "en", "url": "https://stackoverflow.com/questions/19410200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implement a class that support async methods? I already created group of classes that will be responsible about getting the data and saving it to the source. and I want to add async capabilities to these classes but I weak at async programming and I don't know what is the best way to implement it. I wrote an example of what I'm trying to do How to implement the async methods in the best way ? this is the Main class: public sealed class SourceManager : IDisposable { public SourceManager(string connectionString) { ConnectionString = connectionString; MainDataSet = new DataSet(); Elements = new List<SourceElement>(); // this is for example Elements.Add(new SourceElement(this, "Table1")); Elements.Add(new SourceElement(this, "Table2")); Elements.Add(new SourceElement(this, "Table3")); Elements.Add(new SourceElement(this, "Table4")); } public void Dispose() { MainDataSet?.Dispose(); Elements?.ForEach(element => element.Dispose()); } public DataSet MainDataSet { get; } public string ConnectionString { get; } public List<SourceElement> Elements { get; } public void LoadElements() { Elements.ForEach(element => element.Load()); } public Task LoadElementsAsync() { throw new NotImplementedException(); } public void UpdateAll() { Elements.ForEach(element => element.Update()); } public void UpdateAllAsync() { throw new NotImplementedException(); } } this is the element class : public sealed class SourceElement : IDisposable { private readonly SqlDataAdapter _adapter; public SourceElement(SourceManager parentManager, string tableName) { ParentManager = parentManager; TableName = tableName; _adapter = new SqlDataAdapter($"SELECT * FROM [{TableName}];", ParentManager.ConnectionString); _adapter.FillSchema(ParentManager.MainDataSet, SchemaType.Mapped, TableName); } public void Dispose() { _adapter?.Dispose(); } public string TableName { get; } private SourceManager ParentManager { get; } public void Load() { _adapter.Fill(ParentManager.MainDataSet, TableName); } public Task LoadAsync() { throw new NotImplementedException(); } public void Update() { _adapter.Update(ParentManager.MainDataSet.Tables[TableName]); } public Task UpdateAsync() { throw new NotImplementedException(); } } and this is how I use it public partial class Form1 : Form { private SourceManager sourceManager; public Form1() { InitializeComponent(); // here we initialize the sourceManager cuz we need its elements on draw the controls in the form sourceManager = new SourceManager("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // here I want to fill the data tables without interrupting the interface // I need to show a progress sourceManager.LoadElementsAsync(); } public void SaveAll() { // Here I I want to save the data without interrupting the interface thread sourceManager.UpdateAllAsync(); } public void SaveData(string tableName) { // Here I I want to save the data without interrupting the interface thread sourceManager.Elements.Find(element => element.TableName.Equals(tableName))?.UpdateAsync(); } } A: SqlDataAdapter does not have asynchronous methods. You will have to implement it yourself which I don't recommend. sample await Task.Run(() =>_adapter.Fill(ParentManager.MainDataSet, TableName)); But I would look into an alternative solution using other ADO.NET libraries like using an async SqlDataReader. sample public async Task SomeAsyncMethod() { using (var connection = new SqlConnection("YOUR CONNECTION STRING")) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = "YOUR QUERY"; var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) { // read from reader } } } } Look at section Asynchronous Programming Features Added in .NET Framework 4.5 https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming But I would probably not even bother with any of this and just use Dapper which has support for async methods without you having to write all the boilerplate code. https://dapper-tutorial.net/async A: Implement the async versions of your methods like this: public async Task LoadElementsAsync() { await Task.Factory.StartNew(LoadElements); }
{ "language": "en", "url": "https://stackoverflow.com/questions/55763021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to config webpack in a project created by vue-cli 3? By using vue-cli 3, I created a project with the following structure: Then I hope it would support webpack. I tried to add webpack.config.js into build folder, and add script "webpack --config build/webpack.config.js" in package.json file. However it seems that this doesn't work out with an error shows "Error: Cannot find module '/Users/laiyinan/Documents/前端开发/稠行手机银行(个人)/build/webpack.config.js'" How could I use webpack in vue project? Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/55117540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to output asian characters in Logbacks' HTML format I am using Logback to enable logging statements within my code. Currently when I am logging information displayed in asian characters ( Chinese, Korean, Japanese etc ) they appear similar to æ?±äº¬éƒ½. How can I output the proper characters into my logs? For instance, Tokyo should output 東京都 not æ?±äº¬éƒ½ I have enabled the UTF-8 character set within my logback.xml config file: <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <charset>UTF-8</charset> <layout class="ch.qos.logback.classic.html.HTMLLayout"> <pattern>%d{HH:mm:ss.SSS}%thread%level%logger%line%msg</pattern> </layout> </encoder> A: For the logback html file to display correctly, a custom CSS must be specified with font-family: 'lucida sans unicode', tahoma, arial, helvetica, sans-serif; (or a similar font) specified where its needed. For instance I have it set for TR.even and TR.odd classes. As an aside, it turns out that eclipse has issues with these character sets. I was unable to get asian characters to print period, even with simple examples such as Locale locale = new Locale("zh", "CN"); System.out.println(locale.getDisplayLanguage(Locale.SIMPLIFIED_CHINESE)); I ran the same code in NetBeans and it outputs flawlessly. In the case of eclipse I changed the encoding to UTF-8 wherever possible via system preferences, as well as set the default font to the above font with no resolution. I even went so far as to download a new copy of eclipse, extract it to a new directory and create a new workspace before setting everything to UTF-8/changing the font and then creating a test case, again with no resolution. For NetBeans no change was required. --EDIT-- Also please note this seems to be a windows issue only - My home development machine is Linux and it ran the above code perfectly with no alterations to preferences and using a new install of Eclipse.
{ "language": "en", "url": "https://stackoverflow.com/questions/13458228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to calculate the the elements of the arrays separately I have two arrays "Resulted from the SQL query" The first array is Array ( [0] => 100 ) Array ( [0] => 200) The second array is Array ( [0] => 300 ) Array ( [0] => 400) How to calculate the first elements of each arrays (100 + 300) and the second elements of the second arrays (200 + 400) separately? A: $sum = array(); for ($i=0;$i<count(array1);$i++) { $sum[$i] = array1[$i] + array2[$i]; } print_r($sum); =====Update====== <?php $a = array(2, 4, 6, 8); echo "sum(a) = " . array_sum($a) . "\n"; $b = array("a" => 1.2, "b" => 2.3, "c" => 3.4); echo "sum(b) = " . array_sum($b) . "\n"; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/15932081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A way to see the number of active IAP subscribers? Apologies if this question has an obvious answer, but dozens of Google and Stack Overflow searches haven't brought me any closer to the answer... We have an iOS app that uses In-App Purchase to allow users to sign up for a subscription. This subscription automatically bills monthly. In iTunes Connect I can see the total number of subscription transactions being processed each month, but I can't see how many subscribers we're adding / retaining. Ideally, we'd like to be able to see: * *Total number of active subscribers *Number of new subscribers in this period *Number of cancellations in this period Any ideas on how to find this info - either from iTunes Connect or a third-party solution - would be appreciated. Thanks! A: I received an email today that you now have visibility to active subscriptions. Log into iTunes connect, Go to "Sales and Trends" then select "Subscriptions" from the report chooser. Report Chooser
{ "language": "en", "url": "https://stackoverflow.com/questions/17364417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: jquery ui toggle button to trigger setTimeout function I am trying to create a toggle button which should run a function when toggel is pressed. and function should stop when toggle is off.But whenever toggle is turned on, it should run function constantly. JSBIN Try: http://jsbin.com/AbIzuNO/1/edit HTML: <input type="checkbox" id="check" /> <label for="check">Toggle</label> JS: var Autoreload; $("#check").button({ icons: { primary: "ui-icon-circle-triangle-s" } }).click(function () { var iconClass; if ($(this).is(':checked')) { iconClass = "ui-icon-circle-triangle-e"; Autoreload = setTimeout(function () { //Run somefunction here constantly untill cleared //$.getJSON( "ajax/test.json", function( data ) { // some success calls //}); console.log("Running"); }, 100); } else { iconClass = "ui-icon-circle-triangle-s"; clearTimeout(Autoreload); } $(this).button("option", { icons: { primary: iconClass } }); }); A: Change * *setTimeout to setInterval *clearTimeout to clearInterval
{ "language": "en", "url": "https://stackoverflow.com/questions/19157576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: where to set xpages/ibmsbt proxy configuration I have intranet based domino 9x (running windows) server sitting behind a firewall and proxy. To make http/s requests via server side java I set the http/s.proxyHost and other jvm settings to allow my java.net calls. Works fine when doing a simple GET via java.net classes, but fails when I attempt to use the ibmsbt ProfileService call (code works fine when outside our network). Can anyone out there direct me to what is probably an obvious answer on where to configure the proxy settings (host, port, username, password)? I've seen a few references to the manaaged-bean.xml file, but it seems it is associated with some debugging proxy, and doesn't have any settings for username/password that I'm aware of. SmartCloudFilesEndpoint config in faces-config: <managed-bean> <managed-bean-name>smartcloud</managed-bean-name> <managed-bean-class>com.ibm.xsp.extlib.sbt.services.client.endpoints.SmartCloudFilesEndpoint </managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <!-- Endpoint URL --> <managed-property> <property-name>url</property-name> <value>https://apps.na.collabserv.com</value> </managed-property> <managed-property> <property-name>serviceName</property-name> <value>SmartCloud</value> </managed-property> <!-- OAuth parameters --> <managed-property> <property-name>appId</property-name> <value>XPagesSBT</value> </managed-property> <managed-property> <property-name>credentialStore</property-name> <value>CredStore</value> </managed-property> <managed-property> <property-name>requestTokenURL</property-name> <value>https://apps.na.collabserv.com/manage/oauth/getRequestToken</value> </managed-property> <managed-property> <property-name>authorizationURL</property-name> <value>https://apps.na.collabserv.com/manage/oauth/authorizeToken</value> </managed-property> <managed-property> <property-name>accessTokenURL</property-name> <value>https://apps.na.collabserv.com/manage/oauth/getAccessToken</value> </managed-property> <managed-property> <property-name>consumerKey</property-name> <value>xxxxxxxxxx</value> </managed-property> <managed-property> <property-name>consumerSecret</property-name> <value>xxxxxxxxxx</value> </managed-property> A: SBT currently supports this for debug purposes. You can enable this by adding below property to you endpoint. <managed-property> <property-name>httpProxy</property-name> <value>IpOfProxy:PortNumberOfProxy</value> </managed-property> If you need to enable this for all endpoint, just add this to you sbt.properties directly sbt.httpProxy=127.0.0.1:8888 We do not support the credentials for now as this is not required by most of the proxies used for debugging like Fiddler or Wireshark. Can you provide me more details of your environment and I can check if we can enhance the code to work in your environment. A: Try Ports -> Proxies in Server Document.
{ "language": "en", "url": "https://stackoverflow.com/questions/19123230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django Admin: admin.sites.register(MyModel) doesn't work By mistake I deleted the migration files, and now my Admin does not register my Models, apparently because they were already registered and appeared correctly but now they do not appear and do not register them, and also if I try to do 'admin.sites.unregister' it indicates that it's not registered. How do I force djago to register my model again? :( Here my admin.py from django.contrib import admin from .models import Post, Category # Register your models here. admin.site.register(Post) admin.site.register(Category)
{ "language": "en", "url": "https://stackoverflow.com/questions/57898364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jsonSchema attribute conditionally required based on uri parameter Consider an API with an endpoint in which you pass a parameter foo as part of the URL-path, and pass some parameters as json in the body of a POST request. * *This uri parameter foo must have one of the values fooBar and fooBaz. Otherwise the request gest a 404. *If the value of foo is fooBar then the body attribute bar is required. *If the value of foo is fooBaz then the body attribute baz is required. How do I specify a jsonSchema for such an endpoint? An example for such a request would be: POST /path/to/endpoint/fooBar HTTP/1.1 Accept: application/json Content-Type: application/json Content-Length: 20 {"bar":"something"} So far I came up with the following based on this and that but I have no idea if this is correct. { "$schema": "http://json-schema.org/draft-03/schema#", "id": "http://json-schema.org/draft-03/schema#", "definitions": { "foo": { "enum": ["fooBar", "fooBaz"] } }, "type": "object", "properties": { "foo": { "$ref": "#/definitions/foo" }, "bar": { "type": "string" }, "baz": { "type": "string" } }, "links": [{ "rel": "self", "href": "/path/to/endpoint/{foo}", "hrefSchema": { "properties": { "foo": {"$ref": "#/definitions/foo"} } } }], "anyOf": [ { "properties": { "foo": { "enum": ["fooBar"] } }, "required": ["bar"] }, { "properties": { "foo": { "enum": ["fooBaz"] } }, "required": ["baz"] }, ] } A: JSON Schema validation is not aware of the URI that the data being validated came from (if any). You can use JSON Hyper-Schema to tell your users how to send that data in the way you expect, but you will still need to do an additional check on the server-side to validate that the request was sent properly. Before I get into the solution, I want to point out a couple things. Your $schema is set to "draft-03". If you really need "draft-03", this solution won't work. anyOf, allOf and the array form of required were added in "draft-04". hrefSchema was added in "draft-06". Since "draft-06" is brand new and is not well supported yet and you don't need hrefSchema anyway, I'm going to assume "draft-04" ("draft-05" was effectively skipped). The next thing to mention is that you are using id wrong. It should be the identifier for your schema. You usually don't need this, but if you do, it should be the full URI identifying your schema. That is how my solution uses it. Last thing before I get into the solution. If you are using the link keyword, you are using JSON Hyper-Schema and your $schema should reflect that. It should have "hyper-schema" instead of "schema" at the end of the URI. Now the solution. I broke it into two parts, the schema that you put through the validator and the hyper-schema that tells users how to make the request. You've got the first one right. I only fixed the $schema and id. { "$schema": "http://json-schema.org/draft-04/schema#", "id": "http://example.com/schema/my-foo-schema", "type": "object", "properties": { "foo": { "enum": ["fooBar", "fooBaz"] }, "bar": { "type": "string" }, "baz": { "type": "string" } }, "anyOf": [ { "properties": { "foo": { "enum": ["fooBar"] } }, "required": ["bar"] }, { "properties": { "foo": { "enum": ["fooBaz"] } }, "required": ["baz"] } ] } Next is the hyper-schema. You can't reference anything external (href, instance data) in a request schema, but you can write your schema so that it matches your href. The duplication is unfortunate, but that's the way you have to do it. { "$schema": "http://json-schema.org/draft-04/hyper-schema#", "links": [ { "rel": "http://example.com/rel/my-foo-relation", "href": "/path/to/endpoint/fooBar", "method": "POST", "schema": { "allOf": [{ "$ref": "http://example.com/schema/my-foo-schema" }], "properties": { "foo": { "enum": ["fooBar"] } } } }, { "rel": "http://example.com/rel/my-foo-relation", "href": "/path/to/endpoint/fooBaz", "method": "POST", "schema": { "allOf": [{ "$ref": "http://example.com/schema/my-foo-schema" }], "properties": { "foo": { "enum": ["fooBaz"] } } } }, { "rel": "self", "href": "/path/to/endpoint" } ] } Usually when I come across something that is difficult to model with hyper-schema, it means that I am doing something overly complicated with my API and I need to refactor. I suggest taking a few minutes to think about alternative designs where this switching on an enum isn't necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/45034662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FileStream constructor and default buffer size We have a logging class written in C# using .NET 4. I want to add a constructor argument which will optionally set the FileOptions.WriteThrough flag when constructing a FileStream. As this is widely used library code I want to change as little as possible. Existing FileStream constructor call: _stream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.Read); The problem: To our constructor I have added an optional bool argument named writeDirectToDisk. I thought I'd then be able to do something like this: var fileOptions = writeDirectToDisk ? FileOptions.WriteThrough : FileOptions.None; _stream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.Read, fileOptions); but no, there's no such overload! Unless I'm missing something the only overloads available for FileStream's constructor which accept a FileOptions argument also require a buffer size argument! What I've tried: I've tried setting buffer size to zero hoping that would use the default buffer size but no it throws an exception. I've searched for and can't find some static property or constant in the framework which specifies what the default buffer size is. My question: I'm not at this stage particularly bothered about how many bytes the default buffer size is. I just want to know how I can add the FileOptions argument to the constructor with as little code impact as possible? I'm wondering if there is some constant or static var which I've missed that I could use as the buffer size argument or if there's an overload I've missed or indeed if there's some smarter way to do this. I'm also wondering if the buffer size is irrelevant when FileOptions.WriteThrough is specified in which case I could do this: if (writeDirectToDisk) { _stream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.Read, 1, FileOptions.WriteThrough); // 1 is the smallest value allowed, it will actually be 8 bytes } else { _stream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.Read); } but I'd rather not unless there's really no more elegant way. A: The default buffer size can be seen in .Net's source code, here. WriteThrough is not supported in .Net. You can use unmanaged Win API calls is you really want that functionality. I just spent a day experimenting with it, and there are no advantages to using it. This was not true 10+ years ago, where the caching had a noticeable effect on speed. Out of interest, someone kindly wrote the whole library for doing the API calls, available here. A: You could use your own factory method to construct the FileStream. Other than that, you could hardwire the buffer size discovered using Reflector (0x1000).
{ "language": "en", "url": "https://stackoverflow.com/questions/9791088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ring topology in PSO algrithm in particle swarm optimization algorithm, there are different types of topologies that can be used such as ring topology and star topology. so if I decided to use ring topology, can I put the value between brackets 2 in the following line of code ? Topology topology = new TopologyRing(2); Thanks a lot
{ "language": "en", "url": "https://stackoverflow.com/questions/54432572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C - given a case-insensitive file path, how to check whether the file exists or not? For example, suppose we have a file called "Hello.txt", then checking if "hello.txt" or "heLLo.txt" exist should both return true. A: If you're running Windows or any case-insensitive filesystem, then there's nothing to do but check one casing. If "Hello.txt" exists, then "hEllo.txt" exists (and is the same file) (the difficult problem here is when you want to make sure that the file is spelled with a given casing in the filesystem) If you're running a case-sensitive filesystem, just take directory name of the current file, list file contents, and compare entries against the current filename, ignoring case. A: Take a look at fcaseopen, which demonstrates how to handle case insensitive file operations. Essentially, the C headers/functions to use are: * *From dirent.h, use opendir/readdir/closedir to go thru the files in a directory *From string.h, use strcasecmp to compare two filesnames, ignoring the case of the characters
{ "language": "en", "url": "https://stackoverflow.com/questions/43480408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Installing a plugin into Drone CI (the Trigger plugin) I'm new to Drone, and I want to use my first plugin, namely this one: http://addons.drone.io/trigger/ However, the Drone documentation doesn't really explain how to install plugins. What I've done is copy the example yaml into my .drone.yml, resulting in this (obviously I've censored the sensitive information, but every single key is the same as the real document): pipeline: build: image: docker commands: - docker build . volumes: - /var/run/docker.sock:/var/run/docker.sock notify: downstream: image: plugins/trigger server: http://my.drone.server repositories: - My/Repo token: mytoken However, when I push this, Drone gives me the error: ERROR: Invalid or missing image If I put the image in, as in notify: image: plugins/trigger downstream: I get: plugins/trigger not found: does not exist or no pull access Am I supposed to build a docker container for each plugin? How do I get access to this plugin? A: The reason you are getting an "image not found" error is because there is no such image called plugins/trigger in the docker registry. Instead I think you probably want the plugins/downstream image [1][2]. [1] http://plugins.drone.io/drone-plugins/drone-downstream/ [2] https://hub.docker.com/r/plugins/downstream/
{ "language": "en", "url": "https://stackoverflow.com/questions/46091401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ID value in mySQL is auto_increment but seems generated in netbeans I'm fairly new to developing web apps in Java. I just connected the database, and as seen in the pictures, my ID_patient is auto_increment, but in Netbeans it looks generated. INSERT INTO sys.patient values('5','elif','nil','er','[email protected]','11111111111','1234a','istanbul') The new record inserted wants this value, while i want it to take INSERT INTO sys.patient values('elif','nil','er','[email protected]','11111111111','1234a','istanbul') and auto-increment and give the id as 1,2,3,4...etc. how can I fix this? thank you in netbeans in mysql A: If you are expecting to create an insert query where you don't want to provide an id and the database should generate it automatically based on table defination then you need to create insert query where you have to mention columns names. Example INSERT INTO <TABLENAME>(COLUMN1, COLUMN2, COLUMN3, COLUMN4) VALUES (VALUE1,VALUE2, VALUE 3,VALUE 4); So in ur case it should be INSERT INTO PATIENT(FirstName,MiddleName,LastName,E_mail) values ('myname','mymiddlename','mylastname','myemailid'); Sequence of column names and their values are very important. They should match exactly. If you don't provide a value for one of column and if its is auto increment, then DB will add an value to it else it will add null value.
{ "language": "en", "url": "https://stackoverflow.com/questions/47800590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decoding json in array , editing array and encoding in json - PHP I am newbee in php and trying to get json in array and wanna change key in that json below is my code : $json = json_decode(file_get_contents('all_json_files/jobs.json'), true); foreach ($json as $key=>$row){ foreach ( $row as $key=>$row){ foreach ( $row as $key=>$row){ foreach ($row as $key=>$row){ if(strcmp($key,"security_block")==0) { foreach ($row as $k=>$r){ if(strcmp($k,"job_payload_hash")==0) { $row[$k]['job_payload_hash']=$base64String; print_r($row); } } } } } } } print_r($json); Issue is print_r($row); is updating properly but print_r($json); does not print the updated string . A: If the key could appear anywhere, the answer is pretty simple: function update_hash(&$item, $key, $base64String) { if ($key == "job_payload_hash") { $item = $base64String; } } array_walk_recursive($json, 'update_hash', 'something'); Update The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach: foreach (array_keys($json['jobs']) as $jobId) { $json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something'; } A: You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work.. You can use recursive function lik answer of @Ja͢ck . A: Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string. Also, use array_key_exists() rather than comparing array key strings. $array = json_decode($json); if(array_key_exists("job_payload_hash", $array){ $array["job_payload_hash"] = base64encode($var); } $json = json_encode($array); A: this is because you have to save not in variables you defined after => in a foreach. You have to store this in format: $json[0][0] ... = $base64String; OR You have to add a new array like $result = array() before you write the foreach and then store it in $result.
{ "language": "en", "url": "https://stackoverflow.com/questions/27859629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combined .NET app for azure and windows, EF, SignalR Client I am creating a basic decentralized .NET logger which IS logging to a relational database using entity framework. The database can be SQL Server, SQL compact, etc. The application itself is a SignalR Client and log messages are pushed from the server to the app. The application needs no user interface or anything. It could be a windows service, console application, etc. My challenge is to choose an application type which can run both on a windows computer as well as being deployed to azure. I have looked into creating it as a console application and deploying it as a web job. Also price is important, the application is basic, so the cost on azure should not be high. What would be an ideal application type for this project? A: As far as I know, a SignalR server could be hosted in IIS, but it could also be self-hosted (such as in a console application or Windows service) using the self-host library. If IIS is not available (or not install) on your windows computer, self-host would be preferable. As you said, you could create a SignalR server that's hosted in a console application, and it could be easy to deploy as a WebJob. In order to save money, if you deploy it as a WebJob in your App Service web app, you should to choose an appropriate App Service plan tier based on your requirements of app capabilities and performance. If you’d like to host it in Azure Cloud Service worker role, you should use appropriate Instance size and count. You could use Pricing calculator to estimate your expected monthly.
{ "language": "en", "url": "https://stackoverflow.com/questions/40411352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hadoop new API - Set OutputFormat I'm trying to set the OutputFormat of my job to MapFileOutputFormat using: jobConf.setOutputFormat(MapFileOutputFormat.class); I get this error: mapred.output.format.class is incompatible with new reduce API mode I suppose I should use the set setOutputFormatClass() of the new Job class but the problem is that when I try to do this: job.setOutputFormatClass(MapFileOutputFormat.class); it expects me to use this class: org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat. In hadoop 1.0.X there is no such class. It only exists in earlier versions (e.g 0.x) How can I solve this problem ? Thank you! A: This problem has no decently easily implementable solution. I gave up and used Sequence files which fit my requirements too. A: Have you tried the following? import org.apache.hadoop.mapreduce.lib.output; ... LazyOutputFormat.setOutputFormatClass(job, MapFileOutputFormat.class);
{ "language": "en", "url": "https://stackoverflow.com/questions/11626328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby On Rails 2.0.2: Update quantity value of a product after order I'm using Instant-Rails 2.0 and following the Depot example project of Agile Web Development with Rails 3rd edition. My question is: When a customer makes an order, with the cart and the order form, I need the update the column quantity of products table. An example: If I have 10 books (the value "10" is stored in products table with the specific id of the product) and the customer wants 2 books, after the order I want that my project updates the quantity value of available books, decrement it to 8 books. I tried to add that in store_controller.rb, in the add_to_cart method: def add_to_cart product = Product.find(params[:id]) @quantity = Product.find(params[:quantity]) @cart = find_cart @current_item = @cart.add_product(product) @removed = Product.remove_q(@quantity) respond_to do |format| format.js if request.xhr? format.html {redirect_to_index} end rescue ActiveRecord::RecordNotFound logger.error("Product not found #{params[:id]}") redirect_to_index("invalid product!") end Where remove_q is a method of product.rb model: def self.remove_q(quantity) @quantity = quantity - 1 end RoR gives me the error "product not found" in the console when I click in the "add to cart" button. What am I doing wrong? UPDATE: Thanks to ipsum for answer. The solution is to decrement the quantities of products after successful order. This is the method save_order of store_controller.rb: def save_order @cart = find_cart @order = Order.new(params[:order]) @order.add_line_items_from_cart(@cart) @recipient = '[email protected]' @subject = 'Order' email = Emailer.create_confirm(@order, @recipient, @subject) email.set_content_type("text/html") @cliente = sent if @order.save Emailer.deliver(email) return if request.xhr? session[:cart] = nil redirect_to_index("Thank you") else render :action => 'checkout' end end Please note that Emailer is a model for notification via email after successful order, the cart is made from many line_items that are the products customer adds to cart. How can I decrement the quantities of products in cart after successful order? How can I extract products from cart? There is the model cart.rb: class Cart attr_reader :items def initialize @items = [] end def add_product(product) current_item = @items.find {|item| item.product == product} if current_item current_item.increment_quantity else current_item = CartItem.new(product) @items << current_item end current_item end def total_price @items.sum { |item| item.price} end def total_items @items.sum { |item| item.quantity } end end and the model line_item.rb: class LineItem < ActiveRecord::Base belongs_to :order belongs_to :product def self.from_cart_item(cart_item) li = self.new li.product = cart_item.product li.quantity = cart_item.quantity li.total_price = cart_item.price li end end A: You try to find a product through the quantity. but "find" expects a primary key Instead of: @quantity = Product.find(params[:quantity]) try this: @quantity = product.quantity UPDATE: def add_to_cart product = Product.find(params[:id]) @cart = find_cart @current_item = @cart.add_product(product) product.decrement!(:quantity, params[:quantity]) respond_to do |format| format.js if request.xhr? format.html {redirect_to_index} end rescue ActiveRecord::RecordNotFound logger.error("Product not found #{params[:id]}") redirect_to_index("invalid product!") end
{ "language": "en", "url": "https://stackoverflow.com/questions/5620572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: subprocess.check_output(['git', 'shortlog']) subprocess.check_output(['git', 'shortlog']) returns empty bytes. subprocess.check_output(['git', 'log']) works, somehow. Does anybody know a workaround?
{ "language": "en", "url": "https://stackoverflow.com/questions/51959265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: not sure where the comma is missing INSERT into manufactures (man_id, man_name, address, social_media_available) VALUES (seq_manufactures.NEXTVAL, 'ALLIANCE INC', address_type('123 MEYNELL ROAD', 'LEICESTER', 'UK'), social_media_varray_type ( social_media_type ('TWITTER', 'ALLIANCE'), social_media_type ('FACEBOOK', 'ALLIANCE'), social_media_type ('INSTAGRAM', 'ALLIANCE')); A: Your'e missing a parenthesis at the end of your statement : social_media_varray_type ( social_media_type ('TWITTER', 'ALLIANCE'), social_media_type ('FACEBOOK', 'ALLIANCE'), social_media_type ('INSTAGRAM', 'ALLIANCE')));
{ "language": "en", "url": "https://stackoverflow.com/questions/68087161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define/implement this interface with generics in a simpler way? I'm working in a Genetic Algorithm and I want it as abstract as possible to be able to reuse the GA. I defined and implemented a Population Interface, and well it works, but I'm sure that's not the best way to do it. I don't have great experience with Java Generics. Is there an easier way of defining and implementing the Population interface (e.g. maybe avoid a cast conversion? avoid a new list in getChromosomes() ?) public interface Population { void addChromosomes(List<? extends Chromosome> chromosomes); List<Chromosome> getChromosomes(); // More code here ... } public class TSPPopulation implements Population { private List<TSPChromosome> chromosomes; @Override public void addChromosomes(List<? extends Chromosome> chromosomes) { for (Chromosome chromosome : chromosomes) { this.chromosomes.add((TSPChromosome) chromosome); } } @Override public List<Chromosome> getChromosomes() { List<Chromosome> newList = new ArrayList<Chromosome>(); for (TSPChromosome chromosome : chromosomes) { newList.add(chromosome); } return newList; } } A: Use a Bounded Wildcard in your interface: public interface Population<T extends Chromosome>{ void addChromosomes(List<T> chromosomes); List<T> getChromosomes(); } public class TSPPopulation implements Population<TSPChromosome> { private List<TSPChromosome> chromosomes; @Override public void addChromosomes(List<TSPChromosome> chromosomes) { ... } @Override public List<TSPChromosome> getChromosomes() { ... } } A: The simplest solution is extending a list (then use addAll(...) to add a list of Chromosoms to the list): class Population<T extends Chromosome> extends ArrayList<T> { } But if you want the same structure I would make Population into a generic list class. That way both add... and get... methods can be handled in the generic base class. If you do want to override any other feature you just extend Population (class TSPPopulation extends Population<TSPChromosome>. Usage: public static void main(String... args) { Population<TSPChromosome> tspPopulation = new Population<TSPChromosome>(); ... } Implementation: class Population<T extends Chromosome> { private List<T> chromosomes = new ArrayList<T>(); public void addChromosomes(List<T> chromosomes) { this.chromosomes.addAll(chromosomes); } public List<T> getChromosomes() { return new ArrayList<T>(this.chromosomes); } } A: It would be much safer if you made the Population generic itself: public interface Population<T extends Chromosome> { void addChromosomes(List<T> chromosomes); List<T> getChromosomes(); } public class TspPopulation implements Population<TspChromosome>{ @Override public void addChromosomes(List<TspChromosome> chromosomes){ // } @Override public List<TspChromosome> getChromosomes(){ // } } That way you would not need any casting in client code. A: I know GAs, and I would question whether your Population implementation actually needs to know which kind of Chromosome you put in. Do you really have different Population implementations depending on the Chromosome subclass? Or what you really want is to make sure you have the same subclass of Chromosome in a Population? In this last case, you can define the Population interface as others suggested, and the make a generic implementation (or skip the interface altogether): public class PopulationImpl implements Population<T extends Chromosome> { private List<T> chromosomes; @Override public void addChromosomes(List<T> chromosomes) { this.chromosomes.addAll(chromosomes); } @Override public List<T> getChromosomes() { return new ArrayList<T>(chromosomes); } } Be careful not to put too many generics, or you will end up with generics hell, or tons of casts which will make generics more annoying than useful. A: Yes, for instance: public interface Population<T extends Chromosome> { void addChromosomes(List<T> chromosomes); List<T> getChromosomes(); // More code here ... } public class TSPPopulation implements Population<TSPChromosome> { private List<TSPChromosome> chromosomes; @Override public void addChromosomes(List<TSPChromosome> chromosomes) { this.chromosomes.addAll(chromosomes); } @Override public List<TSPChromosome> getChromosomes() { return new ArrayList<TSPChromosome>(chromosomes); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/4304322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python: mechanize can't find all form inputs I need to fill name="email" out, but mechanize say name="email" does not exist (look output). Why I can not find it? Do I must take an other command? Or can I solve the Problem with replace some text in the html file? <input class="box410" type="text" VCARD_NAME="vCard.Email" id="email" name="email" value="" tabindex="17" placeholder="Kontakt E-Mail Adresse" /> Code: import mechanize reg = "https://reg.webmail.freenet.de/freenet/Registration" browser = mechanize.Browser() browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] browser.open(reg) browser.select_form(nr = 0) browser.form['localpart'] = "hansp3056" #Wunschname browser.click(type="image", nr=0) #Weiter browser.submit().read() browser.select_form(nr = 0) print [form for form in browser.forms()][0] Output: <regForm POST https://reg.webmail.freenet.de/freenet/Registration application/x-www-form-urlencoded <TextControl(localpart=)> <RadioControl(gender=[HERR, FRAU, FIRMA])> <TextControl(business=)> <TextControl(firstname=)> <TextControl(lastname=)> <TextControl(zip=)> <TextControl(town=)> <TextControl(street=)> <TextControl(number=)> <SelectControl(bday=[*, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])> <SelectControl(bmonth=[*, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12])> <SelectControl(byear=[*])> <PasswordControl(password1=)> <PasswordControl(password2=)> <TextControl(code=)> <HiddenControl(patrick=MjQyMDY5NC1iNDkwNzU0OThlYWE5YTM5OTgyMjk3NzA1MjQ5NzU1ZS0xMzk2NDU1NDIyLTg4ZWNjMjIzZTQzMw==) (readonly)> <CheckboxControl(agb=[yes])> <ImageControl(<None>=Senden)> <HiddenControl(mandant=freenet) (readonly)> <HiddenControl(action=Registration) (readonly)> <HiddenControl(JSEnabled=0) (readonly)> <HiddenControl(productID=2001004) (readonly)> <HiddenControl(startDate=2014-04-02T18:17:02+02:00) (readonly)> <HiddenControl(orderType=MAILBASIC) (readonly)> <HiddenControl(referer=) (readonly)> <HiddenControl(mitarbeiter=0) (readonly)> <HiddenControl(cid=) (readonly)> <HiddenControl(pwdstrength=inaktiv) (readonly)> <HiddenControl(pwdstrength2=inaktiv) (readonly)> <HiddenControl(altDomain=) (readonly)> <HiddenControl(pidUrlValue=) (readonly)> <HiddenControl(epidUrlValue=) (readonly)> <HiddenControl(ipidUrlValue=) (readonly)> <HiddenControl(pcUrlValue=) (readonly)> <HiddenControl(subpcUrlValue=) (readonly)> <HiddenControl(scpacoUrlValue=) (readonly)> <HiddenControl(scevidUrlValue=) (readonly)> <HiddenControl(ccUrlValue=) (readonly)> <HiddenControl(pidCookieValue=) (readonly)> <HiddenControl(epidCookieValue=) (readonly)> <HiddenControl(ipidCookieValue=) (readonly)> <HiddenControl(scevidCookieValue=) (readonly)> <HiddenControl(scpacoCookieValue=) (readonly)> <HiddenControl(subpcCookieValue=) (readonly)> <HiddenControl(pcCookieValue=) (readonly)>> Code: browser.form["email"] = "[email protected]" Output: Traceback (most recent call last): File "C:\Users\Lucas\Documents\MEGAsync_Python\Hitnews generator\email freenet.py", line 47, in <module> browser.form["email"] = "[email protected]" #Kontaktemailadresse File "build\bdist.win32\egg\mechanize\_form.py", line 2780, in __setitem__ control = self.find_control(name) File "build\bdist.win32\egg\mechanize\_form.py", line 3101, in find_control return self._find_control(name, type, kind, id, label, predicate, nr) File "build\bdist.win32\egg\mechanize\_form.py", line 3185, in _find_control raise ControlNotFoundError("no control matching "+description) ControlNotFoundError: no control matching name 'email' A: You should first select the form that you want to use and then specify the element by id. It's called localpart in the webpage that you have referred to. Here's the sample code: import mechanize br = mechanize.Browser() response = br.open("https://reg.webmail.freenet.de/freenet/Registration") # Check response here # : # : form = -1 count = 0 for frm in br.forms(): if str(frm.attrs["id"])=="regForm": form = count break count += 1 # Check if form is not -1 # : # : br.select_form(nr=form) Or, if you know that there is only one form, you could have simply done br.select_form(nr=0) And then, finally: br.form["localpart"] = "[email protected]"
{ "language": "en", "url": "https://stackoverflow.com/questions/22818882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ESP-Touch import to iOS project written in Swift I'm trying to use ESP-Touch SDK for iOS which is written in Objective-C. I've not found any usage guides on official SDK resource only one article on Medium. Does some one have step by step guide how to import and use it?
{ "language": "en", "url": "https://stackoverflow.com/questions/73687933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to upload videos faster to a server? I have captured a 900 MB video and want to transfer it to a server from my PC. I try to upload this with Filezilla, but it takes so long, like few hours, and I have fast Internet connection as well. So are there any free programs that can be installed on the PC and used for fast transfer of videos? Any other suggestions are greatly appreciated. Thanks in advance, Adia:) A: You could for example use Handbreak to encode the video in a smaller format. I'd suggest to use H.264 (x264) as it can produce good quality at low bitrates (to the quality/size ratio is good) and is widely supported. If you're completely unexperienced with this you'll probably need to try around a bit with the options, but Handbreak makes it fairly easy. However, remember the smaller the file the worse the quality in the end. Also it's better if you have good quality in the source material as the compression can usually work more efficiently. A: I'm going to say no. Your limited by the server's net connection and your own Also, a fast internet connection can have different meaning to different people. I have 50mb broadband but someone else might consider 8mb as fast. Plus remember, you uprate is usually around 10x slower than your down rate on your connection. Sometimes more, sometimes less. The alternative to waiting is to transcode your video to a smaller size before uploading
{ "language": "en", "url": "https://stackoverflow.com/questions/5492440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ServiceStack adding roles and permissions with custom AuthUserSession I'm trying to add roles and permissions when a new user is registered. I'm running into the problem that adding to the session roles and permissions does not get persisted to the database. I've written a Custom AuthUserSession and overridden OnAuthenticated. The code below uses the AssignRolesService, and that seems like it would be exactly what I need except for one problem. When the authentication is handled by Facebook auth provider session.UserAuthName is null so I can't call the service. To clarify, all code snippets below are contained within: public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) The suggested way of doing this (from what I found on SO/Google): using (var assignRoles = authService.ResolveService<AssignRolesService>()) { assignRoles.Post(new AssignRoles { UserName = session.UserAuthName, Roles = { RoleNames.Admin } }); } Also tried this but it did not work: session.Roles.Add("user"); session.Permissions.Add("setup"); authService.SaveSession(session); The only thing that I found that seems to work, but seems like a hack is: UserAuth ua = db.GetById<UserAuth>(session.UserAuthId); ua.UserName = user.Email; ua.Roles.Add("user"); ua.Permissions.Add("setup"); db.Save(ua); A: Hi I just figured it out! if just by a a coincidence you're using LoadUserInfo that have a try / catch when you are trying to assign the values, hiding a null reference exception and doing the redirect without doing a re-throw that got fixed just by creating a new List like this: userSession.Roles = new List<string> {"your-role-here"};
{ "language": "en", "url": "https://stackoverflow.com/questions/17715011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Select rows from a table, ignore rows until a field value is encountered Let's say I have a table that contains information about user savings to a thrift society and the assessment of each deposit type as good or bad based on internal logic. How do I select rows from this table so that all preceding rows to the last good row are skipped per user? Before id | user |type | amount ---------------------------- 20 | 98 | good | 40 35 | 98 | bad | 30 62 | 98 | good | 20 89 | 98 | bad | 60 93 | 98 | bad | 10 100 | 99 | good | 20 103 | 99 | good | 22 109 | 99 | good | 220 121 | 99 | bad | 640 193 | 99 | bad | 110 I would like to ignore all records for a user until the last good row is encountered, then subsequent rows can be counted. The rows are ordered by increasing ids which are not consecutive. After id | user |type | amount ---------------------------- 62 | 98 | good | 20 89 | 98 | bad | 60 93 | 98 | bad | 10 100 | 99 | good | 220 121 | 99 | bad | 640 193 | 99 | bad | 110 A: Join the table to a query that returns the maximum id for each user with type = 'good': select t.* from tablename t inner join ( select user, max(id) id from tablename where type = 'good' group by user ) tt on tt.user = t.user and tt.id <= t.id See the demo. Results: | id | user | type | amount | | --- | ---- | ---- | ------ | | 62 | 98 | good | 20 | | 89 | 98 | bad | 60 | | 93 | 98 | bad | 10 | | 109 | 99 | good | 220 | | 121 | 99 | bad | 640 | | 193 | 99 | bad | 110 | A: One method uses a correlated subquery: select t.* from t where t.id >= (select max(t2.id) from t t2 where t2.user = t.user and t2.type = 'good' ); This should have good performance if you have an index on (user, type, id). Based on the phrasing of your question, I am interpreting it as requiring at least one good row. If this is not the case, then the following logic can be used: select t.* from t where t.id >= all (select t2.id from t t2 where t2.user = t.user and t2.type = 'good' ); You can also use window functions: select t.* from (select t.*, max(case when type = 'good' then id end) over (partition by user) as max_good_id from t ) t where id >= max_good_id; A: For MariaDB 10.2+, Window Analytic Functions might be used such as SUM() OVER (PARTITION BY ... ORDER BY ...) WITH T2 AS ( SELECT SUM(CASE WHEN type = 'good' THEN 1 ELSE 0 END) OVER (PARTITION BY user ORDER BY id DESC) AS sum, T.* FROM T ) SELECT id, user, type, amount FROM T2 WHERE ( type = 'good' AND sum = 1 ) OR ( type != 'good' AND sum = 0 ) ORDER BY id; Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/59600207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ggplot2 - Overlay Mean of Each Group I am trying to mimic this lattice plot using ggplot. The data for this plot is lme4::Dyestuff. I am able to plot each of the points in a similar manner, but I am unable to plot the line which represents the mean of each batch. library (lme4) library (ggplot2) ggplot (Dyestuff, aes (Yield, Batch, colour = Batch)) + geom_jitter () Q. How can I add this line using ggplot? Notice also how the batches on the y-axis are ordered by the mean yield of the batch. A: One solution is to use Batch as x values and Yield as y values. Line is added with stat_summary() and argument fun.y=mean to get mean value of Yield. Then coord_flip() is used to get Batch as y axis. To change order of Batch values you can use reorder() function inside the aes() of ggplot(). ggplot (Dyestuff, aes (reorder(Batch,Yield), Yield)) + geom_jitter(aes(colour=Batch))+ stat_summary(fun.y=mean,geom="line",aes(group=1))+ coord_flip()
{ "language": "en", "url": "https://stackoverflow.com/questions/23113502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: php: Unable to update a "lastseen" record on DB I need to update a "last seen" record on database, every time a user logs in. I create the us_lastseen record (type DATETIME), with no positive result. After trying to change its type to VARCHAR, it neither records the actual time so I guess the error is on the piece of code: $now = date("Y-m-d H:i:s"); $lastSeen= mysqli_query($con, "UPDATE ws_users SET us_lastseen=$now WHERE us_id=$user_id"); I have also tried: $lastSeen= mysqli_query($con, "UPDATE ws_users SET us_lastseen=GETDATE() WHERE us_id=$user_id"); A: Use the DATETIME type and the following code : $lastSeen= mysqli_query($con, "UPDATE ws_users SET us_lastseen=NOW() WHERE us_id=$user_id"); Or add quotes : $now = date("Y-m-d H:i:s"); $lastSeen= mysqli_query($con, "UPDATE ws_users SET us_lastseen='$now' WHERE us_id=$user_id"); You should debug your query and execute it to see if it throws an error (using phpmyadmin i.e.)
{ "language": "en", "url": "https://stackoverflow.com/questions/32440221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ffmpeg why is output video contrast / brightness too bright? I have a .mov file which I run through ffmpeg to create HLS segments / chunks. However, when I playback the HLS video it is too bright. For a sanity check, I ran the same .mov video file through the FlowPlayer processing pipeline and the results were the same, the output video is too bright! I have a number of videos. Most do not have this problem but some (and only some) of the .mov files exhibit this issue. A broken video stream reports (see below for full output): Stream #0:0[0x1](und): Video: hevc (Main 10) (hvc1 / 0x31637668), yuv420p10le(tv, bt2020nc/bt2020/arib-std-b67), 1920x1080, 8507 kb/s, 29.98 fps, 29.97 tbr, 600 tbn (default) A working video stream reports (see below for full output): Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 3840x2160, 45457 kb/s, 29.99 fps, 29.97 tbr, 600 tbn (default) Is this something to do with hevc v h264 (whatever they mean)? BTW I am using the native HTML5 video player in conjunction with hls.js to playback the videos. How do I fix this? TIA Here is my ffmpeg command: ffmpeg -i "rgb.mov" \ -v warning -preset ultrafast -g 59.96 -sc_threshold 0 \ -map 0:0 -map 0:0 \ -s:v:0 1920x1080 -c:v:0 libx264 -b:v:0 4521k \ -s:v:1 1920x1080 -c:v:1 libx264 -b:v:1 7347k \ -var_stream_map "v:0 v:1" \ -master_pl_name master.m3u8 -f hls \ -hls_time 6 -hls_list_size 0 -hls_playlist_type vod \ -hls_segment_filename "hls/v%v/chunk%d.ts" "hls/v%v/index.m3u8" And here are some screenshots showing the original video in comparison to the output video. ORIGINAL: OUTPUT: For the problem video ffmpeg -i "rgb.mov" -hide_banner gives: Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'rgb.mov': Metadata: major_brand : qt minor_version : 0 compatible_brands: qt creation_time : 2021-08-03T11:23:40.000000Z com.apple.quicktime.location.accuracy.horizontal: 3.594173 com.apple.quicktime.location.ISO6709: +51.5483+000.1628+000.459/ com.apple.quicktime.make: Apple com.apple.quicktime.model: iPhone 12 Pro com.apple.quicktime.software: 14.7.1 com.apple.quicktime.creationdate: 2021-08-03T12:23:40+0100 Duration: 00:00:54.54, start: 0.000000, bitrate: 8730 kb/s Stream #0:0[0x1](und): Video: hevc (Main 10) (hvc1 / 0x31637668), yuv420p10le(tv, bt2020nc/bt2020/arib-std-b67), 1920x1080, 8507 kb/s, 29.98 fps, 29.97 tbr, 600 tbn (default) Metadata: creation_time : 2021-08-03T11:23:40.000000Z handler_name : Core Media Video vendor_id : [0][0][0][0] encoder : HEVC Side data: DOVI configuration record: version: 1.0, profile: 8, level: 4, rpu flag: 1, el flag: 0, bl flag: 1, compatibility id: 4 Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 172 kb/s (default) Metadata: creation_time : 2021-08-03T11:23:40.000000Z handler_name : Core Media Audio vendor_id : [0][0][0][0] Stream #0:2[0x3](und): Data: none (mebx / 0x7862656D), 0 kb/s (default) Metadata: creation_time : 2021-08-03T11:23:40.000000Z handler_name : Core Media Metadata Stream #0:3[0x4](und): Data: none (mebx / 0x7862656D), 0 kb/s (default) Metadata: creation_time : 2021-08-03T11:23:40.000000Z handler_name : Core Media Metadata Stream #0:4[0x5](und): Data: none (mebx / 0x7862656D), 34 kb/s (default) Metadata: creation_time : 2021-08-03T11:23:40.000000Z handler_name : Core Media Metadata At least one output file must be specified For a working video ffmpeg -i "rgb.mov" -hide_banner gives: Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'rgb.mov': Metadata: major_brand : qt minor_version : 0 compatible_brands: qt creation_time : 2021-12-01T10:53:47.000000Z com.apple.quicktime.location.accuracy.horizontal: 4.785777 com.apple.quicktime.location.ISO6709: +51.5485+000.1627+012.533/ com.apple.quicktime.make: Apple com.apple.quicktime.model: iPhone 12 Pro com.apple.quicktime.software: 14.8.1 com.apple.quicktime.creationdate: 2021-12-01T10:53:47+0000 Duration: 00:00:36.35, start: 0.000000, bitrate: 45692 kb/s Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 3840x2160, 45457 kb/s, 29.99 fps, 29.97 tbr, 600 tbn (default) Metadata: creation_time : 2021-12-01T10:53:47.000000Z handler_name : Core Media Video vendor_id : [0][0][0][0] encoder : H.264 Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 188 kb/s (default) Metadata: creation_time : 2021-12-01T10:53:47.000000Z handler_name : Core Media Audio vendor_id : [0][0][0][0] Stream #0:2[0x3](und): Data: none (mebx / 0x7862656D), 0 kb/s (default) Metadata: creation_time : 2021-12-01T10:53:47.000000Z handler_name : Core Media Metadata Stream #0:3[0x4](und): Data: none (mebx / 0x7862656D), 0 kb/s (default) Metadata: creation_time : 2021-12-01T10:53:47.000000Z handler_name : Core Media Metadata Stream #0:4[0x5](und): Data: none (mebx / 0x7862656D), 34 kb/s (default) Metadata: creation_time : 2021-12-01T10:53:47.000000Z handler_name : Core Media Metadata At least one output file must be specified A: caniuse.com explains that: The High Efficiency Video Coding (HEVC) compression standard is a video compression format intended to succeed H.264 and further reveals that browser support for HEVC is currently very poor. @Gyan comments that: Your source video is HDR. You'll have to tonemap it to SDR. Now I assume @Gyan knows it HDR based on the fact that its using HEVC. This article explains HDR (High Dynamic Range) and talks in detail how it impacts brightness, color and contrast. Finally, this article explains that HDR looks bad - e.g. brightness, contrast and color issues - on devices that do not support HDR. Thankfully it also gives an ffmpeg fix by using this filter: -vf zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p Adding this flag to my existing ffmpeg command did the HDR to SDR (Standard Dynamic Range) conversion / tonemap, making it work on Chrome and fixing my problem. NOTE: Detecting HDR is an issue in its own right so I won't cover that here but please refer to this link
{ "language": "en", "url": "https://stackoverflow.com/questions/70544342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to print "a/b" where a and b are numeric value in JavaScript. I dont want to print the resultant value how to print "a/b" where a and b are numeric value in JavaScript. I dont want to print the resultant value if a=5,b=10 Output: 5/10 I know how to solve in Java but in JavaScript the var datatype automatically detect the type of value and perform calculation. Removing the decimal points from the number. A: So just add them as strings. var out = a + "/" + b; or use toString() var out = a.toString() + b.toString();
{ "language": "en", "url": "https://stackoverflow.com/questions/37436803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to merge array of keys and arrays of values into an object? I have the following arrays: var a = ["F", "M"]; var b = ["female", "male"]; var c = ["fa-female", "fa-male"]; and I am able to assign b to a using for loop with: ans[a[i]] = values[i]; // { M: "male", F: "female" } how would I go about adding the third array and assign it to a as well? { M: {"male", "fa-male"}, F: {"female", "fa-female"} } or something similar? EDIT: Result could either be an array or an object. A: Using Object.fromEntries(), you can build an array of [key, value] pairs by mapping (.map()) each key (ie: value) from a to an array of values from the same index from all the other arrays: const a = ["F", "M"]; const b = ["female", "male"]; const c = ["fa-female", "fa-male"]; const buildObj = (keys, ...values) => Object.fromEntries(keys.map( (key, i) => [key, values.map(arr => arr[i])] )); const res = buildObj(a, b, c); console.log(res); Object.fromEntries() has limited browser support, however, it can easily be polyfilled. Alternatively, instead of using an object, you could use a Map, which would remove the need of .fromEntries(): const a = ["F", "M"]; const b = ["female", "male"]; const c = ["fa-female", "fa-male"]; const buildMap = (keys, ...values) => new Map(keys.map( (key, i) => [key, values.map(arr => arr[i])] )); const res = buildMap(a, b, c); console.log("See browser console:", res); // see browser console for output A: use this one. var a = ["F", "M"]; var b = ["female", "male"]; var c = ["fa-female", "fa-male"]; var resultArray = []; for(var i = 0; i < a.length; i++) { resultArray [a[i]] = [b[i], c[i]]; } A: You could combine your arrays to form key/value pairs for Object.fromEntries: Object.fromEntries([['M', 'male'], ['F', 'female']]); //=> {M: 'male', F: 'female'} However Object.fromEntries does not handle collisions: Object.fromEntries([['M', 'male'], ['F', 'female'], ['F', 'fa-female']]); //=> {M: 'male', F: 'fa-female'} As you can see, the previous value for F just got overridden :/ We can build a custom fromEntries function that puts values into arrays: const fromEntries = pairs => pairs.reduce((obj, [k, v]) => ({ ...obj, [k]: k in obj ? [].concat(obj[k], v) : [v] }), {}); fromEntries([['M', 'male'], ['M', 'fa-male'], ['F', 'female'], ['F', 'fa-female']]); //=> {M: ["male", "fa-male"], F: ["female", "fa-female"]} How do you create key/value pairs then? One possible solution: zip const zip = (x, y) => x.map((v, i) => [v, y[i]]); zip(['F', 'M'], ['female', 'male']); //=> [["F", "female"], ["M", "male"]] So to produce all pairs (and your final object) fromEntries([ ...zip(['F', 'M'], ['female', 'male']), ...zip(['F', 'M'], ['fa-female', 'fa-male']) ]); A: var a = ["male","female"]; var b = ["m","f"]; var c = ["fa male","fa female"]; var result = a.reduce((res,val,key) => { var temp = [b,c]; res[val] = temp.map((v) => v[key]); return res; },{}); This is bit expensive. It is a nested loop. A: Here is one line with forEach. Another way using reduce and Map. var a = ["F", "M"]; var b = ["female", "male"]; var c = ["fa-female", "fa-male"]; const ans = {}; a.forEach((key, i) => (ans[key] = [b[i], c[i]])); console.log(ans) // Alternate way var ans2 = Object.fromEntries( a.reduce((acc, curr, i) => acc.set(curr, [b[i], c[i]]), new Map()) ); console.log(ans2); A: A solution using map and filter var a = ["M", "F"]; var b = ["female", "male"]; var c = ["fa-female", "fa-male"]; const bAndC = b.concat(c); let returnObj = {}; a.map(category => { let catArray = [] if(category === 'F') { catArray = bAndC.filter(item => item.includes('female')); } else { catArray = bAndC.filter(item => item.includes('male') && !item.includes('female')); } return returnObj[category] = catArray; });
{ "language": "en", "url": "https://stackoverflow.com/questions/59997461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Full date varchar to date I need convert a varchar field, to date. My varchar look like this: Jan 11 17:18:53 +0000 2011 I need: 2011-01-11 Any ideas? I tried with: DATE_FORMAT(STR_TO_DATE(my_field, '%Y-%m-%d'), '%Y-%m-%d') mydate but this returns NULL. EDIT - MORE DETAILS: Query (string data_field): SELECT date_field FROM my_table LIMIT 1; +--------------------------------+ | date_field | +--------------------------------+ | Tue Jan 11 17:18:53 +0000 2011 | +--------------------------------+ 1 row in set (0.00 sec) I tried: SELECT STR_TO_DATE(date_field, '%Y') FROM my_table LIMIT 1; +---------------------------------------+ | STR_TO_DATE(date_field, '%Y-%m-%d') | +---------------------------------------+ | NULL | +---------------------------------------+ 1 row in set, 1 warning (0.00 sec) // Other query SELECT DATE_FORMAT(STR_TO_DATE(my_field, '%b %d %H:%i:%s +0000 %Y'), '%Y-%m-%d') FROM my_tableLIMIT 1; +-------------------------------------------------------------------------- ----------+ | DATE_FORMAT(STR_TO_DATE(my_field, '%b %d %H:%i:%s +0000 %Y'), '%Y-%m-%d') | +-------------------------------------------------------------------------- ----------+ | NULL | +------------------------------------------------------------------------- ----------+ 1 row in set, 1 warning (0.00 sec) ------- EDIT FINAL ------- SOLUTION!! YEYYY!! In the response of @paul, he's recommend me try this: DATE(STR_TO_DATE(my_field, '%b %d %H:%i:%s +0000 %Y')) And this works correctly! Message for all proyects managers and developers: NEVER save dates in varchars fields PLEASE!!!! Thanks for everyone! A: If the +0000 part is always the same and doesn't matter, you can use: DATE(STR_TO_DATE(my_field, '%b %d %H:%i:%s +0000 %Y')) The used specifiers here are: Specifier | Description ----------|------------ %b | Abbreviated month name (Jan..Dec) %d | Day of the month, numeric (00..31) %H | Hour (00..23) %i | Minutes, numeric (00..59) %s | Seconds (00..59) %Y | Year, numeric, four digits See the full list of specifiers in the documentation under DATE_FORMAT() A: SELECT DATE_FORMAT(STR_TO_DATE('Jan 11 17:18:53 +0000 2011 ', '%b %d %H:%i:%s +0000 %Y'), '%Y-%m-%d'); A: I don't think that +0000 is a fixed number. so i would use Select STR_TO_DATE('Jan 11 17:18:53 +0000 2011','%b %e %H:%i:%s +%f %Y') A: You can use following query to get the required result: select TO_DATE('Jan 11 17:18:53 +0000 2011', 'Mon DD HH24:MI:SS +0000 YYYY') For more formatters you refer to following link: https://www.postgresql.org/docs/9.0/functions-formatting.html
{ "language": "en", "url": "https://stackoverflow.com/questions/57295944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I Call SmartContract Token ERC20, Why Show Hashing Output? I do not know why with this, even though in the previous version (web3 + Metamask) can issue real data. But now used as hashing (output). I took the example in the code and output below (to get the TotalSupply on the ERC20 Token): Output : 0x18160ddd const contractInstance = web3.eth.contract(contractAbi).at(contractAddress); const total_supply = contractInstance.totalSupply.getData(); console.log(total_supply); How to showing real data? In a sense it doesn't come out hashing. Thanks A: .getData() returns the ABI-encoded input you would have to send to the smart contract to invoke that method. If you want to actually call the smart contract, use .call() instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/57760940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: simple captcha error TypeError can't convert nil into Integer i am using rails 3.0.2 and ruby 2.0.0 with simple captcha gem. Gemfile - gem 'simple_captcha', :git => 'git://github.com/galetahub/simple-captcha.git' View - Verification code:<%= show_simple_captcha :label => "Please type the verification code", :image_style => "simply_green", :object => "foo" %> but captcha image is not showing in view. Every time i am getting this error in rails console - Started GET "/simple_captcha?code=d3423b2321c833f8974c50e34528603f111c0d40&time=1399313320" for 127.0.0.1 at 2014-05-05 23:38:41 +0530 TypeError (can't convert nil into Integer) I also tried following this blog but it did not work. Controller:- def contact if request.post? @contact = Contact.new(params[:contact]) if @contact.valid_with_captcha? @contact.save_with_captcha flash[:title] = "Thank you" else flash[:title] = "Sorry" end redirect_to contact_us_path else @contact = Contact.new end end Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/23479103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I allocate array of objects in Java? I've been allocating arrays using the following syntax while going through some Java tutorials so far: // Ok, all the elements are zero upon creation int[] a = new int[5]; // I can set all the elements however I want! for (int i = 0; i < a.length; i++) a[i] = i+1 But since when I started using a class, things have been confusing me: class Employee { public Employee(String name, int age) { emp_name = n; emp_age = a; } void setName(String name) { emp_name = name; } void setAge(int age) { emp_age = age; } private String emp_name; private String emp_age; } I use this class in the main function like the following: Employee[] staff = new Employee[3]; This line should give me an array of three objects default initialized by the constructor as I assume. When I do the following I get an exception on the runtime. staff[0].setName("Test"); In C++, this has been be fairy simple which doesn't require an extra new: Employee *e[3]; So, upon further searching something tells me that I still need to allocate memory for each of the elements in array to actually start using them. If so, then what was the purpose of using new operator? Doesn't it already allocate memory for the array? How come this doesn't happen with int array? A: When you create an array of Objects, you create an array full of null objects. The array is full of "nothingness". An Employee will not be created until you explicitly create one. Employee[] staff = new Employee[3]; At this point your array looks like: [null] [null] [null] You can then create an Employee by doing: staff[0] = new Employee(); At this point, your default Employee constructor is called and your array now has an Employee object in the first position: [Employee1][null][null] Now that you have an actual Employee in the first position, you should be able to call: staff[0].setName("Test"); Update: In regard to the question: what was the purpose of using new operator? Doesn't it already allocate memory for the array? How come this doesn't happen with int array? Similar questions were already asked here and here. In short, when you create the array of Objects, you really create an array of references. At first, all these references just point to null objects. When you do staff[0] = new Employee();, you are in essence doing two things: * *Creating and allocating memory for a "new" Employee *Telling staff[0] to now point to the new Employee object instead of null A: In Java, all "objects" are actually just references (pointers, sort of). So you are correct in assuming that Java auto-initializes the values in the array, but in your second array, you have an array of references, which are basically memory addresses, and therefore are initialized to null. You are getting your exception because you are calling a method on a null reference. Also, notice that when you created an array of primitives, you are using the assignment operator with the different indices in the array. In your example with objects, you are just immediately using the values in the array, not assigning them. So technically, what you were doing in the primitive array example can be done with object arrays, since it is simple assignment. A: In Java, when you create an array of objects, the default values of every entry in the array is null. There are no constructors being called. You'll have to loop over the array and create an object for each entry. for example for(int i=0; i<staff.length; i++){ staff[i] = new Employee("name" + i, 20); }
{ "language": "en", "url": "https://stackoverflow.com/questions/31394904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java HashMultiMap Storing Issue I am using HashMultiMap in my code. My HashMultiMap structure is like, Key1 -> Value11 -> Value12 -> Value13 .... Key2 -> Value21 -> Value22 .... Now, I want if key1 has same values (example: value11 = value12) then keep (or do not store) only one copy of the value (example: keep only value11 or do not store value12). Can anybody help me how to achieve this with an efficient (faster) way. A: According to the HashMultiMap Javadoc, you chose the right MultiMap for that purpose: The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect. Now, you only have to make sure that equals() (and hashCode()) is implemented correctly on your values. I don't think you should worry about a faster way to do this. The HashMultiMap should be implemented pretty efficiently. A: If you want this behavior why not use a structure like: Map<Key,Set<Values>> myMap = new HashMap<Key,Set<Values>>(); EDIT: If you want to use the HashMultiMap i would recommend the one bellow Implementation of the MultiMap interface that uses a HashMap for the map and HashSets for automatically created sets. http://people.csail.mit.edu/milch/blog/apidocs/common/HashMultiMap.html
{ "language": "en", "url": "https://stackoverflow.com/questions/9851549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to connect to file on same Tomcat server at server startup from within ServletContext I am trying to connect to a file(say index.jsp) on my tomcat server at server startup from within the context initializer method. What is the best way to do this? In essence I want to make an HttpConnection to a file on the same server when the server is starting up. Thanks! A: There is no port defined for a servlet, so there's no place to query. Tomcat can have 26 HTTP connectors listening on 26 different TCP ports. You are trying to be smarter than the system by picking the port number from some HTTP request because HTTP requests of course have a destination port - however that's just that: the destination port used for that particular HTTP request, and it must be known before writing the HTTP request to the socket. Chicken and egg. By the way, why do you need a port number? I mean, in a reverse-proxy deployment, for example, the port number is only used by the reverse proxy and should not be used to make hyperlinks, for example. So, here are some advices: the Internet address of your application (protocol, hostname, port) is deployment configuration that cannot be guessed inside the application itself. Similarly, low level connection details like port numbers are server configuration that still can't be guessed inside the application and must be passed instead. These pieces of configuration are usually passed via: * *a table in the database *a configuration file on the filesystem *environment variables The most recent trend is employing environment variables, that are used to pass configuration bits between programs written in many different languages and deployed in a variety of environments (virtual machines, containers)
{ "language": "en", "url": "https://stackoverflow.com/questions/32233906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What might cause a 503 Service Unavailable for reports area of an asp.net mvc3 application? We're switching our MVC3 application from IIS 6 to 7.5. I'm working on setting up my local development environment on Windows 7. The app works fine for the most part, but I just discovered that ONE out of the many different MVC Areas I have doesn't work. When I try hit an action under this area, I get a 503 Service Unavailable error back. This does not happen anywhere else in my application. * *There is only one application pool for the whole website. *MVC 3 *.Net 4.0 *64 bit *Failed request tracing doesn't see these requests. *There is nothing relevant in the Windows application or system logs. *The area works fine under visual studio 2010 cassini, problem happens when I run it under local iis 7.5 (not express) *App pool isn't crashing or otherwise stopped *There's nothing in my ELMAH log *Everyone full control on entire tree in the filesystem security *The url is http://localhost/reports I'm totally stumped. I can't find any evidence that IIS is even getting the request at all. Is there some other log file beside the ones I listed? [Update] Is there any way to view the http.sys URL reservations? I have found some talk about SQL Reporting services calling dibs on /Reports url. A: Check the account / IIS -> Application Pool -> Advanced Settings -> Process Model -> Identity under which your pool is running. I had my password changed, and didn't get a log on invalid password, but rather assemlby load failure, which in turn caused the app pool to be shut off, and the "503 Service Unavailable" was given to the user. A: I figured it out. It was due to SQL Reporting services having reserved the http://+:80/Reports url in http.sys. I didn't actually have reporting services installed, but it apparently still reserved the url. I fixed it with the following command: netsh http delete urlacl url=http://+:80/Reports A: Another solution is, I had the same problem with my http://ApplicationURL/Reports And yes the SSRS was the issue. A better solution for this one is * *OpenReporting Services Configuration Manager. *Connect to your local service usually COMPUTERNAME\MSSQLSERVER *Go to "Report Manager URL" Option *Modify your virtual directory with another name instead of Reports. Just remember with this change you reports for SSRS will be in the name that you defined. Carlos A: Are you using any ODBC or other components in this area that you are not anywhere else? I have experienced this error (or one similar, can't remember off the top of my head) when running the app pool in 64bit mode and the underlying calls are referencing at 32bit 'something'. You could try enabling 32bit applications in the application pool settings to see if it affects the outcome. A: As mentioned before it is related to SQL Reporting services You can follow this approach to fix this problem: Log on to the server that hosts SSRS. Go to Start > Programs > SQL Server 2008 R2 > Configuration Tools > Reporting Services Configuration Manager Connect to the server in question (usually your local server) Go to the Web Service URL section Change the TCP port to an open port other than port 80 (81 happened to work on my server) and hit Apply Go to the Report Manager URL section Click Advanced Click the entry with a TCP port of 80 and then click the Edit button. Change the TCP Port entry to the same thing you changed it to in the Web Service URL section previously and Click OK. Click OK again.
{ "language": "en", "url": "https://stackoverflow.com/questions/8139778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Java Cross Platform File Operations I developed a software in netbeans + Ubuntu and then converted the runnable .jar file of netbeans to .exe file using a converter software. I used: File f = new File("./dir/fileName"); which works fine in Ubuntu but it gives an error in Windows, because the directory pattern of both OSs are different. A: Absolute paths should not be hardcoded. They should be read e.g. from a config file or user input. Then you can use the NIO.2 File API to create your file paths: Paths.get(...) (java.io.File is a legacy API). In your case it could be: Path filePath = Paths.get("dir", "fileName"); A: I used: File f = new File("./dir/fileName") which works fine in Ubuntu but it gives error in Windows, bcz the directory pattern of both os are different. It is presumably failing because that file doesn't exist at that path. Note that it is a relative path, so the problem could have been that the the path could not be resolved from the current directory ... because the current directory was not what the application was expecting. In fact, it is perfectly fine to use forward slashes in pathnames in Java on Window. That's because at the OS level, Windows accepts both / and \ as path separators. (It doesn't work in the other direction though. UNIX, Linux and MacOS do not accept backslash as a pathname separator.) However Puce's advice is mostly sound: * *It is inadvisable to hard-code paths into your application. Put them into a config file. *Use the NIO2 Path and Paths APIs in preference to File. If you need to assemble paths from their component parts, these APIs offer clean ways to do it while hiding the details of path separators. The APIs are also more consistent than File, and give better diagnostics. But: if you do need to get the pathname separator, File.separator is an acceptable way to get it. Calling FileSystem.getSeparator() may be better, but you will only see a difference if your application is using different FileSystem objects for different file systems with different separators. A: You can use File.separator as you can see in api docs: https://docs.oracle.com/javase/8/docs/api/java/io/File.html
{ "language": "en", "url": "https://stackoverflow.com/questions/57494210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python while loop neither works nor breaks My code and the output is as below. I expected loop but it doesn't work and it doesn't break either. Still running. Can someone fix the code and teach why it doesn't loop ? I know I can make it loop if I use for instead while. But I want to know why. code: absent = [2,5] student = 1 while student < 11: if student in absent : continue print(f"student {student} is attended!") student += 1 output: student 1 is attended! A: I'm pretty sure it is because of the continue and absent of the break. It gets stuck in an infinite loop. You could do it like this: absent = [2,5] student = 1 while student < 11: if student not in absent: print(f"student {student} is attended!") student += 1 Here some info about the continue and break in a loop: https://www.programiz.com/python-programming/break-continue A: when student is 1,do: print(f"student {student} is attended!") student += 1 but when student is 2, if-statement is True, continue works and passes: print(f"student {student} is attended!") student += 1" and 3,4,5..10 don't go on. A: Your code runs infinite times because at first iteration if condition fails and prints the output and increments the student. In second iteration if condition will be true then it continues(which skips all the statements below the continue statement and moves to the loop) so that your student will be always 2. try this: absent = [2, 5] student = 1 while student < 11: if student in absent: student += 1 else: print(f"student {student} is attended!") student += 1
{ "language": "en", "url": "https://stackoverflow.com/questions/74078585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python/Linux - Check if some other app is fullscreen I have developed a controller for RGB LEDs on the back of my monitor, and I would like to control them so that they match the average color on the screen when I have a full screen app running, such as a movie. I already have the whole controller up and running in the background, but I got stuck trying to figure out how to determine if there is some app running full-screen or not. How could i do it? I am using python3 on Debian testing. Thanks a lot for any help! A: I found an answer here and modified it a bit to make it more usable. Here is my code that works on gnome. You might have to adjust the escaped windows names for other gdms. import Xlib.display #Find out if fullscreen app is running screen = Xlib.display.Display().screen() root_win = screen.root def is_fullscreen(): #cycle through all windows for window in root_win.query_tree()._data['children']: width = window.get_geometry()._data["width"] height = window.get_geometry()._data["height"] #if window is full screen, check it the window name if width == screen.width_in_pixels and height == screen.height_in_pixels: if window.get_wm_name() in ['Media viewer', 'mutter guard window']: continue #return true if window name is not one of the gnome windows return True #if we reach this, no fs window is open return False
{ "language": "en", "url": "https://stackoverflow.com/questions/67054535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Layout behind status bar - Android Lollipop I want in my application to be able to implement this effect: where the status bar is semi transparent and the layout is behind the status bar. Every example that I've read on the subject, was mainly associated with the navigation drawer and mostly used the ScrimInsetScrollView (or ScrimInsetsFrameLayout). I tried implementing this with ScrimInsetsFrameLayout. Basically I have an activity that holds a fragment, and this is my layout (the fragment is later added to the container in the activity's onCreate method): <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true" > <com.test.app.widget.ScrimInsetsFrameLayout xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:insetForeground="#4000" android:id="@+id/container" ></com.test.app.widget.ScrimInsetsFrameLayout> </FrameLayout> And also I've set the android:statusBarColor to transparent in themes. The solution does not work for me. Apparently I am doing something wrong here. Can someone point out where I am mistaken? A: Have you tried @Override public void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); as described in the Android documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/28945860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Does Java JDK have a GUI based program like Visual Basics or Android Studio? So I was learning Java with command prompt to compile my x.java file, but now I use Android Studio to use java to make apps. Is there a program like Android Studio or Visual Basics program where you write and test your java code? A: I was looking for an IDE. Such as Netbeans.
{ "language": "en", "url": "https://stackoverflow.com/questions/37896256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Exporting Dart APIs to JavaScript, without a Dart VM I'd like to export a Dart API to JavaScript on browsers without a Dart VM. For example, given a class A: class A { String name; A(); A.withName(this.name); } I'd like to create a JavaScript object using the exported API with: var a = new A(); An answer to my previous question pointed me to js-interop. However, I'm not able to get the expected result when working through the README example. It appears that my Dart library isn't being exported into JavaScript. pubspec.yaml: name: interop description: > A library useful for applications or for sharing on pub.dartlang.org. version: 0.0.1 dev_dependencies: unittest: any dependencies: js: git: url: git://github.com/dart-lang/js-interop.git transformers: - js - js/initializer example/main.dart library main: import 'package:js/js.dart'; main() { initializeJavaScript(); } lib/a.dart library a; import 'package:js/js.dart'; @Export() class A { String name; A(); A.withName(this.name); } index.html <html> <head> <script src="packages/js/interop.js"></script> </head> <body> <script type="application/dart" src="build/example/main.dart"></script> </body> </html> (It's not clear where the src attribute of that last script tag should point. I've tried using /example/main.dart as well, which doesn't change my result.) I expected to be able to open a console after compiling (Tool -> Pub Build) and loading index.html, and then do this: var a = new dart.a.A(); However, I get this instead: "Cannot read property 'A' of undefined". In other words, dart.a is undefined. The inclusion of raw Dart script in index.html suggests that js-interop is intended for a browser with a Dart VM. I tried running index.html on Dartium with the same result. What am I missing? A: The src attribute of the script tag still has to point to a file with a Dart script that contains a main() method. When the application is built to JavaScript using pub build Dart is compiled to JavaScript and can be run in browsers without a Dart VM. A: Yes, it does work on a JavaScript only browser. It turns out the documentation doesn't give all of the steps. Here's what worked for me, starting with a new project. Create a new package project called 'jsout' using (File-> New Project/package). Delete these files: * *test/all_test.dart *example/jsout.dart Edit these files: pubspec.yaml name: jsout description: > A library useful for applications or for sharing on pub.dartlang.org. version: 0.0.1 dev_dependencies: unittest: any dependencies: js: git: url: git://github.com/dart-lang/js-interop.git transformers: - js - js/initializer lib/main.dart part of main; @Export() class A { String name; A(); A.withName(this.name); talk() { print(name); } } Create folder web, and add these files: web/main.dart library main; import 'package:js/js.dart'; part '../lib/jsout.dart'; main() { initializeJavaScript(); } web/index.html <!DOCTYPE html> <html> <head></head> <body> <script src="main.dart_initialize.js"></script> <script src="main.dart.js"></script> </body> </html> After updating these files, load index.html, and open a console: var a = new dart.main.A.withName('foo'); a.talk(); // returns 'foo' This procedure worked as of revision 7afdb.
{ "language": "en", "url": "https://stackoverflow.com/questions/27323539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing a parameter to a $resource? I have a controller that that looks like this: (function() { angular .module("main") .controller("HomeCtrl", ["branchResource", "adalAuthenticationService", HomeCtrl]); function HomeCtrl(branchResource, adalService){ var vm = this; vm.copyrightDate = new Date(); vm.user = adalService.userInfo.userName; // right here, can I insert the vm.user from above // as a parameter to the resource's query? branchResource.query(function (data) { vm.branches = data; }); }}()); The user is authenticated by the time they reach this point in the app. So, the user's info is available. I have a backend API that takes a user's name and returns the names of branches that user is authorized to. I can paste the URL into my browser, along with a valid user name, and get expected results. I'm trying to use that API in my branchResource: (function () { "use strict"; angular .module("common.services") .factory("branchResource", ["$resource", branchResource]); function branchResource($resource){ return $resource("/api/user/GetAllUserBranches?federatedUserName=:user") }}()); My problem, though, is that I don't know how to pass the vm.user to the branchResource from the controller. Can someone point me in the right direction? A: Create the $resource object with: function branchResource($resource){ ̶r̶e̶t̶u̶r̶n̶ ̶$̶r̶e̶s̶o̶u̶r̶c̶e̶(̶"̶/̶a̶p̶i̶/̶u̶s̶e̶r̶/̶G̶e̶t̶A̶l̶l̶U̶s̶e̶r̶B̶r̶a̶n̶c̶h̶e̶s̶?̶f̶e̶d̶e̶r̶a̶t̶e̶d̶U̶s̶e̶r̶N̶a̶m̶e̶=̶:̶u̶s̶e̶r̶"̶)̶ ̶ return $resource("/api/user/GetAllUserBranches") }} Call the $resource object with: branchResource.query({"federatedUserName": vm.user}, function (data) { vm.branches = data; }); //OR vm.branches = branchResource.query({"federatedUserName": vm.user}); It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?. For more information, see AngularJS ngResource $resource API Reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/48013532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is HashTable Delete O(1)? I understand why a HashTable Add is O(1) (however please correct me if I'm wrong): The item being added is always allocated to the first available spot in the backing array. I understand why a Lookup is O(n) (again, please correct me if I'm wrong): You need to walk through the backing array to find the value/key requested, and the running time of this operation will be directly proportional to the size of the collection. However, why, then, is a Delete constant? Seems to me the same principals involved in an Add/Lookup are required. EDIT The MSDN article refers to a scenario where the item requested to be deleted isn't found. It mentions this as being an O(1) operation. A: The worst cases for Insert and Delete are supposed to be O(n), see http://en.wikipedia.org/wiki/Hash_table. When we Insert, we have to check if the value is in the table or not, hence O(n) in the worst case. Just imagine a pathological case when all hash values are the same. Maybe MSDN refers to average complexity. A: O(1) is the best case, and probably the average case if you appropriately size the table. Worst case deletion for a HashTable is O(n).
{ "language": "en", "url": "https://stackoverflow.com/questions/25194551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: R shiny datable with styleColorBar not aligning the data on the left hand side I have the following code and my goal is to add styleColorBar to the WGT column, aligning the yellow bars on the left hand side of the column. df = data.frame(WGT=c(10, 10, 15, 5, 30, 8, 2, 5, 1, 4, 10), STATE=c("NY","NJ","OH","TX","CA","NC","MA","FL","AL","PA","AZ"), stringsAsFactors = F) dft <- datatable(df, rownames= T, options = list(scrollX = T , lengthChange = F , paging =F # this completely hides the Next, Previous and Page number at the bottom of the table , autoWidth = F , pageLength = 20 # this determines how many rows we want to see per page , info = F # this will hide the "Showing 1 of 2..." at the bottom of the table --> https://stackoverflow.com/questions/51730816/remove-showing-1-to-n-of-n-entries-shiny-dt , searching = F # this removes the search box -> https://stackoverflow.com/questions/35624413/remove-search-option-but-leave-search-columns-option )) dft <- dft %>% formatStyle('WGT', background = styleColorBar(df[,'WGT'], 'yellow'), backgroundSize = '100% 80%', backgroundRepeat = 'no-repeat', backgroundPosition = 'left') As you can see, the horizontal yellow bars are instead aligned on the right hand side of the WGT column and I can't figure out why. I checked other similar posts here but I couldn't find an answer to this probably simple question. Thanks A: How about the angle parameter in styleColorBar function? Try this: dft <- dft %>% formatStyle('WGT', background = styleColorBar(df[,'WGT'], 'yellow', angle = -90), backgroundSize = '100% 80%', backgroundRepeat = 'no-repeat', backgroundPosition = 'center') Output :
{ "language": "en", "url": "https://stackoverflow.com/questions/72221815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adjust parents height to fit relative child When in work earlier today I ran into a problem that I'll encounter tomorrow morning, so trying to prepare myself! Essentially, <div class="holder"> <div class="element-1"></div> <div class="element-2"> <img> </div> </div> both elements are displayed side by side with equal with, and are inline block divs. element 2 has a position of relative and i've positioned it so it's half within holder and half out of it, using top: 200px. However, at the moment holder is the height of its largest child, which is element 2 - but it's not taken into account that element-2 has been positioned 200pxs from it's original state, leaving lots of spare space at the bottom of holder! Summary: I want holders height to take into account an element has been moved - hopefully this makes sense? A: Assuming that your codepen would look something like this from your explanations. The solution would be to add margin instead of top on the element 2 and vertically align the first element to top so it sticks to the top border. .element-2 { margin-top: 200px; } .element-1 { vertical-align: top; }
{ "language": "en", "url": "https://stackoverflow.com/questions/47166964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: do we have map like collections in nodejs as in java? Do we have any colllections like map in nodejs. I would like to have a collection which can store my key value. Is there something like the same in nodejs A: Map was added to the ECMAScript standard library in ECMAScript 2015. This is not just "something like a map", this is a map. Here is a question with an answer of mine that uses a Map: How to declare Hash.new(0) with 0 default value for counting objects in JavaScript?
{ "language": "en", "url": "https://stackoverflow.com/questions/61745221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Mysql event schedule creation SQL error I'm trying to build a scheduled query but something is triggering an error, and it's not clear what's wrong. Event scheduling is a bit new to me but I have plenty others working, so there's some piece of information I'm missing: DELIMITER // CREATE EVENT gen_firstJoins ON SCHEDULE EVERY 1 HOUR ON COMPLETION PRESERVE DO BEGIN CREATE TEMPORARY TABLE tmp_joins SELECT username, MIN(player_join) AS player_join FROM joins GROUP BY username ORDER BY player_join ASC ; TRUNCATE joins_first; INSERT INTO joins_first (username, player_join) SELECT username, player_join FROM tmp_joins GROUP BY username ORDER BY player_join; END// DELIMITER ; Error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ame, MIN(player_join) AS player_join FROM joins GROUP BY username ORDER BY playe' at line 6 A: Answered in comments, so reposting comment as answer Re: https://meta.stackexchange.com/questions/90263/unanswered-question-answered-in-comments You may have a hidden character / line feed etc? Just select and delete the entire work "username" (after the SELECT) and try retyping.
{ "language": "en", "url": "https://stackoverflow.com/questions/12084600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display HTML with qTip2 I've created a minimized sponsor section with small (50x50 sized) thumbnails through the List Category Posts WordPress plug-in on my site (can be seen here). This plug-in simply displays posts from certain categories anywhere on your website. I now want to add a tooltip on hovering the image, which would essentially display the posts the_content();. For the tooltip I'd be using qTip2, since this seems to be the best tooltip solution. My problem occour, when nothing happens on hovering. Can you spot the error? I've been battling this problem for 3 straight days now. When looking at the HTML, think as if, you couldn't modify it. The code can be found on JSFIDDLE (I hope the code is valid, but I'm not sure, since this is the first time I'm using JSFIDDLE). A: The problem that you are having is your selector for the content of the Qtip. You have $(this).next('div:hidden'), but it appears that your text is actually in a <p> tag. EDIT: Just saw the part about not editing the HTML, you'll just have to revise your selector to choose the next <p> tag. Something like this $(this).parent().next('p')[0].textContent, fiddle EDIT 2: Ideally, I would edit the HTML and do this: Looking through the Qtip2 documentation, the author offers the solution of putting your desired text content into an attribute of the target element. Here is a fiddle demonstrating this. The relevant HTML: <a href="http://dacc.fredrixdesign.com/global-imports-bmw-2/"><img width="50" height="50" src="http://dacc.fredrixdesign.com/wp-content/uploads/bmw-150x150.jpg" class="attachment-50x50 wp-post-image" alt="DACC Sponsor" qtip-content="Hello, I'm text!"/></a> The qTip code: $('.lcp_catlist a img').each(function () { $(this).qtip({ content: $(this).next('div:hidden') }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/15349081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSTableView does not refresh after update I'm stuck with a NSTable refresh problem.... I update a DetailViewController table and do the [self.managedObjectContext save:&error]; When I then hit the back button the table records are not changed even though I reload the table with a NSNotification setting. Now if I go back and update another record and go back after the first updated record reflects the changes made before..... After the app is closed and reopened all the changes are reflected so I know it's saving, just not refreshing. - (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (managedObjectContext == nil) { managedObjectContext = [(APLViewController *)[[UIApplication sharedApplication] delegate] managedObjectContext]; } NSManagedObjectContext *context = managedObjectContext; NSManagedObjectContext *moc = context; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:moc]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setReturnsObjectsAsFaults:NO]; [request setEntity:entityDescription]; NSError *error1 = nil; NSArray *productArray = @[sortDescriptor]; productArray = [[NSMutableArray alloc] initWithArray:[moc executeFetchRequest:request error:&error1 ]]; NSSortDescriptor *sortAZ = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSSortDescriptor *sortZA = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; NSArray *sortedArray = [productArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortAZ, nil]]; NSArray *desortedArray = [productArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortZA, nil]]; _products = sortedArray; [self.tableView reloadData]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/22183636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Fix: Main function is Unreachable - Python 3.5 I'm trying to make a dead-simple bot according to this video: https://www.youtube.com/watch?v=5Jwd69MRYwg The main function that is supposed to be called when a part of the screen changes color simply is not being run at all. I've tried ending the program with "main()" and "if __name__ == '__main__': main()" respectively. Neither have allowed the code to run def restart_game(): time.sleep(1) pyautogui.click(Coordinates.replayBtn) def image_grab(): box = (290, 465, 305, 487) image = image_grab_lib.grab(box) grey = ImageOps.grayscale(image) a = array(grey.getcolors()) print(a.sum()) return a.sum() def main(): restart_game() print("blip") if image_grab() != 577: print("Jump") press_space() time.sleep(1) restart_game() if __name__ == '__main__': main() I expect the main function to run and give print "blip" and "jump", currently running all the other code and entirely skipping the main function. shows what the warning looks like in PyCharm - image A: Your code is unreachable because you have an infinite while loop before main() definition. It's a good practice in applications that require while loop to put it inside if name == 'main' condition after all variables are declared. Like this: if __name__ == '__main__': while True: do_something()
{ "language": "en", "url": "https://stackoverflow.com/questions/56693551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get an item from object in AsyncStorage saved? I save an object containing user data like email, username, etc. I used AsyncStorage to save them, and when I get them I just see a string when I log or use it in my textInput so how to handle this and just get a specific data like Just Email or Just Username I saved? My Code Sign Up const { username, email, city, mobileNumber, } = this.state; const profileData = { "username": username, "email": email, "city": city, "mobileNumber": mobileNumber } firebase .auth() .createUserWithEmailAndPassword(email, password) .then(async user => { firebase .database() .ref(`users/${user.user.uid}`) .set({ username: username, type: type, email: email, city: city, mobileNumber: mobileNumber, token: fcmToken }); this.props.navigation.navigate("Home"); await AsyncStorage.setItem('@MyProfile:data', JSON.stringify(profileData)).then(() => console.log("Saved")); }).catch(err => console.log(err)); Profile Screen async componentDidMount() { try { await AsyncStorage.getItem('@MyProfile:data') .then(data => this.setState({ data })) .catch(error => console.log('@error' + error)); console.log(this.state.data); // } catch (error) { console.log("@CError", error); } } render(){ return( <View style={styles.logoSection}> {/* <SvgComponent height={100} /> */} <Icon name="ios-contact" size={90} color='#4d8dd6' style={{ marginTop: 9 }} /> <Text style={{ fontSize: 18, color: "#000", margin: 35, marginTop: 7 }}>{this.state.data}</Text> // i wnat just display username here from storage </View> ) } Console console.log(this.state.data); As a string i think: {"username":"user","email":"[email protected]","city":"usercity","mobileNumber":"0597979979"} A: {this.state.data.username} or {this.state.data['username']} But probably in this line inside {this.state.data} you wont have username access in the first render, probably this.state.data will be empty so you need to validate before use this.state.data['username']!
{ "language": "en", "url": "https://stackoverflow.com/questions/56449669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Regex To match string starting and ending with characters I need a regex to perform search in eclipse to match all strings that start with ${ and end with } but should not have pageContext between the two. For Example ${requestScope.user} ${sessionScope.user} should match but ${pageContext.request} should not After all efforts I have made this regex (\${) which matches strings starting with ${ but some how doesn't meet my requirement.any help will be appreciated. A: You may use a negative lookahead to exclude specific matches: \$\{(?!pageContext\.).*?\} ^^^^^^^^^^^^^^^^ The (?!pageContext\.) lookahead will fail all matches where { is followed with pageContext.. Also, you can use [^{}]* instead of .*?. See the regex demo Pattern details: * *\$ - a literal $ *\{ - a literal { *(?!pageContext\.) - fail the match if a pageContext. follows the { immediately *.*? - any 0+ characters other than a newline (or [^{}]* - zero or more characters other than { and }) *\} - a literal }. NOTE: If you need to avoid matching any ${...} substring with pageContext. anywhere inside it, use \$\{(?![^{}]*pageContext\.)[^{}]*\} ^^^^^^^^^ Here, the [^{}]* inside the lookahead will look for pageContext. after any 0+ chars other than { and }. A: Look aheads or look behinds are expensive. You should prefer the optional match trick: \$\{(?:.*pageContext.*|(.*))\} Live Example To avoid confusion let me specify that this will match any string with a "${" prefix and a "}" suffix, but if that string contained "pageContext" the 1st capture will be empty. If the 1st capture is non-empty you have a string matching your criteria.
{ "language": "en", "url": "https://stackoverflow.com/questions/38721623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Generic recursive function in typescript I want to write generic recursive function like below function withChildren< T extends { id?: string; parentId?: string; }, TWithChild extends T & { children: TWithChild[]; } >(parentItem: T, items: T[]): TWithChild { const children = items.filter((ba) => ba.parentId === parentItem.id); return { ...parentItem, children: children.map((child) => withChildren(child, items)), }; } but typescript throw an error Type 'T & { children: (T extends BusinessAreaWithAccess ? BusinessAreaWithChildrenAndAccess : BusinessAreaWithChildren)[]; }' is not assignable to type 'T extends BusinessAreaWithAccess ? BusinessAreaWithChildrenAndAccess : BusinessAreaWithChildren' i have search for the error, but still not found any solution A: TWithChild extends T & ..., meaning if used as explicit type parameter it can union e.g. {a: 1}, you don't know its exact type, so you can't instantiate it. Define it as a known limited generic type, then it'll work type TWithChild<T> = T & {children: TWithChild<T>[]} function withChildren< T extends { id?: string; parentId?: string; } >(parentItem: T, items: T[]): TWithChild<T> { const children = items.filter((ba) => ba.parentId === parentItem.id); return { ...parentItem, children: children.map((child) => withChildren(child, items)), }; } Playground
{ "language": "en", "url": "https://stackoverflow.com/questions/74570237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure `I18n Ally` vscode plugin to read my locals? I am using i18next and react-i18next. i18n Ally v2.8.1. I have one locale file: /locales/en.json Structure of this file: { "pagetitle.home": "Home", "pagetitle.restore": "Restore", "pagetitle.register": "Register" } When hover on code i18n.t('pagetitle.restore') ru: i18n key "en.pagetitle.restore" does not exist(i18n-ally-key-missing) Which config of extension should be? P.S. I cant change locales structure. A: Try changing the .vscode/settings.json to add your "locals" path: { "i18n-ally.localesPaths": ["src/locales"], "i18n-ally.sourceLanguage": "english", } If this does not work, try to add a defaultNamespace to your language file: Example: en.json { "translation": { "login": { "title": "Welcome!", "user": "User", "password": "Password", }, } } Implementation: const {t} = useTranslation(); const title = title: t('login.title') .vscode/settings.json { "i18n-ally.localesPaths": ["src/utils/language"], "i18n-ally.defaultNamespace": "translation", "i18n-ally.sourceLanguage": "english", "i18n-ally.keystyle": "nested" }
{ "language": "en", "url": "https://stackoverflow.com/questions/72015511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PYTHON TKINTER > e = Entry() > e.bind('', function) I am not allowed to add images yet to question posts. Question below: My app currently uses a window that is coded in a class. My ultimate goal is to press enter while entering letters and numbers into an entry widget and press enter, then the function would update text that correlates to a label in my main window. Detailed description below: I cannot figure out how to create and entry and then bind the enter key so that when I run my app, I can click in the entry, type a value and press enter. I see plenty of button references and I can get the button to work, but I am trying to learn how to do things and do not want to rely on buttons in this instance. I saw in some other posts that if you call .get with an entry object, that the python code will just execute it and move on. I tested with a print statement in the function I want to call upon pressing enter, and the print statement appeared in the terminal before I typed anything in the entry widget. I then tried to type and press enter, and nothing would occur. Should I abandon binding the ENTER key and stick with buttons in tkinter as a rule, or is there a proper way to do this? In my code example, you will see up_R is the function I am trying to execute when pressing Enter. If I use up_R(), it executes immediately. If I use up_R, then I get a TCL Error. Specific Partial code located below: def up_R(): print('Makes it here') self.R.update_disp(self.e.get()) self.e.bind('<ENTER>',up_R) The full code is below if required for assistance: #NOAA SPACE WEATHER CONDITIONS from tkinter import * class window: def __init__(self): #main window self.window = Tk() self.window.title('NOAA SPACE WEATHER CONDITIONS') self.window.geometry('800x600') #window organization self.window.grid_rowconfigure(0, weight = 1) self.window.grid_rowconfigure(1, weight = 1) self.window.grid_columnconfigure(0, weight = 1) self.window.grid_columnconfigure(1, weight = 1) #temp entry frame self.e = Entry(self.window) self.e.grid(row = 1, column = 0, sticky=N) self.e.insert(END, 'R entry') #init class R self.R = R() #init class S self.S = S() #init class g self.G = G() #frame for RSG self.frame = Frame(self.window) self.frame.grid(row = 0, column = 0, columnspan = 2, padx=10, pady=10) #disp class R self.rf = Frame(self.frame, highlightbackground='black', highlightcolor='black', highlightthickness=1) self.rf.pack(side = LEFT) self.rl = Label(self.rf, text = self.R.dkey, bg='#caf57a') self.rl.pack(side=TOP) self.rl_lower = Label(self.rf, text= self.R.tile_text, bg='#caf57a') self.rl.pack(side=BOTTOM) #Value update methods # self.R.update_disp(self.e.get()) # #action def up_R(): print('Makes it here') self.R.update_disp(self.e.get()) self.e.bind('<ENTER>',up_R()) #main window call - goes at end of class self.window.mainloop() class R: def __init__(self): d = {'R':'None','R1':'Minor','R2':'Moderate','R3':'Strong','R4':'Severe','R5':'Extreme'} self.dkey = 'R' self.tile_text = d[self.dkey] print(d[self.dkey]) def update_disp(self, dkey): self.dkey = dkey class S: d = {'S1':'Minor','S2':'Moderate','S3':'Strong','S4':'Severe','S5':'Extreme'} pass class G: d = {'G1':'Minor','G2':'Moderate','G3':'Strong','G4':'Severe','G5':'Extreme'} pass t = window() A: The ENTER should be changed with Return, and the function should accept an event Also, don't forget in a 'class' to use self in the method and self.method to call it. def up_R(self, event): print('Makes it here') self.R.update_disp(self.e.get()) self.rl.config(text=self.R.dkey) self.e.bind('<Return>', self.up_R)
{ "language": "en", "url": "https://stackoverflow.com/questions/65535609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does -Namespace do in this script: Get-WmiObject WmiMonitorID -Namespace root\wmi I can't find what this does! Can someone breakdown each part of that script? Get-WmiObject WmiMonitorID -Namespace root\wmi A: Generally, "namespaces" are like directories ... meaning all WMIs (Windows Management Instrumentations) will be associated to a namespace. This allows us to logically group/associate WMI together with higher level concepts. From https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-wmiobject?view=powershell-5.1 The -Namespace parameter: When used with the Class parameter, the Namespace parameter specifies the WMI repository namespace where the specified WMI class is located. When used with the List parameter, it specifies the namespace from which to gather WMI class information. The WmiMonitorID is described as such (here --> https://learn.microsoft.com/en-us/windows/desktop/wmicoreprov/wmimonitorid): The WmiMonitorID WMI class represents the identifying information about a video monitor, such as manufacturer name, year of manufacture, or serial number. The data in this class correspond to data in the Vendor/Product Identification block of Video Input Definition of the Video Electronics Standard Association (VESA) Enhanced Extended Display Identification Data (E-EDID) standard.
{ "language": "en", "url": "https://stackoverflow.com/questions/56675002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android library update cause build time error I have a pretty weird issue. As soon as I update my dependencies this error occures at build time. e: error: Cannot figure out how to save this field into database. You can consider adding a type converter for it. - mBagOfTags in androidx.lifecycle.ViewModel e: error: Cannot find getter for field. - mBagOfTags in androidx.lifecycle.ViewModel e: error: Cannot find getter for field. - mCleared in androidx.lifecycle.ViewModel e: error: Cannot find setter for field. - mBagOfTags in androidx.lifecycle.ViewModel e: error: Cannot find setter for field. - mCleared in androidx.lifecycle.ViewModel e: error: Cannot figure out how to read this field from a cursor. - mBagOfTags in androidx.lifecycle.ViewModel e: error: Cannot find setter for field. - mBagOfTags in androidx.lifecycle.ViewModel e: error: Cannot find setter for field. - mCleared in androidx.lifecycle.ViewModel I am using Material 1.0.0 but I need to update it. I can update until 1.1.0-alpha05. After that version like 1.1.0-alpha06 causes this error. I've checked release notes and nothing related changed at 1.1.0-alpha06. It is the same for AppCompat version now it is 1.0.2 and as soon as I update it, this error occurs again. I've tried to update core-ktx and the result is the same... Any help will be highly appreciated. Thanks! A: So I've found out that one of my entity class extends ViewModel. Removing it solved the problem. Just check your entity class. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/61489491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to compare current date with selected date in android with java I am taking current date using the code like below long millis=System.currentTimeMillis(); java.sql.Date date=new java.sql.Date(millis); And I am selecting date using CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) String s = +year + " : " + (month + 1) + " : " +dayOfMonth ; and passing it on next activity as-- Intent in = new Intent(MainActivity.this, sec.class); in.putExtra("TextBox", s.toString()); startActivity(in); I want to check here if user selected previous date from current date then give a message and don't go on next activity. A: Use SimpleDateFormat: If your date is in 31/12/2014 format. String my_date = "31/12/2014" Then you need to convert it into SimpleDateFormat SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date strDate = sdf.parse(my_date); if (new Date().after(strDate)) { your_date_is_outdated = true; } else{ your_date_is_outdated = false; } or SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date strDate = sdf.parse(my_date); if (System.currentTimeMillis() > strDate.getTime()) { your_date_is_outdated = true; } else{ your_date_is_outdated = false; } A: I am providing the modern answer. java.time and ThreeTenABP Use LocalDate from java.time, the modern Java date and time API. To take the current date LocalDate currentDate = LocalDate.now(ZoneId.systemDefault()); System.out.println(currentDate); When I ran this code just now, the output was: 2020-01-05 To get selected date in your date picker int year = 2019; int month = Calendar.DECEMBER; // but don’t use `Calendar` int dayOfMonth = 30; LocalDate selectedDate = LocalDate.of(year, month + 1, dayOfMonth); System.out.println(selectedDate); 2019-12-30 Your date picker is using the same insane month numbering that the poorly designed and long outdated Calendar class is using. Only for this reason, in an attempt to produce readable code, I am using a constant from that class to initialize month. In your date picker you are getting the number given to you, so you have no reason to use Calendar. So don’t. And for the same reason, just as in your own code I am adding 1 to month to get the correct month number (e.g., 12 for December). Is the date in the past? if (selectedDate.isBefore(currentDate)) { System.out.println("" + selectedDate + " is in the past; not going to next activity"); } else { System.out.println("" + selectedDate + " is OK; going to next activity"); } 2019-12-30 is in the past; not going to next activity Converting to String and back If you need to convert your selected date to a string in order to pass it through the Intent (I don’t know whether this is a requirement), use the toString and parse methods of LocalDate: String dateAsString = selectedDate.toString(); LocalDate recreatedLocalDate = LocalDate.parse(dateAsString); System.out.println(recreatedLocalDate); 2019-12-30 Question: Doesn’t java.time require Android API level 26? java.time works nicely on both older and newer Android devices. It just requires at least Java 6. * *In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. *In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom). *On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages. Links * *Oracle tutorial: Date Time explaining how to use java.time. *Java Specification Request (JSR) 310, where java.time was first described. *ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310). *ThreeTenABP, Android edition of ThreeTen Backport *Question: How to use ThreeTenABP in Android Project, with a very thorough explanation. A: Use below code, * *Create a date object using date formator. *Compare date (There many way out to compare dates and one is mentioned here) *Open intent or make toast as you said message. CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { String s = (month + 1) + "-" + dayOfMonth + "-" + year; SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy"); Date dateSource = null; Calendar cal = Calendar.getInstance(); Date sysDate = cal.getTime(); try { dateSource = sdf.parse(s); if(dateSource.compareTo(sysDate)>0){ Toast.makeToast("Selected worng date",Toast.SHOW_LONG).show(); }else{ Intent in = new Intent(MainActivity.this, sec.class); in.putExtra("TextBox", s.toString()); startActivity(in); } } catch (ParseException e) { Loger.log("Parse Exception " + e); e.printStackTrace(); } } } Edit * *You need a view xml having the calender defined in it. It can be a fragment or activity view xml file *Inflate the view in your Activity or fragment class. View _rootView = inflater.inflate({your layout file},container, false); *Get the respective control java object from the xml like cal = (CalendarView)_rootView.findViewById(R.id.calViewId); *Now call event listener on this cal object. A: Try this lines of code, this may help. Cheers!!! SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = sdf.parse(enteredDate); if (System.currentTimeMillis() > date.getTime()) { //Entered date is backdated from current date } else { //Entered date is updated from current date } } catch (ParseException e) { e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/31759388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: mat-select panelOpen always false I have following template: <mat-select #select> <mat-option *ngFor="let option of optionsData"> {{ select.panelOpen ? option.viewValue : option.value }} </mat-option> </mat-select> And following test which fails: it('should populate options list with view values', async () => { const expected = optionsData.map(o => o.viewValue); const select = de.query(By.css('.mat-select')).nativeElement; select.click(); fixture.detectChanges(); await fixture.whenStable().then(() => { for (const option of select.children) { expect(expected.findIndex(e => e === option.textContent)).toBeGreaterThan(-1); } }); }); But if I change first line in the test to: const expected = optionsData.map(o => o.value) Then the test would pass. That means panelOpen is always false and is only getting the value instead of the viewValue, even though I clicked on the 'select' element. Why does click() not change panelOpen from false to true? A: I fixed this issue with a directive import { OnInit, Directive, EventEmitter, Output } from '@angular/core'; import { MatSelect } from '@angular/material/select'; @Directive({ selector: '[athMatOptionDirective]' }) export class MatOptionDirective implements OnInit { @Output() matOptionState: EventEmitter<any> = new EventEmitter(); constructor(private matSelect: MatSelect) { } ngOnInit() { this.matSelect.openedChange.subscribe(isOpen => { if(isOpen) return this.matOptionState.emit(true) return this.matOptionState.emit(false) }) } } in your html component: <mat-form-field> <mat-select athMatOptionDirective (matOptionState)="getMatOptionState(event)"> </mat-select> </mat-form-field typescript component: getMatOptionState(event) { console.log('is mat-option open?', event) } Many thanks to Juri Strumpflohner (https://juristr.com/blog/2020/06/access-material-select-options) example here: stackblitz
{ "language": "en", "url": "https://stackoverflow.com/questions/69298223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Optimize the rearranging of bits I have a core C# function that I am trying to speed up. Suggestions involving safe or unsafe code are equally welcome. Here is the method: public byte[] Interleave(uint[] vector) { var byteVector = new byte[BytesNeeded + 1]; // Extra byte needed when creating a BigInteger, for sign bit. foreach (var idx in PrecomputedIndices) { var bit = (byte)(((vector[idx.iFromUintVector] >> idx.iFromUintBit) & 1U) << idx.iToByteBit); byteVector[idx.iToByteVector] |= bit; } return byteVector; } PrecomputedIndices is an array of the following class: class Indices { public readonly int iFromUintVector; public readonly int iFromUintBit; public readonly int iToByteVector; public readonly int iToByteBit; public Indices(int fromUintVector, int fromUintBit, int toByteVector, int toByteBit) { iFromUintVector = fromUintVector; iFromUintBit = fromUintBit; iToByteVector = toByteVector; iToByteBit = toByteBit; } } The purpose of the Interleave method is to copy bits from an array of uints to an array of bytes. I have pre-computed the source and target array index and the source and target bit number and stored them in the Indices objects. No two adjacent bits in the source will be adjacent in the target, so that rules out certain optimizations. To give you an idea of scale, the problem I am working on has about 4,200 dimensions, so "vector" has 4,200 elements. The values in vector range from zero to twelve, so I only need to use four bits to store their values in the byte array, thus I need 4,200 x 4 = 16,800 bits of data, or 2,100 bytes of output per vector. This method will be called millions of times. It consumes approximately a third of the time in the larger procedure I need to optimize. UPDATE 1: Changing "Indices" to a struct and shrinking a few of the datatypes so that the object was just eight bytes (an int, a short, and two bytes) reduced the percentage of execution time from 35% to 30%. A: These are the crucial parts of my revised implementation, with ideas drawn from the commenters: * *Convert object to struct, shrink data types to smaller ints, and rearrange so that the object should fit into a 64-bit value, which is better for a 64-bit machine: struct Indices { /// <summary> /// Index into source vector of source uint to read. /// </summary> public readonly int iFromUintVector; /// <summary> /// Index into target vector of target byte to write. /// </summary> public readonly short iToByteVector; /// <summary> /// Index into source uint of source bit to read. /// </summary> public readonly byte iFromUintBit; /// <summary> /// Index into target byte of target bit to write. /// </summary> public readonly byte iToByteBit; public Indices(int fromUintVector, byte fromUintBit, short toByteVector, byte toByteBit) { iFromUintVector = fromUintVector; iFromUintBit = fromUintBit; iToByteVector = toByteVector; iToByteBit = toByteBit; } } *Sort the PrecomputedIndices so that I write each target byte and bit in ascending order, which improves memory cache access: Comparison<Indices> sortByTargetByteAndBit = (a, b) => { if (a.iToByteVector < b.iToByteVector) return -1; if (a.iToByteVector > b.iToByteVector) return 1; if (a.iToByteBit < b.iToByteBit) return -1; if (a.iToByteBit > b.iToByteBit) return 1; return 0; }; Array.Sort(PrecomputedIndices, sortByTargetByteAndBit); *Unroll the loop so that a whole target byte is assembled at once, reducing the number of times I access the target array: public byte[] Interleave(uint[] vector) { var byteVector = new byte[BytesNeeded + 1]; // An extra byte is needed to hold the extra bits and a sign bit for the BigInteger. var extraBits = Bits - BytesNeeded << 3; int iIndex = 0; var iByte = 0; for (; iByte < BytesNeeded; iByte++) { // Unroll the loop so we compute the bits for a whole byte at a time. uint bits = 0; var idx0 = PrecomputedIndices[iIndex]; var idx1 = PrecomputedIndices[iIndex + 1]; var idx2 = PrecomputedIndices[iIndex + 2]; var idx3 = PrecomputedIndices[iIndex + 3]; var idx4 = PrecomputedIndices[iIndex + 4]; var idx5 = PrecomputedIndices[iIndex + 5]; var idx6 = PrecomputedIndices[iIndex + 6]; var idx7 = PrecomputedIndices[iIndex + 7]; bits = (((vector[idx0.iFromUintVector] >> idx0.iFromUintBit) & 1U)) | (((vector[idx1.iFromUintVector] >> idx1.iFromUintBit) & 1U) << 1) | (((vector[idx2.iFromUintVector] >> idx2.iFromUintBit) & 1U) << 2) | (((vector[idx3.iFromUintVector] >> idx3.iFromUintBit) & 1U) << 3) | (((vector[idx4.iFromUintVector] >> idx4.iFromUintBit) & 1U) << 4) | (((vector[idx5.iFromUintVector] >> idx5.iFromUintBit) & 1U) << 5) | (((vector[idx6.iFromUintVector] >> idx6.iFromUintBit) & 1U) << 6) | (((vector[idx7.iFromUintVector] >> idx7.iFromUintBit) & 1U) << 7); byteVector[iByte] = (Byte)bits; iIndex += 8; } for (; iIndex < PrecomputedIndices.Length; iIndex++) { var idx = PrecomputedIndices[iIndex]; var bit = (byte)(((vector[idx.iFromUintVector] >> idx.iFromUintBit) & 1U) << idx.iToByteBit); byteVector[idx.iToByteVector] |= bit; } return byteVector; } * *#1 cuts the function from taking up 35% of the execution time to 30% of the execution time (14% savings). *#2 did not speed the function up, but made #3 possible. *#3 cuts the function from 30% of exec time to 19.6%, another 33% in savings. Total savings: 44%!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/33790773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to have a double border for a cell I want to display a double bordered like following image... The border has a dark color (magenta) and a light color (white) (not the actual colors). I have created a custom .xib file and a custom class extending UITableViewCell for my table view cells. self.tableView.separatorColor = [UIColor whiteColor]; Then in the custom table view class, I did this... - (void)awakeFromNib { [super awakeFromNib]; UIView *cellBottom = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height, self.bounds.size.width, 1.0f)]; cellBottom.backgroundColor = [UIColor magentaColor]; // [self addSubview:cellBottomView]; // ... other code } I got the following result... there seems to be some gap between backgroundColor and separatorColor. Why is this happening? The height of UIView has been set to 1 and is positioned at the bottom of UIView as well. If there is some better solution to this could somebody throw some light on that? A: Michal Zygar is partially correct. Make sure your -(NSInteger)tableView:(UITableView*) heightForRowAtIndexPath:(NSIndexPath*) is correctly set to the height of the view. It doesn't automatically do that for you. The other tip I would suggest as I do it myself, is to NOT use separators. Set your separator to none, and then add in two 1px-heigh views at the top and bottom of the cell in the XIB file. Make sure to set the autosizing for the bottom two to stick only to the bottom edge, just in case you want to change the cell's height!
{ "language": "en", "url": "https://stackoverflow.com/questions/10276703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get the selected items on Source Control History window when creating a Visual Studio Extension? I develop a Visual Studio extension. I attached a button to the Source Control History Window's Context Menu (the menu with 'changeset details', 'compare', etc.. on it) I need to get the selected History items from the window, but couldn't figure it out how to do it. Update: I'm using team foundation server as source control. Here's the screenshot of the window i want to access to. Screenshot I have found a way to retrieve the window object's data, but i still have some issues: package.FindToolWindow(typeof(/*I don't know the type of the window*/), 0, false); (package is instance of Microsoft.VisualStudio.Shell.Package class) What is the type of the Source Control History window (the one on the screenshot)? This is the missing part of the puzzle i think. Please help :) Thanks. A: Maybe this will be helpful for your needs: Tool Window I dont know your other code parts, but I guess you initiate a window application, where you want to render the history list. This window application needs: private FirstToolWindow window; private void ShowToolWindow(object sender, EventArgs e) { window = (FirstToolWindow) this.package.FindToolWindow(typeof(FirstToolWindow), 0, true); ...
{ "language": "en", "url": "https://stackoverflow.com/questions/48061180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Select Data from 3 tables whereas multiple values should be comma separated I have following 3 tables: ....... ....... ………………………… ……………………………… ………………………… I run the following query SELECT Employee.EmployeeId, EmployeeName, ProjectName FROM Employee JOIN ProjEmp ON Employee.EmployeeId=ProjEmp.EmployeeId JOIN Project ON Project.ProjectId=ProjEmp.ProjectId And it gives following result: But I need result like this: Suggest me the best query for my desired result. A: You can do the following to get what you are looking for : WITH CTE AS(SELECT Employee.EmployeeId, EmployeeName, ProjectName FROM Employee JOIN ProjEmp ON Employee.EmployeeId=ProjEmp.EmployeeId JOIN Project ON Project.ProjectId=ProjEmp.ProjectId) SELECT EmployeeId,EmployeeName, ProjectName = STUFF(( SELECT ',' + convert(varchar(10),T2.ProjectName) FROM CTE T2 WHERE T1.EmployeeName = T2.EmployeeName FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') FROM CTE T1 GROUP BY EmployeeId,EmployeeName ORDER BY EmployeeId Result: EMPLOYEEID EMPLOYEENAME PROJECTNAME 1 Emp1 ProjA,ProjB 3 Emp3 ProjC 4 Emp4 ProjC,ProjD 5 Emp5 ProjE 7 Emp7 ProjE 8 Emp8 ProjE See result in SQL Fiddle.
{ "language": "en", "url": "https://stackoverflow.com/questions/23674844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: extracting the generic type of other props in interface How can I achieve something like this? interface Props { result: <type of function with a lot of generic> data: <type of one of the generics in the function above> } I've found a question that sounds similar here, but I'm such a newbie and not sure if this applies to my case. The background: I'm using react-query, and want to make a wrapper component that takes a react-query result object and a component, then shows spinner or the given component based on the query state (isLoading, isSuccess etc), whatever the query response data type is. import React from 'react' import {useQuery} from 'react-query' interface WrapperProps { result: <type of react query result>; render: (data: <type of query data>) => React.ReactNode; } const Wrapper: React.FC<WrapperProps> = ({result, render}) => { if (result.isLoading) { return <div>spinner</div> } if (result.isSuccess) { return render(result.data) } return <div>otherwise</div> } const App: React.FC = () => { const responseString = useQuery( ['string'] async () => Promise.resolve("string") ) const responseNumber = useQuery( ['number'] async () => Promise.resolve(3) ) return ( <div> <Wrapper result={responseString} render={(data) => (<div>successfully loaded string {data}</div>)} // <= want the data to be type string /> <Wrapper result={responseInt} render={(data) => (<div>successfully loaded int {data}</div>)} // <= want the data to be type number /> </div> ) } *1 the type of useQuery is something like this A: You were close. You need to update Wrapper component a bit. First of all, you need to get rid FC. Instead you need to add extra generic type to infer query result. Consider this example: import React from 'react' import { useQuery, UseQueryResult } from 'react-query' interface WrapperProps<T> { result: UseQueryResult<T, unknown> render: (data: T) => JSX.Element; } const Wrapper = <T,>({ result, render }: WrapperProps<T>) => { if (result.isLoading) { return <div>spinner</div> } if (result.isSuccess) { return render(result.data) } return <div>otherwise</div> } const App: React.FC = () => { const responseString = useQuery( ['string'], async () => Promise.resolve("string") ) const responseNumber = useQuery( ['number'], async () => Promise.resolve(3) ) return ( <div> <Wrapper result={responseString} render={(data /** string */) => (<div>successfully loaded string {data}</div>)} /> <Wrapper result={responseNumber} render={(data /** number */) => (<div>successfully loaded int {data}</div>)} /> </div> ) } Playground Please keep in mind that it is impossible to infer component props with extra generic and FC explicit type. Please be aware that TS since 2.9 supports explicit generics for react components
{ "language": "en", "url": "https://stackoverflow.com/questions/69969478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL Syntax Error With Stored Procedures I must be missing something simple because I can't figure out what is causing my script to fail. Below is the stored procedure I've written: CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT, IN `in_first_name` VARCHAR(255)) IF in_first_name IS NOT NULL THEN SELECT * FROM `contacts` WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name; END IF; When I try and execute this on my MySQL server I get the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5 I'd like to know what is causing this error and why so I can avoid it again. Any help is appreciated! A: Try adding "BEGIN", "END" and "DELIIMITER", like this: DELIMITER $$ CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT, IN `in_first_name` VARCHAR(255)) BEGIN IF in_first_name IS NOT NULL THEN SELECT * FROM `contacts` WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name; END IF; END $$ DELIMITER ;
{ "language": "en", "url": "https://stackoverflow.com/questions/67645327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mapping a many-to-two relationship in fluent-nhibernate I'm working with a node/link structure, but I'm having problems mapping it using fluent nhibernate. This is a simplification of the classes I'm using. class Node { public virtual IList Links { get; set; } } class Link { public virtual Node StartNode { get; set; } public virtual Node EndNode { get; set; } } A node can have many links connected to it. A link has to be connected to two nodes. And I need to know which node is the start node and end node, so they have to be specific. Which is why I can not use a list and limit it to two nodes. Has anyone come across this problem and found a solution to it? Edit: Clearifying question I'm not using Automapping, I'm using the explisit mapping methods: References, HasMany and HasManyToMany. Essentially following the methods found in the introductory tutorial: http://wiki.fluentnhibernate.org/Getting_started#Your_first_project I don't have a database either, I'll create the database schema from the mappings using nhibernate. What I'm asking is, how do I create a many-to-two relation? A: Well there's not a special many to two relationship but what you'd probably do is something like this: public class NodeMap : ClassMap<Node> { public NodeMap() { //Id and any other fields mapped in node HasMany(x => x.Links); } } public class LinkMap : ClassMap<Link> { public LinkMap() { //Id and any other fields mapped in node References(x => x.StartNode); References(x => x.EndNode); } } Again this is just a brief overview above. You will probably need additional mapping attributes if you want to for example cascade any create/update/delete actions.
{ "language": "en", "url": "https://stackoverflow.com/questions/5943592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to feed in and retrieve state of LSTM in tensorflow C/ C++ I'd like to build and train a multi-layer LSTM model (stateIsTuple=True) in python, and then load and use it in C++. But I'm having a hard time figuring out how to feed and fetch states in C++, mainly because I don't have string names which I can reference. E.g. I put the initial state in a named scope such as with tf.name_scope('rnn_input_state'): self.initial_state = cell.zero_state(args.batch_size, tf.float32) and this appears in the graph as below, but how can I feed to these in C++? Also, how can I fetch the current state in C++? I tried the graph construction code below in python but I'm not sure if it's the right thing to do, because last_state should be a tuple of tensors, not a single tensor (though I can see that the last_state node in tensorboard is 2x2x50x128, which sounds like it just concatenated the states as I have 2 layers, 128 rnn size, 50 mini batch size, and lstm cell - with 2 state vectors). with tf.name_scope('outputs'): outputs, last_state = legacy_seq2seq.rnn_decoder(inputs, self.initial_state, cell, loop_function=loop if infer else None) output = tf.reshape(tf.concat(outputs, 1), [-1, args.rnn_size], name='output') and this is what it looks like in tensorboard Should I concat and split the state tensors so there is only ever one state tensor going in and out? Or is there a better way? P.S. Ideally the solution won't involve hard-coding the number of layers (or rnn size). So I can just have four strings input_node_name, output_node_name, input_state_name, output_state_name, and the rest is derived from there. A: I managed to do this by manually concatenating the state into a single tensor. I'm not sure if this is wise, since this is how tensorflow used to handle states, but is now deprecating that and switching to tuple states. Instead of setting state_is_tuple=False and risking my code being obsolete soon, I've added extra ops to manually stack and unstack the states to and from a single tensor. Saying that, it works fine both in python and C++. The key code is: # setting up zero_state = cell.zero_state(batch_size, tf.float32) state_in = tf.identity(zero_state, name='state_in') # based on https://medium.com/@erikhallstrm/using-the-tensorflow-multilayered-lstm-api-f6e7da7bbe40#.zhg4zwteg state_per_layer_list = tf.unstack(state_in, axis=0) state_in_tuple = tuple( # TODO make this not hard-coded to LSTM [tf.contrib.rnn.LSTMStateTuple(state_per_layer_list[idx][0], state_per_layer_list[idx][1]) for idx in range(num_layers)] ) outputs, state_out_tuple = legacy_seq2seq.rnn_decoder(inputs, state_in_tuple, cell, loop_function=loop if infer else None) state_out = tf.identity(state_out_tuple, name='state_out') # running (training or inference) state = sess.run('state_in:0') # zero state loop: feed = {'data_in:0': x, 'state_in:0': state} [y, state] = sess.run(['data_out:0', 'state_out:0'], feed) Here is the full code if anyone needs it https://github.com/memo/char-rnn-tensorflow
{ "language": "en", "url": "https://stackoverflow.com/questions/42423589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where exactly are variables or identifiers stored in C++? According to my current knowledge variables(identifiers) point to object of a particular type(int,bool,etc..) that are objects in memory. Where and how are the the variables themselves store? Are they stored with the objects they point to or are they stored in some other place? For example; int main() { int a_number = 2; return 0; } So the variable a_number point to an int object in memory, but where is a_number itself?? If say the 2 is in a 4 byte memory, is a_number consuming a portion of it?? Or is a_number consuming some other allocated memory somewhere?? By the way I currently studying C++(am a beginner in programming) and I was considering this and couldn't really visualize it. Thank you. A: In this particular case, a_number names an int object that consumes sizeof(int) bytes and has automatic storage duration. Memory for storage with automatic duration is typically allocated in the stack frame of the function to which the declaration belongs (main() in this case). a_number effectively becomes a name for the int object stored in these bytes. The name does not exist at runtime, because it is no longer needed at that time. The only purpose of the name is to allow you to refer to the object in code. A: Variables can stored in memory areas or in processor registers, depending on the compiler and optimization settings. Let's assume that your compiler is using a stack for function local variables and parameters. Your a_number variable would be placed on the stack since it's lifetime is temporary (will disappear after execution leaves the function). The compiler is allowed to place the a_number into a processor register. In this case, the variable doesn't exist in memory because processor registers are not in memory (they don't have addresses). Since your program doesn't use the a_number variable after declaration, the compiler can eliminate the variable and not use memory. There is no difference in behavior of your program with or without the variable; thus the compiler can eliminate the variable. The location of your variable depends on your compiler. You compiler can store variables "on the stack", in a processor register or eliminate the variable. The location also depends on the "optimization setting" on your compiler. Some compilers may not optimize on the lowest settings and remove the variable on the higher settings. A: but where is a_number itself? Just where you see it, in the source code file. The compiler sees it there and keeps track of it, generating what code it needs to. If you have debugging turned on, then the symbol is stored along with the code in a special look up table so you can see it in the debugger as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/58510801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google App Flexible Java Logging Not Working I have a simple servlet as below. And I'm unable to see any of System.out or log.info in the gcloud logs. I used gcloud app logs tail -s my-app-name. I only see logs for GET and favicon. Please help to enable logs in my google cloud app. @SuppressWarnings("serial") @WebServlet(name = "Home", description = "Write low order IP address to response", urlPatterns = "/") public class HomeServlet extends HttpServlet { Logger logger = Logger.getLogger(HomeServlet.class.getName()); Connection conn; @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if(logger.isLoggable(Level.FINE)) { log("FINE is loggable."); System.out.println("This is System Out. FINE is loggable"); logger.fine("Received GET request"); } else { log("FINE is not loggable"); System.out.println("This is System Out. FINE is not loggable"); logger.severe("Received GET request"); } String path = req.getRequestURI(); if (path.startsWith("/favicon.ico")) { return; // ignore the request for favicon.ico } PrintWriter out = resp.getWriter(); resp.setContentType("text/plain"); String userIp = req.getRemoteAddr(); out.print("Your IP is: " + userIp); log("responded GET request from: " + userIp); } } A: You can use the command this way: gcloud app logs tail --service=my-service --version=my-app-version in order to specify the service and version, then see If you're not really getting all the logs. See a list of all options here. Also you can see all your logs by going to Stackdriver -> Logging -> Logs: Once there, you can filter the logs by app version: Also be aware that depending on the request you make, sometimes you'll only see certain kind of logs. I pasted your code in the quickstart for app engine flexible and I got this: ........... 2017-12-18 09:40:07 my-service[my-app-version] "GET /favicon.ico" 200 2017-12-18 09:40:07 my-service[my-app-version] "GET /" 200 2017-12-18 09:40:07 my-service[my-app-version] "GET /favicon.ico" 200 2017-12-18 09:40:08 my-service[my-app-version] "GET /" 200 2017-12-18 09:40:13 my-service[my-app-version] org.eclipse.jetty.server.handler.ContextHandler.root: com.example.appengine.gettingstartedjava.helloworld.HomeServlet: FINE is not loggable 2017-12-18 09:40:13 my-service[my-app-version] com.example.appengine.gettingstartedjava.helloworld.HomeServlet: Received GET request 2017-12-18 09:40:13 my-service[my-app-version] org.eclipse.jetty.server.handler.ContextHandler.root: com.example.appengine.gettingstartedjava.helloworld.HomeServlet: responded GET request from: 35.187.117.231 2017-12-18 09:40:13 my-service[my-app-version] This is System Out. FINE is not loggable 2017-12-18 09:40:15 my-service[my-app-version] This is System Out. FINE is not loggable .......... In addition to this, you can use the Stackdriver Logging Client Libraries. First add this to your POM dependencies: <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-logging</artifactId> <version>1.14.0</version> </dependency> then use the quickstart and paste this code in the HelloServlet.java. Your code would look like this: @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); out.println("Hello, world - Flex Servlet"); Logging logging = LoggingOptions.getDefaultInstance().getService(); String logName = "My-log"; String text = "Hello World"; LogEntry entry = LogEntry.newBuilder(StringPayload.of(text)).setSeverity(Severity.ERROR).setLogName(logName) .setResource(MonitoredResource.newBuilder("global").build()).build(); logging.write(Collections.singleton(entry)); System.out.printf("Logged: %s%n", text); } You can see this result in Stackdriver:
{ "language": "en", "url": "https://stackoverflow.com/questions/47851388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not getting expected return value from function So, I am getting a csv file from a url. I am then turning each row into an array of objects. const translation = { '緯度': 'latitude', '経度': 'longitude', '測定局コード': 'Measuring station code', '測定局名称': 'Bureau name', '所在地': 'location', '測定局種別': 'Measuring station type', '問い合わせ先': 'Contact information', '都道府県コード': 'Prefecture code' } const csv_url = 'https://soramame.env.go.jp/data/map/kyokuNoudo/2022/10/06/01.csv'; // request the csv file from csv_url and create an array of stations objects var stations = []; request(csv_url, (err, res, body) => { if (err || res.statusCode !== 200) { console.log(err); } else { const rows = body.split('\n'); const headers = rows[0].split(','); for (let i = 1; i < rows.length; i++) { // start at 1 to skip headers let station = {}; // create a new station object for each row const row = rows[i].split(','); // split the row into columns for (let j = 0; j < row.length; j++) { // loop through each column station[translation[headers[j]]] = row[j]; // add the value to the station object by using the header as the key } var data = stations.push(station) console.log(stations) return data; } } } ); That all works fine... when I console.log(stations) inside of the function I get the expected output. { latitude: '43.123333', longitude: '141.245000', 'Measuring station code': '01107030', 'Bureau name': '手稲', location: '札幌市手稲区前田2-12', 'Measuring station type': '一般局', 'Contact information': '札幌市', 'Prefecture code': '01' } { latitude: '43.123333', longitude: '141.245000', 'Measuring station code': '01107030', 'Bureau name': '手稲', location: '札幌市手稲区前田2-12', 'Measuring station type': '一般局', 'Contact information': '札幌市', 'Prefecture code': '01' } { latitude: '43.123333', longitude: '141.245000', 'Measuring station code': '01107030', 'Bureau name': '手稲', location: '札幌市手稲区前田2-12', 'Measuring station type': '一般局', 'Contact information': '札幌市', 'Prefecture code': '01' } however when I console.log(stations) outside of the function I get an empty list. I am declaring 'stations' outside of the function, and the function is appending the objects to the array. Why isn't it working and what can I do to solve this? also, when I return 'data' that doesn't return the array from. 'stations' either. A: The call to request is asynchronous. Therefore, calling console.log(stations) in the line immediately after your call to request will print the empty list while your request continues to run in the background. It prints too quickly - before the stations list has been populated. Whatever you need to do with stations, you either need to do it in a success callback passed to request, or you need to await the request. As Dai says above, push is actually mutating the stations array. I am not sure what implementation of request you are using but it may return a value so you may be able to do something like const response = await request(...) (this could work in conjunction with fixing the error Dai pointed out - one way would be to move the declaration of stations inside the else clause, and then return stations at the end of the else clause). If you can't await it, you will need to pass a callback that performs the pushes to stations defined as is.
{ "language": "en", "url": "https://stackoverflow.com/questions/73993070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the desired output by modifying string after removing / from string I have a string like this: 30/04/2018 o/p=300418 01/03/2017 o/p=010317 10/11/2018 o/p=101118 12/11/2123 o/p=121123 1/1/2018 o/p =010118 code tried but can't get the last one 1/1/2018 string a = "31/04/2018"; string b = a.Replace("/",""); b = b.Remove(4, 2); A: You should parse to a DateTime and then use the ToString to go back to a string. The following works with your given input. var dateStrings = new []{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"}; foreach(var ds in dateStrings) { Console.WriteLine(DateTime.ParseExact(ds, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("ddMMyy")); } The only change I made is to the first date as that is not a valid date within that month (April has 30 days, not 31). If that is going to be a problem then you should change it to TryParse instead, currently I assumed your example was faulty and not your actual data. A: Your structure varies, all of the examples above use two digit month and day, while the bottom only uses a single digit month and day. Your current code basically will replace the slash with an empty string, but when you remove index four to two your output would deviate. The simplest approach would be: var date = DateTime.Parse("..."); var filter = $"o/p = {date:MMddyyyy}"; Obviously you may have to validate and ensure accuracy of your date conversion, but I don't know how your applications works. A: If you can reasonably expect that the passed in dates are actual dates (hint: there are only 30 days in April) you should make a function that parses the string into DateTimes, then uses string formats to get the output how you want: public static string ToDateTimeFormat(string input) { DateTime output; if(DateTime.TryParse(input, out output)) { return output.ToString("MMddyy"); } return input; //parse fails, return original input } My example will still take "bad" dates, but it will not throw an exception like some of the other answers given here (TryParse() vs Parse()). There is obviously a small bit of overhead with parsing but its negligible compared to all the logic you would need to get the proper string manipulation. Fiddle here A: Parse the string as DateTime. Then run ToString with the format you desire. var a = "1/1/2018"; var date = DateTime.Parse(a); var result = date.ToString("ddMMyyyy"); A: You can use ParseExact to parse the input, then use ToString to format the output. For example: private static void Main() { var testData = new List<string> { "31/04/2018", "01/03/2017", "10/11/2018", "12/11/2123", "1/1/2018", }; foreach (var data in testData) { Console.WriteLine(DateTime.ParseExact(data, "d/m/yyyy", null).ToString("ddmmyy")); } GetKeyFromUser("\nDone! Press any key to exit..."); } Output A: You didn't specify whether these are DateTime values or just strings that look like date time values. I'll assume these are DateTime values. Convert the string to a DateTime. Then use a string formatter. It's important to specify the culture. In this case dd/mm/yyyy is common in the UK. var culture = new CultureInfo("en-GB");//UK uses the datetime format dd/MM/yyyy var dates = new List<string>{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"}; foreach (var date in dates) { //TODO: Do something with these values DateTime.Parse(date, culture).ToString("ddMMyyyy"); } Otherwise, running DateTime.Parse on a machine with a different culture could result in a FormatException. Parsing dates and times in .NET.
{ "language": "en", "url": "https://stackoverflow.com/questions/49986322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stop youtube player when resize screen under 768px? I would like to stop the youtube video only in mobile. I need to show it on desktop device, and hide it on mobile. Is possibile with javascript? I'm sorry but I don't know Javascript, I need a complete code. The Html code is: <div class="video-wrapper"> <div id="player"></div> </div> Can I integrate the windows resize function with youtube? function stopVideo() { player.stopVideo(); Please Help me! If I use only a "display: none" the video disappears but you can still hear the sound.
{ "language": "en", "url": "https://stackoverflow.com/questions/56809054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Frequency Distribution Histogram with Bins with Two Variables on the Y-axis in R I was given this dataframe, which is at the same time a frequency distribution, and was given a task of plotting a histogram of the age distribution of the whole population adding to the plot the male and female profile. What I need to achieve is a histogram like this one for example: Two-variable frequency bar plot with the male and female profile overlapping, but with the AgeClasses on the x axis. This is my code: AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99') Frequencies <- c(1000,900,800,700,600,500,400,300,200,100) SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65) df$Females <- c(SexRatioFM*Frequencies) df$Males <- c(Frequencies-Females) library(ggplot2) ggplot(df) + geom_bar(mapping = aes(x = AgeClasses, y = Females), stat = "identity") I would really appreciate your help in solving this task. A: This type of plot is a stacked bar plot. To produce it most easily with ggplot2, you need to transform your data into long format, so that one column has all the counts for both male and female, and another column contains a factor variable with the labels "Male" and "Female". You can do this using tidyr::pivot_longer: library(ggplot2) library(tidyr) pivot_longer(df, cols = c(Females, Males)) %>% ggplot() + geom_col(mapping = aes(x = AgeClasses, y = value, fill = name)) + labs(x = "Age", y = "Count", fill = "Gender") A: Try the following code: AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99') Frequencies <- c(1000,900,800,700,600,500,400,300,200,100) SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65) Females <- SexRatioFM*Frequencies Males <- Frequencies-Females df <- data.frame(AgeClasses=AgeClasses, Females=Females, Males=Males) df <- reshape2::melt(df, id.vars = 'AgeClasses') library(ggplot2) ggplot(df) + geom_bar(mapping = aes(x = AgeClasses, y = value, fill=variable), stat = "identity") A: Allan is right, but to make the one in the plot, you need the bars superposed rather than stacked. I did it like this: library(ggplot2) library(dplyr) AgeClasses <- c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99') Frequencies <- c(1000,900,800,700,600,500,400,300,200,100) SexRatioFM <- c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65) df <- tibble( Females = c(SexRatioFM*Frequencies), Males = c(Frequencies-Females), AgeClasses = AgeClasses, Frequencies=Frequencies, SexRatioFM = SexRatioFM) df %>% select(AgeClasses, Males, Females) %>% tidyr::pivot_longer(cols=c(Males, Females), names_to = "gender", values_to="val") %>% ggplot() + geom_bar(mapping = aes(x = AgeClasses, y=val, fill=gender, alpha=gender), stat="identity", position="identity") + scale_alpha_manual(values=c(.5, .4)) A: You'll need to revamp how you create your sample dataframe. Here's one way to do it: df <- data.frame( AgeClasses = c('0-9','10-19','20-29','30-39','40-49', '50-59', '60-69','70-79','80-89', '90-99'), Frequencies = c(1000,900,800,700,600,500,400,300,200,100), SexRatioFM = c(0.4,0.42,0.44,0.48,0.52,0.54,0.55,0.58,0.6,0.65)) df$Females = df$SexRatioFM*df$Frequencies df$Males = df$Frequencies-df$Females library(ggplot2) ggplot(df) + geom_bar(mapping = aes(x = AgeClasses, y = Females), fill="purple", stat = "identity", alpha=.8) + geom_bar(mapping = aes(x = AgeClasses, y = Males), fill="navy blue", stat = "identity", alpha=.4) And you should get something like this:
{ "language": "en", "url": "https://stackoverflow.com/questions/63797479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can you use Python to fill out HTML forms that also have Javascript? I am making a python program that automatically enters information into a form on a website. I looked at a module called mechanize at first but then I realized that it didn't support javascript. Is there any way to take a piece of information and insert it into a "form" on a website that uses javascript? The website I am using is www.locationary.com. If you login and then go to a place/business page like this, http://www.locationary.com/place/en/US/California/Los_Angeles/Z_Pizza-p1001157911.jsp then you will see a bunch of spots that need to be filled in. I looked at the page source and this "form" uses javascript. I just need a way to fill in those blanks now. Like I said, I tried mechanize and it didn't work but I also googled it and got nothing. The "form" uses "onclick" If you could offer any advice, I would really appreciate it. Thanks. A: I think probably the best way to do this is to use a framework that can operate through a browser. There are several options, but the most pythonic is windmill http://www.getwindmill.com/ I've found it useful on a number of projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/8610043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flex 4 Combo - using IME I am trying to use ime (for hiragana input) in a flex 4 spark combo. On creation complete I am setting the following. cbx_text.textInput.imeMode = IMEConversionMode.JAPANESE_HIRAGANA; And to check, tracing the following: trace(cbx_text.textInput.enableIME); returns true; trace(cbx_text.textInput.imeMode); returns JAPANESE_HIRAGANA; However, when I select the text input and start to type some text I am unable to switch to hiragana. I can set it to work on a textinput component with no problems. <s:TextInput imeMode="JAPANESE_HIRAGANA"></s:TextInput> Has anyone had any experience with this? Any insights much appreciated. A: Although I haven't had any experience with IME, I took a quick look at the documentation : http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/IME.html Can it be that it's not enabled application wise? That, maybe what returns true is only valid for the component you are tracing from? A: Obvious questions first: Are you certain the TextInput is a member of cbx_text? I know this seems silly, but it's best to eliminate the obvious first. Do you have an IME enabled on your computer? For example, do you regularly type in hiragana on your computer and have the appropriate language pack enabled? Are you sending the IME the string appropriately? IME.setCompositionString() for windows computers? Does your OS support the use of IMEs? Linux only supports the following methods: * *Capabilities.hasIME *IME.enabled <= Can set or return value. Try tracing hasIME and see if it's installed. Again, we're shotgunning here – trying to track down any possibility of a problem. When all else fails, go to the source: * *http://livedocs.adobe.com/flex/3/html/help.html?content=18_Client_System_Environment_6.html
{ "language": "en", "url": "https://stackoverflow.com/questions/5864296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Add Custom label in JSQViewMessageViewController iOS I want to add a custom label (with a time stamp) in each cell as well as an image (for warning message) in JSQMessageViewController. I am already using bottomlabel as well as toplabel. But I am unable to get the result I want. The image is a reference of what I would like it to look like A: UIImage *bubbleImage = [UIImage imageNamed:@"Commentbox_right.png"]; UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(textFrame.origin.x-2, textFrame.origin.y-2, textFrame.size.width+4 , textFrame.size.height+7)]; imgView.image= [bubbleImage stretchableImageWithLeftCapWidth:bubbleImage.size.width/2-5 topCapHeight:bubbleImage.size.height/2]; [cell addSubview:imgView]; [cell bringSubviewToFront:txtViewMessage]; UILabel *lblTimeStamp = [[UILabel alloc]initWithFrame:CGRectMake(textFrame.origin.x+2, imgView.frame.size.height+imgView.frame.origin.y, 90, 10)]; [lblTimeStamp setText:message.dateTime];//set time here [lblTimeStamp setFont:FONT_300_LIGHT(7)]; [lblTimeStamp setTextColor:GET_COLOR_WITH_RGB(129,129,129, 1)]; [lblTimeStamp setTextAlignment:NSTextAlignmentLeft]; [lblTimeStamp setBackgroundColor:[UIColor clearColor]]; [cell addSubview:lblTimeStamp]; A: Sorry i didn't get much time to look in to it .. but again you can add that image in same message bubble xib and add constraints according to your need. Try this xib A: How I add custom Label in JSQMessageviewcontroller is... I declare Label text before ViewDidLoad. // Add Text Label let myLabel: UILabel = { let lb = UILabel() lb.translatesAutoresizingMaskIntoConstraints = false lb.textAlignment = .center lb.numberOfLines = 1 lb.textColor = UIColor.white lb.font=UIFont.systemFont(ofSize: 22) lb.backgroundColor = UIColor(red: 0.0/255.0, green:70.0/255.0, blue:110.0/255.0, alpha:1) lb.text = NSLocalizedString("No Notification", comment: "") return lb }() And add this code in viewDidiLoad or call anywhere you like. self.view.addSubview(myLabel) setUpMyLabel() This is how I add custom label in my app. Hope this will help you. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/33097256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can not connect to MySQL in a thread in python (fine on main thread) Problem in short: MySQLdb.connect() works on main thread, doesn't work in other threads. I have a class called Bot with some methods. something like this: class Bot(): def task1(): read_from_db() # some other work def task2(): read_from_db() # some other work and i have a thread class which accepts a Bot object and a task_name and starts the task on the bot object. class taskThread (threading.Thread): def __init__(self, bot, task): threading.Thread.__init__(self) self.bot = bot self.task = task def run(self): print "Starting " + self.task + " for " + self.bot.username if self.task == "task1": self.bot.task1() elif self.task == "task2": self.bot.task2() print "Exiting " + self.task + " for " + self.bot.username I tried every thing in read_from_db() but it does not work in a thread. it works fine if i call bot.task1() in main thread but if i create a myThread object and tell it to run task1 it stops exactly on MySQLdb.connect() line with no error. it just stops. def read_from_db(): db = MySQLdb.connect(host="localhost", user="root", passwd="", db="db_name", unix_socket="/opt/lampp/var/mysql/mysql.sock") db.set_character_set('utf8') I have searched a lot but i couldn't find anything. edit: weirdly when the code is stopped right before creating a connection to db, if i press ctrl+c in terminal (where i ran the code) the code resumes and works just as expected. do anyone know such a behavior ? A: You have a problem with your def run(self):. You're referencing a task variable that isn't defined. You mean self.task: # Consider renaming: it's more standard to have `TaskThread` class taskThread (threading.Thread): # Init is fine def run(self): print "Starting " + self.task + " for " + self.bot.username # It used to be just 'task'. Make it self.task if self.task == "task1": self.bot.task1() elif self.task == "task2": self.bot.task2() print "Exiting " + self.task + " for " + self.bot.username You also might want to consider: def run(self): print "Starting " + self.task + " for " + self.bot.username action = getattr(self.bot, self.task) action() print "Exiting " + self.task + " for " + self.bot.username
{ "language": "en", "url": "https://stackoverflow.com/questions/46200206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UML-Designer: Hide labels on associations My first post on stackoverflow, 'hope I do it the right way :-) I want to create a new entity-relationship-model of our new project. After a little bit of search I found UMLDesigner. Installation was easy and create this first classes also. But when I "paint" associations, I got "hundreds" of labels around them. Have a look into the documentation, I found a way to hide labels, but ... But a) I could not select association lables in bulk. The filter works only of the caption of a object and not of the typ (e.g. association vs. class). Is there a way to only select "associations"? b) If I hide "a" label of the association, all labels are hidden. What I wanted was to hide only the "end"/role"-labels, but not the name of the association itself c) Is there a global way to hide/show labels or have I always select a new created object and then hide things? Question over question, maybe someone can answer them :-) Ingo A: Thanks great to see you managed to install it. Sorry, no it exists no bulk actions on hide you should select one by one the element or decide to hide all.
{ "language": "en", "url": "https://stackoverflow.com/questions/67724253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Method retake in Java I'm developing a project in which i have a method to know if a JTextField is empty or not, but i was wondering if a way to implement that method just once and send several JTextFields components to check if they are empty or not exists, if so, could you please tell me how?, here's my sample code. public static void Vacio(JTextField txt){ if(txt.getText().trim().equals(null)==true){/*Message*/} } Also i would like to know if i could improve the method using some Lambda Expressions, beforehand. A: Use : if(txt.getText().trim().length()==0) //Do something Your code will not work because a blank string("") is not a null String. I simply check if the trimmed length() of TextField is 0. A sample function: public boolean isEmpty(JTextField jtf) { try{ jtf.getText(); }catch(NullPointerException e){return true;} if(jtf.getText().trim().length() == 0) return true; return false; } A: Check explicitly for null and then compare with "". public static void Vacio(JTextField txt){ String str = null; try { str = txt.getText(); } catch (NullPointerException npe) { System.out.println("The document is null!"); return; } if(str.trim().equals("")==true){/*Message*/} } A: I cannot imagine how adding Lambda expressions can improve what you're trying to do (?). Anyway, to check for an empty String I'd probably use: field.getText().trim().isEmpty() You don't need to check for null but you do need to catch NullPointerException in the event that the underlying document in the JTextField is null. For the other part of your quesiton, if you really want to check multiple JTextFields in one method you could pass them as a variable length argument list: public static void vacio(JTextField... fields) { for(JTextField field : fields) { try { if( field.getText().trim().isEmpty() ) { // do something } } catch(NullPointerException ex) { // handle exception (maybe log it?) } } } and call it like: vacio(field1, field2, field3); But, generally speaking, keeping functions brief and only doing one thing is usually better than trying to make a function do too much. One final aside, your method is named Vacio but java naming conventions suggest you should compose method names using mixed case letters, beginning with a lower case letter and starting each subsequent word with an upper case letter.
{ "language": "en", "url": "https://stackoverflow.com/questions/24114176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open Fragments through App Bar/Toolbar using Navigation component I implemented a bottom navigation view which also handles multiple backstacks using Google's own workaround as given in the architecture components sample ,using the file private fun setupBottomNavigationBar() { val navGraphIds = listOf( R.navigation.blog, R.navigation.events, R.navigation.practice, R.navigation.login ) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav) val controller = bottomNavigationView.setupWithNavController( navGraphIds = navGraphIds, fragmentManager = supportFragmentManager, containerId = R.id.fragment, intent = intent ) //use this to setup Action bar controller.observe(this) { navController -> setupActionBarWithNavController(navController) } currentNavController = controller } This is how I setup the bottom navigation view. I have an app bar which should open the settings fragment , but so far I have been unable to do so. Any solutions? This is how selecting the options should look like override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.settings -> TODO()//->should open settings fragment } return true } I cannot directly navigate to settings as the current architecture has multiple nav graphs and as such it says, java.lang.IllegalArgumentException: Navigation action/destination com.istemanipal.lumos:id/themeFragment cannot be found from the current destination Destination(com.istemanipal.lumos:id/blogFragment A: if the id of the menu item is set to the fragment id, you could probably use navigation controller to switch the destination. override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.settings -> currentNavController.navigate(R.id.navigation_destination_id) } return true }
{ "language": "en", "url": "https://stackoverflow.com/questions/67265247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you change the timeout on a flash.net.netconnection? Timeout appears to be about 10 seconds. Can this be modified? A: I don't see a built-in way to do it. However, it's definitely possible to implement on your own. Just create a transaction class representing each call you make to a NetConnection instance. This transaction class, for example "NetTransaction", should keep a private static list of all active transactions, and should store the result handler function in a private instance variable that is to be called when a transaction completes (on result, on status, or on timeout). Note that this handler is unified, so it handles all kinds of results (success/error/timeout/canceled). In your transaction class's constructor, add "this" new instance to the active transactions list, start a timeout timer if a non-zero timeout is specified (adding an event listener pointing to the cancelTransaction function described below), and then perform the network call last. When you complete a transaction (success/error/timeout/canceled), remove it from the active transactions list, cancel the timeout timer if one was set, and finally forward a meaningful result to the result handler function. The trick to making this all work is that you must create result and status handler functions in the transaction class, and pass THOSE to your call to NetConnection. Those two functions will be responsible for INTERCEPTING the network result (result or status), completing the transaction (as described above), and forwarding a unified result to the REAL result handler function that was passed to the constructor. Here's the stripped down insides of the base NetTransaction class with the basic necessities. My implementation has more stuff, including generating transaction ids (just a simple static counter, a method for looking up an active transaction by id number. It also has overridable get/set methods for the transaction's data object, so I can have automatic header wrapping/unwrapping for custom data protocols in classes deriving from NetTransaction (e.g. WidgetNetTransaction). static private var active_transactions:Array = new Array(); //active network requests pending a result static private var transaction_count:int = 0; //incremented each time a NetTransaction instance is created so each one can have a unique transaction id number assigned to it private var transaction_id:int; //Transaction identifier, which may assist a widget in managing its own concurrent transactions. It comes from a static field, auto-incremented in the NetTransaction constructor, so it is always unique for each NetTransaction within the current session... unless more than 2147483648 transactions occur in a single session and the value wraps around, but by then, old transactions wil be forgotten and there shouldn't be any problems as a result. private var description:String; //an optional description string to describe the transaction or what it is supposed to do (especially for error-reporting purposes). private var request_data:Object; //this stores the data that will be forwarded to your web server private var result_handler:Function; //this is the method to be called after intercepting a result or status event. it's left public, because it's acceptable to modifiy it mid-transaction, although I can't think of a good reason to ever do so private var internal_responder:Responder; //internal responder attached to the transaction private var timeout:int; private var timeout_timer:Timer; //Constructor public function NetTransaction( network_service:NetworkService, request_data:Object, result_handler:Function = null, description:String = null, timeout:int = 0 ) { //Throw something a little more friendly than a null-reference error. if (network_service == null) throw new ArgumentError( "A NetworkService object must be specified for all NetTransaction objects." ); if (timeout < 0) throw new ArgumentError( "Timeout must be 0 (infinite) or greater to specify the number of milliseconds after which the transaction should be cancelled.\rBe sure to give the transaction enough time to complete normally." ); //Save information related to the transaction this.result_handler = result_handler; this.request_data = request_data; this.internal_responder = new Responder( net_result, net_status ); //should use override versions of these methods this.description = description; this.timeout = timeout; this.timeout_timer = null; //Grab a new transaction id, add the transaction to the list of active transactions, set up a timeout timer, and finally call the service method. this.transaction_id = transaction_count++; active_transactions.push( this ); //transaction is now registered; this is done BEFORE setting the timeout, and before actually sending it out on the network if (timeout > 0) //zero, represents an infinite timeout, so we'll only create and start a timer if there is a non-zero timeout specified { timeout_timer = new Timer( timeout, 1 ); timeout_timer.addEventListener( TimerEvent.TIMER, this.cancelTransaction, false, 0, true ); timeout_timer.start(); } network_service.call( internal_responder, request_data ); } //Finalizes a transaction by removing it from the active transactions list, and returns true. //Returns false to indicate that the transaction was already complete, and was not found in the active transactions list. private function completeTransaction():Boolean { var index:int = active_transactions.indexOf( this ); if (index > -1) { active_transactions.splice( index, 1 ); if (timeout_timer != null) { timeout_timer.stop(); timeout_timer.removeEventListener( TimerEvent.TIMER, this.cancelTransaction, false ); } return true; } else { //Transaction being removed was already completed or was cancelled return false; } } //An instance version of the static NetTransaction.cancelTransaction function, which automatically passes the transaction instance. public function cancelTransaction( details_status_object:Object = null ) { NetTransaction.cancelTransaction( this, details_status_object ); } //Cancels all active transactions immediately, forcing all pending transactions to complete immediately with a "NetTransaction.Call.Cancelled" status code. static public function cancelAllActiveTransactions( details_status_object:Object ) { for each (var transaction:NetTransaction in active_transactions) transaction.cancelTransaction( details_status_object ); } //Cancels the transaction by spoofing an error result object to the net_status callback. static public function cancelTransaction( transaction:NetTransaction, details_status_object:Object ) { //Build cancel event status object, containing somewhat standard properties [code,level,description,details,type]. var status:NetTransactionResultStatus = new NetTransactionResultStatus( "NetTransaction.Call.Cancelled", "error", //cancelling a transaction makes it incomplete, so the status level should be "error" "A network transaction was cancelled. The description given for the transaction was: " + transaction.description, details_status_object, //include, in the details, the status object passed to this method "" //no type specified ); //Call the net_status handler directly, passing a dynamic Object-typed version of the NetTransactionResultStatus to the net_status handler. transaction.net_status( status.ToObject() ); } //Result responder. Override, then call when you're ready to respond to pre-process the object returned to the result_handler. protected function net_result( result_object:Object ):void { if (completeTransaction()) if (result_handler != null) result_handler.call( null, new NetTransactionResult( this, result_object, null ) ); } //Status responder. Override, then call when you're ready to respond to pre-process the object returned to the result_handler. protected function net_status( status_object:Object ):void { if (completeTransaction()) if (result_handler != null) result_handler.call( null, new NetTransactionResult( this, null, NetTransactionResultStatus.FromObject( status_object ) ) ); } The NetTransactionResult and NetTransactionResultStatus classes are just simple data classes I've set up for type-safe results to be sent to a unified result handler function. It interprets results as an error if the NetTransactionResult has a non-null status property, otherwise, it interprets the result as a success and uses the included data. The NetworkService class you see is just a wrapper around the NetConnection class that handles specifying the call path, and also handles all the low-level NetConnection error events, packages status messages compatible with the NetTransaction class, and finally calls cancelAllTransactions. The beauty of this setup is that now no matter what kind of error happens, including timeouts, your result handler for a transaction will ALWAYS be called, with all the information you need to handle the result (success/error/timeout/canceled). This makes using the NetConnection object almost as simple and reliable as calling a local function! A: Not really. Unless you write your own functionality for aborting after a specified amount of time, using a Timer object (or better, a GCSafeTimer object, if you don't know that one, google it).
{ "language": "en", "url": "https://stackoverflow.com/questions/1237065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoid to get "system.indexes" as a collection name in casbah I'm using casbah to find collection names in a mongodb-database val mongoClient = MongoClient() val db = mongoClient("db_name") val coll = db.collectionNames() It also gives 'system.indexes' because each mongo database has that one. Is there any way to get rid from this ? A: You have to filter it by yourself. val coll = db.collectionNames().filterNot(_.startsWith("system."))
{ "language": "en", "url": "https://stackoverflow.com/questions/22031264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Emacs With GUI on mac os. Different keyboard layout key bindings I am using two version of emacs. One in terminal, and other from emacsformacosx.com. In terminal I can use non-English keyboard layout and everything fine. But emacs version with gui don't understands these commands. Why it happening? Why I can't just run terminal version with GUI? update: For example when I pressed M-x with non-English keyboard layout in minibuffer appear text - M-ч is undefined. ч is a symbol equal to x. Pressing same shortcut in terminal version of Emacs works fine. Emacs running on other OS haven't this problem. I think to solve it needs to run terminal version with gui and use it. It is impossible. But why?
{ "language": "en", "url": "https://stackoverflow.com/questions/24087904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the finding links from the post content I need some help in finding links in html code. function get_content_link( $content = false, $echo = false ){ if ( $content === false ) $content = get_the_content(); $content = preg_match_all('#[\'"]https?://([^/]+\.)*example.com/[^\'"]*[\'"]#siU', $content, $links ); $content = $links[1][0]; if ( empty($content) ) { $content = false; } return $content; } This doesn't work as it should I'm afraid. I don't know what is wrong because have no experience with preg_match. Any help would be appreciated. Thanks. A: This is the answer To help for all function get_Example( $content = false, $echo = false ){ if ( $content === false ) $content = get_the_content(); $regexp = '/href=\"https:\/\/example\.com\/([^\"]*)"/i'; if(preg_match_all($regexp, $content, $link)) { $content = $link[1][0]; } if ( empty($content) ) { $content = false; } return $content; }
{ "language": "en", "url": "https://stackoverflow.com/questions/23179319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to reset counter results to zero by clicking button in Python I made a game with python 3.9.5, kivy 2.0.0rc4 and kivymd 0.104.2. I've made counter. It's adding one after "check" button is pressed. Game works smoothly but I want to reset this counter results to zero by clicking "back" button. Because, when I get back to it, I want to start the game from the top. Technically restart the game. Here's my python code: class Begin(MDFloatLayout): def back_on(self): self.ids.to_back.source = 'icons/back_pressed.png' click = SoundLoader.load('sounds/clickb_effect.wav') if click: click.play() def back_off(self): self.ids.to_back.source = 'icons/back.png' myapp.screen_manager.transition = SlideTransition(direction='right', duration=.25) myapp.screen_manager.current = 'Second' def update_score(self, score_one): self.ids.score_one.text = score_one class Begin1After(MDFloatLayout): count = -1 my_text = StringProperty("0") def check_on(self): self.ids.to_check.source = 'icons/check_pressed.png' correct = SoundLoader.load('sounds/correct.wav') if correct: correct.play() def check_off(self, *args): self.ids.to_check.source = 'icons/check.png' self.count += 1 self.my_text = str(self.count) begin = self.my_text = str(self.count) myapp.begin.update_score(begin) And here's my kivy/kivymd code: <Begin>: Label: id: score_one text: "0" color: 0, 1, 0, 1 pos_hint: {'x': -.22, 'y': .33} font_size: 80 font_name: 'CursedTimerUlil-Aznm' Button: size_hint: .1, .11 pos_hint: {'x': .01, 'y': .9} background_color: 0, 0, 0, 0 on_press: root.back_on() on_release: root.back_off() Image: id: to_back source: "icons/back.png" allow_stretch: True allow_ratio: True keep_ratio: True size: 160, 160 center_x: self.parent.center_x center_y: self.parent.center_y <Begin1After>: Label: text: root.my_text pos_hint: {'x': .0, 'y': .35} font_size: 100 bold: True color: 0, 20, 0, 1 Button: size_hint: .19, .11 pos_hint: {'x': .76, 'y': .14} background_color: 0, 0, 0, 0 on_press: root.check_on() on_release: root.check_off() Image: id: to_check source: "icons/check.png" allow_stretch: True allow_ratio: True keep_ratio: True size: 170, 170 center_x: self.parent.center_x center_y: self.parent.center_y A: Good day. 1. Reset Function Create a 'reset' method to contain all the code to revert your game as you might have other attributes to change as well. 2. Callback Method Create a callback function for your 'back' button. This callback might check for a condition before it calls the 'reset' method. i,e if game_won: reset()
{ "language": "en", "url": "https://stackoverflow.com/questions/68333177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ranking users with weekly date period and listing all first ranked users I have a table called coupons with schema below: CREATE TABLE "public"."coupons" ( "id" int4 NOT NULL, "suprise" bool NOT NULL DEFAULT false, "user_id" int4 NOT NULL, "start" timestamp NOT NULL, "win_price" numeric(8,2) NOT NULL DEFAULT 0::numeric, "fold" int4 NOT NULL DEFAULT 3, "pay" numeric(8,2) NOT NULL DEFAULT 0::numeric, "rate" numeric(8,2) NOT NULL DEFAULT 0::numeric, "win" varchar(255) NOT NULL DEFAULT 'H'::character varying COLLATE "default", "end" timestamp NOT NULL, "win_count" int4 NOT NULL DEFAULT 0, "match_count" int4 NOT NULL DEFAULT 0, "played" bool NOT NULL DEFAULT false, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL ) WITH (OIDS=FALSE); To rank users over win_price weekly I wrote the query below to get top 5 between 27-07-2015 and 03-08-2015: SELECT ROW_NUMBER() OVER(ORDER BY sum(win_price) DESC) AS rnk, sum(win_price) AS win_price, user_id, min(created_at) min_create FROM coupons WHERE played = true AND win = 'Y' AND created_at BETWEEN '27-07-2015' AND '03-08-2015' GROUP BY user_id ORDER BY rnk ASC LIMIT 5; I'm looking to a new query that lists first ranked users basis on weekly but in given date period. I.e : for the period between 01-09-2015 and 30-09-2015: rnk - win_price - user_id - min_create 1 - 1.52 - 1 - ........... (first week) 1 - 10.92 - 2 - ........... (send week) 1 - 11.23 - 1 - ........... (third week and so on) A: SELECT * FROM ( SELECT date_trunc('week', created_at) AS week , rank() OVER (PARTITION BY date_trunc('week', created_at) ORDER BY sum(win_price) DESC NULLS LAST) AS rnk , sum(win_price) AS win_price , user_id , min(created_at) min_create FROM coupons WHERE played = true AND win = 'Y' AND created_at BETWEEN '27-07-2015' AND '03-08-2015' GROUP BY 1, 4 -- reference to 1st & 4th column ) sub WHERE rnk = 1 ORDER BY week; This returns the winning users per week - the ones with the greatest sum(win_price). I use rank() instead of row_number(), since you did not define a tiebreaker for multiple winners per week. The added clause NULLS LAST prevents NULL values from sorting on top in descending order (DESC) - if you should have NULL. See: * *Sort by column ASC, but NULL values first? The week is represented by the starting timestamp, you can format that any way you like with to_char(). The key feature of this query: you can use window functions over aggregate functions. See: * *Postgres window function and group by exception Consider the sequence of events in a SELECT query: * *Best way to get result count before LIMIT was applied
{ "language": "en", "url": "https://stackoverflow.com/questions/31702597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: OData [JsonConverter] attribute serialization I am trying to use the default .Net serialization methods when serving OData via EntitySetController. When using: [DataContract] public class TestClassA { public int Id { get; set; } public string Stam { get; set; } [DataMember] public TestClassB TestClassB { get; set; } } public class TestClassB { public int Ids { get; set; } public string Name { get; set; } } The result of calling GET { "odata.metadata":"http://**MyHost**/odata/$metadata#TestClassA","value":[ { "TestClassB":{ "Ids":110,"Name":"Bla" } } ] } Which works great with the DataContract Attributes. However, when trying to use the [JsonConverter] attribute: public class TestClassA { public int Id { get; set; } public string Stam { get; set; } [JsonConverter(typeof(MyFormatter))] [DataMember(EmitDefaultValue = false)] public TestClassB TestClassB { get; set; } } public class TestClassB { public int Ids { get; set; } public string Name { get; set; } } public class MyFormatter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } } The JsonConverter is completely ignored. (the MyFormatter class is never created). Any idea how to make it work?
{ "language": "en", "url": "https://stackoverflow.com/questions/21409277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass properties to a method in another namespace I have defined some settings and plan on defining many more in my VS 2008 C# WPF project. I am aware that settings can be specified in the project through the settings designer at design time. I am also aware that the settings can be retrieved and set during run time. What I would like to do though is be able to access the settings from other assemblies and projects. I don't understand how this can be done without writing a new class. Since the settings class is defined in my root namespace, I can't access the settings directly from other assemblies without creating a circular reference (which is what happens if you try to add a reference to a project that is already referencing that project). Is there a way to pass the properties without having to create a duplicate class with the exact same property definitions? A: I understand you're trying to read properties from an assembly that you did not reference in your project. In that case, reflection is the answer. Read the info from that assembly, wherever the dll is. Load the Settings class, get the Default settings, and access the parameter you want. As an example, I have a dll called se2.dll, with a parameter that I'd normally access as: string parameterValue = se2.Settings2.Default.MyParameter; Now, from a different project, I have to use reflection like this: // load assembly System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(@"M:\Programming\se2\se2\bin\Debug\se2.exe"); // load Settings2 class and default object Type settingsType = ass.GetType("se2.Settings2"); System.Reflection.PropertyInfo defaultProperty = settingsType.GetProperty("Default"); object defaultObject = defaultProperty.GetValue(settingsType, null); // invoke the MyParameter property from the default settings System.Reflection.PropertyInfo parameterProperty = settingsType.GetProperty("MyParameter"); string parameterValue = (string)parameterProperty.GetValue(defaultObject, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/15800919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way of Creating lnk file using javascript mslink.sh As per this link Is there a way of Creating lnk file using javascript I am trying to create a .lnk file. I would like to know how to set the property Start In, which is a folder location of the .lnk file and also the .lnk file that I am trying to create has additional parameters in the Target property. Ex : Expected .lnk file properties Target : "C:\Windows\System32\Calc.exe" /mode:QWE /role:Admin Start In : C:\Windows\System32\ Is there a way of Creating lnk file using javascript A: You can use the WScript.Shell function CreateShortcut var objShell = new ActiveXObject("WScript.Shell") var lnk = objShell.CreateShortcut("C:\\my_shortcut.lnk") lnk.TargetPath = "C:\\Windows\\System32\\Calc.exe"; lnk.Arguments = "/mode:QWE /role:Admin"; lnk.Description = "Your description here..."; lnk.IconLocation = "C:\\Windows\\System32\\Calc.exe, 0"; lnk.WorkingDirectory = "C:\\Windows\\System32"; lnk.Save();
{ "language": "en", "url": "https://stackoverflow.com/questions/57909000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Brower cache issue for animated GIF loader image I am displaying animated GIF image as loader in the web page using below code. It's working fine. Loader image has animation which plays for 3 seconds and then stops and stays non-animated. <style> .content {display:none;} .loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999; background: url('../images/loader.gif?random=323527528432525.24234') 50% 50% no-repeat rgb(0,0,0, 0.90); } </style> <script> setTimeout(function(){ $('.loader').css('display', 'none'); }, 5000); </script> Now, when page is loaded first time or reloaded using CTRL+F5, animated GIF is displaying from start to end. For rest of the time, whenever page is refreshed, it just shows non-animated part of the loader image due to browser's caching. To resolve caching issue, I have tried following things but no one is working. #1 - I have attached random number as a query string after image name shown as below. background: url('../images/loader.gif?random=1234.5678') #2 - HTML headers to not to cache pages are mentioned as below: <meta http-equiv="Cache-control" content="no-cache"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Expires" content="-1"> Am I missing something more or else? Or is it not caching issue? Please advise.
{ "language": "en", "url": "https://stackoverflow.com/questions/65316799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }