_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d9901 | train | It's returning a JSON response. You can do var responseObj = JSON.parse(data) and access the fields like responseObj.imei or responseObj.brand | unknown | |
d9902 | train | You can use NSStrings size for string in the heightForRow: delegate method e.g.
CGSize maxSize = CGSizeMake(300, 800); //max x width and y height
NSString *cellTitle = @"Lorem ipsum";
UIFont *stringFont = [UIFont systemFontOfSize:14]; // use the same font your using on the cell
CGSize cellStringSize = [myString sizeWithFont:stringFont constrainedToSize:maximumSize lineBreakMode: UILineBreakModeWordWrap];
This will give you a CGSize you can then use the height from here and add a little padding. You can find more information here: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html
Tim
A: Use – sizeWithFont:constrainedToSize:lineBreakMode: of NSString (you can find more on this on this portal) or use an array containing height for every indexPath as shown in this example (SectionInfo class) http://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html. | unknown | |
d9903 | train | The smoothing attribute only affects how the video is scaled - that is, whether or not the video is smoothed if you play it at double size or the like. If your Video component is scaled the same size as the source video, this attribute won't do anything.
With that said, please understand that there's no such thing as anti-aliasing going on at the player end of things. Assuming that everything is the right size (so your video isn't being scaled up to 103% or anything), what you see in the Flash player is exactly the data in the source FLV. So any aliasing you see happened when the video was encoded, not at runtime.
So assuming your sizes are right, my guess would be that you should look at the encoding end of things to solve the problem. Is your FLV of a comparable size as the lossless quicktime? If it's a lot smaller, then you're probably compressing it a lot, and increasing the quality settings might help. Likewise, what codec did you use? If you're using the newest codec (H264), the quality ought to be very similar to a quicktime movie of similar size. But the older codecs can have significantly less quality. Especially the old Sorenson Sparc codecs (the ones that require player 6/7 or better to view) are pretty sad by today's standards. And especially the Sorenson codec was heavily customized for low-bandwidths, so even if you encode with very high quality settings you tend to get big increases in file size but very little increase in quality. For these reasons it's highly recommended to make sure you're using the newest codec available for the player version you're targeting.
If none of that helps, please update with some details about what codecs and encode settings you're using. | unknown | |
d9904 | train | Check your IPN history in PayPal. If it shows anything other than 200 response code you know something is wrong with your IPN listener.
You can check your web server logs to see exactly what error is happening when the script is hit.
Alternatively, you could setup a simple HTML form with hidden fields that match what you'd expect to get from PayPal. Then you can submit this in a browser so you can see the result on screen.
Keep in mind that testing this way will result in an INVALID response back from PayPal because the IPN data did not come from their server, but you can adjust for that accordingly for testing purposes, get your issues fixed, and then you'll be good to go.
A: Debugging tips: check your IPN configuration at the PayPal backend. Replace your script by a simple script that just shows you when it's called and with what input. | unknown | |
d9905 | train | Simple, just set the BindingContext of each of your tabs to the TabbedPage's BindingContext in your code-behind.
A: You have to add these properties in the XAML page to bind the viewmodel
xmlns:mvvm="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
mvvm:ViewModelLocator.AutowireViewModel="True" | unknown | |
d9906 | train | I do not know anything abuot FANN but I can assure you that R has an actively maintained interface to the Stuttgart Neural Net Simulator (SNNS) library via the
RSNNS package --- as RSNNS happens to employ the
Rcpp package for interfacing R and C++ which I am involved in. | unknown | |
d9907 | train | You've written the whole function as one big statement. You need to use delimiters. Here's the example from the MySQL manual:
mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> CALL simpleproc(@a);
Query OK, 0 rows affected (0.00 sec)
A: You must end each line/command with a ; so
BEGIN
DECLARE Distance FLOAT;
DECLARE EARTH_RADIUS FLOAT;
SET EARTH_RADIUS = 6378137.00;
etc .....
A: Add ';' as ManseUK suggested.
All declarations must be at the begining of the BEGIN...END clause -
CREATE DEFINER = CURRENT_USER FUNCTION GET_DISTANCE(LatBegin FLOAT,
LngBegin FLOAT,
LatEnd FLOAT,
LngEnd FLOAT
)
RETURNS FLOAT
BEGIN
DECLARE Distance FLOAT;
DECLARE EARTH_RADIUS FLOAT;
DECLARE dlat FLOAT;
DECLARE dlng FLOAT;
SET EARTH_RADIUS = 6378137.00;
SET LatBegin = LatBegin * PI() / 180.0;
SET LngBegin = LngBegin * PI() / 180.0;
SET LatEnd = LatEnd * PI() / 180.0;
SET LngEnd = LngEnd * PI() / 180.0;
SET dlat = LatBegin - LatEnd;
SET dlng = LngBegin - LngEnd;
SET Distance = (1 - COS(dlat)) / 2.0 + COS(LatBegin) * COS(LatEnd) * ((1 - COS(dlng)) / 2.0);
SET Distance = ASIN(SQRT(Distance)) * EARTH_RADIUS * 2.0;
SET Distance = ROUND(Distance * 10000, 2) / 10000;
RETURN Distance;
END | unknown | |
d9908 | train | Install VSCommand 2010.
Select two files then group two item from the context menu.
A: Right-click both files and click Exclude from project.
Then, click Show all Files on top of the Solution Explorer, then right-click the .cs file and click Include in project.
A: You mean one as a subtree of the other? If what SLaks says doesn't work you can edit the proj file.
I think it is like this, using the dependentupon xml
<Compile Include="FPtoICVService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="FPtoICVService.Designer.cs">
<DependentUpon>FPtoICVService.cs</DependentUpon>
</Compile> | unknown | |
d9909 | train | Better option would be to join tables and do aggregate.
You can join tables based on row_num from table2 and n1, n2, n3 from table1 as below.
SELECT
id,
SUM(points1) AS points1,
SUM(points2) AS points2,
SUM(points3) AS points3
FROM table1 JOIN table2
ON row_num in (n1, n2, n3)
GROUP BY id
Output of the query:
id
points1
points2
points3
a
86
99
31
c
122
183
118
b
91
59
15 | unknown | |
d9910 | train | One way would be to add a submit button to your form (it could be hidden) and invoke the click action so that it will trigger an asynchronous form postback:
<%using (Ajax.BeginForm("UpdateItem", "Products",
new AjaxOptions { UpdateTargetId = "content" })) {%>
<%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
<%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(), new { size = 2,
maxlength = 2, onchange = "document.getElementById('button').click();" })%>
<input type="submit" id="button" style="display: none" />
<% } %>
And if you don't like the idea of putting hidden buttons this also works but one may find it ugly:
<%using (Ajax.BeginForm(
"UpdateItem",
"Products",
new AjaxOptions {
UpdateTargetId = "content"
},
new {
id = "myForm"
}))
{ %>
<%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
<%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(),
new {
size = 2,
maxlength = 2,
onchange = "var event = new Object(); event.type='submit'; $get('myForm').onsubmit(new Sys.UI.DomEvent(event));"
})
%>
<% } %>
Off-topic: simplify your life with unobtrusive javascript and jQuery. | unknown | |
d9911 | train | You will want to create a server mapping of users to connection id's. See: SignalR 1.0 beta connection factory.
You will want to let your users persist past an OnDisconnected event and when they connect with a different connection Id you can continue pumping data down to them.
So the thought process could be as follows:
*
*Page loads, SignalR connection is instantiated
*Once connection is fully started call => TryCreateUser (returns a user, whether it existed or it was created).
*Long Running process Starts
*Client changes pages -> SignalR connection stops
*New Page loads, new SignalR connection is instantiated
*Once connection is fully started see if you have a cookie, session, or some type of data representing who you are => TryCreateUser(userData) (returns the user you created on the last page).
*Data continues pumping down to user.
Note: if you take an authentication approach you will have to be authenticated prior to starting a connection and that data cannot change during the lifetime of a SignalR connection, it can only be created/modified while the connection is in the disconnected state. | unknown | |
d9912 | train | This can be a solution
SELECT Date, Name
FROM SampleData
GROUP BY Date, Name
HAVING
MIN(Status) = 1
AND MAX(Status) = 2
A: Here is my solution:
declare @test table (Date varchar(8), Name varchar(3), status int)
insert @test values
('20200222','BBB',1),
('20200222','BBB',2),
('20200223','AAA',1),
('20200224','AAA',2),
('20200225','AAA',1),
('20200225','BBB',1),
('20200225','CCC',2),
('20200225','CCC',4),
('20200225','DDD',3),
('20200225','AAA',2)
select distinct date, name, status
from @test
where status in (1,2)
Edited:
This is NOT the solution. Sherkan's is, I did not understand well your first question. | unknown | |
d9913 | train | You can with the help of the extension Command Variable it allows you to use the content of a file as a command in the terminal. The file can also contain Key-Value pairs or be a JSON file.
Say you store this userTask.txt or userTask.json file in the .vscode folder and add the file to the .gitignore file.
With the current version of the extension the file userTask.txt has to exist, I will add an option to supply alternative text in case the file does not exist. You can fill the file with a dummy command like echo No User Task
Set up your task.json like
{
"version": "2.0.0",
"tasks": [
{
"label" : "do it",
"type" : "shell",
"windows": {
"command": "internal_command"
},
"linux": {
"command": "internalCommand"
},
"dependsOrder": "sequence",
"dependsOn": ["userTask"]
},
{
"label" : "userTask",
"type" : "shell",
"command": "${input:getUserTask}"
}
],
"inputs": [
{
"id": "getUserTask",
"type": "command",
"command": "extension.commandvariable.file.content",
"args": {
"fileName": "${workspaceFolder}/.vscode/userTask.txt"
}
}
]
} | unknown | |
d9914 | train | I think this is what you're asking for:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim counter As Integer
Dim filePath As String
Set wb = ActiveWorkbook
countet = 1
filePath = "c:/" 'Enter your destination folder here
For Each ws In wb.Sheets
Sheets("Sheet1").Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
ActiveWorkbook.SaveAs filePath & counter & ".xlsx", FileFormat:=51
counter = counter + 1
Next ws
End Sub
This is mostly taken from here.
The counter is a bit of a hack to make sure that the files aren't all being saved as the same name and overwriting each other. Maybe there's a more appropriate way that you can get around this. | unknown | |
d9915 | train | 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. | unknown | |
d9916 | train | You have already set functionAppScaleLimit to 1, another thing you should do is setting the batch size to 1 in host.json file according to this document :
If you want to minimize parallel execution for queue-triggered
functions in a function app, you can set the batch size to 1. This
setting eliminates concurrency only so long as your function app runs
on a single virtual machine (VM). | unknown | |
d9917 | train | You need to skip the first few lines, which you don't need.
Then split the lines to get the various numbers. Index 0 contains the serial no., 1 and 2 contain the coordinates. Then parse them to int. eg:
in.nextLine();// multiple times.
//...
String cs = in.nextLine(); // get the line
City city = new City(Integer.parseInt(cs.split(" ")[1]), Integer.parseInt(cs.split(" ")[2]));
TourManager.addCity(city);
String cs2 = in.nextLine();
City city2 = new City(Integer.parseInt(cs2.split(" ")[1]), Integer.parseInt(cs2.split(" ")[2]));
TourManager.addCity(city2);
String cs3 = in.nextLine();
City city3 = new City(Integer.parseInt(cs3.split(" ")[1]), Integer.parseInt(cs3.split(" ")[2]));
TourManager.addCity(city3);
A: Whenever you use in.nextLine(), actually it takes the string that you entered. So try to assign it to some string variable. For example:
String s =in.nextLine();
Also, just using in.nextLine(); which you did in 2nd,3rd 4th,8th and 9th line is not needed. | unknown | |
d9918 | train | Hi Finally i got the solution.
Here i am using getResponse = (HttpWebResponse)getRequest.GetResponse();
The problem is we can use only one HttpWebResponse at a time. In my case i am using the same object in two times without any disposing and closing. That's make me the error.
So I updated my code like this.
byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
getResponse = (HttpWebResponse)getRequest.GetResponse();
getresponse.Close();
This solved my error. Thanks | unknown | |
d9919 | train | I'm getting a SOAP request as string, from which I want to extract a
Java object. Is it possible?
Yes.
If yes, then how?
You need to convert the String into something that JAXB can unmarshal. Examples include a StringReader or XMLStreamReader.
What API can be used for this?
Since a SOAP message contains more information than what corresponds to the domain model I would recommend using JAXB with a StAX XMLStreamReader. You use StAX to parser the String. Then you advance the XMLStreamReader to the element that contains the content you wish to unmarshal. Then you unmarshal the XMLStreamReader at that point.
*
*http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html | unknown | |
d9920 | train | You could try something like:
Cells(i, 2).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText
Cells(i, 3).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText
Since address1, address2 and phone would all be in Cells(i, 3) you might want to use to use text to column to split them into their appropriate columns.
Additionally you could create an array to store these data in if you're doing a bigger search. Then you could paste the array values into their cells after you've finished scraping, like:
searchInfo(i, 1) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText
searchInfo(i, 2) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText
Then after looping:
For i = 1 to last row
Cells(i,2).Value = searchInfo(i, 1)
Cells(i,3).Value = searchInfo(i, 2)
Next i
You'd still have the text to column issue but that can be solved pretty easily with some code in the loop. Specifics just depend on how the third column's values come out.
EDIT: Based on your comments below, this worked for me. It might take a little customizing, but this is the idea.
' remove .getelementsbytagname("a")(0).Click and replace with this
.location = .getElementsByTagName("a").getAttributes("href") | unknown | |
d9921 | train | Before Initialising the Chart Object, fetch the data from the API and create the data array, then initialise the Chart Object.
If you want the graph to be continually changing, use Observables to get the data continuously and keep updating the charts. | unknown | |
d9922 | train | MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => {
if ((bool)e.NewValue == true)
{
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
{
// do something
}));
}
};
B:
MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => {
if ((bool)e.NewValue == true)
{
Dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() =>
{
// do something
}));
}
};
I thought the only difference between Invoke and BeginInvoke is that the first one waits for the task to be finished while the latter retuns instantly. Since the Dispatcher call is the only thing that happens in the EventHandler, I assumed that using Invoke would have the exact same effect as using BeginInvoke in this case. However I have a working example where this is clearly not the case. Take a look for yourself:
MainWindow.xaml
<Window x:Class="DataGridFocusTest.MainWindow"
x:Name="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DataGridFocusTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<TextBox DockPanel.Dock="Top"></TextBox>
<DataGrid x:Name="MyDataGrid" DockPanel.Dock="Top" SelectionUnit="FullRow"
ItemsSource="{Binding SomeNumbers, ElementName=MyWindow}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Data" Binding="{Binding Data}"
IsReadOnly="True" />
<DataGridTemplateColumn Header="CheckBox">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace DataGridFocusTest
{
public class MyDataClass
{
public string Data { get; set; }
}
public partial class MainWindow : Window
{
public IList<MyDataClass> SomeNumbers
{
get
{
Random rnd = new Random();
List<MyDataClass> list = new List<MyDataClass>();
for (int i = 0; i < 100; i++)
{
list.Add(new MyDataClass() { Data = rnd.Next(1000).ToString() });
}
return list;
}
}
public MainWindow()
{
InitializeComponent();
MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) =>
{
if ((bool)e.NewValue == true)
{
// whenever MyDataGrid gets KeyboardFocus set focus to
// the selected item
// this has to be delayed to prevent some weird mouse interaction
Dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() =>
{
if (MyDataGrid.IsKeyboardFocusWithin &&
MyDataGrid.SelectedItem != null)
{
MyDataGrid.UpdateLayout();
var cellcontent = MyDataGrid.Columns[1].GetCellContent(MyDataGrid.SelectedItem);
var cell = cellcontent?.Parent as DataGridCell;
if (cell != null)
{
cell.Focus();
}
}
}));
}
};
}
}
}
What we have here is a DataGrid which rows include a CheckBox. It implements two specific behaviors:
*
*When the DataGrid gets keyboard focus it will focus it's selected row (which for some reason is not the default behavior).
*You can change the state of a CheckBox with a single click even when the DataGrid is not focused.
This works already. With the assumption at the top of the post, I thought that it would not matter whether I use Invoke or BeginInvoke. If you change the code to BeginInvoke however, for some reason the 2cnd behavior (one-click-checkbox-selection) does not work anymore.
I don't look for a solution (the solution is just using Invoke) but rather want to know why Invoke and BeginInvoke behave so differently in this case. | unknown | |
d9923 | train | Since you're using componentWillReceiveProps to keep a local state in sync with props you have two alternatives:
Declare your initial state based on props and use componentDidUpdate to ensure props synchronicity
class Component extends React.Component{
state = { foo : this.props.foo }
componentDidUpdate(prevProps){
if(this.props.foo !== prevProps.foo)
this.setState({ foo : prevProps.foo })
}
}
This is actually triggering an extra render everytime, if you have some local state that is always equal to some prop you can use the prop directly instead.
Use getDerivedStateFromProps to update the state based on a prop change, but keep in mind that you probably don't need to use it
class Component extends React.Component{
static getDerivedStateFromProps(props){
return { foo : props.foo }
}
}
A: The answer to the question you asked is probably not going to be satisfactory. :-) The answer is that if you really need to derive state from props (you probably don't, just use props.errors directly in render), you do it with the newer getDerivedStateFromProps static method that accepts props and state and (potentially) returns a state update to apply:
static getDerivedStateFromProps(props, state) {
return props.errors ? {errors: props.errors} : null;
}
or with destructuring and without the unused state parameter:
static getDerivedStateFromProps(({errors})) {
return errors ? {errors} : null;
}
But, you're saying "But that doesn't do the authentication thing...?" That's right, it doesn't, because that componentWillReceiveProps shouldn't have, either, it violates the rule props are read-only. So that part shouldn't be there. Instead, if that entry in props.history is supposed to be there, it should be put there by the parent component. | unknown | |
d9924 | train | At the end of the day it's the docker container running on a machine and in docker container you can run services that listen to the data that is posted on those services. Some solutions can be:-
*
*A http server running on your edge module container and producers posting data to the RESTful api exposed by the container. Once data received, push it to IoT Hub using routes in edgeHub.
*You can also run a consumer on docker container that listens to a message broker and passes that data to IoT hub using edgeHub routes. | unknown | |
d9925 | train | If you look at the help for strings:
Usage: strings [option(s)] [file(s)]
Display printable strings in [file(s)] (stdin by default)
You see that stdin is the default behavior if there are no arguments. By adding - the behavior seems to change, which is strange, but I was able to reproduce that result too.
So it seems the correct way to do what you want is:
data-source | strings | grep needle
In a comment, you asked why not strings datasource |grep -o needle ?
If you could arrange that command so datasource is a stream, it might work, but it's usually easier to arrange that using |.
For example, the below are roughly equivalent in zsh. You'd have to figure out a way to do it in your shell of choice if that's not zsh.
strings <(tail -f syslog) | grep msec
tail -f syslog | strings | grep msec | unknown | |
d9926 | train | Since your FileUpload control is inside the InsertTemplate, you cannot access the FileUpload control directly. You have to do something like this:
Dim fileUpload As FileUpload = TryCast(YOURFORMVIEWID.FindControl("ErrorScreen"), FileUpload)
If fileUpload Is Nothing Then
' Handle if the FileUpload can't be found
Else
Dim filereceived = fileUpload.PostedFile.FileName
' Continue your code here...
End If | unknown | |
d9927 | train | There is no "best" - everything is contextual, and only you have most of the context.
However! Some minor thoughts on performance:
*
*a nested approach requires more objects; usually this is fine, unless your volumes are huge
*a nested approach may make it easier to understand the object model and the relationships between certain parts of the data
*a flat approach requires larger field numbers; field numbers 1-15 take a single byte header; field numbers 16-2047 require 2 bytes header (and so on); in reality this extra byte for a few fields is unlikely to hurt you much, and is offset by the overhead of the alternative (nested) approach:
*a nested approach requires a length-prefix per sub-object, or a start/end token ("group" in the protocol); this isn't much in terms of extra size, but:
*
*length-prefixe requires the serializer to know the length in advance, which means either double-processing (a "compute length" sweep), or buffering; in most cases this isn't a big issue, but it may be problematic for very large sub-graphs
*start/end tokens are something that google has been trying to kill, and is not well supported in all libraries (and IIRC it doesn't exist in "proto3" schemas); I still really like it though, in some cases :) protobuf-net (from the tags) supports the ability to encode arbitrary sub-data as groups, but it might be awkward if you need to x-plat later
Out of all of these things, the one that I would focus on if it was me is the second one.
Perhaps start with something that looks usable, and measure it for realistic data volumes; does it perform acceptably? | unknown | |
d9928 | train | I added some code to your Directory class. If you run it(I also added a Main method for testing purposes), you see it creates a list of directories and serializes this list as JSON. I added a constructor to make it easy to create some directories. I also added a getJSON method that serializes a directory. I added a getJSON(List directories) method to serialize a list of directories.
If you see to it this serialized list gets into your variable S3DirectoryList you can pass it to your javascript function as follows:
function showDirectory(dirList) {
var markup = "";
for(var i = 0; i < dirList.length; i++) {
markup += dirList[i].folderName + "<br />";
}
document.getElementById("dispdir").innerHTML = markup;
}
window.onload = function() {
showDirectory($(S3DirectoryList));
};
the Directory class:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Directory{
String folderName;
HashMap<String, String> objects;
List<Directory> dChild;
public Directory(String folderName, String[] objects) {
this.folderName = folderName;
this.objects = new HashMap<String, String>();
for(int i = 0; i < objects.length; i = i + 2) {
this.objects.put(objects[i], objects[i + 1]);
}
this.dChild = new ArrayList<Directory>();
}
public void addChildDirectory(Directory childDirectory) {
if(this.dChild == null)
this.dChild = new ArrayList<Directory>();
this.dChild.add(childDirectory);
}
public String toJSON() {
StringBuilder b = new StringBuilder();
b.append("{");
b.append("'folderName': '").append(folderName == null ? "" : folderName).append("'");
b.append(",objects: {");
if(objects != null) {
Iterator<Map.Entry<String, String>> objectsIterator = objects.entrySet().iterator();
if(objectsIterator.hasNext()) {
Map.Entry<String, String> object = objectsIterator.next();
b.append("'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
}
while (objectsIterator.hasNext()) {
Map.Entry<String, String> object = objectsIterator.next();
b.append(",'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
}
}
b.append("}");
b.append(",'dChild': ");
b.append("[");
if(dChild != null) {
if(dChild.size() > 0)
b.append(dChild.get(0).toJSON());
for(int i = 1; i < dChild.size(); i++) {
b.append(",").append(dChild.get(i).toJSON());
}
}
b.append("]");
b.append("}");
return b.toString();
}
public static String getJSON(List<Directory> directories) {
StringBuilder b = new StringBuilder();
b.append("[");
if(directories.size() > 0)
b.append(directories.get(0).toJSON());
for(int i = 1; i < directories.size(); i++) {
b.append(",").append(directories.get(i).toJSON());
}
b.append("]");
return b.toString();
}
private static Directory generateDirectory(int seed) {
List<Directory> directories = new ArrayList<Directory>();
for(int i = 0; i < 5; i++) {
directories.add(
new Directory(
"folderName_" + seed + "_" + i,
new String[]{"k_" + seed + "_" + i + "_1", "v_" + seed + "_" + i + "_1", "k_" + seed + "_" + i + "_2", "k_" + seed + "_" + i + "_2"}));
}
Directory directory_root = directories.get(0);
Directory directory_1_0 = directories.get(1);
Directory directory_1_1 = directories.get(2);
Directory directory_1_0_0 = directories.get(3);
Directory directory_1_0_1 = directories.get(4);
directory_root.addChildDirectory(directory_1_0);
directory_root.addChildDirectory(directory_1_1);
directory_1_0.addChildDirectory(directory_1_0_0);
directory_1_0.addChildDirectory(directory_1_0_1);
return directory_root;
}
public static void main(String[] args) {
List<Directory> directories = new ArrayList<Directory>();
for(int i = 0; i < 2; i++) {
directories.add(generateDirectory(i));
}
System.out.println(toJSON(directories));
}
} | unknown | |
d9929 | train | //first, check number through GET
if(isset($_GET['number'])){
$text = $_GET['number'];
}else{
//second, check REQUEST_URI
$urlparts = parse_url( $_SERVER['REQUEST_URI']);
$text = $urlparts['query'];
}
echo $text;
A: Take a look at the parse_url() function. It takes a URL as the input and returns an array containing all of the separate parts.
A slightly altered example from the documentation:
$url = 'http://username:[email protected]/path?arg=value#anchor';
print_r( parse_url( $url ) );
Outputs:
Array
(
[scheme] => http
[host] => example.com
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
I believe you are looking for the query part of the URL. From there you could possibly use the parse_str() function to split that string into variables. | unknown | |
d9930 | train | What helped me was checking every few seconds if my transactiopn finished, and if yes hiding the loader.
if (latestTx != null) {
window.web3.eth.getTransactionReceipt(latestTx, function (error, result) {
if (error) {
$(".Loading").hide();
console.error ('Error1::::', error);
}
console.log(result);
if(result != null){
latestTx = null;
$(".Loading").hide();
}
});
}
A: You don't need jquery to do this. React state can manage the status of the progress automatically. All you have to do is to call setState function.
class EthereumFrom1 extends React.Component {
state = {
loading: false
};
constructor(props) {
super(props);
this.doPause = this.doPause.bind(this);
}
doPause() {
const {pause} = this.state.ContractInstance;
pause(
{
gas: 30000,
gasPrice: 32000000000,
value: window.web3.toWei(0, 'ether')
},
(err) => {
if (err) console.error('Error1::::', err);
this.setState({loading: true});
})
}
render() {
return (
<div>
{this.state.loading ?
<div className="Loading">
Loading...
</div> : <div>done</div>
}
</div>
)
}
} | unknown | |
d9931 | train | On your last line, you could try using
call start sendMailApp.exe
I think this might fix it, call will cause start to run a new process and open a new window for the process which should show the GUI.
Docs here:
http://ss64.com/nt/call.html
http://ss64.com/nt/start.html | unknown | |
d9932 | train | Insight can be gained by looking at how Microsoft does this for the SQL Server service. In the Services control panel, we see:
Service name: MSSQLServer
Path to executable: "C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe" -sMSSQLSERVER
Notice that the name of the service is included as a command line argument. This is how it is made available to the service at run time. With some work, we can accomplish the same thing in .NET.
Basic steps:
*
*Have the installer take the service name as an installer parameter.
*Make API calls to set the command line for the service to include the service name.
*Modify the Main method to examine the command line and set the ServiceBase.ServiceName property. The Main method is typically in a file called Program.cs.
Install/uninstall commands
To install the service (can omit /Name to use DEFAULT_SERVICE_NAME):
installutil.exe /Name=YourServiceName YourService.exe
To uninstall the service (/Name is never required since it is stored in the stateSaver):
installutil.exe /u YourService.exe
Installer code sample:
using System;
using System.Collections;
using System.Configuration.Install;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.ServiceProcess;
namespace TestService
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private const string DEFAULT_SERVICE_NAME = "TestService";
private const string DISPLAY_BASE_NAME = "Test Service";
private ServiceProcessInstaller _ServiceProcessInstaller;
private ServiceInstaller _ServiceInstaller;
public ProjectInstaller()
{
_ServiceProcessInstaller = new ServiceProcessInstaller();
_ServiceInstaller = new ServiceInstaller();
_ServiceProcessInstaller.Account = ServiceAccount.LocalService;
_ServiceProcessInstaller.Password = null;
_ServiceProcessInstaller.Username = null;
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
_ServiceProcessInstaller,
_ServiceInstaller});
}
public override void Install(IDictionary stateSaver)
{
if (this.Context != null && this.Context.Parameters.ContainsKey("Name"))
stateSaver["Name"] = this.Context.Parameters["Name"];
else
stateSaver["Name"] = DEFAULT_SERVICE_NAME;
ConfigureInstaller(stateSaver);
base.Install(stateSaver);
IntPtr hScm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
if (hScm == IntPtr.Zero)
throw new Win32Exception();
try
{
IntPtr hSvc = OpenService(hScm, this._ServiceInstaller.ServiceName, SERVICE_ALL_ACCESS);
if (hSvc == IntPtr.Zero)
throw new Win32Exception();
try
{
QUERY_SERVICE_CONFIG oldConfig;
uint bytesAllocated = 8192; // Per documentation, 8K is max size.
IntPtr ptr = Marshal.AllocHGlobal((int)bytesAllocated);
try
{
uint bytesNeeded;
if (!QueryServiceConfig(hSvc, ptr, bytesAllocated, out bytesNeeded))
{
throw new Win32Exception();
}
oldConfig = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(ptr, typeof(QUERY_SERVICE_CONFIG));
}
finally
{
Marshal.FreeHGlobal(ptr);
}
string newBinaryPathAndParameters = oldConfig.lpBinaryPathName + " /s:" + (string)stateSaver["Name"];
if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
newBinaryPathAndParameters, null, IntPtr.Zero, null, null, null, null))
throw new Win32Exception();
}
finally
{
if (!CloseServiceHandle(hSvc))
throw new Win32Exception();
}
}
finally
{
if (!CloseServiceHandle(hScm))
throw new Win32Exception();
}
}
public override void Rollback(IDictionary savedState)
{
ConfigureInstaller(savedState);
base.Rollback(savedState);
}
public override void Uninstall(IDictionary savedState)
{
ConfigureInstaller(savedState);
base.Uninstall(savedState);
}
private void ConfigureInstaller(IDictionary savedState)
{
_ServiceInstaller.ServiceName = (string)savedState["Name"];
_ServiceInstaller.DisplayName = DISPLAY_BASE_NAME + " (" + _ServiceInstaller.ServiceName + ")";
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr OpenSCManager(
string lpMachineName,
string lpDatabaseName,
uint dwDesiredAccess);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr OpenService(
IntPtr hSCManager,
string lpServiceName,
uint dwDesiredAccess);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct QUERY_SERVICE_CONFIG
{
public uint dwServiceType;
public uint dwStartType;
public uint dwErrorControl;
public string lpBinaryPathName;
public string lpLoadOrderGroup;
public uint dwTagId;
public string lpDependencies;
public string lpServiceStartName;
public string lpDisplayName;
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool QueryServiceConfig(
IntPtr hService,
IntPtr lpServiceConfig,
uint cbBufSize,
out uint pcbBytesNeeded);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ChangeServiceConfig(
IntPtr hService,
uint dwServiceType,
uint dwStartType,
uint dwErrorControl,
string lpBinaryPathName,
string lpLoadOrderGroup,
IntPtr lpdwTagId,
string lpDependencies,
string lpServiceStartName,
string lpPassword,
string lpDisplayName);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseServiceHandle(
IntPtr hSCObject);
private const uint SERVICE_NO_CHANGE = 0xffffffffu;
private const uint SC_MANAGER_ALL_ACCESS = 0xf003fu;
private const uint SERVICE_ALL_ACCESS = 0xf01ffu;
}
}
Main code sample:
using System;
using System.ServiceProcess;
namespace TestService
{
class Program
{
static void Main(string[] args)
{
string serviceName = null;
foreach (string s in args)
{
if (s.StartsWith("/s:", StringComparison.OrdinalIgnoreCase))
{
serviceName = s.Substring("/s:".Length);
}
}
if (serviceName == null)
throw new InvalidOperationException("Service name not specified on command line.");
// Substitute the name of your class that inherits from ServiceBase.
TestServiceImplementation impl = new TestServiceImplementation();
impl.ServiceName = serviceName;
ServiceBase.Run(impl);
}
}
class TestServiceImplementation : ServiceBase
{
protected override void OnStart(string[] args)
{
// Your service implementation here.
}
}
}
A: I use this function in VB
Private Function GetServiceName() As String
Try
Dim processId = Process.GetCurrentProcess().Id
Dim query = "SELECT * FROM Win32_Service where ProcessId = " & processId.ToString
Dim searcher As New Management.ManagementObjectSearcher(query)
Dim share As Management.ManagementObject
For Each share In searcher.Get()
Return share("Name").ToString()
Next share
Catch ex As Exception
Dim a = 0
End Try
Return "DefaultServiceName"
End Function | unknown | |
d9933 | train | Write a stored Procedure that takes the filter query dynamically according to cases
Create procedure GetPoi (@Name nvarchar (100),@Version nvarchar (100))
as
begin
declare @Command nvarchar(max)
set @Command = 'select * from tablename where name ='''+@Name+''' and Version='''+@Version+''''
exec sp_executeSql @Command
end
Also you have to make a test to check if the Parameters provided are empty strings and modify your where clause accordingly.
Check Dynamic SQL for more info | unknown | |
d9934 | train | When a player quits a game, usually his/her actions are no longer relevant for new players. To avoid congestion on join, Photon server by default automatically cleans up events that have been cached by a player, that has left the room for good.
If you want to manually clean up the rooms' event cache you can create rooms with RoomOptions.CleanupCacheOnLeave set to false.
See the docs. | unknown | |
d9935 | train | Add this code in button.component.ts
@Output() clickFunctionCalled = new EventEmitter<any>();
callFunction() {
this.clickFunctionCalled.emit();
}
No change in button.template.html
Add this code where you use app-button component in html
<app-button (clickFunctionCalled)="callCustomClickFunction($event)"></app-button>
Add this in login.component.ts
callCustomClickFunction() {
console.log("custom click called in login");
this.login();
}
Basically, emit the click event from the child component. Catch the event in the parent component and call the desired function of the parent component.
You can also directly call the parent component's function like this
<app-button (clickFunctionCalled)="login($event)"></app-button>
As you are using dynamic component creator for creating the button component, you need to do something like this, for binding output event
loginButton.instance.clickFunctionCalled.subscribe(data => {
console.log(data);
}); | unknown | |
d9936 | train | That should work fine. If the preferences system is able to create the lock file, that means your app has appropriate privileges to create files in that directory and has correctly looked up the location where it should put them. Therefore, something else must be going wrong.
Is there any Console logging when this occurs? What's the return value of -synchronize?
(aside: in general -synchronize is not necessary and will just make your app slower, NSUserDefaults will handle that itself) | unknown | |
d9937 | train | As you say, add/0 expects an array as input.
Since it's a useful idiom, consider using map(select(_)):
echo "$json" | jq 'map(select(.name | contains("example")) | .amount) | add'
However, sometimes it's better to use a stream-oriented approach:
def add(s): reduce s as $x (null; . + $x);
add(.[] | select(.name | contains("example")) | .amount) | unknown | |
d9938 | train | [EDIT: Since you've added that you're using Android, here's the Java version.. I've also left the old python version below for reference]
String name = "ABC DEF GHI JKL MNO";
String[] splits = name.split(" ");
String a = splits[0];
String b = splits[1];
String c = splits[2];
String d = splits[3];
String e = splits[4];
System.out.println(b);
System.out.println(d);
The pre-edit Python 2.7 version:
name = "ABC DEF GHI JKL MNO"
a, b, c, d, e = name.split()
print(b)
print(d)
A: str.replace(" ","");
or
String name = yourString.replace(" ","");
or
str.split();
A: For PHP/Java/JavaScript AND C# the explode() function may be what you're looking for.
Example in PHP:
$strings[] = explode(" ", $name);
A: I would say the majority of languages/libs have some kind of string.split(); function. | unknown | |
d9939 | train | Yes, you can do this with the next commands:
The all following examples are valid:
@supports not (not (transform-origin: 2px)) - for test browser on non-support
or
@supports (display: grid) - for test browser on support
or
@supports (display: grid) and (not (display: inline-grid)). - for test both
See MDN for more info: https://developer.mozilla.org/en-US/docs/Web/CSS/@supports | unknown | |
d9940 | train | std::string vertShaderSource = LoadFileToString(vertShaderPath);
std::string fragShaderSource = LoadFileToString(vertShaderPath);
^^^^^^^^^^^^^^ wat
Don't try to use a vertex shader as a fragment shader.
Recommend querying the compilation and link status/logs while assembling the shader:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cstdarg>
struct Program
{
static GLuint Load( const char* shader, ... )
{
GLuint prog = glCreateProgram();
va_list args;
va_start( args, shader );
while( shader )
{
const GLenum type = va_arg( args, GLenum );
AttachShader( prog, type, shader );
shader = va_arg( args, const char* );
}
va_end( args );
glLinkProgram( prog );
CheckStatus( prog );
return prog;
}
private:
static void CheckStatus( GLuint obj )
{
GLint status = GL_FALSE;
if( glIsShader(obj) ) glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
if( glIsProgram(obj) ) glGetProgramiv( obj, GL_LINK_STATUS, &status );
if( status == GL_TRUE ) return;
GLchar log[ 1 << 15 ] = { 0 };
if( glIsShader(obj) ) glGetShaderInfoLog( obj, sizeof(log), NULL, log );
if( glIsProgram(obj) ) glGetProgramInfoLog( obj, sizeof(log), NULL, log );
std::cerr << log << std::endl;
exit( EXIT_FAILURE );
}
static void AttachShader( GLuint program, GLenum type, const char* src )
{
GLuint shader = glCreateShader( type );
glShaderSource( shader, 1, &src, NULL );
glCompileShader( shader );
CheckStatus( shader );
glAttachShader( program, shader );
glDeleteShader( shader );
}
};
#define GLSL(version, shader) "#version " #version "\n" #shader
const char* vert = GLSL
(
330 core,
layout( location = 0 ) in vec3 in_pos;
void main()
{
gl_Position.xyz = in_pos;
gl_Position.w = 1;
}
);
const char* frag = GLSL
(
330 core,
out vec3 color;
void main()
{
color = vec3(1,0,0);
}
);
int main()
{
if (glfwInit() == false)
{
//did not succeed
fprintf(stderr, "GLFW failed to initialise.");
return -1;
}
//4 AA
glfwWindowHint(GLFW_SAMPLES, 4);
//tells glfw to set opengl to 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(640, 480, "DJ KELLER KEEMSTAR", NULL, NULL);
if (!window)
{
fprintf(stderr, "Window failed to create");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
fprintf(stderr, "Glew failed to initialise");
glfwTerminate();
return -1;
}
//generate VAO
GLuint vaoID;
glGenVertexArrays(1, &vaoID);
glBindVertexArray(vaoID);
static const GLfloat verts[] =
{
//X, Y, Z
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
GLuint program = Program::Load
(
vert, GL_VERTEX_SHADER,
frag, GL_FRAGMENT_SHADER,
NULL
);
//generate VBO
GLuint vboID;
glGenBuffers(1, &vboID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
do
{
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glUseProgram(program);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
} while (glfwWindowShouldClose(window) == false);
return 0;
}
That way if you try something like:
GLuint program = Program::Load
(
vert, GL_VERTEX_SHADER,
vert, GL_VERTEX_SHADER,
NULL
);
...it will bail out early and give you a better indication of what went wrong:
Vertex shader(s) failed to link.
Vertex link error: INVALID_OPERATION.
ERROR: 0:2: error(#248) Function already has a body: main
ERROR: error(#273) 1 compilation errors. No code generated | unknown | |
d9941 | train | The correct syntax for SpEL would be like filterObject instanceof T(Project). (Please see SpEL section 6.5.6.1 - Relational operators) | unknown | |
d9942 | train | You're returning False too soon. Instead, you could keep a running tally of the amount of consecutive numbers you've seen so far, and reset it when you come across a number that breaks the streak.
def straightCheck(playerHand):
playerHand.sort()
tally = 1
for i in range(len(playerHand)-1):
if playerHand[i] != playerHand [i+1] - 1:
tally = 0
tally += 1
if tally >= 5:
return True
return False
A: Right now you check if numbers are not consecutive and then return false. I think you could better check if numbers are consecutive and if so raise a counter and if not then reset it. That way you know how many numbers are consecutive. If that is 5 or higher you should return True.
A: If you have a working function, you could just process all the 5-card sets in a loop:
for i in range(len(values) - 4):
is_straight = straightCheck(values[i:i+5])
if is_straight:
break
print(is_straight)
A: def straightCheck(playerHand):
playerHand.sort()
print(playerHand)
count = 0;
for i in range(len(playerHand)-1):
if playerHand[i] == playerHand [i+1] - 1:
count += 1
if count >= 5:
return True
else:
count = 0
return False | unknown | |
d9943 | train | Is there a way to do that without having to duplicate all fields in an interface?
You can put the object into a config property:
interface MyObjOptions {
a?:number;
b?:number;
c?:number;
d?:number;
}
class MyObj {
constructor(public options:MyObjOptions) {
}
}
But if you want defaults you have to list them in the interface + write them out so you must write e.g. a twice. No way around it | unknown | |
d9944 | train | import java.sql.*;
public class DescQueryOutput{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test","root","root");
Statement stmt = con.createStatement();
String query = "DESC newaccount";
ResultSet rs = stmt.executeQuery(query);
System.out.println("COLUMN NAME\tDATATYPE\tNULL\tKEY\tDEFAULT\tEXTRA");
while (rs.next())
{
System.out.print(rs.getString(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.print(rs.getString(4)+"\t");
System.out.print(rs.getString(5)+"\t");
System.out.println(rs.getString(6));
}
}
catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
}
}
} | unknown | |
d9945 | train | Thank you, upgrading to Python 3.7.3 solved the issue. | unknown | |
d9946 | train | PHP, being a server-side scripting language, is executed before the data is sent to your browser. JavaScript, a client-side scripting language, is executed as soon as the script is encountered by the browser.
Your approach is forgetting this separation between front- and back-end.
To accomplish what you're trying to do, simply output the setCookie call when you've submitted your form in php:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
printf( '<script>setCookie("ID", %d);</script>', $lastid );
}
?> | unknown | |
d9947 | train | To download the file on specific location you can try like blow.
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\Data_Files\output_files"
})
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
A: *
*You should not use hardcoded sleeps like time.sleep(20). WebDriverWait expected_conditions should be used instead.
*Adding a sleep between getting element and clicking it doesn't help in most cases.
*Clicking element with JavaScript should be never used until you really have no alternative.
*This should work in case the button you trying to click is inside the visible screen area and the locator is unique.
def scrape_data():
DRIVER_PATH = r"C:\chrome\chromedriver.exe"
driver = webdriver.Chrome(DRIVER_PATH)
wait = WebDriverWait(driver, 30)
driver.get('Link to the dashboard')
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Download CSV')]"))).click() | unknown | |
d9948 | train | Try to execute your .exe with Run as Adminstrator on the server.If it works properly then add the below code:
p.StartInfo.Verb = "runas";
A: @Chintan Udeshi Thank you for you quick answer. I can run the AcroRd32.exe by Run as Administrator but when I tried with runas I got the error which says; "No application is associated with the specified file for this operation".
I also tried to place absolute Acrobat Reader Path, but it still didn't work. Any idea?
p.StartInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe")
{
CreateNoWindow = true,
Verb = "runas",
FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf", // "c:\\pdf\\",
}; | unknown | |
d9949 | train | You can try something like this. $unwind the tracking array followed by $sort on tracking.keyword and tracking.created_at. $group by tracking.keyword and $first to get starting position, $avg to get average position and $last to get the today's position. Final $group to roll up everything back to tracking array.
db.website.aggregate([{
$match: {
"_id": ObjectId("58503934034b512b419a6eab")
}
}, {
$lookup: {
from: "seo_tracking",
localField: "website",
foreignField: "real_url",
as: "tracking"
}
}, {
$unwind: "$tracking"
}, {
$sort: {
"tracking.keyword": 1,
"tracking.created_at": -1
}
}, {
$group: {
"_id": "$tracking.keyword",
"website": {
$first: "$website"
},
"website_id": {
$first: "$_id"
},
"avg_position": {
$avg: "$tracking.position"
},
"start_position": {
$first: "$tracking.position"
},
"todays_position": {
$last: "$tracking.position"
}
}
}, {
$group: {
"_id": "$website_id",
"website": {
$first: "$website"
},
"tracking": {
$push: {
"keyword": "$_id",
"avg_position":"$avg_position",
"start_position": "$start_position",
"todays_position": "$todays_position"
}
}
}
}]); | unknown | |
d9950 | train | Its possible.
You can add this functions to ReflectionOnClass:
public void setNumber(int num){
this.number = num;
label.setText("X: " + this.number);
}
public int getNumber(){
return this.number;
}
and just call them from ExecReflection:
final ReflectionOnClass rF = new ReflectionOnClass();
rF.setNumber(4);
System.out.println("Value number: " + rF.getNumber());
A: Nothing is changing because you are not actually changing value that is displayed
private int number = 2;
private JLabel jLabel = new JLabel("X: " + number);
You need to access jLabel field, as this is your displayed value, and change text to something else, if number is used in other places, then you probably need to change both of them, so number to this example 100 value, and jLabel text to X: 100 | unknown | |
d9951 | train | You called your controller OrderPartController so your API URL should be /api/orderpart. Take off the s at the end. | unknown | |
d9952 | train | You have only declared the methods of the class. You also need to define (i.e. implement) them. At the moment, how should the compiler know the constructor of Person is supposed to do?
A: You need to link with the library or object file that implements class Person.
If you have a libqjson.a file on a Unix variant, you need to add -lqjson to your link command line. If you're on Windows with qjson.lib, you need to link with qjson.lib. If you have a .cpp file that implements Person, you need to compile it and link it with your executable. | unknown | |
d9953 | train | Change CSS:
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
vertical-align:top;
margin:0;
}
.large {
font-size: 50px;
line-height:1;
}
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
vertical-align:top;
margin:0;
}
.large {
font-size: 50px;
line-height:1;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
A: Here is the edited version of your code
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
margin:0;
}
.container p.first {
vertical-align:top;
line-height:40px;
}
.large {
font-size: 50px;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
A: You would need to change the code to look more like this:
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
margin:0;
}
.large {
font-size: 50px;
line-height:1;
}
.first {
vertical-align:top;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
A: That's how I would do it: https://jsfiddle.net/7ofrravh/5/ .
By making container flexible with content alignment an the start by using align-items: flex-start . Then simply fixing first paragraph position with a margin: 10px 0 0 0. | unknown | |
d9954 | train | I seems that your object doesn't get transparent, but rather that it is being covered by the other object even though it should be in front of it.
Sorting is a common problem with objects that use some sort of blending:
In this case this is probably due to the other object being in a ui element. You could try to enforce the draw order by modifying the render queue in the material, or force it to use depth testing by using an alpha cutout shader instead (but its edges will not look as nicely anti-aliased without an extra MSAA or FXAA) | unknown | |
d9955 | train | I think you've got the solution space right: Either disambiguate the call by passing in only explicitly size_t-typed ns, or use SFINAE to only apply the range constructor to actual iterators. I'll note, however, that there's nothing "magic" (that is, nothing based on implementation-specific extensions) about MSVC's _Is_iterator. The source is available, and it's basically just a static test that the type isn't an integral type. There's a whole lot of boilerplate code backing it up, but it's all standard C++.
A third option, of course, would be to add another fill constructor overload which takes a signed size. | unknown | |
d9956 | train | If you look at the NLTK classes for the Stanford parser, you can see that the the raw_parse_sents() method doesn't send the -outputFormat wordsAndTags option that you want, and instead sends -outputFormat Penn.
If you derive your own class from StanfordParser, you could override this method and specify the wordsAndTags format.
from nltk.parse.stanford import StanfordParser
class MyParser(StanfordParser):
def raw_parse_sents(self, sentences, verbose=False):
"""
Use StanfordParser to parse multiple sentences. Takes multiple sentences as a
list of strings.
Each sentence will be automatically tokenized and tagged by the Stanford Parser.
The output format is `wordsAndTags`.
:param sentences: Input sentences to parse
:type sentences: list(str)
:rtype: iter(iter(Tree))
"""
cmd = [
self._MAIN_CLASS,
'-model', self.model_path,
'-sentences', 'newline',
'-outputFormat', 'wordsAndTags',
]
return self._parse_trees_output(self._execute(cmd, '\n'.join(sentences), verbose)) | unknown | |
d9957 | train | Long poll with setWaitTimeSeconds(waitTimeSeconds)? Or switch from pull (via SQS) to push (via SNS)? | unknown | |
d9958 | train | Quick guess - Try (untested):
$write = '
<?php
include "/home/history/public_html/issue1.php";
echo \'<a class="prev" href="' . $data[16] . '">\';
?>
';
It's just a bit tricky with the multiple quotes... think you might have lost track of which ones need escaping...
Hmmmm... so that didn't work... the next thing I would try is to construct the $write variable over several lines (hopefully making the job a bit easier, so perhaps easier to avoid error) - note that I also threw in a repeating filewrite to see what the output is:
$hF = fopen('__debug.log', "a"); //outside your loop
//inside loop
$hrf = $data[16];
$write = '<?php' + "\n";
$write .= 'include "/home/history/public_html/issue1.php";' + "\n";
$write .= "echo '<a class=\"prev\" href=\"";
$write .= $hrf;
$write .= "\">';" + "\n";
$write .= '?>';
fwrite($hF, $write);
and make sure to close the file before your script ends:
//outside the loop
fclose($hF);
A: Using a variable inside a write statement didn't work while inside a fopen statement. I ended up having to use ob_start to get it to work. Hat tip to gibberish for getting me on the right path.
<?php
ob_start();
include 'issue1.php';
$issueone = ob_get_contents();
ob_end_clean();
$row = 1;
if (($handle = fopen("issue-heads-1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
$csv[] = $data;
}
fclose($handle);
}
$file = fopen($csv[$row][14], "w") or die("Unable to open file!");
fwrite($file, $issueone);
fwrite($file, "<a class=\"prev\" href=\"" . $csv[$row][16] . "\">");
fclose($file);
print "ok";
?>
A: If you have unique headers in your CSV
$headers = [];
while (false !== ($data = fgetcsv($handle))) {
if(empty($headers)){
$headers = $data; //["foo", "bar"] (for example)
continue; //skip to next iteration
}
//$data [1,2] (for example)
$row = array_combine($headers, $data);
//$row = ["foo"=>1,"bar"=>2] (for example)
}
Now you can use the text headers instead of 16 etc...
One thing to be careful of is array combine is very sensitive to the length of the arrays. That said if it errors you either have duplicate keys (array keys are unique) or you have either an extra , or a missing one for that line.
Array combine takes the first argument as the keys, and the second as the values and combines them into an associative array. This has the added benefit that the order of your CSV columns will not be important (which can be a big deal).
PS as I have no idea what your headers are, I will leave that part up to you. But lets say #16 is issues. Now you can simply do $row['issues'] just like a DB source etc...
Cheers. | unknown | |
d9959 | train | Implement NavigationDrawer in Main Activity instead of a fragment,
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, mToolBar, R.string.openDrawer, R.string.closeDrawer) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, 0); // this disables the animation
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> menuItemResList = Arrays.asList(getResources().getStringArray(R.array.nav_drawer_items));
ArrayList<String> menuItemResArrayList = new ArrayList<String>(menuItemResList);
final NavigationRecyclerAdapter navigationRecyclerAdapter = new NavigationRecyclerAdapter(MainActivity.this, menuItemResArrayList);
mRecyclerView.setAdapter(navigationRecyclerAdapter); | unknown | |
d9960 | train | It's not clear for me where is the js file. But you should try the same folder:
"./pages/counter.js"
A: Looks like pages has the same hierarchy level as index.html, so the path getting used is incorrect.
Try using the following path:
</div>
<script type="text/javascript" src="./pages/counter.js"></script>
Let me know in case of issues
A: Seems like your index file is in same directory as of pages. So try | unknown | |
d9961 | train | Figured it out. Very simple, in case someone else runs into the same issue:
var wordDialog =
Globals.ThisDocument.ThisApplication.Dialogs[Word.WdWordDialog.wdDialogFileSaveAs];
wordDialog.Show(); | unknown | |
d9962 | train | Late answer, but maybe it will help someone. For me the key to getting unique fb comments to render on a single page application was FB.XFBML.parse();
Each time I want to render unique comments:
*
*Change the url, each fb comments thread is assigned to the specific url
So I might have www.someurl.com/#123, www.someurl.com/#456, www.someurl.com/#789, each with its own fb comment thread. In AngularJs this can be done with $location.hash('123');
*Create a new fb-comments div, where 'number' equals '123', '456' or '789'
<div class="fb-comments" data-href="http://someurl.com/#{{number}}" data-numposts="5" data-width="100%" data-colorscheme="light">
</div>
*Call a function that executes the fb SDK
function FBfun(path) {
setTimeout(function() { // I'm executing this just slightly after step 2 completes
window.fbAsyncInit = function() {
FB.init({
appId : '123456789123',
xfbml : true,
version : 'v2.2'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
FB.XFBML.parse(); // This is key for all this to work!
}, 100);
}
A: i added the script to app.js like
initializeFB: function () {
if (!isFBInitialized.isInitialized) {
FB.init({
appId: 'xxxxxxxxxxxx',
appSecret: 'xxxxxxxxxxxxxxx',
// App ID from the app dashboard
channelUrl: '//mysite//channel.html', // Channel file for x-domain comms
status: true, // Check Facebook Login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // Look for social XFBML plugins on the page to be parsed
});
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any auth related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function (response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testFBAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct user interaction (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
isFBInitialized.isInitialized = true;
}
},
and call it in viewattached
as
app.initializeFB();
then it works well
A: Step 3 for my React app become (more linter friendly):
componentDidMount() {
window.fbAsyncInit = () => {
window.FB.init({
appId: '572831199822299',
xfbml: true,
version: 'v4.0',
});
};
(function (d, s, id) {
const fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
const js = d.createElement(s);
js.id = id;
js.src = '//connect.facebook.net/ru_RU/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
setTimeout(() => {
window.FB.XFBML.parse();
}, 100);
} | unknown | |
d9963 | train | Try to use this code:
@diagram = Diagram.new(diagram_params)
@diagram.save
component = Component.create(params.require(:isit).permit(:xposition, :yposition))
@diagram.components << component
@diagram.save
Or use accepts_nested_attributes_for in diagram model, and edit diagram_params method to add the following:
params.require(:diagram).permit(components_attributes: [:xposition, :yposition])
Read about accepts_nested_attributes_for | unknown | |
d9964 | train | use this code
<?php
global $post;
$foo_home_url = site_url();
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if(strpos($url, 'foo_cat')){
$foo_bc_name = get_queried_object()->name;
?>
<ul>
<li><a href="<?php echo $foo_home_url; ?>">Home</a></li>
<li><a href="<?php echo get_term_link($foo_tax_cat->slug, FOO_POST_TAXONOMY) ?>"><?php echo $foo_bc_name; ?></a></li>
</ul>
<?php
}
?>
instead of this code
<?php
global $post;
$foo_home_url = site_url();
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if(strpos($url, 'foo_cat')){
$foo_bc_cat = get_the_terms( $post->ID , FOO_POST_TAXONOMY );
?>
<ul>
<li><a href="<?php echo $foo_home_url; ?>">Home</a></li>
<?php
foreach($foo_bc_cat as $foo_tax_cat){
?>
<li><a href="<?php echo get_term_link($foo_tax_cat->slug, FOO_POST_TAXONOMY) ?>"><?php echo $foo_tax_cat->name ?></a></li>
<?php
}
?>
</ul>
<?php
}
?> | unknown | |
d9965 | train | Actions action = new Actions(webDriver);
action.moveToElement(webDriver.findElement(By.xpath("//*[@id='nav']/li[2]/a")))
.build()
.perform();
Thread.sleep(5000);
webDriver.findElement(By.xpath("//*[@id='nav']/li[2]/ul/li[1]/a")).click();
Note: Thread.sleep is not a good practice. Just use implicit wait in your program or/and WebDriverWait. | unknown | |
d9966 | train | So, I think you have a few issues here.
1. QWidget
The big one is that QWidget (which QQUickWidget inherits from) does not have a signal called "clicked", so the message QObject::connect: No such signal QQuickWidget::clicked() is quite right ;)
What you need to do is create your own object that inherits from QQuickWidget and then re-implement/overload the function void QWidget::mousePressEvent(QMouseEvent * event) and/or void QWidget::mouseReleaseEvent(QMouseEvent * event)
These are the functions that are called in the widget that you can then emit your signal. Which means you also need to add a new signal into you your widget. So your new class header may look a bit like (just including the main elements):
class MyQQuickWidget: public QQuickWidget
{
Q_OBJECT
public:
MyQQuickWidget(QWidget *parent = 0);
signals:
void clicked();
protected:
void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
};
And then in your implementation:
void MyQQuickWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
emit clicked();
}
}
Then when you connect your MyQQuickWidget signal clicked() to MyClass slot slot() it will connect ok.
2. QTimer
It looks like your timer should fire... but there appears to be no debug in the slot slot() so how would you know if this is working or not? | unknown | |
d9967 | train | which is not a Perl builtin function.
% perl -we 'print which("clang")'
Undefined subroutine &main::which called at -e line 1.
Keep in mind the Windows command line does not use the same quoting rules as the Linux command line, unless you're using something like WSL or bash for Windows.
The subroutine which is defined at https://github.com/openssl/openssl/blob/master/Configure#L3264 (or a similar line in other versions of the code). You'll need to make sure you've got all the build dependencies installed, all the application paths and library/include paths configured correctly, that you're following the installation directions accurately, and that you're doing things in the proper order.
You'll especially want to look in https://github.com/openssl/openssl/blob/af33b200da8040c78dbfd8405878190980727171/NOTES-WINDOWS.md and https://github.com/openssl/openssl/blob/master/NOTES-PERL.md to make sure you're following the OpenSSL project's recommendations for their build system on Windows if native Windows is where you intend to do the builds. | unknown | |
d9968 | train | There is nothing like a Physical Class Diagram, just class diagrams (you may consult Superstructures if you like). What you probably mean is the difference between class model and physical model. The latter focuses on the concrete implementation of a class model. It shows libs, hardware and things you'd need to implement your more abstract class model on some real hardware. With the MDA this part is called PSM (platform specific model) in contrast to the PIM (platform independent model). | unknown | |
d9969 | train | Your example is pretty flawed for any use case in which alerting the developers would be needed. This would need to alert the user not to input a negative number.
def times_two(x):
if x < 0:
raise BrokenException("Attn user. Don't give me negitive numbers.")
return x * 2
Although, I think if your example more accurately described an actual error needing developer attention then you should just fix that and not put it into production knowing there is an error in it.
sentry.io on the other hand can help find errors and help developers fix errors while in production. You may want to look into that if warnings isn't for you. From their README.me:
Sentry fundamentally is a service that helps you monitor and fix
crashes in realtime. The server is in Python, but it contains a full
API for sending events from any language, in any application.
A: Builtin Exception 'ValueError' is the one that should be used.
def times_two(x):
if x < 0:
raise ValueError('{} is not a positive number.'.format(x))
return x * 2
A: This seems like an XY problem. The original problem is that you have some code which is incomplete or otherwise known to not work. If it is something you are currently working on, then the correct tool to use here is your version control. With Git, you would create a new branch which only be merged into master and prepared for release to production after you have completed the work. You shouldn't release a partial implementation.
A: Do you want to stop execution when the function is called? If so, then some sort of exception, like the BrokenException in your example is a good way of doing this.
But if you want to warn the caller, and then continue on anyway, then you want a Warning instead of an exception. You can still create your own:
class BrokenCodeWarning(Warning)
pass
When you raise BrokenCodeWarning, execution will not be halted by default, but a warning will be printed to stderr.
The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception).
https://docs.python.org/3.7/library/warnings.html#the-warnings-filter | unknown | |
d9970 | train | I did a lot of digging and I was able to find something that worked.
There is a helper that comes with rails called options_for_select(). What this does is it will take something like this
<%= select_tag(:destination, '<option value="1">SLC</option>...') %>
And it will auto-generate the options using a multidimensional array
Since I already had a multidimensional array by using the select_options method, I was able to use them both in conjunction with each other like so:
<td><%= select_tag(:destination, options_for_select(Location.select_options)) %></td>
This pulls up exactly what I needed, and appends the correct value to the database when selected.
Another method is without the options_for_select helper, but it would need to have a parameter for which row is selected available.
@pallet = Pallet.find(2)
<td><%= select(:pallet, :destination, Location.select_options) %></td>
The advantage of this one is that it automatically defaults to what was already there. This makes it easier for when you update something that isn't the location. | unknown | |
d9971 | train | Your issue is with the XPath that Nokogiri is using. You need to specify what the namespace is in attributes. More info at the Nokogiri documentation.
Here is an example for looking up an item, using your params will probably work as well.
doc = Nokogiri::XML(File.read("sdn.xml"))
doc.xpath("//sd:lastName[text()='INVERSIONES EL PROGRESO S.A.']", "sd"=>"http://tempuri.org/sdnList.xsd")
>> [#<Nokogiri::XML::Element:0x80b35350 name="lastName" namespace=#<Nokogiri::XML::Namespace:0x80b44c4c href="http://tempuri.org/sdnList.xsd"> children=[#<Nokogiri::XML::Text:0x80b34e3c "INVERSIONES EL PROGRESO S.A.">]>]
A: user_input = "CHOMBO" # However you are getting it
doc = Nokogiri.XML(myxml,&:noblanks) # However you are getting it
doc.remove_namespaces! # Simplify your life, if you're just reading
# Find all sdnEntry elements with a lastName element with specific value
sdnEntries = doc.xpath("/sdnList/sdnEntry[lastName[text()='#{user_input}']]")
sdnEntries.each do |sdnEntry|
p [
sdnEntry.at_xpath('uid/text()').content, # You can get a text node's contents
sdnEntry.at_xpath('firstName').text # …or get an element's text
]
end
#=> ["7491", "Ignatius Morgan"]
#=> ["9433", "Marian"]
#=> ["9502", "Ever"]
Instead of requiring the exact text value, you might also be interested in the XPath functions contains() or starts-with(). | unknown | |
d9972 | train | Check out the curses module (http://docs.python.org/2/library/curses.html). | unknown | |
d9973 | train | With Frame.ofRecords you can extract the table into a dataframe and then operate on its rows or columns. In this case I have a very simple table. This is for SQL Server but I assume MySQL will work the same. If you provide more details in your question the solution can narrowed down.
This is the table, indexed by ID, which is Int64:
You can work with the rows or the columns:
#if INTERACTIVE
#load @"..\..\FSLAB\packages\FsLab\FsLab.fsx"
#r "System.Data.Linq.dll"
#r "FSharp.Data.TypeProviders.dll"
#endif
//open FSharp.Data
//open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Deedle
[<Literal>]
let connectionString1 = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\userName\Documents\tes.sdf.mdf"
type dbSchema = SqlDataConnection<connectionString1>
let dbx = dbSchema.GetDataContext()
let table1 = dbx.Table_1
query { for row in table1 do
select row} |> Seq.takeWhile (fun x -> x.ID < 10L) |> Seq.toList
// check if we can connect to the DB.
let df = table1 |> Frame.ofRecords // pull the table into a df
let df = df.IndexRows<System.Int64>("ID") // if you need an index
df.GetRows(2L) // Get the second row, but this can be any kind of index/key
df.["Number"].GetSlice(Some 2L, Some 5L) // get the 2nd to 5th row from the Number column
Will get you the following output:
val it : Series<System.Int64,float> =
2 -> 2
>
val it : Series<System.Int64,float> =
2 -> 2
3 -> 3
4 -> 4
5 -> 5
Depending on what you're trying to do Selecting Specific Rows in Deedle might also work.
Edit
From your comment you appear to be working with some large table. Depending on how much memory you have and how large the table you still might be able to load it. If not these are some of things you can do in increasing complexity:
*
*Use a query { } expression like above to narrow the dataset on the database server and convert just part of the result into a dataframe. You can do quite complex transformations so you might not even need the dataframe in the end. This is basically Linq2Sql.
*Use lazy loading in Deedle. This works with series so you can get a few series and reassemble a dataframe.
*Use Big Deedle which is designed for this sort of thing. | unknown | |
d9974 | train | Having this same issue, last time I resolved it by back-switching to Python 3.8.7 perhaps. But now I installed 3.11 and now again pysha3 is not installing. (Window 10) | unknown | |
d9975 | train | The solution:
You will need to browse to this installation path:
C:\SQLServer2017Media\<YOUR_SQL_ENU>\1033_ENU_LP\x64\Setup
Then while the setup is stuck at “Install_SQLSupport_CPU64_Action” run
SQLSUPPORT.msi
And follow the installation procedure.
Once installed, run the following command in cmd:
taskkill /F /FI "SERVICES eq msiserver"
The SQL Server setup will continue and succeed.
Edit:
according to @snomsnomsnom, it seems that SQL Server 2019 unpacks to C:\SQL2019...
if the error code is 0x851a001a, then you need to change the sector size of the hard drives. Here is the guideline for that.
https://learn.microsoft.com/en-us/troubleshoot/sql/admin/troubleshoot-os-4kb-disk-sector-size
A: I had this issue when installing sql server 2016, the taskkill solution not work for me. Therefore, I tried do uninstallation for SQL Server 2012 Native Client, and install the one in the setup\x64\sqlncli.msi and reinstall the sql server again, and no more issue anymore. | unknown | |
d9976 | train | Most of your ActionScript code must go inside a method; and you have code that must be put in a method. Variable definitions are okay. Import statements are okay. I think some directives, such as include are okay. But, other code must be in a method.
This is your annotated code:
<fx:Script>
<![CDATA[
// this is a variable definition so it is good
var xmlLoader:URLLoader = new URLLoader();
// these two lines are code that executes; so they must be put inside a method; something you did not do. Comment them out
//xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here
//xmlLoader.load(new URLRequest("books.xml")); // 2nd error here
// this is a variable definition so it is okay
var xmlData:XML = new XML();
// this is a function definition so it is okay
function loadXML(e:Event):void{
xmlData = new XML (e.target.data);
}
// move your executing code into a method
public function load():void{
xmlLoader.addEventListener(Event.COMPLETE, loadXML);
xmlLoader.load(new URLRequest("books.xml"));
}
]]>
</fx:Script>
I bet that removes your errors. However, you'll also want to / need to do something to execute that load method. When you do this depends on how the data is used in your app and the current component. But, I'd probably add a preinitialize event listener:
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
preinitialize="load()">
If preinitialize doesn't work; I'd move the code to the initialize event. If that doesn't work; I'd go to the creationComplete event. | unknown | |
d9977 | train | I have fixed the issue by calling default function in the axios.
const axios = require("axios").default; | unknown | |
d9978 | train | Have a try. This may fix this, but it may not be the proper solution. If anyone have any better idea, feel free to leave comments.
Just remove the __reduce__ method.
Then implement __getnewargs__ and __getnewargs_ex__
import pickle
class Cache:
def __init__(self):
self.d = {}
def __setitem__(self, obj, val):
self.d[obj] = pickle.dumps(val)
def __getitem__(self, obj):
return pickle.loads(self.d[obj])
def __contains__(self, x):
return x in self.d
class Car:
cache = Cache()
def __new__(cls, name, extra=None, _FORCE_CREATE=False):
if _FORCE_CREATE or name not in cls.cache:
car = object.__new__(cls)
car.init(name)
car.extra = extra
cls.cache[name] = car
return car
else:
return cls.cache[name]
def init(self, name):
self.name = name
def __repr__(self):
return self.name
def __getnewargs__(self):
return (self.name, None, True)
def __getnewargs_ex__(self):
# override __getnewargs_ex__ and __getnewargs__ to provide args for __new__
return (self.name, ), {"_FORCE_CREATE": True}
a = Car('audi', extra="extra_attr")
b = Car('audi')
print(id(a), a.extra) # 1921399938016 extra_attr
print(id(b), b.extra) # 1921399937728 extra_attr | unknown | |
d9979 | train | Fortran allocatables may imply dynamic memory allocation (whether or not that is then actually done on the offloading device), and that is implemented via support routines in libgfortran. I suppose _gfortran_os_error would be called in case of a memory allocation error. Per https://gcc.gnu.org/PR90386 "Offloading: libgfortran, libm dependencies" you currently have to manually specify -foffload=-lgfortran to resolve such errors. | unknown | |
d9980 | train | The general mental model is that unstaged changes are left alone, and everything else in the working copy is updated when checking out a different commit. Or as the docs put it:
git checkout <branch>
To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.
This is consistent with both cases that you've observed. | unknown | |
d9981 | train | If your input in prompt( either cmd or powershell) is causing problems due to incompatibility of using differents encodings just try to encode it via methods in script.encode "UTF-8" #in case of Ruby language If you dont know what methods do that just google your_language_name encoding | unknown | |
d9982 | train | First of all, your loop should start at viewlist.Items.Count - 1 and end at 0. This is because the right side of To is only evaluated prior to the first iteration. Due to this the loop will go to whatever viewlist.Items.Count - 1 was before the loop was run, instead of what it actually is after removing items (hence why you got the ArgumentOutOfRangeException from my previous code).
By starting from the end and going towards 0 i will always represent a valid index as long as you remove at most one item per iteration. This can be illustrated by the following:
First iteration Second iteration Third iteration (and so on)
Item 0 Item 0 Item 0
Item 1 Item 1 (i) Item 1
Item 2 (i) Item 2 [Removed]
(i) Item 3 [Removed] [Removed]
Now, to get a sub-column of an item you can use the ListViewItem.SubItems property. Your Gender column is currently at index 1 - the first sub-item (index 0) is apparently the owner of all sub-items, that is, the original ListViewItem.
For i = viewlist.Items.Count - 1 To 0 Step -1
Dim CurrentSubItems As ListViewItem.ListViewSubItemCollection = viewlist.Items(i).SubItems
If CurrentSubItems.Count >= 2 AndAlso CurrentSubItems(1).Text = ComboBox4.Text Then
viewlist.Items.RemoveAt(i)
End If
Next
ComboBox4.Items.Remove(ComboBox4.Text)
If you want to use case-insensitive string comparison you can change the If-statement in the loop to:
If CurrentSubItems.Count >= 2 AndAlso String.Equals(CurrentSubItems(1).Text, ComboBox4.Text, StringComparison.OrdinalIgnoreCase) Then | unknown | |
d9983 | train | First of All You Haven't included Document .ready in your Script
Here's The Code Try this
$(document).ready(function(){
var text=$('.pp-post-content-location').text(); //text Is Jquery Function which gets the content inside a element
if(text==""){
$('.pp-post-content-location').parent().hide();
}
});
Then Just a Simple If Condition to check That is there any Content In Specified Element If it has not Any content then it will hide the PARENT element | unknown | |
d9984 | train | PDO solution
Assuming you're using PDO(not specified by you), if you want to save it as blob then following steps should be done
try
{
$fp = fopen($_FILES['fic']['tmp_name'], 'rb'); // read the file as binary
$stmt = $conn->prepare("INSERT INTO image (titre, selogon, description, img_blob) VALUES (?, ?, ?, ?)"); // prepare statement
// bind params
$stmt->bindParam(1, $img_titre);
$stmt->bindParam(2, $selogon);
$stmt->bindParam(3, $description);
// this is important I will explain it below after the code
$stmt->bindParam(4, $fp, PDO::PARAM_LOB);
$stmt->execute();
// if you want to check if it was inserted use affected rows from PDO
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
The most important thing is bind the file pointer ($fp) to PDO param called LOB which stands for Large Object
PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.
http://php.net/manual/en/pdo.lobs.php
After that you can use power of PHP streams and save it as binary safe stream. Reading the from streams make more sense but if I were you I'd really think if you want to save pictures directly in db, this doesn't seem to be a good idea.
MYSQLI solution:
If you don't use PDO but for example mysqli then streams are good idea as well but the solution is different.
The best option is to check SHOW VARIABLES LIKE 'max_allowed_packet'; this will print what is max allowed package size, if your image is bigger the blob will be corrupted.
To make it work you'll need to send data in smaller chunks using fread() + loop + feof() and mysqli function send_long_data
Example from php.net site: you can adjust it to your needs quite similar as I did above, the difference is that params are bound in different way.
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen($_FILES['fic']['tmp_name'], "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
A: I have been solve the problem :
solution : in augmentation of size of photo in type (blob --> longblob ) . | unknown | |
d9985 | train | The build command should be run as npm run cordova -- build ios --release --device , double dashes are essential or else npm run does not pass build ios --release --device as arguments to cordova scripts. Uph, it's taken awhile for me to find it out. | unknown | |
d9986 | train | Assuming that the number of arguments is always even, you can do it simply like this:
bool check() {
return true;
}
template <typename T, typename... Ts>
bool check(T t1, T t2, Ts... ts) {
return t1 < t2 && (check(ts...));
}
A: #include <iostream>
template <typename ... Ints>
constexpr bool check( Ints... args) requires(std::is_same_v<std::common_type_t<Ints...>, int> && sizeof... (Ints) %2 == 0)
{
int arr[] {args...};
for(size_t i{}; i < sizeof... (args)/2; ++i){
if (!(arr[2*i] < arr[2*i + 1])) return false;
}
return true;
}
int main()
{
std::cout << check(4, 3, 7, 9, 2, 4);
}
requires(std::is_same_v<std::common_type_t<Ints...>> && sizeof... (Ints) %2 == 0) makes sure that the number of inputs is even and they are integers
Demo
A recursive version
template <typename Int, typename ... Ints>
constexpr bool check(Int int1,Int int2, Ints... ints)requires(std::is_same_v<std::common_type_t<Int, Ints...>, int> && sizeof... (Ints) %2 == 0)
{
if constexpr (sizeof... (Ints) == 0) return int1 < int2;
else return int1 < int2 && (check(ints...));
}
Demo | unknown | |
d9987 | train | Yes!
You can use both a fill color inside your rectangle and a stroke color around your rectangle.
Here is code an a Fiddle: http://jsfiddle.net/m1erickson/myGky/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "red";
ctx.fillRect(100,100,50,50);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(100,100,50,50);
ctx.fillStyle = this.color;
ctx.fillRect(105, 105, 40, 40);
ctx.fill();
ctx.beginPath();
ctx.rect(160,102.5,45,45);
ctx.fillStyle = 'rgb(163,0,0)';
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgb(204,0,0)';
ctx.stroke();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=600 height=400></canvas>
</body>
</html> | unknown | |
d9988 | train | You need to provide the relevant code and/or full traceback for anyone to know what exactly is going on, but that's likely just a warning that you're passing an id parameter to an API method that doesn't expect it.
Tweepy v4.0.0 changed many API methods to no longer accept id parameters.
A: You need to use screen_name instead of id parameter. | unknown | |
d9989 | train | Short answer you can't. Why?
Simply because 500 - Internal Server Error is exactly what it says Internal Server Error, it has nothing to do with Laravel. Server software (Apache in your case) causes error 500. Most likely permissions problem. (server software can not read / write to certain files etc.)
From Laravel documentation:
After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run.
You have to check Apache logs
Default on OSX machine /private/var/log/apache2
You want to see more errors? Follow up this SO thread.
Neat trick, make sure to have one entry per project in your hosts file.
#127.0.0.1 project1.dev www.project1.dev
#127.0.0.1 project2.dev www.project2.dev
.
.
.
Why? You can just comment out / delete line, searchable, easier to read.
A: @MajAfy You can use barryvdh/laravel-debugbar. This will give you in depth knowledge of every error. What query you are running and lot more.
Here is the link https://github.com/barryvdh/laravel-debugbar .
Its easy to install due to its well documentation.
A: After many tries, I found problem,
Everything return to file permissions,
I changed the permission of laravel.log in storage/logs to 777 and everything work fine ! | unknown | |
d9990 | train | You can test several types of histogram equalization techniques. I've scripted down two examples of histogram equalization with your above photo. You can than later keep preprocessing those raw results for better outcomes depending on your data variance.
import cv2
import matplotlib.pyplot as plt
# read a image using imread
img = cv2.imread("test.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# creating a Histograms Equalization
equ = cv2.equalizeHist(img_gray)
# clahe
clahe = cv2.createCLAHE(clipLimit=10.0, tileGridSize=(100,100))
cl = clahe.apply(img_gray)
# show image input vs output
plt.figure(figsize=(10,10))
plt.imshow(img)
plt.title("original image")
plt.show()
plt.figure(figsize=(10,10))
plt.imshow(equ, cmap='gray', vmin=0, vmax=255)
plt.title("histogram equalization")
plt.show()
plt.figure(figsize=(10,10))
plt.imshow(cl, cmap='gray', vmin=0, vmax=255)
plt.title("CLAHE")
plt.show()
The results are: | unknown | |
d9991 | train | You didn't post your entire grammar, so I cannot tell you what exactly is wrong with your grammar. You can however do something like this to parse your input:
file
: ( translation | COMMENT )* EOF
;
translation : '<' ( text | var_def )* '>' ;
text
: TEXT+
;
var_def
: VAR_DEF_START text VAR_DEF_END
;
COMMENT
: '//' ~[\r\n]*
;
SPACES
: [ \t\r\n]+ -> skip
;
VAR_DEF_START
: '${'
;
VAR_DEF_END
: '}'
;
TEXT
: '\\' [\\<>]
| ~[\\<> \t\r\n]
;
It is important to match single (!) TEXT characters in the lexer, and "glue" them together inside the text parser rule. If you try to match multiple TEXT chars in the lexer, you will end up matching too much characters. | unknown | |
d9992 | train | If proportions of document is known, you can draw appropriate inner (for min document size) and outer (for max document size) bounding rectangles on preview (as shown on pict) and control that user positioned document within outer and over inner bounding rect. That is also helps to control right document angle. Also You can control tilt and orientation of smartphone as described in answers for this questions.
Then process preview image (or even its small copy) on-the-fly with lightweight quality estimation algorithms and inform user about low quality and its reason (e.g. low brightness, you can estimate brightness of outer rectangle region, for example, as described in this question) and, may be, block "take snapshot" control.
A: You can use classifier (Machine Learning techniques) to reject low quality images using various features which can differentiate between low and good quality or images captured from long distance by detecting the document in the image. | unknown | |
d9993 | train | template<class T> void f(T,
typename size_map<sizeof(&U::foo)>::type* = 0);
This doesn't work, because U does not participate in deduction. While U is a dependent type, during deduction for f it's treated like a fixed type spelled with a nondependent name. You need to add it to the parameter list of f
/* fortunately, default arguments are allowed for
* function templates by C++0x */
template<class T, class U1 = U> void f(T,
typename size_map<sizeof(&U1::foo)>::type* = 0);
So in your case because U::foo does not depend on parameters of f itself, you receive an error while implicitly instantiating S<X> (try to comment out the call, and it should still fail). The FCD says at 14.7.1/1
The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates;
That is, if you implicitly instantiate S<X> the following function template declaration will be instantiated
template<class T> void S<X>::f(T,
typename size_map<sizeof(&X::foo)>::type* = 0);
Analysis on that template declaration will then find that it can't resolve the reference to X::foo and error out. If you add U1, the template declaration will not yet try to resolve the reference to U1::foo (since U1 is a parameter of f), and will thus remain valid and SFINAE when f is tried to be called. | unknown | |
d9994 | train | Default file sizes for MongoDB
.ns => 16MB
.0 => 64 MB
.1 => 128 MB
.2 => 256 MB
.3 => 512 MB
.4 => 1024 MB
Add that up and you're just under 2GB. So if you've filled the .4 file, then you won't be able to allocate any more space. (the .5 file will be 2GB)
If you log into Mongo and do a db.stats(), how much space are you using? That should tell you how close you are to the limit.
A: What size is the /data/db? This error is most likely from Mongo trying to allocate a new database file and that new file would push the size of the db past 2GB. MongoDB allocates database files in fairly large chunks so if you are anywhere near 2GB this could be the problem. | unknown | |
d9995 | train | When you map a folder from the host to the container, the host files become available in the container. This means that if your host has file a.txt and the container has b.txt, when you run the container the file a.txt becomes available in the container and the file b.txt is no longer visible or accessible.
Additionally file b.txt is not available in the host at anytime.
In your case, since your host does not have sample.sh, the moment you mount the directory, sample.sh is no longer available in the container (which causes the error).
What you want to do is copy the sample.sh file to the correct directory in the host and then start the container.
A: The problem is in volume mapping. If I create a volume and map it subsequently it works fine, but directly mapping host folder to container folder does not work.
Below worked fine
docker volume create my-vol
docker run -d -p 8081:8080 --name Test -v my-vol:/test test:v1 | unknown | |
d9996 | train | using 'pd.concat' can do the job here.
import pandas as pd
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
print 'df1:\n', df1
appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print 'appended\n:',appended
df_concat =pd.concat([appended,df1],axis=0)
print 'concat\n:',df_concat
Will results with:
df1:
Series_Date Value Type Desc
0 2017-03-10 1 SP Check SP
1 2017-03-10 1 1M Check 1M
2 2017-03-10 1 3M Check 3M
3 2017-03-13 1 SP Check SP
4 2017-03-13 1 1M Check 1M
5 2017-03-13 1 3M Check 3M
appended
: Series_Date Value Type Desc
0 2017-03-13 1 SP Check SP
1 2017-03-13 1 1M Check 1M
2 2017-03-13 1 3M Check 3M
concat
: Series_Date Value Type Desc
0 2017-03-13 1 SP Check SP
1 2017-03-13 1 1M Check 1M
2 2017-03-13 1 3M Check 3M
0 2017-03-10 1 SP Check SP
1 2017-03-10 1 1M Check 1M
2 2017-03-10 1 3M Check 3M
3 2017-03-13 1 SP Check SP
4 2017-03-13 1 1M Check 1M
5 2017-03-13 1 3M Check 3M
A: How about merging on both desc and Series_date
adfs = {k:df.merge(appended,on=['Desc' , 'Series_Date'], how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}
A statement like appended.Desc == df.Desc is problematic, as these series are of different shape. You can try isin, such as appended.Desc.isin(df.Desc). | unknown | |
d9997 | train | One possibility would be to find the cumulative maxima of the vector, and then extract unique elements:
unique(cummax(a))
# [1] 2 5 6 8
A: The other answer is better, but i made this iterative function which works as well. It works by making all consecutive differences > 0
increasing <- function (input_vec) {
while(!all(diff(input_vec) > 0)){
input_vec <- input_vec[c(1,diff(input_vec))>0]
}
input_vec
} | unknown | |
d9998 | train | It doesn't look to me like you need the model to be posted to your controller for what you're doing. In addition, yes, you absolutely can do this with jquery! On a side note, you could also do it with an Ajax.BeginForm() helper method, but lets deal with your jquery example.
Rather than complexify your jquery with your @Url.Action, you can simply call the path itself.
$("#btnrefresh").click(function () {
var ref = 'ControllerName/RefreshDepartments';
$.each(result, function (index, val) {
$('#whateverYourRenderedDropdownListHtmlObjectis')
.append($("<option></option>")
.attr("value", val.Text)
.text(val.Text));
});
});
Now, for your controller...
public JsonResult RefreshDepartments()
{
return Json(GetDepartments, JsonRequestBehavior.AllowGet);
}
private SelectList GetDepartments
{
var deparments = GetDepartments;
SelectList list = new SelectList(departments);
return list;
}
This is an alternative to returning the model. It allows you to manipulate the raw JSON instead. Hope it helps!
A: You almost did it all! Why don't you send the data, I mean list, by RefreshDepartments action? You sent a message to view, so you can send the list similarly and instead of alerting the result you can fill the dropdownlist. something like this:
public ActionResult RefreshDepartments(EmployeeModel empModel)
{
return Json(new { departments = GetDepartments()}, JsonRequestBehavior.AllowGet);
}
$.getJSON(ref, data, function (result) {
$("#Department").html("");
for (var i = 0; i < result.departments.length; i++) {
var item = result.departments[i];
$("#Department").append(
$("<option></option>").val(item.Id).html(item.Name);
);
});
}); | unknown | |
d9999 | train | If you have a vector representing the arrow, you could make a unit vector then times it by the length that you want and place the point at the end of the new shortened vector.
A: You already know the angle and location of the arrow, so what you should do is just draw the point based on the arrows end-point (the blunt end-point) and in the direction of the arrow + 90º. | unknown | |
d10000 | train | If you use addToBackstack to open new Fragments, it should work without the keyback listener. The fragmentTransaction manages this for you. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.