text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
PHP Force Download - Gives 190byte files
Been trying to get this to work for a while now, and I've read through a bunch of SO posts. But I've tried it all, and it doesnt work..
This is the code I'm trying now:
header("Content-type: application/octet-stream");
header("Content-Length: " . filesize($_REQUEST['file']));
header("Content-Disposition: attachment; filename=".basename($_REQUEST['file']));
readfile($_REQUEST['file']);
But it doesnt work. It works for all my other files, but not .FLV.
It shows size is 190bytes, and it only saves a file that's 190bytes. It does have the correct url, as I can enter the url in my browser and it plays the video.
Any ideas?
I've tried a lot of headers:
header('Pragma: public'); // required
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".basename($_REQUEST['file']));
header("Content-Type: video/mpeg");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($_REQUEST['file']));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0', false);
header('Cache-Control: private', false); // required for certain browsers
What I want is a savefile.php file that can save all the different video formats, and also zip, rar, exe and so on files. It would be great if there would be some way of supporting it all, based on the file extension given by the file...
EDIT:
I've even tried using fopen, but nothing works. It shows 190 bytes, but I know for a fact that the url is correct. And the file works (testing this locally on xampp now, so I have easy access to my files)
A:
Ahhh, found the answer.. Didnt think about opening up the 190 byte .flv file and check what was in it. There was an error message:
<br />
<b>Fatal error</b>: Allowed memory size of 134217728 bytes exhausted (tried to allocate 197980160 bytes) in <b>C:\xampp\htdocs\portfolio_003\savefile.php</b> on line <b>47</b><br />
So, I just had to change the value in php.ini
| {
"pile_set_name": "StackExchange"
} |
Q:
JSF - cannot display data from HashMap
I have this JSF page:
<div id="settingsdiv" style="width:350px; height:400px; position:absolute; background-color:r; top:20px; left:1px">
<h:form>
<h:panelGrid columns="2">
<h:panelGroup>User Session Timeout</h:panelGroup>
<h:panelGroup>
<h:selectOneMenu value="#{ApplicationController.settings['SessionTTL']}">
<f:selectItem itemValue="#{ApplicationController.settings['SessionTTL']}" itemLabel="#{ApplicationController.settings['SessionTTL']}" />
<f:selectItem itemValue="two" itemLabel="Option two" />
<f:selectItem itemValue="three" itemLabel="Option three" />
<f:selectItem itemValue="custom" itemLabel="Define custom value" />
<f:ajax render="input" />
</h:selectOneMenu>
<h:panelGroup id="input">
<h:inputText value="#{ApplicationController.settings['SessionTTL']}" rendered="#{ApplicationController.settings['SessionTTL'] == 'custom'}" required="true" />
</h:panelGroup>
</h:panelGroup>
<h:panelGroup>Maximum allowed users</h:panelGroup>
<h:panelGroup></h:panelGroup>
</h:panelGrid>
<h:commandButton value="Submit" action="#{ApplicationController.updateDBSettings()}"/>
</h:form>
</div>
And this bean:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/* include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import org.glassfish.osgicdi.OSGiService;
@Named("ApplicationController")
@SessionScoped
public class Application implements Serializable {
/* This Hash Map will be used to store setting and value */
private HashMap<String, String> settingsMap = null;
public Application(){
}
/* Call the Oracle JDBC Connection driver */
@Resource(name = "jdbc/Oracle")
private DataSource ds;
/* Hash Map
* Send this hash map with the settings and values to the JSF page
*/
public HashMap<String, String> getsettings(){
return settingsMap;
}
/* Get a Hash Map with settings and values. The table is genarated right
* after the constructor is initialized.
*/
@PostConstruct
public void initSettings() throws SQLException
{
settingsMap = new HashMap<String, String>();
if(ds == null) {
throw new SQLException("Can't get data source");
}
/* Initialize a connection to Oracle */
Connection conn = ds.getConnection();
if(conn == null) {
throw new SQLException("Can't get database connection");
}
/* With SQL statement get all settings and values */
PreparedStatement ps = conn.prepareStatement("SELECT * from GLOBALSETTINGS");
try
{
//get data from database
ResultSet result = ps.executeQuery();
while (result.next())
{
settingsMap.put(result.getString("SettingName"), result.getString("SettingValue"));
}
}
finally
{
ps.close();
conn.close();
}
}
/* Update Settings Values */
public void updateDBSettings() throws SQLException {
String SQL_Statement = null;
if (ds == null) throw new SQLException();
Connection conn = ds.getConnection();
if (conn == null) throw new SQLException();
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQL_Statement = "UPDATE GLOBALSETTINGS " +
"SET \"SettingValue\" = " +
"CASE " +
"WHEN \"SettingName\" = 'SessionTTL' THEN ? " +
"WHEN \"SettingName\" = 'MaxUsersActive' THEN ? " +
"END " +
"WHERE \"SettingName\" IN ('SessionTTL', 'MaxUsersActive')";
PreparedStatement updateQuery = conn.prepareStatement(SQL_Statement);
updateQuery.setString(1, settingsMap.get("SessionTTL"));
updateQuery.setString(2, settingsMap.get("MaxUsersActive"));
updateQuery.executeQuery();
conn.commit();
committed = true;
} finally {
if (!committed) conn.rollback();
}
}
finally {
conn.close();
}
}
}
When I try to enter some data into the input field and click submit button I don't see any data into the field when I reload the JSF page. I can see with SQL developer that the data into the database table is updated. Do you find any problems in the code?
Best wishes
Peter
A:
What if you create a method
public void setMapValue(String value) {
settingsMap.put("SessionTTL", value);
}
and use in the xhtml page:
<h:inputText value="#{ApplicationController.mapValue}" />
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change subdomain in requests test with Rspec (for API testing)
I have a question which is really specific.
I don't want to do a controller test but a requests test. And I don't want to use Capybara because I don't want to test user interaction but only response statuses.
I have the following test under spec/requests/api/garage_spec.rb
require 'spec_helper'
describe "Garages" do
describe "index" do
it "should return status 200" do
get 'http://api.localhost.dev/garages'
response.status.should be(200)
response.body.should_not be_empty
end
end
end
This works. But as I have to do more tests.. is there any way to avoid to repeat this? http://api.localhost.dev
I tried with setup { host! 'api.localhost.dev' } But it doesn't do anything.
A before(:each) block setting @request.host to something, of course crashes because @request is nil before performing any http request.
The routes are set correctly (and in fact they work) in this way
namespace :api, path: '/', constraints: { subdomain: 'api' } do
resources :garages, only: :index
end
A:
You can create a helper method in the spec_helper.rb, something like:
def my_get path, *args
get "http://api.localhost.dev/#{path}", *args
end
And its usage will be:
require 'spec_helper'
describe "Garages" do
describe "index" do
it "should return status 200" do
my_get 'garages'
response.status.should be(200)
response.body.should_not be_empty
end
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
What causes chain suck?
Specifically when changing gears from middle chain ring to smallest, the chain will sometimes get 'sucked' up between the inner chainring and chain stay. It seems to happen more often in muddy conditions. I keep my drive train clean and lube my chain often.
I bought the bike new and maybe 1200-1500 miles on the original chain/derailers.
I have swapped out the original (aluminum) inner chainring with a new steel chainring and still get chain suck.
A:
The problem you describe is caused by either a badly worn cog, a rear derailer with insufficient "tooth capacity" (given the gear combo you're using), a seriously deficient rear derailer tension spring, or a chain that is simply too long. A worn chain will tend to exacerbate things, as will a chain that's "sticky" from grease or mud.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't Authorize to MongoLab service on Azure
I have been created Mongodb Database via add-on of MongoLab on Azure Cloud. I have been able to connect to database but i always get below exception;
Command 'count' failed: db assertion failure (response: { "assertion"
: "unauthorized db:YourDefinition ns:YourDefinition.Terms lock type:1
client:94.245.107.14", "assertionCode" : 10057, "errmsg" : "db
assertion failure", "ok" : 0.0 })
How can i get rid of this problem ?
Update :
Here is my connection string
"mongodb://YourDefinitionDB:hQIkxfNlgF8rp6o6zb4KDVe_t8RILePrBLPieIvWS1M-@ds045087.mongolab.com:45087/YourDefinitionDB"
I have used wrong database name but still i get below exception.
Command 'authenticate' failed: auth fails (response: { "errmsg" :
"auth fails", "ok" : 0.0 })
I can say that it works on external gui but not via .net driver.
A:
This guide may help you get up and running: https://www.windowsazure.com/en-us/develop/net/tutorials/website-with-mongodb-mongolab/
Specifically these code snippets:
private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
private string dbName = "myMongoApp";
and
MongoServer server = MongoServer.Create(connectionString);
MongoDatabase database = server[dbName];
You would just need to set the "CUSTOMCONNSTR_MONGOLAB_URI" environment variable to be your MongoLab URI. Eg:
mongodb://<dbuser>:<dbpassword>@<host_name>.mongolab.com:<port>/<db_name>
EDIT: Just noticed your update containing the connection string. Looks like you're missing the db portion at the end of it. See the example connection string above.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I force my website to use a Google font instead of a locally one with the same name?
I'm using for a website the font Oxygen via GoogleFont. However, for webdesign purpose, I downloaded in my computer the Oxygen font via FontSquirrel.
Apparently it's the same, but it looks different and I have size issues. So I was thinking:
Is there a way to declare "I want to use the GoogleFont font and not the font stored in the computer even if it has the same name"?
Because if someone has a totally different font with the same name, there could be a lot of display problems.
EDIT: What about downloading the font on Google's server and hosting it on my website? (The font is 100% free for commercial use.) But why do a lot of websites use Google Fonts if it could be that simple?
A:
If you have the web fonts you could host yourself and give them any name you want in the css and avoid the potential of the local font loading.
For example:
@font-face {
font-family: 'myspecialfont';
src: url('oxygen-webfont.eot');
src: url('oxygen-webfont.eot?#iefix') format('embedded-opentype'),
url('oxygen-webfont.woff2') format('woff2'),
url('oxygen-webfont.woff') format('woff'),
url('oxygen-webfont.ttf') format('truetype'),
url('oxygen-webfont.svg#oxygenregular') format('svg');
font-weight: normal;
font-style: normal;
}
h1 {font-family: "myspecialfont", sans-serif;}
Just make sure you're pointing the CSS to the correct path for those files (e.g. if you put them in a fonts folder it'd could be "../fonts/oxygen-webfont")
The main reason people use google is they've optimized it for serving fonts, it takes load off your server, and potentially people have the font cached from google making it load faster. If it's an uncommon font and your server is decent these may negligible.
| {
"pile_set_name": "StackExchange"
} |
Q:
HLSL and DX Skybox Issues (creates seams)
I'm (re)learning DirectX and have moved into HLSL coding. Prior to using my custom .fx file I created a skybox for a game with a vertex buffer of quads. Everything worked fine...texture mapped and wrapped beautifully. However now that I have HLSL setup to manage the vertices there are distinctive seams where the quads meet. The textures all line up properly I just cant get rid of this damn seam!
I tend to think the problem is with the texCube...or rather all the texturing information here. I'm texturing the quads in DX...it may just be that I still don't quite get the link between the two..not sure. Anyway thanks for the help in advance!
Heres the .fx file:
float4x4 World;
float4x4 View;
float4x4 Projection;
float3 CameraPosition;
Texture SkyBoxTexture;
samplerCUBE SkyBoxSampler = sampler_state
{
texture = <SkyBoxTexture>;
minfilter = ANISOTROPIC;
mipfilter = LINEAR;
AddressU = Wrap;
AddressV = Wrap;
AddressW = Wrap;
};
struct VertexShaderInput
{
float4 Position : POSITION0;
};
struct VertexShaderOutput
{
float4 Position : POSITION0;
float3 TextureCoordinate : TEXCOORD0;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;
float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);
output.Position = mul(viewPosition, Projection);
float4 VertexPosition = mul(input.Position, World);
output.TextureCoordinate = VertexPosition - CameraPosition;
return output;
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
return texCUBE(SkyBoxSampler, normalize(input.TextureCoordinate));
}
technique Skybox
{
pass Pass1
{
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
A:
To avoid seams you need to draw your skybox in a single DrawIndexedPrimitive call, preferably using triangle strip. DON'T draw each face as separate primitive transformed with individual matrix or something like that - you WILL get seams. If you for some unexplainable reason don't want to use single DrawIndexedPrimitive call for skybox parts, then you must ensure that all faces are drawn using same matrix (same world + view + projection matrix used in every call) and same coordinate values for corner vertices - i.e. "top" face should use exactly same vectors (position) for corners that are used by "side" faces.
Another thing is that you should either store skybox as
cubemap (looks like that's what you're doing) - make just 8 vertices for skybox, draw them as indexed primitive.
Or an unwrapped "atlas" texture that has unused areas filled. with border color.
Or - if you're fine with shaders, you could "raytrace" skybox using shader.
| {
"pile_set_name": "StackExchange"
} |
Q:
ArcGIS Rest API returns No Results When Should Intersect
I can download statewide NY senate districts using ...
https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Current/MapServer/56/query?where=STATE+%3D+36&text=&objectIds=&time=&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentsOnly=false&datumTransformation=¶meterValues=&rangeValues=&f=geojson
When I query lat/lng against the api... I get zero results.
https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Current/MapServer/56/query?where=STATE+%3D+36&text=&objectIds=&time=&geometry=-73.831676%2C42.768687&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentsOnly=false&datumTransformation=¶meterValues=&rangeValues=&f=geojson
But when I map the statewide dataset and map the lat/lng I can see I should have an intersect. Can someone tell me why this intersect returns no results when the point falls within zone on the map???
A:
The spatial reference of the service you are querying is different from the one one of your point (EPSG 3857 vs EPSG 4326). You are trying to specify a geographic point in a projected coordinate system and therefore you get no intersection. However, you can specify the spatial reference of your point in the query with the inSR parameter. If you specify inSR=4326 in the query url you will get a result. Check the fourth line of the following url versus the fourth line of your query. inSR is empty in yours.
https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Current/MapServer/56/query?where=STATE+%3D+36&text=&objectIds=&time=&geometry=-73.831676%2C42.768687&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentsOnly=false&datumTransformation=¶meterValues=&rangeValues=&f=geojson
| {
"pile_set_name": "StackExchange"
} |
Q:
Change textbox depending on boolean parameter choice in SSRS
I have a report that holds two tables, one is for a Detail report and the other a Summary report. I've set it where if the Summary parameter (a boolean) is set to true then you only see the Summary table and vice versa if it's set to false. But I have a text box in the header that reads Report (Detail). I would like this text box to change depending on the same parameter, so if the summary parameter is set to "true" then the textbox will read Report (Summary) and if set to false it will read Report (Detail). How can I write this expression, I've searched but found nothing other than mentions of IIF expressions but I'm new to SSRS and don't know how to write these off the top of my head yet. Sorry if it has been answered I just couldn't find it.
This is how I have the expression for my Details visibility table to show if the Summary parameter is false (I found this out online too):
=IIF(Parameters!IsSummary.Value = 1, True,False)
A:
I believe you get rep for selecting an answer (I also gave your question an upvote)
=IIF(Parameters!IsSummary.Value = 1, "Report (Summary)", "Report (Detail)")
The basic structure of the Iif is:
Iif(<equality>,<do this when true>, <do this when not true>)
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add data Labels to seaborn countplot / factorplot
I use python3, seaborn countplot, my question :
how to add the count values for every bar? Show the label at the top of
each bar?
how to have these bars in descending order?
I wrote this:
fig = plt.figure(figsize=(10,6))
sns.countplot(data_new['district'],data=data_new)
plt.show()
Thanks a lot !
A:
I used a simple example data I generated but you can replace the df name and column name to your data:
ax = sns.countplot(df["coltype"],
order = df["coltype"].value_counts().index)
for p, label in zip(ax.patches, df["coltype"].value_counts().index):
ax.annotate(label, (p.get_x()+0.375, p.get_height()+0.15))
This generates:
You will be likely to play around with the location a little bit to make it look nicer.
| {
"pile_set_name": "StackExchange"
} |
Q:
FATAL EXCEPTION: AsyncTask #1:java.lang.RuntimeException: An error occured while executing doInBackground()
I'm trying to translate a language to another language with Microsoft Text Translator API. I already have this working on java, but when I ported it to Android. It gives me this error. It seems to be pointing me out to IOUtils but I think i already added that prerequisite in the Project Structure. Is there anyway to not use the IOUtils though?. Like OutputStream?. It seems that IOUtils is the problem, but IDK. I can't understand the logcat error. :/
my logcat is here:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.ExceptionInInitializerError
at org.apache.commons.io.IOUtils.write(IOUtils.java:2049)
at com.example.joshu.translatorownimplementation.MainActivity.translate(MainActivity.java:101)
at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:70)
at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:55)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NoClassDefFoundError: java.nio.charset.StandardCharsets
at org.apache.commons.io.Charsets.<clinit>(Charsets.java:120)
at org.apache.commons.io.IOUtils.write(IOUtils.java:2049)
at com.example.joshu.translatorownimplementation.MainActivity.translate(MainActivity.java:101)
at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:70)
at com.example.joshu.translatorownimplementation.MainActivity$LongOperation.doInBackground(MainActivity.java:55)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Here is my Code:
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MSTranslateAPI {
private static String output;
private static String key = "<MS KEY for Translator API>";
public static void main(String[] args) throws Exception {
// TODO: Specify your translation requirements here:
String fromLang = "en";
String toLang = "ko";
String text = "Hello Friend";
MSTranslateAPI.translate(fromLang, toLang, text);
}
public static void translate(String fromLang, String toLang, String text) throws Exception {
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setDoOutput(true);
authConn.setRequestMethod("POST");
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
authConn.disconnect();
System.out.println("TOKEN: "+token);
if(authConn.getResponseCode()==200) {
String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
String text2 = URLEncoder.encode(text, "UTF-8");
String from = fromLang;
String to = toLang;
String translatorTextApiUrl ="https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid="+appId+"&text="+text2+"&from="+from+"&to="+to+"&maxTranslations=5";
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("POST");
translateConn.setDoOutput(true);
IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
translateConn.disconnect();
System.out.println(resp+"\n\n");
}
else {
}
}
}
A:
The stacktrace in the logcat message indicates the StandardCharsets class is not available. According to https://developer.android.com/reference/java/nio/charset/StandardCharsets.html, the class is in the android JDK, but requires API version 19 or higher. You could upgrade the android version you target if you want to keep your use of IOUtils.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why was Abraham Lincoln an ape?
In Tim Burton's Planet of the Apes... what is up with the final scene? It was my favorite scene in the movie but is there actually a plausible explanation for it?
A:
It's not Lincoln.
It's General Thade
From the wikia
...Leo had returned to Earth in his own time only to find technologically-advanced apes in charge and a large statue of Thade in place of Abraham Lincoln on the Lincoln Memorial where it was written:
How Thade achieved his journey to Earth isn't explained, though an insert in the DVD release suggested that he took Leo Davidson's crashed spacepod, went to a point earlier in Earth's history and became a prominent leader in an ape uprising. In contrast, Dark Horse Comics' The Human War suggested that he died in disgrace on Ashlar. His disappearance could possibly have been assumed on his home planet to be a sign of weakness. The ending was intended to form the basis of a movie sequel, plans for which were soon abandoned.
| {
"pile_set_name": "StackExchange"
} |
Q:
Executing CREATE VIEW & ALTER VIEW from SQLCMD
I'm trying to execute a sql file with the following contents using sql cmd.
sqlcmd -S localhost\dbInstance -i Sample.sql -v filepath="C:\Sql\"
Sample.sql contents:
USE Sample_db
GO
BEGIN
BEGIN TRANSACTION;
BEGIN TRY
CREATE VIEW [dbo].[Test_View]
AS SELECT * from Sample_table;
ALTER VIEW [dbo].[Sample_View]
AS SELECT * FROM table_9;
ALTER TABLE [Sample_Table_2] ADD Col_4 VARCHAR(20);
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber ,
ERROR_SEVERITY() AS ErrorSeverity ,
ERROR_STATE() AS ErrorState ,
ERROR_PROCEDURE() AS ErrorProcedure ,
ERROR_LINE() AS ErrorLine ,
ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
END
GO
When I execute the sqlcmd, it throws the following error:
C:\Sql>sqlcmd -S localhost\dbInstance -i Sample.sql -v filepath="C:\Sql\"
Changed database context to 'Sample_db'.
Msg 156, Level 15, State 1, Server localhost\dbInstance, Line 5
Incorrect syntax near the keyword 'VIEW'.
Question:
Why am I not able to create view and alter view from sqlcmd, while I'm able to alter table?
When I comment out the CREATE VIEW and ALTER VIEW statement, the script executed fine.
Thanks!
A:
As per the manual:
The CREATE VIEW must be the first statement in a query batch.
Although, to tell the truth, that statement is rather misleading, because in actual fact CREATE VIEW must be the only statement in the batch, as you can ascertain for yourself from this illustration of a very simple test:
The error message in the Messages pane says Incorrect syntax near keyword 'SELECT', but if you hover over the underscored CREATE VIEW statement, a hint message appears that reveals that you can't put anything neither before CREATE VIEW nor after its SELECT statement.
And it's precisely the same issue with ALTER VIEW.
So, you can have a CREATE VIEW and/or an ALTER VIEW statement(s) perform within a transaction (by delimiting them with GO keywords), but you will not be able to use BEGIN TRY ... BEGIN CATCH to catch exceptions raised by those statements.
Unless, as Aaron Bertrand correctly reminds me, you execute those statements as dynamic queries, using either EXEC(…) or EXEC sp_executesql …, something like this, perhaps:
…
BEGIN TRY
EXEC sp_executesql N'CREATE VIEW [dbo].[Test_View]
AS SELECT * from Sample_table';
EXEC sp_executesql N'ALTER VIEW [dbo].[Sample_View]
AS SELECT * FROM table_9';
ALTER TABLE [Sample_Table_2] ADD Col_4 VARCHAR(20);
END TRY
BEGIN CATCH
…
| {
"pile_set_name": "StackExchange"
} |
Q:
Scala case class to json schema
I want to generate json schema of case class in order to provide some information to other service that is going to expose my app with rest api
I've got this class:
case class Vendor(
name: String,
synonyms: List[String],
transalit: String,
urlPart: String)
How can i generate like this:
{
"type":"object",
"properties":{
"name":{
"type":"string"
},
"synonyms":{
"type":"array",
"items":{
"type":"string"
}
},
"translit":{
"type":"string"
},
"urlPart":{
"type":"string"
}
}
}
i found this: https://github.com/coursera/autoschema but sbt can't find dependency.
also i found this Is there a way to get a JSON-Schema from a Scala Case Class hierarchy? and this question is very similar to mine but there is no answer..
May be i'm looking for answer that doesn't exist. May be it's better to use some other techniques
A:
It seems that the Maven artifact for autoschema does not exist and this is why sbt can't find the dependency.
Good news is that with sbt you can import a project from github and add it as a dependency. In your build.sbt add the following:
lazy val autoschemaProject =
ProjectRef(uri("https://github.com/coursera/autoschema.git"), "autoschema")
lazy val root = (project in file(".")).dependsOn(autoschemaProject)
Notice that root might already be defined in your build.sbt, in this case only add dependsOn(autoschemaProject).
I tested this with sbt 0.13.7 and I managed to use autoschema to generate a json schema from a case class.
| {
"pile_set_name": "StackExchange"
} |
Q:
PhpSpreadsheet Populate cells using a loop
I am using PHP library PhpSpreadsheet and would like to populate a spreadsheet (xlsx) using data from MySQL table using a loop to iterate through the cells and rows, something similar to this:
.------------------------.
|ID first_name last_name |
|1 John Smith |
|2 John Doe |
`------------------------`
My table will have the first row as header (bold text) and the rows below will be the data from MySQL.
Here is the script I wrote for this purpose:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold( true );
$header_row_array = ['ID', 'First Name', 'Last Name'];
$spreadsheet->getActiveSheet()->fromArray( $header_row_array, NULL, 'A1' );
global $wpdb;
$query = 'SELECT * FROM custom_table WHERE DATE( ts ) BETWEEN SUBDATE( NOW(), 1) and NOW()';
$rows = $wpdb->get_results( $query, OBJECT );
foreach( $rows as $row ) {
for( $i = 2; $i <= count( $rows ) + 1; $i++ ) {
foreach( range( 'A', 'C' ) as $v ) {
switch( $v ) {
case 'A': {
$value = $row->id;
break;
}
case 'B': {
$value = $row->first_name;
break;
}
case 'C': {
$value = $row->last_name;
break;
}
}
$spreadsheet->getActiveSheet()->setCellValue( $v . $i, $value );
}
}
//echo '<pre>';var_dump( $row );echo '</pre>';
}
$writer = new Xlsx( $spreadsheet );
$writer->save( 'test.xlsx' );
I also think these loops are a crude way to solve this, if you have any idea on improvements please share!
The result I am getting is:
The same row data in every row, as if the outer loop doesn't really loop through the items.
Please advise.
Thanks
A:
The problem came from your loops.
$rows = [
['id'=> 1, 'first_name'=> 'John', 'last_name'=> 'Smith'],
['id'=> 2, 'first_name'=> 'Jane', 'last_name'=> 'Doe'],
];
foreach( $rows as $row ) {
for( $i = 2; $i <= count( $rows ) + 1; $i++ ) {
foreach( range( 'A', 'C' ) as $v ) {
switch( $v ) {
case 'A': {
// $value = $row->id;
$value = $row['id'];
break;
}
case 'B': {
// $value = $row->first_name;
$value = $row['first_name'];
break;
}
case 'C': {
// $value = $row->last_name;
$value = $row['last_name'];
break;
}
}
print $v.$i.' : '. $value . "\n";
}
print '--------' . "\n";
}
}
return
A2 : 1
B2 : John
C2 : Smith
--------
A3 : 1
B3 : John
C3 : Smith
--------
A2 : 2
B2 : Jane
C2 : Doe
--------
A3 : 2
B3 : Jane
C3 : Doe
--------
Edit
For not thinking here is the solution
$i = 2;
foreach( $rows as $row ) {
foreach( range( 'A', 'C' ) as $v ) {
switch( $v ) {
case 'A': {
$value = $row->id;
break;
}
case 'B': {
$value = $row->first_name;
break;
}
case 'C': {
$value = $row->last_name;
break;
}
}
print $v.$i.' : '. $value . "\n";
}
$i++;
}
output
A2 : 1
B2 : John
C2 : Smith
A3 : 2
B3 : Jane
C3 : Doe
| {
"pile_set_name": "StackExchange"
} |
Q:
Create Index MATLAB
I'm fried from trying do this successfully. I have data A in a matrix with size(A) = [100 612]. The column data is in chunks of 12 months by 51 sites, i.e, 612 total columns.
I need to create an index to select columns in this sequence; 1:51:612 and then 2:51:612, etc. up to 51:51:612. The final array should be a 100 row by 612 column matrix with this sequence
Row 1: Columns 1-12=(1,52,103,154,205,256,307,358,409,460,511,562)
Columns 13-24=(2,53,104,155,206,257,308,359,410,461,512,563)
...
etc to the end of the first row with the last 12 columns with these numbers
Columns 601-612=(51,102,153,204,255,306,357,408,459,510,561,612).
Then repeated 100 times to give 100 rows. I need this to use as a logical index for extracting or to re-sort the original data in A given above.
A:
Here is a one-liner using permute and reshape
out = A(:,reshape(permute(reshape(1:612,51,[]),[2 1 3]),1,[]));
Or you could just avoid permute by using transpose
out = A(:,reshape(reshape(1:612,51,[]).',1,[]));
| {
"pile_set_name": "StackExchange"
} |
Q:
Access all TabBar buttons and UIButtons programmatically in iOS
I am in UIViewController and I want to access all UIButtons and TabBarButtons to disable them.
I tried with, and some other variations, but not working.
for (UITabBarItem *item in self.tabBarController.tabBarItem)
{
item.enabled = enable;
}
A:
You can disable the whole window interaction by adding:
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
Enable interaction again with:
if ([[UIApplication sharedApplication]isIgnoringInteractionEvents])
{
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Form a quadratic equation with the following details.
If $\alpha, \beta$ are the roots of the equation
$
x^2 - px + q = 0
$
and $\alpha_1, \beta_1$ are the roots of the equation $x^2 - qx + p = 0$,
Form the quadratic equation whose roots are
$$
\frac{1}{\alpha_1 \beta} + \frac{1}{\alpha \beta_1} and \frac{1}{\alpha_1 \alpha} + \frac{1}{\beta_1 \beta}
$$
A:
Calculation gives $$\left(\frac{1}{\alpha_1 \beta} + \frac{1}{\alpha \beta_1}\right)+\left(\frac{1}{\alpha_1 \alpha} + \frac{1}{\beta_1 \beta}\right)=\frac{(\alpha +\beta)(\alpha_1+\beta_1)}{\alpha\alpha_1\beta\beta_1}=1$$ and similarly
$$\left(\frac{1}{\alpha_1 \beta} + \frac{1}{\alpha \beta_1}\right)*\left(\frac{1}{\alpha_1 \alpha} + \frac{1}{\beta_1 \beta}\right)=\frac{p^3+q^3-4pq}{(pq)^2}$$ Then the equation is
$$(pq)^2X^2-(pq)^2X+p^3+q^3-4pq=0$$
| {
"pile_set_name": "StackExchange"
} |
Q:
sql reporting services unhandled error with subreport in 3rd level group
I'm getting an error when trying to put a subreport inside a inside a 3rd level group of a table or list (it doesn't matter, same error)
I have put a clean subreport without datasource without parameters, just a textbox
when I put that subreport inside 1st or 2nd level group it's ok, when I put it inside a 3rd level group(or higher) I receive an unhandled error.
A:
well, my solution is not to put suberports in 3rd level group, that's it for now
you could put the 3rd level, 4th level ... etc group in the subreport or somthing like that i guess, that's what i did
| {
"pile_set_name": "StackExchange"
} |
Q:
setting PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_PATH_PROPERTY
I have difficulties setting the capability PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_PATH_PROPERTY in my Java program correctly in order to use the newest version of Ghostdriver from github together with my installed phantomjs version (1.9.1)
Here is what I do in my Java program
DesiredCapabilities caps = DesiredCapabilities.phantomjs();
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"/xxx/phantomjs-1.9.1-linux-x86_64/bin/phantomjs" );
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_PATH_PROPERTY,
"/xxx/ghostdriver/src/main.js");
WebDriver driver = new PhantomJSDriver(caps);
The selenium driver starts correctly, if i do not set the PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_PATH_PROPERTY, but I get some errors in my tests that are supposed to be fixed in the current developer branch of ghostdriver. So i followed this advice and set up the cuttent github version of ghostdriver.
However, now I get the following error:
[ERROR - 2013-07-12T10:22:36.897Z] GhostDriver - Main - Could not start Ghost Driver => {
"message": "Could not start Ghost Driver",
"line": 79,
"sourceId": 140320571924032,
"sourceURL": "/xxx/ghostdriver/src/main.js",
"stack": "Error: Could not start Ghost Driver\n at /xxx/ghostdriver/src/main.js:79",
"stackArray": [
{
"sourceURL": "/xxx/ghostdriver/src/main.js",
"line": 79
}
]
}
My question is, does anyone know how to fix this? Must I change the config.js of ghostdriver somehow to make this work?
Info: I am crossposting this also to the github issues of ghostdriver.
A:
So I had the same problem, it was that the port I was attempting to use was already in use. Try a different port. i.e:
phantomjs --webdriver=8089 --webdriver-selenium-grid-hub=...
A:
I turns out, that this only works as expected for selenium version >= 2.33. I updated my selenium and this fixed the issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use item renderer to view multiple fields?
Our app contacts the server, and get a json based array, each item has:
First_Name
Last_Name
Image_Url
So, how to use the item renderer so that we can use custom data template to view name and image?
Also, can we have access to the json item being rendered from inside the renderer code?
Any examples would be highly appreciated.
A:
http://help.adobe.com/en_US/flex/using/WS77c1dbb1bd80d3836ecbb5ec129ec77b1e1-8000.html
just above the 'Controlling the background display of an item renderer' section, there is a custom itemrenderer example, you can use it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Geolocation package with laravel: Midnite81\Geolocation\GeoLocationServiceProvider' not found
I want to use the following package for geolocation with laravel.
https://github.com/midnite81/geolocation
I have done everything they wrote in their documentation but find an error
Midnite81\Geolocation\GeoLocationServiceProvider' not found
i am unable to solve this problem. Can't understand what's wrong. What i did, at first, write "midnite81/geolocation": "1.*" in the composer.json file.
"require": {
"php": ">=7.0.0",
"fideloper/proxy": "~3.3",
"laravel/framework": "5.5.*",
"laravel/tinker": "~1.0",
"midnite81/geolocation": "1.*"
},
After that run composer update. Then run composer dump-autoload -o. Then in the config/app.php file, put the following part in providers and aliases array.
'providers' => [
Midnite81\Geolocation\GeoLocationServiceProvider::class
];
'aliases' => [
'GeoLocation' => Midnite81\GeoLocation\Facades\GeoLocation::class,
];
then run the following command.
php artisan vendor:publish --provider="Midnite81\GeoLocation\GeoLocationServiceProvider"
Then got the error, Midnite81\Geolocation\GeoLocationServiceProvider' not found
Can't figure out what's wrong in it.
A:
I verified and confirm the problem.
The problem is:
Midnite81\Geolocation\GeoLocationServiceProvider::class
You should change this into
Midnite81\GeoLocation\GeoLocationServiceProvider::class
Notice the difference Geolocation vs GeoLocation. It seems there is error in readme for this package on Github
I've already sent Pull request https://github.com/midnite81/geolocation/pull/2 to fix readme for this package
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use javascript add image with link in specific explorer?
I want to add an image with link only when I in Safari, and this is my html and js.I am new for javascript.
var isSafari = navigator.userAgent.match("Safari") ;
if (isSafari) {
alert('You are using Safari or Google');
var image = document.createElement('img');
image.setAttribute('src','images/ar_but.png');
document.getElementsByClassName('gallery').getElementsByClassName('thumbnail').getElementById('AddImageInhere').appendChild(image);
}
<!-- Main Container -->
<div class="container">
<div class="gallery">
<div class="thumbnail">
<a href="#"><img src="images/icon01.jpg" alt="" width="2000" class="cards" /></a>
<h4>TITLE</h4>
<a href="sofa.usdz" rel="ar" id="AddImageInhere"> !!!</a>
<p class="tag">HTML, CSS, JS, WordPress</p>
<p class="text_column">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
</div>
</div>
<!-- Main Container Ends -->
But this code doesn't work. I want to add an image like right one at !!! here the result : one two
It appear the alert. But at !!! . There's no image.
I use brackets. Thank for reading.
edit:
Here is the error.
ERROR: 'navigator' is not defined. [no-undef] var isSafari = navigator.userAgent.match("Safari");
ERROR: 'alert' is not defined. [no-undef] alert('You are using Safari or Google');
ERROR: 'document' is not defined. [no-undef] var image = document.createElement('img');
ERROR: 'document' is not defined. [no-undef] document.getElementById('AddImageInhere').appendChild(image);
A:
Just remove the first 2 getElementsByClassName() functions. You can't chain them since they return a nodelist. Nodelists don't have the getElementsByClassName() function.
See https://developer.mozilla.org/en-US/docs/Web/API/NodeList
var isSafari = navigator.userAgent.match("Safari");
if (isSafari) {
alert('You are using Safari or Google');
var image = document.createElement('img');
image.setAttribute('src', 'https://dummyimage.com/600x400/000/fff');
document.getElementById('AddImageInhere').appendChild(image);
}
<!-- Main Container -->
<div class="container">
<div class="gallery">
<div class="thumbnail">
<a href="#"><img src="images/icon01.jpg" alt="" width="2000" class="cards" /></a>
<h4>TITLE</h4>
<a href="sofa.usdz" rel="ar" id="AddImageInhere"> !!!</a>
<p class="tag">HTML, CSS, JS, WordPress</p>
<p class="text_column">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>https://stackoverflow.com/questions/58320852/how-to-use-javascript-add-image-with-link-in-specific-explorer/58320966#
</div>
</div>
For multiple images I suggest using QuerySelector all and create a new image for each append.
var isSafari = navigator.userAgent.match("Safari");
if (isSafari) {
alert('You are using Safari or Google');
document.querySelectorAll('.AddImageInhere').forEach((el) => {
el.appendChild(getImage());
});
}
function getImage() {
var image = document.createElement('img');
image.setAttribute('src', 'https://dummyimage.com/600x400/000/fff');
return image;
}
<!-- Main Container -->
<div class="container">
<div class="gallery">
<div class="thumbnail">
<a href="#"><img src="images/icon01.jpg" alt="" width="2000" class="cards" /></a>
<h4>TITLE</h4>
<a href="sofa.usdz" rel="ar" class="AddImageInhere"> !!!</a>
<a href="sofa.usdz" rel="ar" class="AddImageInhere"> !!!</a>
<a href="sofa.usdz" rel="ar" class="AddImageInhere"> !!!</a>
<a href="sofa.usdz" rel="ar" class="AddImageInhere"> !!!</a>
<p class="tag">HTML, CSS, JS, WordPress</p>
<p class="text_column">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>https://stackoverflow.com/questions/58320852/how-to-use-javascript-add-image-with-link-in-specific-explorer/58320966#
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Task 'bundleReleaseJsAndAssets' not found in root project
I am unable to get a successful build with the React Native project in Jenkins. I get this error:
14:41:59 FAILURE: Build failed with an exception. 14:41:59 14:41:59 *
What went wrong: 14:41:59 Execution failed for task
':app:bundleDevReleaseJsAndAssets'. 14:41:59 > Process 'command
'node'' finished with non-zero exit value 1 14:41:59
I did find an answer here:
React-Native assembleRelease fails for task ':app:bundleReleaseJsAndAssets'
The problem is when its time to build, the second step:
./gradlew assembleRelease -x bundleReleaseJsAndAssets
I get this error:
FAILURE: Build failed with an exception.
* What went wrong:
Task 'bundleReleaseJsAndAssets' not found in root project 'engage-application.mobile'.
* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Running gradlew tasks does not provide any insights to me:
✗ gradle tasks
> Task :tasks
------------------------------------------------------------
Tasks runnable from root project
------------------------------------------------------------
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'engage-application.mobile'.
components - Displays the components produced by root project 'engage-application.mobile'. [incubating]
dependencies - Displays all dependencies declared in root project 'engage-application.mobile'.
dependencyInsight - Displays the insight into a specific dependency in root project 'engage-application.mobile'.
dependentComponents - Displays the dependent components of components in root project 'engage-application.mobile'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'engage-application.mobile'. [incubating]
projects - Displays the sub-projects of root project 'engage-application.mobile'.
properties - Displays the properties of root project 'engage-application.mobile'.
tasks - Displays the tasks runnable from root project 'engage-application.mobile'.
To see all tasks and more detail, run gradle tasks --all
To see more detail about a task, run gradle help --task <task>
BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
Also, notice I had to run gradle tasks.
The few related articles on SO are either 3 to 5 years old and speaks to versions of
buildscript {
ext {
buildToolsVersion = "27.0.3"
minSdkVersion = 16
compileSdkVersion = 27
targetSdkVersion = 26
supportLibVersion = "27.1.1"
}
inside of build.gradle that are not appropriate for my version of RN:
System:
OS: macOS High Sierra 10.13.6
CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
Memory: 609.73 MB / 16.00 GB
Shell: 5.3 - /bin/zsh
Binaries:
Node: 11.10.1 - /usr/local/bin/node
Yarn: 1.10.1 - /usr/local/bin/yarn
npm: 6.7.0 - /usr/local/bin/npm
Watchman: 4.7.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
Android SDK:
API Levels: 23, 25, 26, 27, 28
Build Tools: 23.0.1, 26.0.2, 27.0.3, 28.0.3
System Images: android-28 | Google Play Intel x86 Atom
IDEs:
Android Studio: 3.4 AI-183.5429.30.34.5452501
Xcode: 10.1/10B61 - /usr/bin/xcodebuild
npmPackages:
react: 16.6.3 => 16.6.3
react-native: 0.57.8 => 0.57.8
npmGlobalPackages:
react-native-cli: 2.0.1
react-native-git-upgrade: 0.2.7
I recently upgraded to version 0.57.8 and followed this guide:
https://reactnative.thenativebits.com/courses/upgrading-react-native/upgrade-to-react-native-0.57/
It was explained to me that I needed to run:
✗ ./gradlew assembleRelease -x bundleDevReleaseJsAndAssets
and I did and I continue to get the error.
FAILURE: Build failed with an exception.
* What went wrong:
Task 'bundleDevReleaseJsAndAssets' not found in root project 'engage-application.mobile'.
* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
If I then try to follow the step by Kartik Shah:
React-Native assembleRelease fails for task ':app:bundleReleaseJsAndAssets'
I get this error:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':react-native-sentry:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 7s
208 actionable tasks: 195 executed, 13 up-to-date
I ran into this issue three days ago and I thought with the upgrade it would be resolved:
https://github.com/getsentry/react-native-sentry/issues/610
So I upgraded React Native Sentry and the errors I get now are as follows:
The TaskInternal.executer property has been deprecated and is scheduled to be removed in Gradle 5.0. There are better ways to re-use task logic, see https://docs.gradle.org/4.4/userguide/custom_tasks.html#sec:reusing_task_logic.
at sentry_c79fxbhuascug468f001tukcq$_run_closure1$_closure6.doCall(/Users/danale/Projects/engage-application.mobile/node_modules/react-native-sentry/sentry.gradle:19)
(Run with --stacktrace to get the full stack trace of this deprecation warning.)
error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
/Users/danale/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/478ea8d2caa80bc12b39e3960167e1f6/res/values/values.xml:251:5-69: AAPT: error: resource android:attr/fontStyle not found.
/Users/danale/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/478ea8d2caa80bc12b39e3960167e1f6/res/values/values.xml:251:5-69: AAPT: error: resource android:attr/font not found.
/Users/danale/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/478ea8d2caa80bc12b39e3960167e1f6/res/values/values.xml:251:5-69: AAPT: error: resource android:attr/fontWeight not found.
error: failed linking references.
It seems like the offending code is around here:
def bundleTasks = tasks.findAll { task -> task.name.startsWith("bundle") && task.name.endsWith("JsAndAssets") && !task.name.contains("Debug")}
bundleTasks.each { bundleTask ->
def shouldCleanUp
def sourcemapOutput
def bundleOutput
def props = bundleTask.getProperties()
def reactRoot = props.get("workingDir")
Does anyone have any workaround or experience with this for React Native Sentry?
A:
The only difference I see is that your original error is for task bundleDevReleaseJsAndAssets as opposed to the bundleReleaseJsAndAssets task that failed in the other post that you linked. So possibly try running this instead:
./gradlew assembleRelease -x bundleDevReleaseJsAndAssets
Basically as-is you were telling it to exclude a task that might not be part of your project. You have to specify the correct one.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to upload a filepath to local database and receive the file path when I click download button
The problem is when I am downloading the file, I can see the path in the download file. I am not getting the actual contents of the file inside.
When I am attaching a file called sample.txt and the path for sample.txt is== C:\Users\smohan\Downloads\databse\LocalDataBaseAp\sample.txt. I can see the path gets binded with my datagrid. But when I click the cell of the grid and download the same file. The file is downloading. But when I open.. The downloaded file I can see inside is missing the actual contents, but instead the path is saved as content (i.e.) C:\Users\smohan\Downloads\database\LocalDataBaseAp\sample.txt
What's wrong with my code?
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = fileDialog.FileName;
SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.CncConnectionString);
//FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] imgData;
imgData = File.ReadAllBytes(fileDialog.FileName);}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string strId = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = System.Text.Encoding.ASCII.GetBytes(s);
string strFileToSave = saveFileDialog1.FileName;
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
}
A:
I understand what you're doing now; So, here's the pertinent code part:
objData = System.Text.Encoding.ASCII.GetBytes(s);
The problem is I think you are misunderstanding what System.Text.Encoding.ASCII.GetBytes(string) does. It does not read a file's contents; it encodes the string you pass to it. So, you are writing your file path from your Grid - not the contents of the file. This is more like what you want:
objData = File.ReadAllBytes(s);
That reads all the bytes from the file at the path you pass to it, returning a byte[], as you were using.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как найти записи значения которых есть в обеих колонках?
Есть таблица со структурой:
id - auto_increment
A - int(11)
B - int(11)
В таблице записи типа:
1 | 10 | 5
2 | 12 | 3
3 | 5 | 10
Каким образом мне найти записи с id 1 и 3 (именно у них значения ячейки A = значению ячейки B (id 3) И значение ячейки B = значению ячейки А (id 3). ?
A:
SELECT GROUP_CONCAT(id)
FROM table
GROUP BY LEAST(a,b), GREATEST(a,b)
HAVING COUNT(DISTINCT id) > 1
Если id - первичный ключ или хотя бы уникальное поле, DISTINCT можно убрать.
Функция LEAST() возвращает меньший из аргументов, GREATEST() соответственно больший. Неважно, как расположены значения в полях - большее в А, меньшее в В, или наоборот, но использование функций даст одну и ту же пару - сперва меньшее, потом большее. Т.е. пары образуют одну группу, даже если порядок не совпадает.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Register these class In Autofac
I am using autofac as Ioc Container.
I have Three Classes:
class Service
{
public Service(Repository rep,UnitOfWork context){}
}
Class Repository
{
public Repository(UnitOfWork context){}
}
class UnitOfWork{}
the Service and Repository need the same instance of UnitOfWork
How to do that?
and How to wirte it in XmlConfiguration
A:
EDIT: I misread this and thought it was a question about how to use autofac to register dependencies. If you want to keep the same UnitOfWork, you need to scope the lifetime of the instance to something. If you're using this in an ASP.NET or WCF application you can register your dependencies like this:
typeBuilder.RegisterType<UnitOfWork>().InstancePerLifetimeScope();
typeBuilder.RegisterType<Repository>();
typeBuilder.RegisterType<Service>();
First thing you need to do in order to use a container like Autofac is register all your dependencies. In Autofac you can do that a few ways but all of them rely on using the a ContainerBuilder. The ContainerBuilder relies on extension methods so make sure you have a using statement for the Autofac namespace.
You can explicitly define the factory methods:
// Explicitly
var builder = new ContainerBuilder();
builder.Register<UnitOfWork>(b => new UnitOfWork());
builder.Register<Repository>(b => new Repository(b.Resolve<UnitOfWork>()));
builder.Register(b => new Service(b.Resolve<Repository>(), b.Resolve<UnitOfWork>()));
Using ContainerBuilder we access the Register<>() method to provide the service interface (which is how we will be asking the container for the service) in this case, I'm not using interfaces, just the actual type. Any time you ask the container for a UnitOfWork it will use the factory method new UnitOfWork() to generate one. In real life, you would probably be asking for an IUnitOfWork. This can all be a bit verbose, but it's very handy when you need custom logic for dependency creation.
You can use the builder like any other dependency container and just register the types.
// Implicitly
var typeBuilder = new ContainerBuilder();
typeBuilder.RegisterType<UnitOfWork>();
typeBuilder.RegisterType<Repository>();
typeBuilder.RegisterType<Service>();
This approach relies on registering all the dependencies needed to build up a class. The container will then use reflection to resolve any constructor arguments. If an argument is not registered, the container will throw an exception with the type it could not resolve. In this case, the service has a dependency on UnitOfWork and Repository. Repository also has a dependency on UnitOfWork. These dependencies are expressed as constructor arguments. In order to request a Repository or a Service from the container, all dependencies must be registered
You can use the configuration approach.
If you're using an app.config file, you can define your config file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>
</configSections>
<autofac defaultAssembly="AutoFacTest">
<components>
<component
type="AutoFacTest.Repository, AutoFacTest"
service="AutoFacTest.Repository" />
<component
type="AutoFacTest.UnitOfWork, AutoFacTest"
service="AutoFacTest.UnitOfWork" />
<component
type="AutoFacTest.Service, AutoFacTest"
service="AutoFacTest.Service" />
</components>
</autofac>
</configuration>
First, notice that we have to define a config section (notice the <ConfigSections>). Then, we can create an <autofac> section that defines all our dependencies. The notation is pretty simple, you basically create a <component> for every dependency. Each component has a service attribute which defines the type that will be requested. There is also a type attribute that defines the object to be created when an instance of the service is requested. This is analogous to builder.Register<UnitOfWork>(b => new UnitOfWork()) where UnitOfWork is the service requested (and in this case) also the type to be created.
To create the builder using the configuration, use a ConfigurationSettingsReader()
// Config
var configBuilder = new ContainerBuilder();
configBuilder.RegisterModule(new ConfigurationSettingsReader("autofac"));
You have to pass in the name of your configuration section (in this case, autofac). Once you've configured the dependencies, you have to build a container. The ContainerBuilder contains a method to do this:
var container = builder.Build();
var typeContainer = typeBuilder.Build();
var configContainer = configBuilder.Build();
And once you have the container, you can request instances of your service:
container.Resolve<Service>().DoAwesomeness();
typeContainer.Resolve<Service>().DoAwesomeness();
configContainer.Resolve<Service>().DoAwesomeness();
Complete program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
using Autofac.Configuration;
namespace AutoFacTest
{
class Program
{
static void Main(string[] args)
{
// Explicitly
var builder = new ContainerBuilder();
builder.Register<UnitOfWork>(b => new UnitOfWork());
builder.Register<Repository>(b => new Repository(b.Resolve<UnitOfWork>()));
builder.Register(b => new Service(b.Resolve<Repository>(), b.Resolve<UnitOfWork>()));
// Implicitly
var typeBuilder = new ContainerBuilder();
typeBuilder.RegisterType<UnitOfWork>();
typeBuilder.RegisterType<Repository>();
typeBuilder.RegisterType<Service>();
// Config
var configBuilder = new ContainerBuilder();
configBuilder.RegisterModule(new ConfigurationSettingsReader("autofac"));
var container = builder.Build();
var typeContainer = typeBuilder.Build();
var configContainer = configBuilder.Build();
container.Resolve<Service>().DoAwesomeness();
typeContainer.Resolve<Service>().DoAwesomeness();
configContainer.Resolve<Service>().DoAwesomeness();
Console.Read();
}
}
public class Repository
{
private readonly UnitOfWork _unitOfWork;
public Repository(UnitOfWork uow)
{
_unitOfWork = uow;
}
public void PrintStuff(string text)
{
Console.WriteLine(text);
}
}
public class Service
{
private readonly Repository _repository;
private readonly UnitOfWork _unitOfWork;
public Service(Repository repo, UnitOfWork uow)
{
_repository = repo;
_unitOfWork = uow;
}
public void DoAwesomeness()
{
_repository.PrintStuff("Did awesome stuff!");
_unitOfWork.Commit();
}
}
public class UnitOfWork
{
public bool Commit()
{
return true;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
D3.js v4: Access current DOM element in ES6 arrow function event listener
In D3.js v4, when registering an event listener through a traditional callback function, this references the current DOM element:
d3.select("div").on('mouseenter', function() {
d3.select(this).text("Yay");
});
ES6 offers arrow functions, which IMHO make D3.js code a lot more readable because they are very concise. However, traditional callbacks cannot blindly be replaced with arrow functions:
d3.select("div").on('mouseenter', () => {
d3.select(this); // undefined
});
The article "On D3 and Arrow Functions" gives a very good explanation of why this is not bound as expected. The article suggests using traditional callbacks for code that needs access to the current DOM element.
Is it possible to access the current DOM element from an arrow function?
A:
There is an idiomatic way of doing this in D3: just use the less famous third argument:
selection.on("mouseenter", (d, i, nodes) => {
d3.select(nodes[i]);
});
And that's the same of:
selection.on("mouseenter", function() {
d3.select(this);
});
I wrote an example here: d3 v4 retrieve drag DOM target from drag callback when `this` is not available
Here is a demo:
d3.selectAll("circle").on("mouseover", (d, i, p) => {
d3.select(p[i]).attr("fill", "maroon")
})
.on("mouseout", (d, i, p) => {
d3.select(p[i]).attr("fill", "seagreen")
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
<circle cx="50" cy="50" r="20" fill="seagreen"></circle>
<circle cx="125" cy="50" r="20" fill="seagreen"></circle>
<circle cx="200" cy="50" r="20" fill="seagreen"></circle>
</svg>
Actually, if you look at the end of the article you linked, he gives the same solution.
Your proposed solution, d3.event.target, despite working for event listeners, does not work in several situations. For instance:
d3.selectAll("circle").each(()=>d3.select(d3.event.target).attr("fill", "red"))
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
<circle cx="50" cy="50" r="20" fill="seagreen"></circle>
<circle cx="125" cy="50" r="20" fill="seagreen"></circle>
<circle cx="200" cy="50" r="20" fill="seagreen"></circle>
</svg>
But the same code works using the third argument:
d3.selectAll("circle").each((d,i,p)=>d3.select(p[i]).attr("fill", "red"))
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
<circle cx="50" cy="50" r="20" fill="seagreen"></circle>
<circle cx="125" cy="50" r="20" fill="seagreen"></circle>
<circle cx="200" cy="50" r="20" fill="seagreen"></circle>
</svg>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does list turn out different than expected?
I have a list with integers. I then want to change the list so that instead of it containing, let's say four 1:s in a row, it shoudl say [[4, 1]]. So I made a function for that, but I get a unexpected result.
This is the function
compressed3 = []
def repeat_comp(data):
rep = 1
for i, item in enumerate(data):
if i < len(data) - 1:
if item == data[i + 1]:
rep += 1
else:
compressed3.append([rep, data[i - 1]])
rep = 1
else:
if item == data[i - 1]:
rep += 1
else:
compressed3.append([rep, data[i - 1]])
rep = 1
repeat_comp(compressed2)
This is the compressed2 list
[0,
1,
2,
3,
1,
1,
1,
1,
4]
Here is the result of the function compared to the expected result
# output of function
[[1, 2832], # why this? (this number is one less than the lenght of another list that has nothing with this list to do)
[1, 0],
[1, 1],
[1, 2],
# excluded value here
[4, 1],
[1, 1], # why this?
[1, 4]]
# expected result
[[1, 0],
[1, 1],
[1, 2],
[1, 3],
[4, 1],
[1, 4]]
A:
You only need to change two things in your code to get the expected results:
def repeat_comp(data):
rep = 1
compressed3 = []
for i, item in enumerate(data):
if i < len(data) - 1:
if item == data[i + 1]:
rep += 1
else:
compressed3.append([rep, item])
rep = 1
else:
if item == data[i - 1]:
rep += 1
else:
compressed3.append([rep, item])
rep = 1
return compressed3
Move the compressed3 list into the function and let the function return it, so every time you call the function compressed3 gets cleared. You can then assign the returned list to another variable:
result = repeat_comp(compressed2)
And I changed data[i - 1] to item
print(result) will give you [[1, 0], [1, 1], [1, 2], [1, 3], [4, 1], [1, 4]]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if Configurable Product is out of stock?
We all know that a configurable product in magento is associated with simple product.
If the simple products associated to the configurable product becomes Inventory = 0, it means that the configurable product is out of stock
So the question is how do i detect if Configurable Product is out of stock? i want to detect so I can display in front-end the "Out of Stock" text.
something like this
if($configurable_product->isOutOfStock()) {
echo "Out of Stock";
}
How can i do this in Magento?
A:
if (!$configurable->isSaleable() ||$configurable_product->getIsInStock()==0){
// out of stock
}
For checking child simple product:
$allProducts = $configurable->getTypeInstance(true)
->getUsedProducts(null, $configurable);
foreach ($allProducts as $product) {
if (!$product->isSaleable()|| $product->getIsInStock()==0) {
//out of stock for check child simple product
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Jssor slider working but not visible
I am trying to integrate the jssor slider into my website but for some reason it is not showing.
The slider should be showing on the right side of my site (bflydev), under the black gearwheel.
When inspecting the element I can clearly see the script working and the images sliding but none is showing.
I've tried z-indexes as well but without success.
Any tips to solve this mystery?
A:
You should explicitly specify fixed size in pixel for slides container instead of 100%.
please replace
<div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; max-width: 100%; height: 300px;">
with
<div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; width: 276px; height: 300px;">
| {
"pile_set_name": "StackExchange"
} |
Q:
How to properly blend colors across two triangles and remove diagonal smear
I am learning WebGL and I've drawn a full screen quad with colors for each vertex. No lighting or normals or perspective matrix or depth buffer; I'm just drawing a gradient background. This is what I get:
It looks good but I cannot help noticing the diagonal smear from the bottom right to the top left. I feel this is an artifact of linear interpolating the far opposite vertices. I'm drawing two triangles: the bottom left, and the top right. I think I would get similar results using OpenGL instead of WebGL.
Given the same four colors and the same size rectangle, is there a way to render this so the edge between the two triangles isn't so apparent? Maybe more vertices, or a different blending function? I'm not sure exactly what the colors should be at each pixel; I just want to know how to get rid of the diagonal smear.
A:
The issue is the top right triangle has no knowledge of the bottom left corner so the top right triangle is not including any of the blue from the bottom left (and visa versa)
A couple of ways to fix that.
One is to use a 2x2 texture with linear sampling. You have to do some extra math to get the interpolation correct because a texture only interpolates between pixels
+-------+-------+
| | |
| +-------+ |
| | | | |
+---|---+---|---+
| | | | |
| +-------+ |
| | |
+-------+-------+
Above is a 4 pixel texture stretched to 14 by 6. Sampling happens between pixels so only this center area will get the gradient. Outside that area would be sampled with pixels outside the texture so using CLAMP_TO_EDGE or on the opposite side of the texture using REPEAT.
const gl = document.querySelector('canvas').getContext('webgl');
const tl = [254, 217, 138];
const tr = [252, 252, 252];
const bl = [18, 139, 184];
const br = [203, 79, 121];
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(
gl.TEXTURE_2D,
0, // mip level
gl.RGB, // internal format
2, // width,
2, // height,
0, // border
gl.RGB, // format
gl.UNSIGNED_BYTE, // type
new Uint8Array([...bl, ...br, ...tl, ...tr]));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const vs = `
attribute vec4 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = position;
v_texcoord = texcoord;
}
`;
const fs = `
precision mediump float;
varying vec2 v_texcoord;
const vec2 texSize = vec2(2, 2); // could pass this in
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex,
(v_texcoord * (texSize - 1.0) + 0.5) / texSize);
}
`;
const program = twgl.createProgram(gl, [vs, fs]);
const positionLoc = gl.getAttribLocation(program, 'position');
const texcoordLoc = gl.getAttribLocation(program, 'texcoord');
function createBufferAndSetupAttribute(loc, data) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(
loc,
2, // 2 elements per iteration
gl.FLOAT, // type of data in buffer
false, // normalize
0, // stride
0, // offset
);
}
createBufferAndSetupAttribute(positionLoc, [
-1, -1,
1, -1,
-1, 1,
-1, 1,
1, -1,
1, 1,
]);
createBufferAndSetupAttribute(texcoordLoc, [
0, 0,
1, 0,
0, 1,
0, 1,
1, 0,
1, 1,
]);
gl.useProgram(program);
// note: no need to set sampler uniform as it defaults
// to 0 which is what we'd set it to anyway.
gl.drawArrays(gl.TRIANGLES, 0, 6);
canvas { border: 1px solid black; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
Note: to see what I mean about the extra math needed for the texture coordinates here is the same example without the extra math
const gl = document.querySelector('canvas').getContext('webgl');
const tl = [254, 217, 138];
const tr = [252, 252, 252];
const bl = [18, 139, 184];
const br = [203, 79, 121];
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(
gl.TEXTURE_2D,
0, // mip level
gl.RGB, // internal format
2, // width,
2, // height,
0, // border
gl.RGB, // format
gl.UNSIGNED_BYTE, // type
new Uint8Array([...bl, ...br, ...tl, ...tr]));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const vs = `
attribute vec4 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = position;
v_texcoord = texcoord;
}
`;
const fs = `
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, v_texcoord);
}
`;
const program = twgl.createProgram(gl, [vs, fs]);
const positionLoc = gl.getAttribLocation(program, 'position');
const texcoordLoc = gl.getAttribLocation(program, 'texcoord');
function createBufferAndSetupAttribute(loc, data) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(
loc,
2, // 2 elements per iteration
gl.FLOAT, // type of data in buffer
false, // normalize
0, // stride
0, // offset
);
}
createBufferAndSetupAttribute(positionLoc, [
-1, -1,
1, -1,
-1, 1,
-1, 1,
1, -1,
1, 1,
]);
createBufferAndSetupAttribute(texcoordLoc, [
0, 0,
1, 0,
0, 1,
0, 1,
1, 0,
1, 1,
]);
gl.useProgram(program);
// note: no need to set sampler uniform as it defaults
// to 0 which is what we'd set it to anyway.
gl.drawArrays(gl.TRIANGLES, 0, 6);
canvas { border: 1px solid black; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
Also of course, rather than do the math in the fragment shader we could fix the texture coordinates in JavaScript
const gl = document.querySelector('canvas').getContext('webgl');
const tl = [254, 217, 138];
const tr = [252, 252, 252];
const bl = [18, 139, 184];
const br = [203, 79, 121];
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(
gl.TEXTURE_2D,
0, // mip level
gl.RGB, // internal format
2, // width,
2, // height,
0, // border
gl.RGB, // format
gl.UNSIGNED_BYTE, // type
new Uint8Array([...bl, ...br, ...tl, ...tr]));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const vs = `
attribute vec4 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = position;
v_texcoord = texcoord;
}
`;
const fs = `
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, v_texcoord);
}
`;
const program = twgl.createProgram(gl, [vs, fs]);
const positionLoc = gl.getAttribLocation(program, 'position');
const texcoordLoc = gl.getAttribLocation(program, 'texcoord');
function createBufferAndSetupAttribute(loc, data) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(
loc,
2, // 2 elements per iteration
gl.FLOAT, // type of data in buffer
false, // normalize
0, // stride
0, // offset
);
}
createBufferAndSetupAttribute(positionLoc, [
-1, -1,
1, -1,
-1, 1,
-1, 1,
1, -1,
1, 1,
]);
createBufferAndSetupAttribute(texcoordLoc, [
0.25, 0.25,
0.75, 0.25,
0.25, 0.75,
0.25, 0.75,
0.75, 0.25,
0.75, 0.75,
]);
gl.useProgram(program);
// note: no need to set sampler uniform as it defaults
// to 0 which is what we'd set it to anyway.
gl.drawArrays(gl.TRIANGLES, 0, 6);
canvas { border: 1px solid black; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
Another way is to do the interpolation yourself based on those corners (which is effectively doing what the texture sampler is doing in the previous example, bi-linear interpolation of the 4 colors).
const gl = document.querySelector('canvas').getContext('webgl');
const tl = [254/255, 217/255, 138/255];
const tr = [252/255, 252/255, 252/255];
const bl = [ 18/255, 139/255, 184/255];
const br = [203/255, 79/255, 121/255];
const vs = `
attribute vec4 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = position;
v_texcoord = texcoord;
}
`;
const fs = `
precision mediump float;
varying vec2 v_texcoord;
uniform vec3 tl;
uniform vec3 tr;
uniform vec3 bl;
uniform vec3 br;
void main() {
vec3 l = mix(bl, tl, v_texcoord.t);
vec3 r = mix(br, tr, v_texcoord.t);
vec3 c = mix(l, r, v_texcoord.s);
gl_FragColor = vec4(c, 1);
}
`;
const program = twgl.createProgram(gl, [vs, fs]);
const positionLoc = gl.getAttribLocation(program, 'position');
const texcoordLoc = gl.getAttribLocation(program, 'texcoord');
const tlLoc = gl.getUniformLocation(program, 'tl');
const trLoc = gl.getUniformLocation(program, 'tr');
const blLoc = gl.getUniformLocation(program, 'bl');
const brLoc = gl.getUniformLocation(program, 'br');
function createBufferAndSetupAttribute(loc, data) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(
loc,
2, // 2 elements per iteration
gl.FLOAT, // type of data in buffer
false, // normalize
0, // stride
0, // offset
);
}
createBufferAndSetupAttribute(positionLoc, [
-1, -1,
1, -1,
-1, 1,
-1, 1,
1, -1,
1, 1,
]);
createBufferAndSetupAttribute(texcoordLoc, [
0, 0,
1, 0,
0, 1,
0, 1,
1, 0,
1, 1,
]);
gl.useProgram(program);
gl.uniform3fv(tlLoc, tl);
gl.uniform3fv(trLoc, tr);
gl.uniform3fv(blLoc, bl);
gl.uniform3fv(brLoc, br);
gl.drawArrays(gl.TRIANGLES, 0, 6);
canvas { border: 1px solid black; }
<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Can a country without a constitution be a Constitutional Monarchy?
I am doing research on the subject of false-authority. The most objective thing to base it on seems to come from the soundness of the terms governments use to define themselves.
One of the main examples that came up from my research is whether a country without a constitution be a Constitutional Monarchy?
A:
The United Kingdom is referred to as a constitutional monarchy far more often than it is referred to as an absolute monarchy. However, it is generally referred to as having an unwritten constitution, as opposed to a written constitution, the Magna Carta and recent human rights laws notwithstanding.
So the answer is yes.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does this regex pattern match?
regex = re.compile(r"\s*[-*+]\s*(.+)")
Especially this part: \s*[-*+]
I want to match this string:
[John](person)is good and [Mary](person) is good too.
But it fails.
Does the \s*[-*+] mean the following:
matches an optional space, followed by one of the characters: -, *, +
This is in Python.
A:
Pattern \s*[-*+]\s*(.+) means:
\s* - match zero or more whitesapces
[-*+] - match one characters from the set: - or * or +
(.+) - match one or more of any characters and store it inside capturing group (. means any character and brackets denote capturing group)
In your sentence, pattern won't match anything due to lack of any of characters from the set -*+.
It would match, for example * (person) is good too. in
[John](person)is good and [Mary] * (person) is good too.
Demo
In order to match names and their description in brackets use \[([^\]]+)\]\(([^)]+)
Explanation:
\[ - match [ literally
([^\]]+) - match one or more characters other from ] and store it in first captuirng group
\] - match [ literally
\( - match ( literally
([^)]+) - match one or more characters other from )
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing "add to wishlist" to "add to cart" , functionality and text EVERYWHERE GLOBALLY
What is the best way to change ALL "add to wishlist" in a magento webshop? I want to REPLACE it with "add to cart"
Thanks!
A:
Take Backup Before that.
Go to app\design\frontend\package\theme\template\catalog\product\view\addto.phtml
Command this
<li>
<a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a>
</li>
then add this
<?php if($_product->isSaleable()): ?>
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<?php else: ?>
<p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
<?php endif; ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
How does a CPU decide which transistors to use?
Perhaps I'm not thinking about this correctly, but when you give the CPU a command such as Multiply Registers (MR) R2,R4 how does it decide which logic gates it will use, is it just the first gates available or is there something I'm not aware of going on under the hood. I understand a CPU has millions of logic gates so how does it manage their use correctly?
A:
Your question is really more in the realm of electrical engineering than in computer science, so its a bit off topic, but I'll see what I can do.
Your multiply instruction would be queued to an Arithmetic Processing Unit on one of its input/output connections.
The ALU uses Combinational Logic in its layout, such that the electricity flows through the entire circuit, and its output varies based on the input received. It does not select a set of gates to use, all of the gates are receiving signal, but the layout of the circuit creates a reproducible transformation of the input signal carrying the result.
Note that at this level, you are working with analog signal as much as digital bits, so the electricity is flowing like water through a network of pipes, and the circuitry is allowing more or less water through different pathways.
The Execution unit driving the instruction sends it the ALU for processing, and on the next clock tick, expects the result to be available on one of the ALUs output registers.
see more details here: https://en.wikipedia.org/wiki/Arithmetic_logic_unit#Circuit_operation
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I pass List to a function that takes generic wildcard List
I have a list view adapter that is reusable across some activities and renders different layouts based on different group items. Since the list view adapter requires flexibility in the collection structure, I've decided to use generics wildcard for the collection:
public ExpandableListAdapter(FragmentActivity context, List<String> group,
Map<String, List<?>> listCollection) {
this.context = context;
this.dataCollections = listCollection;
}
Here's the problem. I have a function that returns a two-level associative array for the adapter. It returns Map<String, List<Model>>. Model is a mapping model.
public Map<String, List<Model>> getAll() {
Map<String, List<Model>> listCollection = new HashMap<String,List<Model>>();
/***Database Query***/
List<Model> rowList = new ArrayList<Model>();
try {
if (cursor.moveToFirst()) {
do {
Model sf = new Model();
sf.title = cursor.getString(cursor.getColumnIndex("title");
sf.group_title = DBMethod.getString(cursor,getColumnIndex("group"));
rowList.add(sf);
Model group = (Model)listCollection.get(sf.group_title);
if(group == null){
listCollection.put(sf.group_title,rowList);
}else{
listCollection.get(sf.group_title).add(sf);
}
} while(cursor.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, "Error while trying to get posts from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return listCollection;
}
public class Model{
public String title;
public String value;
public String group_title;
}
I understand that the returned array from getAll() (Map<String, List<Model>>) doesn't match the wildcard collection required by ExpandableListAdapter (Map<String, List<?>>). But is it still possible to pass it into the adapter? I'm getting incompatible types error in this code:
Map<String, List<Model>> listCollection = getAll();
ExpandableListView expListView = (ExpandableListView) findViewById(R.id.left_drawer);
final ExpandableListAdapter expListAdapter = new ExpandableListAdapter(
this, groupList, listenCollection);
^^^^^^^^^^^
expListView.setAdapter(expListAdapter);
I have tried to modify getAll() to return Map<String, List<? extends Model>>, but it is still getting incompatible type error.
A:
When you declare listCollection as a Map<String, List<?>>, you are declaring that the value type of the map must be exactly List<?>. The wildcard there actually doesn't gain you much. To get the type flexibility you want, you need an extra wildcard: Map<String, ? extends List<?>>.
Note that with this wildcard you will be able to retrieve lists from the map, but not add lists to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
UILabel doesn't fully resize using Auto Layout
I meet a strange issue using Auto Layout with a UILabel where it resizes almost to its content size less one line (driving me nuts) in iphone 4s/5/5s (It works fine on the 6/6+)
this is my storyboard setting, I have set the preferred width with explicit
and I try to add the code in UITableViewCell class
self.describe.preferredMaxLayoutWidth = self.describe.frame.size.width
But the issue still exist
this is my issue
EDIT
This is my to get height
self.address.preferredMaxLayoutWidth = CGRectGetWidth(self.address.bounds)
self.describe.preferredMaxLayoutWidth = CGRectGetWidth(self.describe.bounds)
self.address.text = data.address == nil ? "no data" : data.address
self.describe.text = data.describe == nil ? "no data" : data.describe
self.layoutIfNeeded()
self.updateConstraintsIfNeeded()
return self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
Label called "Address" in storyboard (you can find it in first image in this question) work fine
A:
Try this it may help you
YourCell.m
- (void)layoutSubviews
{
[self.contentView updateConstraintsIfNeeded];
[super layoutSubviews];
[self.contentView layoutIfNeeded];
CGFloat width = [UIScreen mainScreen].bounds.size.width - 60;//your desire width
self.yourLAbel.preferredMaxLayoutWidth = width;
}
EDIT:
Please follow this link it may help you
Dynamic Cells
Or try
yourCell.m in awakefromnib method
- (void)awakeFromNib
{
[super awakeFromNib];
[self setNeedsUpdateConstraints];
[self updateConstraintsIfNeeded];
}
Edit - 2
What is your line break mode, it should be
Edit:3
If you are using height constraints for UILable so that you should provide “Greater than or equal" relation for height autoLayout modify the height for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the smallest positive real allowed in mathematica?
This question may be a bit strange, but in this question, one of the answers suggests substituting some negatives values in a matrix by the smallest positive real number allowed. So, I was wondering how I do that for mathematica.
A:
Within machine numbers, $MinMachineNumber is the smallest positive number that can be used on your system. On a 64-bit system it'll typically be on the magnitude of $10^{-308}$.
If that is not small enough, you can use arbitrary precision arithmetic, such as by: N[10, d]^-10000, where d is the number of digits of precision you need. I'd recommend trying 17 to start with, as that's about one more digit of precision than machine-precision typically tends to be.
There's no practical limit to how small of an arbitrary precision number you can have. The smallest number my system (64-bit, Windows, Intel CPU) accepts without underflowing is N[10, 17]^-1355718576299609, but your results may vary. Note that using that particular number may lead to issues, as it is exceptionally close to underflowing on my system -- dividing it by 1.61 will throw an Underflow[] error. As noted by Chip Hurst, the smallest positive arbitrary number on your system can be found with $MinNumber.
However, for the exact same reason that I'd recommend against using the smallest possible arbitrary precision number, I'd also recommend against using $MinMachineNumber in arithmetic. Henrik Schumacher's suggestion of $MachineEpsilon is a good one for a small number that is still behaves somewhat as expected in machine precision arithmetic, but depending on the intermediate products it may be too large or too small.
If you truly want the absolutely smallest positive real number that can be represented in Mathematica, use arbitrary precision. If you want the smallest machine precision number, use $MinMachineNumber because that's what it's there for. If you want the smallest machine precision number which doesn't vanish (or overflow, as a denominator) in all arithmetic operations, it depends strongly on your intermediate values, but $MachineEpsilon is probably a good starting point.
| {
"pile_set_name": "StackExchange"
} |
Q:
clearfix / JavaScript, absolute position, changeable height
Ok, so I have relative div, and inside it I have two absolute divs, rights and left. Under relative div I want sticky footer, or something like that, but relative div has not children's height, because children is absolute. I know that, I should use javaScript (because of absolute divs it's impossible with css, clearfix), but what is the best way to keep parent's height like children using JavaScript? I do not prefer to set div's height permanently, because it could be uncomfortable with future content changes.
Maybe someone has some ids how to set parent's height like children's without setting height permanently and when it's impossible to use clearfix trick?
I will be really grateful for every suggestion.
A:
You can get the height of your parent container using .outerHeight() or .height(). Then you can use the .on() function to fire the SetHeight function on screen resize and load.
function SetHeight(div){
var x = $(div).outerHeight();
// to get the height
$(div).children().css('height', x);
// set the childrens height
}
$(window).on('load resize', function(){
// fire the function
SetHeight('#my_div');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How much work can a force on a spring do? (Why are two methods wrong?)
This was a question my friend found in a book.
A block attached to a spring pulled by a constant horizontal force is kept on a smooth horizontal surface. Initially the spring is in its natural state. Then the maximum work that the applied force F can do is:
(a) $F^2/k$
(b) $2F^2/k$
(c) $4F^2/k$
(d) $F^2/2k$
My friend thought that the answer is (a) since the maximum displacement is $x=F/k$ and $W=Fx=F^2/k$. But he saw that the book's answer is different and he asked this question to me.
I at first thought that the answer will be (a), but then I realised that this situation is somewhat similar to a charging capacitor. The final energy of the spring is actually $\frac12kx^2=F^2/2k$. So probably the answer is (d)? But the work done is still (a)? But the book says neither. It's (b). This is the logic in the book:
Method 1: in the book:
$$Fx=\frac12kx^2$$
$$x=2F/k$$
$$W=\frac12kx^2=2F^2/k$$
(since the book is an objective questions book it did not have detailed explanations)
What is wrong in the following methods?
Method 2: by calculating the maximum displacement
$$x=F/k$$
$$W=Fx=F^2/k.$$
Method 3: by calculating the final energy
$$x=F/k$$
$$\frac12kx^2=F^2/2k$$
PS: We both know calculus so don't hesitate to use it in the answers.
A:
What's wrong with method 2 as well as method 3 is that
$$x_{max} = F/k$$ is not valid!
When you are applying force F on the body you are also imparting it with kinetic energy. $x = F/k$ is the displacement at which the net force experienced by it becomes zero, but it does not stop there. It goes on until its velocity goes to zero due to the pull of the spring.
At that point all its energy is in the form of the potential energy of the spring as given in the solution.
A:
I have tried to give the background to the solution given in the textbook.
The energy stored or released is given by $\int \vec f \cdot d \vec x$ and the important thing to note is that the force $\vec f$ varies with extension $\vec x$.
This relationship is usually written as $\vec f = - k \vec x$ with the force $\vec f$ being the force exerted by the spring on an external object, so the relationship for an (external) force acting on the spring has a positive sign.
So the energy stored/released is $\displaystyle \int_0^x kx \,dx = \frac 12 kx^2$
Let the static extension of the spring when a force $F$ is applied be $x_o$ and so $F=kx_o$ and the energy stored in the spring is $\frac 12 kx^2_o$.
The situation in the problem is different in that a constant force $F$ is applied and the work done by the force in moving to the static extension position is $Fx_o$.
In moving the mass to that static extension position the force $F$ has also accelerated the mass.
So the mass also has kinetic energy which must be accounted for if one needs to find the total work done by the force $F$ in terms of $k$ and $F$.
Now the kinetic energy must be the work done by the force $Fx_o= kx^2_o$ minus the energy stored in the spring $\frac 12 kx^2_o$.
So the kinetic energy is $\frac 12 kx^2_o$.
Note that although the net force on the mass at the static extension position is zero the mass is moving and so overshoots the static equilibrium position and the force $F$ continues to do work as the direction of the applied force and its displacement are still in the same direction.
Let the extension when the mass finally stops be $x_{\max}$.
This happens when the work done by the force is all stored as potential energy in the spring $FX=\frac12kx_{\max}^2$ and this is the equation given in the textbook's solution.
Using $F=kx_o$ gives $x_{\max}= 2x_o$.
So the maximum work done by the force $F$ is $F\,2x_o=\dfrac{2F^2}{k}$
A:
While the other answers might already show why the books solution is correct, here another point of view that might help:
What is the net force on the object?
$$F_{net} = F + F_{spring}$$
$$= F - kx$$
This is the formula that gives you the equilibrium position of $x_0=F/k$, so let's shift our coordinate system a bit so that $x'_0=0$, i.e. $x' = x - F/k$.
What is now the net force in our new coordinate system, where the equilibrium is at 0?
$$F_{net} = F - kx$$
$$= F - k(x' + F/k)$$
$$= -kx'$$
Oh wait, in this coordinate system the force on the object is proportional to its displacement - that's a harmonic oscillator!
The starting position is the maximum displacement in one direction and as we know from harmonic oscillators, the maximum displacement in the other direction is equal in distance, so the full range this object swings is $x_{max}=2 F/k$.
Together with the usual formula of $W=Fx_{max}$ you get the same result as the book.
You can also choose energy conservation, since all the energy at maximum displacement is stored in the spring and the object is not moving, which is the third line you quoted from the book, $W=\frac{1}{2}kx_{max}^2$.
This is btw. also the energy of the harmonic oscillator.
Or in short: both your methods work if you choose the correct max. displacement.
| {
"pile_set_name": "StackExchange"
} |
Q:
Transact SQL sub query
I would like a single query which will return a list of Order_IDs for orders where all the order line items are in stock. Here are the tables to illustrate:
test_Order:
Order_ID
1001
1002
1003
test_OrderLine:
OrderLine_ID|Order_ID|Item_ID|Quantity
10|1001|101|1
11|1001|102|1
12|1001|103|1
13|1002|101|4
14|1002|102|1
15|1003|101|1
16|1003|104|4
test_Item:
Item_ID|InStockQuantity
101|3
102|1
103|7
So in the example above only Order_ID 1001 should be returned because:
In order 1001, all 3 items in OrderLines have a quantity less or equal to the InStockQuantity in Items.
In order 1002, item 101 has a quantity of 4 but there are only 3 in stock.
In order 1003, item 104 does not exist in the Items table.
This is obviously not correct but something like:
SELECT O.Order_ID
FROM test_Order AS O
LEFT JOIN test_OrderLine OL
ON O.Order_ID = OL.Order_ID
LEFT JOIN test_Item I
ON OL.Item_ID = I.Item_ID
WHERE (OL.Quantity <= I.InStockQuantity)
GROUP BY O.Order_ID
The problem with that query is that only ONE of the OrderLines needs to have a Quantity <= InStockQuantity for its Order_ID to appear in the results, whereas I only want it to appear in the results if ALL Quantities in the order are <= InStockQuantities.
I read something about “ALL” operator but can’t see how that would work in a subquery.
A:
A different way to think about this problem is to return the order_ids that don't have order lines that require a quantity greater than what's in stock. Using a left join and coalesce could allow you treat items that are out of stock completely as though they have a quantity of 0:
SELECT order_id
FROM test_order
WHERE order_id NOT IN (SELECT order_id
FROM test_orderline o
LEFT JOIN test_item i ON o.item_id = i.item_id
WHERE o.quantity > COALESCE(i.instockquantity, 0))
| {
"pile_set_name": "StackExchange"
} |
Q:
Viewing the console log in iOS7
Prior to iOS7, if I wanted to view the output log of an app running on an iOS device, I would use one of:
https://itunes.apple.com/au/app/system-console/id431158981?mt=8
https://itunes.apple.com/au/app/console/id317676250?mt=8
However, since upgrading to iOS7, both of these don't seem to be recording the log output of any app on my phone.
Would this be due to a new setting on my phone? Or has iOS7 changed the way in which logging is handled such that these two apps are now broken?
A:
We're the creator of System Console - https://itunes.apple.com/au/app/system-console/id431158981?mt=8
It looks like in iOS7 the sandbox now prevents an app from seeing the logs of other apps. In iOS6 apps could no longer see kernel and system log entries. Now in iOS7 you can only see your own logs. For System Console this is obviously a deal breaker.
I don't see any apps store approved ways of getting around it.
It might be that we have to find a backdoor way of accessing the logs and release the source code to System Console with this method. i.e you build it yourself.
Chris
A:
iOS 8 + Xcode Method
Within Xcode 6:
In the menu, open Window -> Devices.
Select your device, and there's a little arrow at the bottom:
Click this and it will pop open the device console.
iPhone Configuration Utility Method
This has stopped working for me since iOS 8 was released, but evidently may work if iTunes is updated.
You can do this while plugged into your mac with the iPhone Configuration Utility. Not as portable, but still useful.
http://support.apple.com/kb/DL1465
You can select your device on the sidebar, and among other options, one of the tabs is "Console".
This exists for Windows as well: http://support.apple.com/kb/DL1466
Not quite the same but it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
if else shorthand solution
I am not sure if the following validation can be done with if shorthand.
//if $error is set, echo $errro or just echo blank string.
(isset($error)) ? echo $error:echo '';
I know I got it wrong, Anyone here can help me to correct my code?
Thanks a lot.
A:
echo isset($error) ? $error : '';
A:
There are few good examples in php documentation (ternary operator). But basically usage is:
echo (isset( $error) ? $error : '');
It also has a short form, that can be used in case that $error is always set but is evaluated as (bool)false by default:
echo ($error ?: '');
| {
"pile_set_name": "StackExchange"
} |
Q:
Syllable count in a line of Rosemonde Gérard
The Wikipedia edition of L'éternelle chanson (a poem written by Rosemonde Gérard) seems incorrect :
Lorsque tu seras vieux et que je serai vieille,
Lorsque mes cheveux blonds seront des cheveux blancs,
Au mois de mai, dans le jardin qui s’ensoleille,
Nous irons réchauffer nos vieux membres tremblants.
Comme le renouveau mettra nos cœurs en fête,
Nous nous croirons encore de jeunes amoureux,
The sixth line is problematic : it can't be an alexandrin since it's made of 13 syllables :
Nous(1) nous(2) croi(3)rons(4) en(5)co(6)re(7) de(8) jeu(9)nes(10) a(11)mou(12)reux(13),
Is this line correctly written ? I beg we should read :
Nous nous croirons encor de jeunes amoureux,
... encor being an alternative spelling for encore; moreover, with encor we could have the hémistiche exactly after the sixth syllable, as expected.
May someone check the exact spelling in any paper edition ? I can't check it by myself.
Any help would be appreciated !
By the way, there is(?) another error in the wikipedia edition of this poem. See at the end the famous lines :
Et comme chaque jour je t’aime davantage,
Aujourd’hui plus qu’hier et bien moins que demain,
Qu’importeront alors les rides du visage ?
Mon amour se fera plus grave ― et serein.
The last line I quote should be read :
Mon amour se fera plus grave et plus serein.
That's the way I learned these lines fifteen years ago.
A:
I've always thought that "encor" was used only in 17th or 18th century poetry. But https://fr.wiktionary.org/wiki/encor cites a Boris Vian poem from the 1950's. So it seems right to replace the "encore" in the Rosemonde Gérard poem by "encor".
| {
"pile_set_name": "StackExchange"
} |
Q:
Methods to set a session token by url
I'm writing up a security document and it would be great if programmers in other languages than PHP could chime in on (perhaps the default) way sessions are passed by URL in their language's default session handler.
eg. PHPSESSION=token in PHP
Oh, and if yes does it also use cookies?
A:
ColdFusion has CFID and CFTOKEN by default in cookie but possible in URL.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++11 - I lost a move/copy assignment
I posted this code in another question but I have a new doubt on it:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class X
{
public:
std::vector<double> data;
// Constructor1
X():
data(100000) // lots of data
{
cout << "X default constructor called";
}
// Constructor2
X(X const& other): // copy constructor
data(other.data) // duplicate all that data
{
cout << "X copy constructor called";
}
// Constructor3
X(X&& other): // move constructor
data(std::move(other.data)) // move the data: no copies
{
cout << "X move constructor called";
}
X& operator=(X const& other) // copy-assignment
{
cout << "X copy assignment called";
data=other.data; // copy all the data
return *this;
}
X& operator=(X && other) // move-assignment
{
cout << "X move assignment called";
data=std::move(other.data); // move the data: no copies
return *this;
}
};
class X2
{
public:
std::vector<double> data;
// Constructor1
X2():
data(100000) // lots of data
{}
// Constructor2
X2(X const& other): // copy constructor
data(other.data) // duplicate all that data
{}
X2& operator=(X const& other) // copy-assignment
{
data=other.data; // copy all the data
return *this;
}
};
X make_x()
{
X myNewObject; // Il normale costruttore viene chiamato qui
myNewObject.data.push_back(22);
return myNewObject; // Si crea un oggetto temporaneo prima di ritornare con il move constructor perchè myNewObject dev'essere distrutto
}
int main()
{
X x1 = make_x(); // x1 has a move constructor
X2 x2 = make_x(); // x2 hasn't a move constructor
}
In the main() lines I would expect the move assignment and the copy assignment to get called... but they don't!
MSVC2012 output is:
X default constructor called X move constructor called X default
constructor called X move constructor called
And g++'s one is
X default constructor called X default constructor called
http://liveworkspace.org/code/220erd$2
Where are the assignments?? I thought the first main() line would call a move assignment and the second main() line would call a copy assignment
A:
// Constructor2
X2(X const& other): // copy constructor
data(other.data) // duplicate all that data
{}
X2& operator=(X const& other) // copy-assignment
{
data=other.data; // copy all the data
return *this;
}
First of all, these are not the copy constructor and copy assignment operator for X2 because they take arguments of type X. The first is actually known as a converting constructor, because it can convert from an X to an X2.
int x = 5;
This is not 5 being assigned to x; it is x being initialised with 5. Initialisation, although it looks similar, is not the same as assignment. In fact, no assignment occurs at all in your code, so the move or copy assignment operators will not be used.
We can take a look at what each of the compilers you've given is actually doing:
MSVC
First, myNewObject is created in make_x. This prints out X default constructor called. Then the return myNewObject; will treat the copy to the return value as a move first, find that there is a move constructor, and invoke it.
When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
The return value would then be copied into x1. However, this copy has clearly been elided because we see no X copy constructor called output:
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
Secondly, another myNewObject is created in the second call to make_x. This again prints out X default constructor called. Then the same move happens when doing return myNewObject. The construction of x2 from the return value doesn't output anything because its constructor that takes an X doesn't do any output.
GCC
First, myNewObject is created in make_x, just as with MSVC. This prints out X default constructor called.
Now GCC does an extra optimization that MSVC isn't doing. It realises that it might as well not bother moving from myNewObject to the return value and instead just construct it directly in the return value's place:
in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
Then the same elision caused by constructing x1 from a temporary object is performed as was in MSVC.
The second call to make_x occurs in exactly the same way as with the first, except now x2 is constructed by the converting constructor that takes an X. This, of course, doesn't output anything.
A:
You are seing the effect of the named return value optimization, NRVO. The following code
X f()
{
X tmp;
// ...
return tmp;
}
can remove the temporary completely and construct it in the function caller's return slot. In your example the effect is like the function is inlined and constructs x1 and x2directly.
If you want the assignment to be seen, you can write:
X x1;
x1 = make_x();
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make sure that not everyone can use the ItemTouchHelper?
In my app everyone can add Notes that are displayed in a RecyclerView.
I have added the swipe to delete functionality into the RecyclerView, by creating an ItemTouchHelper with a SimpleCallback and attaching it to the RecyclerView with the attachToRecyclerView method. In the onSwiped callback, I am deleting the corresponding document from the FirestoreDatabase, by calling delete on it’s DocumentReference. This DocumentReference comes from the DocumentSnapshot, by calling getSnapshots().getSnapshot().getReference() in the adapter and passing the position to it.
My issue: I want the user to be able to only delete the note that he has added and not any other note that was added by some other user. What is the logic to implement this?
NoteAdapter.java (adapterclass)
public void deleteItem(int position){
getSnapshots().getSnapshot(position).getReference().delete();
}
Receive.java (mainactivity)
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
Note note = new Note();
String cuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
if (note.getUserId().equals(cuid)) {
//do nothing;
} else {
return 0;
}
return super.getMovementFlags(recyclerView, viewHolder);
}
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
}
A:
I finally was able to get the solution after going through this and with the help of the answer provided by theThapa.
Since his answer was in kotlin and I am developing my app in Java, I had to play around my getMovementFlag() to make it something similar to the one he provided and do the following changes insideItemTouchHelper.SimpleCallback
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
if (adapter.getSnapshots().get(viewHolder.getAdapterPosition()).getUserId().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) {
//do nothing;
}
else {
return 0;
}
return super.getMovementFlags(recyclerView, viewHolder);
}
Once again my sincere thanks to theThapa for helping me with this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get all CPU cache information without SU access
I am trying to find out the cache mapping scheme for all the levels of class of a linux server, however I do not have root access. I would just use DMIdecode for this but you need root access. Is there another way of getting the same information without root?
A:
lscpu, in util-linux, describes the cache layout without requiring root:
[...]
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 8192K
The files in /sys/devices/system/cpu/cpu*/cache/ should contain all the information you're looking for, including associativity, and are readable without being root, but it's a little harder to parse:
grep . /sys/devices/system/cpu/cpu*/cache/index*/*
(I got this on https://stackoverflow.com/questions/716145/l1-memory-cache-on-intel-x86-processors).
| {
"pile_set_name": "StackExchange"
} |
Q:
Word document not reflecting change visually after vba code is used to indent a paragraph
I have a simple vba code in Word 2010:
Sub IncreaseIndent()
For Each p In Selection.Paragraphs
p.LeftIndent = p.LeftIndent + InchesToPoints(0.25)
p.FirstLineIndent = InchesToPoints(-0.25)
Next
End Sub
It works great, does what I need, and I have it associated to a shortcut key. But I'm trying to figure out one last glitch it has. When I use it, the paragraph indents, but it's not visually refreshed properly in the document. I have to scroll so that the text goes out of view, and then scroll it back. (Any action that makes Word re-render works, like switching to another program whose window is on top of Word, and back again.) After that, the paragraph looks as it should.
I'm thinking I'm missing some kind of p.Refresh / Re-render / Recalc command, but don't know what that is. Anyone know how to cause the refresh in the vba code?
Thanks,
Sandra
A:
I was not able to replicate what you describe, but there is a .ScreenRefresh method which might do the trick.
https://msdn.microsoft.com/en-us/library/office/ff193095(v=office.15).aspx
Note: in the example code provided at MSDN (and as modified slightly, below), when I test it the toggling ScreenUpdating property has no effect, it always appears to update for me when I run it, even when set explicitly to False
Sub t()
Dim rngTemp As Range
Application.ScreenUpdating = False
Set rngTemp = ActiveDocument.Range(Start:=0, End:=0)
rngTemp.InsertBefore "new"
Application.ScreenRefresh
Application.ScreenUpdating = True
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
How to evaluate commutator with angular momentum?
I need to evaluate the commutator $[\hat{x},\hat{L}_z]$. I believe the $L_z$ is referring to the angular momentum operator which is:
$L_z = xp_y - yp_x$
using this relationship i end up with:
$[x,L_z] = x(xp_y - yp_x)-(xp_y - yp_x)x$
my next step is substituting in for the p operator but i still dont get anywhere. any suggestions???
A:
I'll help you with a general solution. First, you can write the angular momentum as $L_{i}=\epsilon_{ijk}x_{j}p_{k}$. Where $e_{ijk}$ is the Levi-Civita symbol. Now write a general commutator as $[x_{l},L_{i}]$ where $l,i$ run from 1 to 3. With this you have
$[x_{l},L_{i}]=[x_{l},\epsilon_{ijk}x_{j}p_{k}]$
Now, you use the following identity for commutator $[A,BC]=[A,B]C+B[A,C]$. With this in mind, you get
$[x_{l},\epsilon_{ijk}x_{j}p_{k}]=\epsilon_{ijk}[x_{l},x_{j}]p_{k}+\epsilon_{ijk}x_{j}[x_{l},p_{k}]$
Now, the commutator $[x_{l},x_{j}]$ is zero and $[x_{l},p_{k}]$ is equal to $i\hbar\delta_{lk}$. So, you are left with
$[x_{l},\epsilon_{ijk}x_{j}p_{k}]=[x_{l},L_{i}]=i\hbar\epsilon_{ijk}x_{j}\delta_{lk}=i\hbar\epsilon_{ijl}x_{j}$
From this result you can find your particular commutator.
A:
Usually I find it easiest to evaluate commutators without resorting to an explicit (position or momentum space) representation where the operators are represented by differential operators on a function space.
In order to evaluate commutators without these representations, we use the so-called canonical commutation relations (CCRs)
$$
[x_i,p_j] = i\hbar \,\delta_{ij}, \qquad [x_i, x_j]=0,\qquad [p_i, p_j]=0
$$
Now, in order to evaluate and angular momentum commutator, we do precisely as you suggested using the expression
$$
L_z = x p_y - y p_x
$$
and we use the CCRs
\begin{align}
[x, L_z] &= [x, xp_y-yp_x]\\
&= [x,xp_y] - [x,yp_x]\\
&= x[x,p_y]+[x,x]p_y-y[x,p_x]-[x,y]p_x \\
&= -i\hbar y
\end{align}
In the last step, only the third term was non-vanishing because of the CCRs. I have also used the fact that the commutator is linear in both of its arguments,
$$
[aA+bB,C] = a[A,C] + b[B,C], \qquad [A,bB + cC] = b[A,B] + c[A,C]
$$
where $a,b,c$ are numbers and $A,B,C$ are operators, and the following commutator identity that you'll find useful in general:
$$
[AB,C] = A[B,C] + [A,C]B
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Server side code does not recognize my req.body.variable, stating that it is undefined
Im creating a web application that should send info from the client side to the server side every time a specific button is pressed. When I press the button, the terminal continues to tell me that the value I am trying to pass through the post request body is undefined.
Client side code (Where button is called from) -
function upvote(elem) {
var parentID = elem.parentNode.id;
console.log('Upvote button was clicked' + parentID);
fetch('/upvote', { //This is called to pass the body data to server side code
method: 'post',
body: JSON.stringify({
id: parentID
})
})
.then(function(res) {
if(res.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
function downvote(elem){
var parentID = elem.parentNode.id;
console.log('Downvote button was clicked');
fetch('/downvote', { //This is called to pass the body data to server side code
method: 'POST',
body: JSON.stringify({
id: parentID })
})
.then(function(res) {
if(res.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
setInterval(function() {
fetch('/ranking', {method: 'GET'})
.then(function(response) {
if(response.ok) return response.json();
throw new Error('Request failed.');
})
.then(function(data) {
})
.catch(function(error) {
console.log(error);
});
}, 1000);
My app.js (Server side code) --
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const {getLoginPage, login} = require('./routes/index');
const {players, questionsPage, upvoteQues, downvoteQues, ranking, addQuestionsPage, addQuestion, deleteQuestion, editQuestion, editQuestionPage} = require('./routes/question'); //All my routes
const port = 5000;
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: ''
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); port
app.set('views', __dirname + '/views'); folder to render our view
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.get('/', getLoginPage);
app.get('/questions', questionsPage);
app.get('/add', addQuestionPage);
app.get('/edit/:id', editQuestionPage);
app.get('/delete/:id', deleteQuestion);
app.get('/ranking', ranking);
app.post('/', login);
app.post('/add', addQuestion);
app.post('/edit/:id', editQuestion);
app.post('/upvote', upvoteQues); //This is then used
app.post('/downvote', downvoteQues); //This is then used
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
My question.js (More server side code, just separated into a different file)
const fs = require('fs');
module.exports = {
questionsPage:(req, res) =>{
let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC";
db.query(query, (err, result) => {
if (err) {
console.log('Query error');
res.redirect('/');
}
res.render('questions.ejs', {
title: "JustAsk!",
questions: result,
});
});
},
upvoteQues: (req, res) => {
console.log(req.body.id); //Error here
let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'" //Error here
db.query(updateQuery, (err, result) => {
if(err){
console.log('Query error');
res.redirect('/players')
}
});
},
downvoteQues: (req, res) =>{
console.log(req.body.id); //Error here
let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'" //Error here
db.query(updateQuery, (err, result) => {
if(err){
console.log('Query error');
res.redirect('/players')
}
});
},
ranking: (req, res) => {
let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC";
db.query(query, (err, result) => {
if (err) {
console.log('Query error');
}
res.send(result);
});
}
};
A:
The body should be in JSON format, not a string.
body: JSON.stringify({
id: parentID
})
change to:
body: { id: parentID }
and content type should be 'application/json` like below.
fetch('/url', {
method: 'POST',
body: {id: parentID },
headers: {
"Content-Type": "application/json",
}
})
| {
"pile_set_name": "StackExchange"
} |
Q:
The set of ideals of a solvable lie algebra L is a chain?
I know that every finite dimensional lie algebra over a field $\mathcal{F}$ has a unique maximal solvable ideal, all subalgebras of a solvable lie algebra are also solvable, and a sum of solvable lie algebras is solvable.
For a solvable lie algebra L, its maximal ideal is unique. By induction, the set of ideals of L is a chain relative to the order $\subset$. The maximal ideal of L is a sum of all proper ideals. I want to know if the maximal ideal is [LL]. Let $L^{(1)}=[LL]$, $L^{(i)}=[L^{(1-1)}L^{(1-1)}]$. Suppose that $L^{(n)}=0$, $n \in \mathbb{Z}_{+}$.What is the connection between
\begin{align*}
0 \subset [L^{n-1}L^{n-1}] \subset \ldots \subset [L^{1}L^{1}] \subset [LL] \subset L
\end{align*}
and the chain of ideals of $L$.
A:
This is not true, suppose $L$ is commutative of dimension 2, every 1-dimensional subspace is a maximal ideal, so there is not a unique maximal ideal and $[L,L]=0$.
| {
"pile_set_name": "StackExchange"
} |
Q:
ActionResult not being called when using [AcceptVerbs(HttpVerbs.Post)]
The ActionResult in the controller is not being called. The page is just refreshing.
Check my code below:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
@if (@ViewBag.Message != null)
{
<p style="color: #b94a48;">@ViewBag.Message</p>
}
@Html.HiddenFor(model => model.Id)
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
@Html.TextBoxFor(model => model.UserName, new { @placeholder = "Email", @class = "form-control placeholder-no-fix" })
<p style="color: #b94a48;">@Html.ValidationMessageFor(model => model.UserName)</p>
</div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
@Html.PasswordFor(model => model.Password, new { @placeholder = "Password", @class = "form-control placeholder-no-fix" })
<p style="color: #b94a48;">@Html.ValidationMessageFor(model => model.Password)</p>
</div>
</div>
<div class="form-actions">
<div>
<label class="checkbox">
@Html.CheckBoxFor(model => model.RememberMe, new { @class = "remember" }) Remember me
</label>
</div>
<button type="submit" class="btn blue pull-right">
Login <i class="m-icon-swapright m-icon-white"></i>
</button>
</div>
</fieldset>
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(AccountViewModel model, FormCollection args, string ReturnUrl)
{
}
RouteConfig:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("SJSS", "{controller}/Show/{assetCode}/{action}/{id}", new { controller = "Asset", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Account", action = "Home", id = UrlParameter.Optional });
A:
Try altering your @Html.BeginForm to this:
@Html.BeginForm("***Action Name***", "***Controller Name***", FormMethod.Post)
{
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can prawns and lobsters live out of water for more than six hours?
I live in Telangana which is a state of India.I like eating Non-vegetarian food.People of our state eat pond fish more comparing to other aquafood.In many places near me,I've seen people cutting alive fishes in to pieces with their big knives.I won't feel good to see this.So,usually I bring the pond fishes home and keep them aside for atleast 40 minutes with no water in contact to them.In these 40 minutes I prepare other ingredients needed for the recipe.After these 40 minutes,generally as there is no response from those fishes I start cutting them into pieces.In the same way I don't know how much time it will take for prawns and lobsters to die without water.Do they live more than six hours without water?
This question is not related to the experiments carried out by the biologists on lab creatures.They are great people.I encourage their experiments whether it involves humane killing or inhumane killing because their experiments on one creature may help millions of remaining creatures.
A:
TL;DR version is they are gill breathers and need to be in a humid and moist environment to have a considerable longer life span outside sea water.
Dr. Cowan's on being asked the same question about lobster said:
“Gills work best in seawater, but if lobsters are kept in containers of seawater with no aeration, they quickly use up the oxygen and suffocate,” she said. “That it why it is imperative to transport lobsters in containers with no standing water.” - New York Times
Many lobsters, shrimps and even crayfish & crabs are transported in boxes with a small amount of water in the bottom and they survive for several days like that. However the long term side effects of this are still to be discovered as most crustaceans transported this way get cooked.
| {
"pile_set_name": "StackExchange"
} |
Q:
git not honoring git info exclude
I am working on a shared repository and I want to exclude all the files under certain directory just for myself.
So I made an entry in $GIT_ROOT/.git/info/exclude
/path/to/folder/
After this I removed the indexes using
git rm -r --cached /path/to/folder/*
A git status after this show a long list of deleted file staged for commit.
I commit the changes and till here all is good as any changes made by me are not tracked by git. But I can not push the same to remote as this will mess up other developers working repo.
After this If I pull from remote it shows me a merge conflict modified by them/deleted by us. And with git reset --hard origin/<branch_name> It starts tracking the folder again.
Can this not be achieved because I can not push to remote ?
A:
A more robust solution is to:
move that folder outside of your repo
add a symlink
ignore that symlink with a git update-index --skip-worktree -- mysymlink
add a .gitignore inside that moved folder (with a '*' pattern)
put a sparce checkout in place in order to not fetch/download that specific folder.
.git/info/sparse-checkout content:
*
!/path/to/mysymlink
(with mysymlink being the name of the folder I want to ignore)
See more at "git assume unchanged vs skip worktree - ignoring a symbolic link"
The OP shshnk mentions in the comments the simpler approach:
I was able to implement it using just sparse-checkout.
Basically I mentioned the name of the folders in the format mentioned by you in .git/info/sparse-checkout file. Now git ignores the files in these folders.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hook in NUnit or SpecFlow when a test fails
So I am using SpecFlow with NUnit for developing end-to-end acceptance tests of a web application with Selenium. One of the things we do to try to gauge the nature of a failure, is to take a screenshot of the browser whenever a regression test fails. I am currently doing it by wrapping each of my tests in try/catch blocks, and taking the screenshot in the catch with Selenium then, rethrowing the exception. This works, but it makes the tests messier and more tedious.
Is there a way in either NUnit or SpecFlow to call a hook when any test fails, before any teardown method is called?
A:
You can use the ScenarioContext to detect if a scenario generated an error.
ScenarioContext.Current.TestError
If not null, then an error occurred. You can check this and use it to determine whether to take a screenshot or not. You can see an example on SpecFlow's documentation reference.
You can also make this an AfterScenario Hook so you do not need to have the try/catches everywhere. It would simply check every test at the end to see if an error occurred and whether to create a screenshot.
| {
"pile_set_name": "StackExchange"
} |
Q:
O uso e não uso da palavra function no TypeScript
Por que quando declaro método em uma classe o compilador apita, informando que esta errado o uso da palavra function.
Em lições anteriores do meu aprendizado para criar uma função assinava primeiramente como function.
abstract class Empregado {
abstract getFuncao():string;
}
class Professor extends Empregado {
getFuncao():string {
return "Professor";
}
}
class Diretor extends Empregado {
getFuncao():string {
return "Diretor";
}
}
A:
A resposta já está na pergunta.
Porque você não declara funções dentro de uma classe, declara métodos, então não faria sentido usar function. Além do que dentro de uma classe o compilador tem mais controle do que está acontecendo (a sintaxe é menos ambígua) e pode determinar o início e fim do método, por exemplo não pode ter uma método dentro de outro, mas é possível ter uma função dentro de um método.
| {
"pile_set_name": "StackExchange"
} |
Q:
Molar Specific Heat Definitions for Gases
In most textbooks, the molar specific heat of a gas is defined for gases at constant volume and constant pressure as follows :
$C_v = \frac{Q}{n\Delta T} = \frac{\Delta U}{n \Delta T}$
$C_p = \frac{Q}{n \Delta T}$
But these definitions can also be related by $C_p = C_v + R$, with $R$, being the ideal gas constant.
But it seems that using definition $(1)$ in the first law of thermodynamics leads to contradictions, for example
$$\Delta U = Q - W$$
$$\implies C_v\cdot n \cdot\Delta T = (C_v\cdot n \cdot \Delta T) - W $$
$$\implies W = 0 \ \ (\forall\ C_V, n, \Delta T)$$
Which is obviously not true
Another seeming contradiction can be derived as follows:
$$C_p = C_v + R$$
$$\implies \frac{Q}{n \Delta T} = \frac{Q}{n \Delta T} + R$$
$$\implies R = 0$$
Which again is obviously not true. So it seems one can not just take the definitions of $C_v$ and $C_p$ at face value and use them in equations, there have to be certain conditions where I can or cannot use them.
Textbooks such as Fundamentals of Physics, and University Physics, give very little explanation why the definitions of molar specific heats of gases differ under constant volume and constant pressure, for example why $C_p \neq \frac{Q}{n \Delta T}$, is not explained in much detail if at all in either textbook.
So my question is why do the definitions of molar specific heats of gases differ under constant volume and constant pressure?
And why can I not take the definitions of $C_v$ and $C_p$ at face value and use them in equations?
A:
When you learned this material as a beginning physics student, they taught you that $nC_p\Delta T=Q$, and the focus was typically on a solid or liquid (both of which are nearly incompressible). However, this was only introductory, and was not the correct and precise definition necessary to use in thermodynamics. In thermodynamics, it is recognized that heat capacity is really a physical property of the material, and has nothing to do with any specific process (which in thermo is characterized by W and Q). The new more precise definitions of heat capacities employed in thermodynamics involve the internal energy and the enthalpy of the material (and can apply to any material, including an ideal gas):
$$nC_v=\left(\frac{\partial U}{\partial T}\right)_V$$
$$nC_p=\left(\frac{\partial H}{\partial T}\right)_p$$
If the first equation is combined with the first law, then, in heating tests at constant volume, the amount of heat added Q to the system can be used to experimentally measure Cv directly, since the amount of work is zero. If the second equation is combined with the first law, then, in heating tests at constant pressure, the amount of heat added to the system can be used to experimentally measure Cp directly, since, in this case, $W = p\Delta V$. So the subscripts v and p are used to refer to the conditions required to measure these heat capacities directly by determining the heat Q added is such special tests. However, once these measurements have established the values of the two heat capacities, they can be used for all differential changes in state to determine the partial derivatives of U and H with respect to temperature.
| {
"pile_set_name": "StackExchange"
} |
Q:
Walking distance of or from?
Does this sentence make sense? Or should I use 'of' instead of 'from'?
Also moved to Lake George last year and only 5 minutes of walking distance from the public beach.
A:
It's possible to use either of or from, but there is a specific structure for both options. One can be walking distance from somewhere, or alternatively, within walking distance of somewhere.
To paraphrase your example:
I moved to Lake George last year and now I'm only 5 minutes walking distance from the public beach.
I moved to Lake George last year and now I'm within 5 minutes walking distance of the public beach.
As an aside, the also at the beginning of the sentence seems out of place - one would expect the sentence to begin with I also..., presuming some other element of conversation preceded this sentence. Similarly with only - I'd expect a pronoun of some sort beforehand.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why did this actor play a cameo role in Deadpool 2?
In Deadpool 2, there is a brief moment (couple of seconds) where we see X-Men trying to hide from Deadpool when he is in the mansion.
However, in this scene we see James Mcavoy in the role of Prof. Xavier.
Assuming Deadpool is not in 80's or 90's (he is well in 2010's) then shouldn't Patrick Stewart have played this role?
Or should it be assumed that James Mcavoy has taken 100 % of this role and now he will play the older version too?
So how is this timeline matching?
A:
So how is this timeline matching?
It doesn't.
It's just a two part joke thrown in due to fortunate timing and the availablity of the current X-men actors.
It was joke from the first Deadpool movie that the school was empty even though it should be overflowing with recognisable mutants.
At the time this was due, mostly, to the character "permissions" being tightly controlled and budget issues but now this is not such an issue.
However, the previous iterations of the X-men actors aren't available (Jackman a possible exception) but fortunately, the new versions, it so happened, were.
So...
A scripted joke got enhanced...
Director David Leitch told us how the shot came together. “That was interesting because Simon Kinberg was filming X-Men: Dark Phoenix in Montreal at the same time we were doing Deadpool,” he told Den of Geek. “So this was in the script but we were always wondering how we were going to be able to pull it off. The set supervisor, Dan Glass, who did the Matrix films, he came up with this idea of doing a composite, and getting the plates to match.
“So we shot our side here, and we sent the measurements and the camera positions and things up to Simon's team on Dark Phoenix, and they shot the plate for that there,” continued Leitch. “Then we put the two together. So actually it turned out to be easier than we thought. If we would have had to get all those people in the room it probably wouldn't have happened.
Source
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating the annualized return of the VIX
I need to calculate the annualized return of the VIX and it's Futures by using daily data from six and a half years.
I tried to use the R-function Return.annualized from the PerformanceAnalytics-package:
Return.annualized(vix,scale=252,geometric=TRUE)
But all R shows is "INF" as a result. Am I wrong by just letting the daily index values run through this?
Thanks for your help!
A:
Your data must be corrupted. Can you run summary or hist on them to see whether there are NAs or prices that are not plausible?
The problem is that you work on prices. You should work on the returns of VIX:
What about this:
library(PerformanceAnalytics)
library(xts)
data = read.table("clipboard",header=TRUE)
vix = xts(data$VIX, order.by = as.Date(data$Date,"%d.%M.%Y") )
vix.ret = Return.calculate(vix, method = "discrete")
Return.annualized(vix.ret,scale=252,geometric=TRUE)
| {
"pile_set_name": "StackExchange"
} |
Q:
Best Distro For Artificial Intelligence Research?
Is there a definite best distro for AI research? I want to build a AI that can be used to help me manage all my emails intelligently.
A:
I bet any Linux distribution will do. Depends on what you have experience with.
| {
"pile_set_name": "StackExchange"
} |
Q:
c++ base private method can be accessed after casting itself to derived class?
i found this when I used CRTP (curiously recurring template pattern).
template <typename T>
class Base {
private:
void f() {
//when T has its own f(), it calls that
//when T doesn't have, it calls itself, which is invoked recursively
//but i expect the compiler to complain that f() is private when T doesn't have its own f()
static_cast<T*>(this)->f();
}
public:
void g() {
f();
}
};
class Derived : public Base<Derived> {};
I thought i understand public, protected and private, but for this case, it looks like i am wrong. Any explanation is appreciated!
A:
This will only work if the shadowing declaration is public. See this example:
class Derived : public Base<Derived> {
private:
void f() { }
};
void x(Derived* d) {
d->g();
}
You get:
<source>: In instantiation of 'void Base<T>::f() [with T = Derived]':
<source>:13:9: required from 'void Base<T>::g() [with T = Derived]'
<source>:23:10: required from here
<source>:8:9: error: 'void Derived::f()' is private within this context
static_cast<T*>(this)->f();
^~~~~~~~~~~
<source>:19:10: note: declared private here
void f() { }
^
If the function is not shadowed in Derived, the call is the same as this->Base<Derived>::f(), which has to be legal, as Base is the only class that can access it.
It's also possible that your confusion came from accessing a seemingly different object. Keep in mind that access modifiers restrict access by scope, not by instance. Any method declared in Base can touch any Base instance's private members, not just this's.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I modify the singular values of a matrix in order to get a negative eigenvalue?
Let $A \in \mathbb{R}^{n \times n}$ be a real nonsymmetric matrix with eigenvalues $\left\{\lambda_i : i=1..n\right\}$ with positive real part $\Re(\lambda_i) > 0$ $\forall i=1..n$
Let $A=U\Sigma V^T$ be the singular value decomposition of $A$ with singular values $\left\{\sigma_i : i=1..n\right\}$, $\sigma_i>0$.
Let $\Sigma'$ be a diagonal matrix with a different set of singular values $\left\{\sigma_i' : i=1..n\right\}$, $\sigma_i'>0$ and let $\left\{\lambda_i' : i=1..n\right\}$ be the eigenvalues of $A'= U\Sigma' V^T$.
Is there a set $\left\{\sigma_i' : i=1..n\right\}$ such that there is at least one $\lambda_i'$ with negative real part $\Re(\lambda_i) < 0$?
A:
Not necessarily. For example, consider
$$ A = \pmatrix{\cos(\theta) & -\sin(\theta)\cr \sin(\theta) & \cos(\theta)}$$
with eigenvalues $e^{\pm i \theta}$ having positive real part if $-\pi/2 < \theta < \pi/2$.
Since $A$ is orthogonal, its SVD has $U = A$, $\Sigma = V^T = I$.
Then
$$A' = A \pmatrix{\sigma_1' & 0 \cr 0 & \sigma_2'}$$
has trace $(\sigma_1' + \sigma_2') \cos(\theta) > 0$ and determinant
$\sigma_1' \sigma_2' > 0$, and therefore its eigenvalues have positive
real part.
EDIT:
On the other hand, it is not always impossible. There are $3 \times 3$ examples where the real part
of a complex-conjugate pair of eigenvalues changes sign depending on the $\sigma'_j$. For example, take
$$ \eqalign{U &= \pmatrix{\sqrt{18-6\sqrt{3}}/6 & 0 & -\sqrt{18+6\sqrt{3}}/6 \cr
-\sqrt{9+3\sqrt{3}}/6 & \sqrt{2}/2 & -\sqrt{9-3\sqrt{3}}/6\cr
\sqrt{9+3\sqrt{3}}/6 & \sqrt{2}/2 & \sqrt{9-3\sqrt{3}}/6\cr}\cr
V^T &= \pmatrix{-\sqrt{9-3\sqrt{3}}/6 & \sqrt{9-3\sqrt{3}}/6 & \sqrt{18+6\sqrt{3}}/6\cr \sqrt{2}/2 & \sqrt{2}/2 & 0\cr
-\sqrt{9+3\sqrt{3}}/6 & \sqrt{9+3\sqrt{3}}/6 & -\sqrt{18-6\sqrt{3}}/6\cr}}$$
which come from the SVD of $$\pmatrix{0 & 0 & 1\cr 1 & 0 & -1\cr 0 & 1 & 1\cr}$$
For some $(\sigma'_1, \sigma'_2, \sigma'_3)$, such as $(1,1,0.3)$, the eigenvalues all have positive real part; for others, such as $(1,1,0.4)$,
the real eigenvalue is positive but the complex conjugate pair have negative real part.
| {
"pile_set_name": "StackExchange"
} |
Q:
When should I use the [Obsolete] attribute and when should I delete my code?
The function of [Obsolete] is essentially to stop a class/function from being used but still to maintain it in code for the record.
Is there any good reason why [Obsolete] should be used as opposed to just deleting, or commenting out the code. This question is even more relevant if you have source control so there is no point keeping the code for reference purposes as it will be in the SC.
I'm curious as to what is considered best practice?
A:
It is used mostly for backwards compatibility, so when you do a new implementation of a functionality that has a different expected behaviour, any code using the old functionality will still work, but you make sure that new uses of your library uses the new implementation.
If you are maintaining a library that is being used by third parties, you should develop a road map of when and if the obsolete functionality is going to be removed. The if it's important, because many times you are just indicating that that function is no longer to be maintained and the new one should be used instead.
Internally, it can be used in refactors to replace poorly-implemented-but-working functionality in a gradual way. You mark it as obsolete and start working through the warnings until you see no more of them, then you can proceed to safely remove it.
Be aware that this is an opinion based on experience on renewing legacy code bases and there is no common consensus.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# dotnetcore Regex Hangs When Given Long, Unbroken String
I have a regex that is hanging when it tries to match against a long, unbroken string. Here is a sample console app:
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
Stopwatch sw;
string pattern = @"(?:(?:https?|ftps?):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?";
string input = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
Console.WriteLine("Press any key to match regex.");
Console.ReadKey();
Console.WriteLine("Starting regex...");
sw = Stopwatch.StartNew();
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
sw.Stop();
Console.WriteLine($"Regex completed in {sw.Elapsed}. Press any key to exit.");
Console.ReadKey();
}
}
The Regex is meant to find URLs in user-generated comments. When a normal comment is provided, it processes in no time at all. A 100-word lorem ipsum it processes in about 36ms. As soon as a long, unbroken string is introduced, the regex hangs and, as far as I can tell, never finishes processing. The string does not need to have the same characters repeated.
Any help or insight would be appreciated.
A:
The main problem with your regex is that there are optional patterns alongside obligatory one pattern inside a * / + quantified group, see (?:[a-z\u00a1-\uffff0-9]+-?)*. This may lead (with long non-matching strings) to the the behavior when the regex engine starts trying all possible routes to match a string, and there may appear too many of them, so many that the system appears to freeze: a catastrophic backtracking.
Thus, if you plan to use your simplified solution you should avoid the similar patterns, use
(?:(?:https?|ftp)://)(?:-\.)?[^\s/?.#-]+(?:\.[^\s/?.#-]+)*(?:/\S*)?
where (?:[^\s/?\.#-]+\.?)+ is unrolled as [^\s/?.#-]+(?:\.[^\s/?.#-]+)*. While it is longer, the engine fails much quicker than when the optional pattern is inside the quantified group.
If you want to fix the original pattern, use
string pattern = @"(?:(?:http|ftp)s?://)?(?:\S+(?::\S*)?@)?(?:(?!1(?:0|27)(?:\.\d{1,3}){3})(?!1(?:69\.254|92\.168|72\.(?:1[6-9]|2\d|3[0-1]))(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:[a-z\u00a1-\uffff0-9]+(?:-[a-z\u00a1-\uffff0-9]+)*)(?:\.[a-z\u00a1-\uffff0-9]+(?:-[a-z\u00a1-\uffff0-9]+)*)*(?:\.[a-z\u00a1-\uffff]{2,}))(?::\d{2,5})?(?:/\S*)?";
Check how this regex matches and how (?:[a-z\u00a1-\uffff0-9]+-?)* is unrolled as [a-z\u00a1-\uffff0-9]+(?:-[a-z\u00a1-\uffff0-9]+)* to match patterns so that each subsequent pattern could not match the same chars. I also merged some negative lookaheads with common "suffixes". Note that (?:\S+(?::\S*)?@)? is left untouched as it may need to match any :s up to the last : before the rest of matching patterns.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tolkien-inspired: who am I?
I can walk on the floor, I can walk on the wall
Under trees, on top of hills slowly I do crawl
Back and forth, back and forth, I stalk the streets at night
If I fall I make no sound, but sometimes quite a fright
Who am I?
A:
Answer:
The Shadow
I can walk on the floor, I can walk on the wall
When you walk your shadow is on the floor and on the wall
Under trees, on top of hills slowly I do crawl
The shadow is crawled under trees and on top of hills
Back and forth, back and forth, I stalk the streets at night
The shadow appears more during night
If I fall I make no sound, but sometimes quite a fright
Someone is frightened from the shadow but the shadow makes no sound
A:
I think it's:
Darkness (as in shadows and darkness of the night).
| {
"pile_set_name": "StackExchange"
} |
Q:
Validar diferença de 5 pontos para mais ou menos
Preciso fazer uma validação se um valor tem uma diferença de até 5, tanto para positivo quando para negativo. Gostaria de saber se existe alguma função do JavaScript que me auxilie nisso, sem ter que fazer o seguinte if gigante:
let scoreboard_local_team = 22;
let scoreboard_visiting_team = 26;
let points = 0;
if (
scoreboard_local_team + 1 === scoreboard_visiting_team ||
scoreboard_local_team + 2 === scoreboard_visiting_team ||
scoreboard_local_team + 3 === scoreboard_visiting_team ||
scoreboard_local_team + 4 === scoreboard_visiting_team ||
scoreboard_local_team - 1 === scoreboard_visiting_team ||
scoreboard_local_team - 2 === scoreboard_visiting_team ||
scoreboard_local_team - 3 === scoreboard_visiting_team ||
scoreboard_local_team - 4 === scoreboard_visiting_team
) {
points += 30;
}
console.log(points)
A:
Você pode calcular a diferença e usar Math.abs para obter o valor absoluto desta (ou seja, o valor sem sinal):
let scoreboard_local_team = 22;
let scoreboard_visiting_team = 26;
let points = 0;
// se a diferença é menor que 5
if (Math.abs(scoreboard_local_team - scoreboard_visiting_team) < 5) {
points += 30;
}
console.log(points)
Não ficou muito claro se a diferença entre os valores pode ser zero, pois não tem essa condição no seu if. O código acima assume que pode, mas caso não possa, basta mudar para:
let scoreboard_local_team = 22;
let scoreboard_visiting_team = 26;
let points = 0;
let diff = Math.abs(scoreboard_local_team - scoreboard_visiting_team);
if (0 < diff && diff < 5) {
points += 30;
}
console.log(points)
A:
Imagino que tem até um erro nesta lógica e o que quer seria estabelecer se está dentro de uma faixa, e isto é feito sempre comparando a variável desejada com o menor valor possível e o maior valor possível. Se estiver dentro da faixa é verdadeiro, assim:
if (scoreboard_visiting_team > scoreboard_local_team - 4 && scoreboard_visiting_team <scoreboard_local_team + 4)
Pode ser que realmente não deve ser verdadeiro se for exatamente igual ao valor da variável, então precisaria mudar um detalhe e fazer uma exceção, mas eu duvido que isto seria coreto, o código abaixo faz igual ao seu código, que eu acho estar errado:
if (scoreboard_visiting_team > scoreboard_local_team - 4 && scoreboard_visiting_team <scoreboard_local_team + 4 && scoreboard_visiting_team != scoreboard_local_team)
| {
"pile_set_name": "StackExchange"
} |
Q:
calling an array containing variable int and String
I'm working on a simple product inventory program that allows the user to keep track of a store inventory. I'm using OOP so my program consists of 2 classes one is the class products{} that contains the variables and an initial print method. The second class is called class productdatafinder {} and it contains a long table that contains the inventory information in the form shown bellow:
class productsDataFinder
{
public static void main( String[] not_in_use )
{
products[] products_table =
{
//Milk products:
new products( 3333, "Cheese", "milk product", 1, "A" ),
new products( 6778, "Butter", "milk product", 1, "A" ),
new products( 5642, "Yougurt", "milk product", 1, "A" ),
new products( 4453, "High fat milk", "milk product", 1, "A" ),
new products( 3423, "Low fat milk", "milk product", 1, "A" ),
new products( 2296, "Coco milk","milk product", 1, "A" ),
new products( 1796, "Fruit yougurt", "milk product", 1, "A" ),
//Fruits:
new products( 4379, "Apple", "Fruit", 3, "B" ),
and here is how they are defined in order: int product_id; String product_name; String product_group; int product_aisle; String product_row;
Now my question:
I already know how to print out each product information giving the product_id which is of type int but now I want to do the same by giving the product_name which is of type String. How can I do this? I'm looking for some tips and hits or any useful web links. Here is the programs output:
This program prints out your inventory data.
The serial number is in the form of (1-9)(1-9)(1-9)(1-9)
Insert your serial number: 3333
Your product id is: 3333
Your product name is: Cheese
Your product group is: milk product
Your product aisle number is: 1
Your product row number is: A
Process completed
Thank you and sorry for the long text
here is my print method for variable product_id. This one is in the first class
public void print_products_data()
{
System.out.print( "\n Your product id is: " + product_id +
"\n Your product name is: " + product_name +
"\n Your product group is: " + product_group +
"\n Your product aisle number is: " + product_aisle +
"\n Your product row number is: " + product_row) ;
and here is the second one
System.out.print("\n This program prints out your inventory data. "
+ "\n The serial number is in the form of (1-9)(1-9)(1-9)(1-9) "
+ "\n Insert your serial number: " ) ;
Scanner keyboard = new Scanner( System.in ) ;
int given_id = keyboard.nextInt() ;
int products_index = 0 ;
boolean table_search_ready = false ;
while ( table_search_ready == false )
{
if ( products_index >= products_table.length )
{
table_search_ready = true ;
System.out.print( "\n Sorry, no such product id "
+ given_id + ".\n" ) ;
}
else if ( products_table[ products_index ].get_id() == given_id )
{
products_table[ products_index ].print_products_data() ;
table_search_ready = true ;
}
else
{
products_index ++ ;
}
A:
This would operate the same way that your current lookup system operates. However, instead of checking the product_id, check the product_name (or any other attribute).
//returns the Product which matches the name given by the parameter
//only works for unique names
public Product nameLookup(String name){
for(Product p: products_table){
if(name.equals(p.getProductName()))
return p;
}
}
//If names are not unique
public ArrayList<Product> nameLookup(String name){
List<Product> templist = new ArrayList<Product>();
for(Product p: products_table){
if(name.equals(p.getProductName()))
templist.add(p);
}
return templist;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I get to look like ?
I'm trying to deal with a frustrating Internet Explorer issue that prevents me from using jquery-validate in conjunction with jquery-placeholder. In short, the validation does not work on fields with type=password.
More info Here
One possible fix I came up with is to modify my passwords to be type=text, but this of course displays the passwords in plain-text rather than as *******.
Is there any clever html/js/css trick to make text fields display as though they were passwords?
A:
So potentially you could have something set up like this.
Have a hidden input type that simulates the password values
So I guess jquery wise it would be
//everytime the password changes hidden changes with it.
$('#passwordId').change(function() {
$('#hiddenID').val() = $('#passwordId').val();
});
html:
<input type="password" id="passwordId" />
<input type="hidden" id="hiddenID" />
So this would allow you to validate the hidden input which would be the same value as the password.
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone: Error when using -(id)initWithNibName
I am trying to use the following code, but I always get an error that I can find little information about:
- (id)initWithNibName:@"MyRidesListView" bundle:nil {
if ((self = [super initWithNibName:@"MyRidesListView" bundle:nil])) {
// Custom initialization
}
return self;
}
Error:
expected identifier before 'OBJC_STRING' token
This seems like a simple method to be calling. This is for a UINavigationController.
Ideas?
A:
It looks like you are trying to implement a constructor method in a subclass of UIViewController or UINavigationController.
YOur syntax is a bit off. Without seeing what you are doing in a broader context I don't really know what is going on here, but this might help you out a bit. Its the closesest to your code while being syntactically correct.
- (id)initWithNibName:(NSString *)nibNameOrNull bundle:bundle {
if ((self = [super initWithNibName:nibNameOrNull bundle: bundle])) {
// Custom initialization
}
return self;
}
Then you can do this outside of your class:
[[MyRidesListView alloc] initWithNibNamed:@"MyRidesListView" bundle:nil];
| {
"pile_set_name": "StackExchange"
} |
Q:
Access database won't share
We have an access database on a file share that has permissions for everyone in the department to access. The problem i am having is that when multiple users try accessing the database at the same time they are unable to do this. One user can open the database fine but when another user tries to simultaneously, they double click the file icon, get an hour glass for a split second and nothing happens after. We are using Server 2003 as our domain controller. All permissions have been verified on both a domain level and in the access database under tools-options-advanced and setting relevent permissions to shared and no locks. Do you know what could be causing this issue with a "dead link" when user try to open the file simulateneously?
Any help is greatly appreciated.
Thanks.
A:
Ignore the naysayers - Access is perfectly fine for a small number of users. Either you have the default Access settings to open dbs exclusive which will lock out other users or there is some weird network problem.
EDIT
- noticed you already have default shared access
- is record-level locking on?
- also try giving user full control of the shared network folder (Access needs read/write/create/delete to be able to create and delete the ldb file)
A:
This issue occasionally happens to Access databases for almost no apparent reason. Of the suggested responses by Microsoft, you are already doing the second (opening from within Access) but I believe the first provides somewhat of the answer you are looking for.
In the target of the shortcut, include
the path of MSAccess.exe
According to Microsoft Help and Support
| {
"pile_set_name": "StackExchange"
} |
Q:
Add UIView to UIView
I have a ViewController, on it i have a UIView space:
Here it is:
@property (weak, nonatomic) IBOutlet UIView *iboContentView;
So, i have created a *.XIB file called ExternalDisplayViewController.xib
And the created ExternalDisplayViewController.h and ExternalDisplayTableViewController.m
The in ExternalDisplayViewController.xib to my UIView i added class ExternalDisplayTableViewController ( to tie up classes to UI ).
And on my ViewController i want to place my Custom control ( that is ExternalDisplayTableViewController ) into its place - iboContentView.
In my code i do this:
-(void)showViewController
{
CGRect frame = CGRectMake(0, 0, self.iboContentView.frame.size.width, self.iboContentView.frame.size.height);
ExternalDisplayViewController *view = [[ExternalDisplayViewController alloc]initWithFrame:frame];
view.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
view.contentMode=UIViewContentModeScaleAspectFit;
[self.iboContentView addSubview: view];
}
But it doesn't show up. What am i doing wrong?
Here how my Custom control looks like:
ExternalDisplayViewController.h:
#import <UIKit/UIKit.h>
@interface ExternalDisplayViewController : UIView
@end
A:
UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"ExternalDisplayTableViewController" owner:self options:nil] objectAtIndex:0];
[iboContentView addSubview:view]
| {
"pile_set_name": "StackExchange"
} |
Q:
Why the change to "Let us live to make men free?"
The 5th verse of the Battle Hymn of the Republic
In the beauty of the lilies Christ was born across the sea
With a glory in his bosom that transfigures you and me
As He died to make men worthy, let us die to make men free
While God is marching on
Often is changed to "As He died to make us worthy, let us live to make men free"
I know what this does (it changes the entire meaning of the verse and is, quite frankly, disrespectful to the thousands of people who died in the Civil War), but I do not know why. I know songs are often changed to remove offensive terms (like "n*****" being changed to "chigger" in Oh Susanna), but I don't see how "let us die to make men free" could be seen as offensive in any sense, other than the sexism not addressed by the change. Can someone enlighten me to the reasoning behind the change, and possibly when it took place?
A:
It's a philosophical change. The phrase "die to make men free" has an unmistakeably martial connotation, which matches with the song's origins as a literal "battle hymn" of the Civil War.
The modern version is more pacifist, it has more of a social gospel connotation. The core issue is that people love the song, but have become uncomfortable with its military orientation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stripes JsonResolution causing stackoverflowerror on Hibernate many to one mapping
I've been online trying to fix this for awhile now.
I have an object, which has successfully mapped (including JsonResolution) by using
But when I use the many-to-one mapping for a different relationship the JsonResolution causes a stackoverflow error, I think its getting stuck in a loop on that relationship. I've tried lazy loading, Hibernate.Initialize e.t.c and no luck, I think something needs to be corrected either on the JsonResolution end or with the mapping.
<set name="Audits" table="audits" inverse="true" lazy="false" fetch="select">
<key>
<column name="entityId" not-null="true" />
</key>
<one-to-many class="Audit" />
</set>
<many-to-one name="person" class="Person" column="personId" not-null="false" unique="true" />
code:
@HandlesEvent("getall")
public Resolution getall() {
if(!User.isLoggedInUserAdmin()) { return null; }
EventDTO eDTO = new EventDTO();
Session s = DBUtil.GetHibernateSession();
List<Event> events = s.createCriteria(Event.class)
.setMaxResults(2)
.add(Restrictions.eq("type", "Accident"))
.addOrder(Order.desc("id"))
.list();
if(events.isEmpty()) {
eDTO.setStatus("success");
} else {
for(int i=0; i< events.size(); i++) {
Hibernate.initialize(events.get(i).getPerson());
}
eDTO.setEntities(events);
eDTO.setStatus("success");
}
JsonResolution j = (JsonResolution) new JsonResolution(eDTO);
s.close();
return j;
}
error:
net.sourceforge.stripes.exception.StripesServletException: ActionBean execution threw an exception.
net.sourceforge.stripes.controller.DispatcherServlet.service(DispatcherServlet.java:183)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
net.sourceforge.stripes.controller.StripesFilter.doFilter(StripesFilter.java:247)
root cause
java.lang.StackOverflowError
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.json.JSONObject.populateMap(JSONObject.java:937)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONArray.<init>(JSONArray.java:171)
org.json.JSONObject.wrap(JSONObject.java:1524)
org.json.JSONObject.populateMap(JSONObject.java:939)
org.json.JSONObject.<init>(JSONObject.java:272)
org.json.JSONObject.wrap(JSONObject.java:1539)
org.json.JSONObject.populateMap(JSONObject.java:939)
A:
Probably serialization cannot cope with circular reference (Event -> Person & Person-> Event).
Try to use your own serialization implementation (I don't know whether you can plug your own serializer or not) or use another library (Gson maybe?) for serialization.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql 8 - rds - 1022 Can't write; duplicate key in table
Documenting this error and solution here in case it could help anyone.
We have a MYSQL 8 database on Amazon RDS.
The below group by used to work just fine on Mysql 5.7 but it started giving
1022 Can't write; duplicate key in table '/rdsdbdata/tmp/#sqlf80_1656bc_0'
error once we upgraded to Mysql 8.
GROUP BY DATE_FORMAT(CONCAT(YEAR(performance_stats_date),'-',
MONTH(performance_stats_date),'-',DAY(performance_stats_date)),
'%Y-%m-%d')
A:
There are two solutions we found:
1. Either reduce the number of columns in the query (in our case we have about 800 columns in this particular query, reducing it to less than about 100 solved the problem)
2. or simplify the group by statement to something like GROUP BY performance_stats_date
| {
"pile_set_name": "StackExchange"
} |
Q:
How to start SharePoint 2010 workflow from Infopath 2010 code behind?
I have an Infopath 2010 template with 2 buttons: submit and cancel. When the submit button is clicked I the form is saved to a document library in SharePoint 2010 and the corresponding workflow is clicked off. The user can then open the form and cancel the request by clicking on cancel. I would like to start a different workflow when cancel is clicked. Any ideas as to how that could be done?
Thanks
A:
That is not a bad workaround Nostromo but we actually ended up using the out of the box SharePoint web services to start the workflow from InfoPath code behind. Here is the method we developed to do that.
public static void StartWorkflow(string siteUrl, string docUrl,string workflowName, List<string> approvers,string description)
{
var workflow = new Workflow();
workflow.Url = siteUrl+ "/_vti_bin/workflow.asmx";
workflow.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode assocNode = workflow.GetTemplatesForItem(docUrl);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(assocNode.OwnerDocument.NameTable);
nsmgr.AddNamespace("wf", "http://schemas.microsoft.com/sharepoint/soap/workflow/");
XmlDocument doc = new XmlDocument();
Guid templateID = new Guid();
bool workflowFound = false;
XPathNodeIterator rows = assocNode.CreateNavigator().Select("//wf:WorkflowTemplate", nsmgr);
while (rows.MoveNext())
{
if (rows.Current.GetAttribute("Name", "").ToLower() == workflowName.ToLower())
{
doc.LoadXml(rows.Current.SelectSingleNode("wf:AssociationData/wf:string", nsmgr).Value);
XPathNavigator idNode = rows.Current.SelectSingleNode("wf:WorkflowTemplateIdSet", nsmgr);
templateID = new Guid(idNode.GetAttribute("TemplateId", ""));
workflowFound = true;
break;
}
}
if(!workflowFound)
throw new Exception("System couldn't location the workflow with name: " +workflowName);
XmlElement xmlRoot = doc.DocumentElement;
nsmgr = new XmlNamespaceManager(assocNode.OwnerDocument.NameTable);
nsmgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD");
xmlRoot.SelectSingleNode("/my:myFields/my:Description", nsmgr).InnerText = description;
XmlNode reviewersNode = xmlRoot.SelectSingleNode("/my:myFields/my:Reviewers", nsmgr);
reviewersNode.InnerXml = "";
foreach (var user in approvers)
{
XmlNode personNode = reviewersNode.AppendChild(doc.CreateElement("my:Person"));
XmlNode accountIdNode = personNode.AppendChild(doc.CreateElement("my:AccountId"));
accountIdNode.InnerText = user;
XmlNode accountTypeNode = accountIdNode.AppendChild(doc.CreateElement("my:AccountType"));
accountTypeNode.InnerText = "User";
}
XmlNode workflowNode = workflow.StartWorkflow(docUrl, templateID, doc.DocumentElement);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
SQl statement to monitor SQL Server Locks
Which SQL sentence (function or stored procedure) I can use to monitor an SQL Server DeadLock, caused by an UPDATE statement?
A:
try this query to see blocking processes, including the actual SQL query text:
SELECT
r.session_id AS spid
,r.cpu_time,r.reads,r.writes,r.logical_reads
,r.blocking_session_id AS BlockingSPID
,LEFT(OBJECT_NAME(st.objectid, st.dbid),50) AS ShortObjectName
,LEFT(DB_NAME(r.database_id),50) AS DatabaseName
,s.program_name
,s.login_name
,OBJECT_NAME(st.objectid, st.dbid) AS ObjectName
,SUBSTRING(st.text, (r.statement_start_offset/2)+1,( (CASE r.statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE r.statement_end_offset
END - r.statement_start_offset
)/2
) + 1
) AS SQLText
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text (sql_handle) st
--WHERE r.session_id!=@@SPID --uncomment to not see this query
deadlocks are easily trapped with the profiler:
Try running the run a trace in the profiler (pick the blank template), select the "deadlock graph event", and on the new tab that appears (Events Extraction Settings), save each (check "save deadlock XML events separately") in its own file. Open this file in an xml viewer and it will be easy to tell what is happening. Each process is contained, with an execution stack of procedure/trigger/etc calls, etc. and all locks are in there too.
Look at the "resource list" section of the file, it will show what is being locked and held by each process causing the deadlock. Figure out how to not have one of these locked and the deadlock will be resolved.
Let this trace run until the deadlock happens again, info is only recorded when a deadlock happens, so there isn't much overhead. If it never happens again, good it is solved, if not you have captured all the info.
A:
I think you're better placed to use SQL Profiler to monitor deadlocks - see here. SQL Profiler shows the deadlocks in a diagram to make it easier to determine what caused them.
| {
"pile_set_name": "StackExchange"
} |
Q:
next() fails inside a element
I'm working on a jQuery code that is supposed to display tooltips (<p>) when the corresponding link (<a>) is hovered. For that I use the next() function to find the tooltip which is always placed right after the respective link.
Surprisingly, next() returns no elements when the link and the tooltip element are inside a <p> element. However, when I put those two in a <div>, it works fine - the next element is found.
I have created an entry on jsfiddle.net to help explain my problem:
http://jsfiddle.net/zwEAZ/
The console.log() line in the code always logs 0 when hovering the second link.
I'm curious why it's behaving like that. Thanks in advance for any answers.
Edit: I'm posting the code here too (I'm assuming you have jquery-1.11.0.js in the same directory as the HTML document):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.11.0.js"></script>
<script>
$(function() {
$('.link').mouseenter(function(event) {
$(this).next().css({
left: event.pageX + 10 + 'px',
top: event.pageY + 10 + 'px'
}).stop().fadeIn(500);
console.log($(this).next().length);
}).mouseleave(function() {
$(this).next().stop().fadeOut(250);
});
});
</script>
<style>
* {
margin: 0;
padding: 0;
}
.tooltip {
display: none;
position: absolute;
background-color: #ccc;
border: 1px solid #000;
}
</style>
</head>
<body>
Here it works:
<a href="#" class="link">Link</a>
<p class="tooltip">Tooltip</p>
<p>
And here it doesn't...
<a href="#" class="link">Link</a>
<p class="tooltip">Tooltip</p>
</p>
<div>
But here it works again!
<a href="#" class="link">Link</a>
<p class="tooltip">Tooltip</p>
</div>
</body>
</html>
A:
Because p cannot contain another p element, it is an invalid HTML.
So if you inspect your html using browser development tools, you will see that the structure is modified as
<body>
Here it works:
<a href="#" class="link">Link</a>
<p class="tooltip">Tooltip</p>
<p>
And here it doesn't...
<a href="#" class="link">Link</a>
</p>
<p class="tooltip">Tooltip</p>
<p></p>
<div>
But here it works again!
<a href="#" class="link">Link</a>
<p class="tooltip">Tooltip</p>
</div>
</body>
now the link does not have a next sibling element
| {
"pile_set_name": "StackExchange"
} |
Q:
unchecked exception の方が checked exception より spring philosophy に合致している理由/ソース
spring を扱っている人たちの間で、Checked Exception を取り扱うよりは、 Unchecked Exception を取り扱うほうが、 Spring Philosophy に合致している、という話を耳にします。
たとえば、次の本家SO の答えの最初の行です。
https://stackoverflow.com/a/24401798
具体的に、これ(Unchecked Exception を使うこと)がどうして、
Spring philosophy に合致しているのかについての、
説明ないし、ソースを見つけられずにいるのですが、
ご存知の方はいらっしゃいますでしょうか。
A:
Checked/Unchecked Exceptionと"Spring philosophy"との関係への言及は、Spring Framework Reference Documentationで見つけられます。
12.3 Understanding the Spring Framework transaction abstraction
[...]
Again in keeping with Spring's philosophy, the TransactionException that can be thrown by any of the PlatformTransactionManager interface's methods is unchecked (that is, it extends the java.lang.RuntimeException class). Transaction infrastructure failures are almost invariably fatal. In rare cases where application code can actually recover from a transaction failure, the application developer can still choose to catch and handle TransactionException. The salient point is that developers are not forced to do so.
直接的に"Spring philosophy"を定義する文書は見つけられなかったのですが、Announcing Spring Framework 4.0 GA Releaseにphilosophyとprinciplesについての言及がありました。
The Spring Framework project page is always a great start. But we've worked hard on new guides to accompany the launch of the Framework. In keeping with our philosophy of "let's build a better enterprise" we've developed these getting started guides with a few principles:
Be the simplest possible example, not the "best", as that is subjective
Use the most up-to-date Spring best practices
Do not give in to the temptation to become a full-blown tutorial, keep those separate
Make assumptions. Separate underlying concepts into linked, distinct documents
Stay task oriented, use case-oriented, explain things beyond Spring when relevant
Above all, be a resource that experts and beginners alike can appreciate
A:
SpringのコアはDIコンテナです。DI(依存性の注入)を導入する目的は、利便性など色々ありますが、最大の目的はコンポーネント間の結合度を下げることにあります。
対して検査例外は、プロシージャ内部で発生したエラーが、回復可能であることを呼び出し元に通知する仕組みです。
呼び出し元コンポーネントが例外をハンドリングするということは、子コンポーネントの実装の詳細を知る必要があるということです。これはDIの概念と真っ向から衝突します。
分かりやすい例がSQLExceptionです。
Springを使う場合、データベースから業務データをBeanで取得するケースも多いと思いますが、一般的なJavaでデータベースを扱う場合、SQLExceptionのハンドリングは避けられません。しかし、SQLExceptionが返却するエラーコードはDB製品固有のものであり、コンポーネントの密結合化に繋がります。
そこで、Springでは検査例外のSQLExceptionを、非検査例外のDataAccessExceptionに抽象化することで、コンポーネント内部で例外が閉じるような設計に矯正しています。
加えて、SpringではDIコンテナにAOP(アスペクト指向プログラミング)を連携させることで、例外処理を挿入したハンドラインスタンスに行わせることができます。
業務例外やシステム例外の処理を、それぞれのロジックに書くのではなく、振る舞いのみを抽出して横断的に処理をする、「関心の分離」というやつです。
この辺りの概念に通じてくると、自然と検査例外に対して、
コンポーネント間で実装の詳細を共有する必要が生まれ、疎結合化を阻害する
検査例外は例外処理のボイラープレートコードを強制し冗長である
という思考が生まれて、「非検査例外を使用する」という方向に寄るんじゃないんでしょうか。
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX addListener not working
I'm quite a newbie on JavaFX and I need to bind the visible property of a Label in a way that, if the value it represents reaches 0, the Label should be invisible. Also, it needs to be updated when the bounded integerProperty value changes.
This is my code:
@FXML
private Label kingRewardLabel;
// many other stuff between
IntegerProperty kingBonus = mainApp.getLocalModel().getMap().kingBonus();
kingBonus.addListener((observable, oldValue, newValue) -> {
if (newValue.equals(0)) {
kingRewardLabel.setVisible(false);
} else {
kingRewardLabel.setText(String.valueOf(newValue.intValue()));
}
});
// testing the listener
kingBonus.setValue(25);
I have already tried to debug a little but everything seems fine, no error, no exception thrown, just the listener does not work, or at least not as I expect, because the Label still show the default text "Label", instead of "25"
A:
You can use simply bindings to achieve this:
kingRewardLabel.textProperty().bind(kingBonus.asString());
kingRewardLabel.visibleProperty().bind(kingBonus.greaterThan(0));
The Label kingRewardLabel will display the value of the IntegerProperty kingBonus and it is only visible if the displayed value is greater than zero.
But, if you want to stay with listeners:
kingBonus.addListener((obs, oldVal, newVal) -> {
kingRewardLabel.setVisible(newVal.intValue() > 0);
kingRewardLabel.setText(newVal.toString());
});
This is almost the same as your listener in the question, but in that case, if the Label became invisible, it will never become visible again as kingRewardLabel.setVisible(true) is never called.
Finally, to answer your question about why the listener is "not working" - there can be two possible reasons:
1) The Label, which one is displayed is not the Label stored in kingRewardLabel
2) At the time when you call kingBonus.setValue(25);, the value stored in kingBonus is already 25, no changed event will be fired, therefore the listener is not executed at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Room Configuration did not work properly in google real time multiplayer services for android
i am trying to build a real time multi-player game and now i am exploring sample game provided by google for multi-player. Link is ...
https://github.com/playgameservices/android-samples/tree/master/ButtonClicker
issue is that when i change auto-match criteria configuration as per my requirement
void startQuickGame() {
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 3;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS,
MAX_OPPONENTS, 0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
getGamesClient().createRoom(rtmConfigBuilder.build());
}
then this code not wait for 3rd or 4rh player in room (as i set in MAX_OPPONENTS ) and game starts immediately with 2 player(1 opponent). i want to add timer here and game starts after that specified time.
and surprisingly after room creation MIN_PLAYER value dose'nt work at all in this code that is for default room UI.
final int MIN_PLAYERS = 2;
Intent i = getGamesClient().getRealTimeWaitingRoomIntent(room, MIN_PLAYERS);
// show waiting room UI
startActivityForResult(i, RC_WAITING_ROOM);
my requirement is that after room creation i want to wait for a specific time and then game starts with joined player. no matter they are 2 , 3 or 4.
A:
The automatching algorithm doesn't try very hard to maximize the number of players in the match -- if you set min to 1 and max to 3, getting a 2 player game is possible.
What you should do in this case is set MIN_OPPONENTS and MAX_OPPONENTS to 3, and handle the game start logic from your code.
If you want to implement this timer logic, you can't use our built-in waiting room UI, because it doesn't support starting a game early based on time. So, instead, implement your own waiting room with this logic:
Start your timer.
Show the progress on screen as you see peers being connected or disconnected via onPeerConnected() and onPeerDisconnected(), and other callbacks. See RoomStatusListener and RoomStatusUpdateListener.
When the timer expires, decide what you're going to do. For example, if there are 2+ players connected, start the game. If not, wait longer, give up, etc.
Handle the case when someone joins the game late. This will happen if 2 players joined, the timer expired, the game started and then a 3rd or 4th player shows up. Make sure the experience is not terrible for them (don't just kick them out) :-) If you can't integrate them into the ongoing game, you could have them stay in "spectator mode" and join in the next round/match/etc.
Important: remember that the timers for different players won't be in sync in the logic above -- so you should send a real time reliable message to all peers when you decide to start the game, to let them know that the game is starting and that they should move to the game screen.
If the logic gets more complicated, it might make sense to elect a "server". You can do that, for example, by saying that the client with the lowest Participant ID (lexicographically) is the server. Saying "whoever created the game is the server" is no good, because when automatching, everyone thinks they created the game.
I hope this helped!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass object properties to a function from object itself?
I want to pass an object property to a global function and want to save return value in a new object property .
What I tried:
var Tools = {
id : "tools" ,
key : myfunc(this.id) //I also tried Tools["id"] and id .
};
Here is the function:
function myfunc(tmp){
return tmp;
}
I want to use Tools.key not Tools.key() that's why I'm not using following code:
key : function(){
return myfunc(this.id);
}
A:
This is what you might want to do:
var tools = {
id: 7,
get key() {
var key = 'Key is ' + this.id; // Do something with this.id
return key;
},
};
tools.key; // "Key is 7"
You should read MDN to learn and understand more
Notice that I removed the capital 'T' from tools: since it is not a function that should be used as a constructor, it should not begin with a capital letter.
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJs with large JSON array
1Ok so I'm developing an application that has a Parent-Child hierarchy using AngularJs to bind the data received from the RESTFUL web service to the view.
An example of the JSON the web service would be returning would be:
{"id":0,"name":"Parent One","listOfChildren":[{"id":0,"name":"Child 1","childType":"CHILD1"},{"id":1,"name":"Child 2","childType":"CHILD1"}]}
With this information I know I can put it into an array and display it on a table using Angulars ng-repeat but my problem is a Parent could have hundreds/thousands of children and there could be hundreds/thousands parents so the array would be colossal.
Another problem is when I update a parent with a new child I would have to traverse the whole array looking for the parent and then insert the child into it which is extremely ineffecient.
So my question is basically is there any way I can do this more efficiently without having to use one big array?
Thanks for any help provided.
A:
Given that you have a huge amount of data, I don't know that there is really a perfect solution. Do you have to show every parent and every child at one time? Or could you paginate the results so that you're only showing maybe 100 nodes at a time? in your example, the parent and both of the children have the same id property value of 0. Is that actually the case? or do your parents and children have unique id's? Do you have access to the backend web service? Can you change the format of the json it serves up?
Making some assumptions to the above questions, here's the best proposal I can think of:
Change your JSON into a format similar to this one:
var bigobject = {
100: {
"id":100,
"name":"Parent One",
"listOfChildren":{
101: {
"id":101,
"name":"Child 1",
"childType":"CHILD1"
},
102: {
"id":102,
"name":"Child 2",
"childType":"CHILD1"
}
... // more children here
}
},
103: {
"id":103,
"name":"Parent Two",
"listOfChildren":{
104: {
"id":104,
"name":"Child 3",
"childType":"CHILD1"
},
105: {
"id":105,
"name":"Child 4",
"childType":"CHILD1"
}
... // more children here
}
},
... // more parents here
}
Basically you have one big json object where the key for every node is its node's id. And then you change a parent's listOfChildren from an array to an object that has the keys for all the id's of its children.
To add a new child to your parent, is simple. For example:
var parentId = 103;
var newChild = {"id":110,"name":"Child 2","childType":"CHILD1"};
bigobject[parentId].listOfChildren[newChild.id] = newChild;
And then to paginate your results, you could use the built-in limitTo filter and a custom filter startFrom:
.filter('startFrom', function() {
return function(input, start) {
if(!input) return input;
start = +start;
return input.slice(start);
};
});
And then your ng-repeat would be something like:
<div ng-repeat="(parentId, parent) in bigobject | startFrom:start | limitTo:pageSize">
<div ng-repeat="(childId, child) in bigobject[parentId].listOfChildren">
{{parent.name}} - {{child.name}}
</div>
</div>
I hope that helps or at least points you in a helpful direction.
| {
"pile_set_name": "StackExchange"
} |
Q:
Maximum value of function exists or not
Let $ f : [0,\infty) \to\Bbb R $ be a continuous function with $ \lim\limits_{x\to \infty}f(x)=0 $. Then $f$ has maximum value in $[0, \infty)$.
The given satement is false and I am unable to prove it . Also I didn't get any counter example to argue this statement false.
A:
Take $f(x)=-e^{-x}$ and see what happens.
| {
"pile_set_name": "StackExchange"
} |
Q:
System.ComponentModel.IContainer takes 1 sec to declare?
I'm currently using Red Gate's Performance Profiler to optimize an application. I keep running across a declaration generated by VS and always takes around a second to declare. Its being set to null too. I don't understand why this takes a second to do. I know VS Designer can use this for some components but is there anyway to reduce the number of these declarations? An explanation of why this happens would be great too.
A:
That is a field initializer. The profiler may be measuring the initialization of the entire class at that line. Try setting the field to null within the constructor instead to see if there is a difference in times.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the default port in react js
I could able to start react js with default port 3000. But, when I customised the port to 4200, "start": "PORT=4200 react-scripts start"(Just changed in the package.json), I am not able to start the react js application.
'PORT' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `PORT=4200 react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional lo
ging output above.
npm ERR! A complete log of this run can be found in:
A:
An other option that was not mentioned in the other answer would be to create a .env file in the root directory and put PORT=4200 in it. It will automatically be loaded in your environment variables.
A:
to start APP on another port run the following npm command
npm start --port 3002
or to config in package use
replace the start command with below
"start": "set PORT=3006 && react-scripts start"
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add foreign keys in a compact database in VS2010?
If I create a SQL Express database via VS2010, I can create diagrams and this way set foreign key relationships. What's the case in a compact database? There is no such option in Server Explorer for this type of DB.
A:
Yes there is. In Server Explorer, right click the table, select Table Properties, and use Add Relations view. Remember to press the "Add Relation" button to actually add the releation
| {
"pile_set_name": "StackExchange"
} |
Q:
rename command usage in ubuntu machine for rename a set of files
I have a shell script for renaming multiple files in a folder. It works on a rhel host but throws error on a ubuntu14 host.
#!/usr/bin/env bash
SOME_NUMBER=1
rename _file_name.c _file_${SOME_NUMBER}.c path/of/file/*_file_name.c
What changes shall i make in the code to make it work on a ubuntu14 host?
EDIT-1:
For running the code on ubuntu machine i made following change and it works:
rename 's/\_file_name.c$/\_file_1.c/' path/of/file/*_file_name.c
but following doesn't works and i get below error message:
rename 's/\_file_name.c$/\_file_${SOME_NUMBER}.c/' path/of/file/*_file_name.c
ERROR MESSAGE:
Global symbol "$SOME_NUMBER" requires explicit package name at (eval 1) line 1.
Global symbol "$SOME_NUMBER" requires explicit package name at (eval 1) line 1.
A:
Single quotes prevent parameter expansion. Because Perl and shell syntax is similar in this regard, the literal string s/\_file_name.c$/\_file_${SOME_NUMBER}.c/ is passed to Perl, where it tries to expand the undefined variable $SOME_NUMBER.
Use double quotes instead:
rename "s/\_file_name.c$/\_file_${SOME_NUMBER}.c/" path/of/file/*_file_name.c
See Difference between single and double quotes in Bash
Be sure that the value of SOME_NUMBER in your shell script really is just a number, or at least something that, when expanded, produces a valid Perl expression.
| {
"pile_set_name": "StackExchange"
} |
Q:
Meteor.js: How to dynamically route while limiting subscription?
I'm trying to route to one page if something exists, and another if it doesn't. However, I don't want to subscribe to the entire collection (~thousands), because I think it will affect performance. How do I do this?
I tried something like this, but for some reason Meteor goes through the router code twice on pageload and flashes the error page briefly before redirecting to the item page, and I don't want this to happen.
Here's what I have:
router.coffee
to: (id)->
Meteor.subscribe 'item', id
item = Items.findOne id
if item
# if the item exists, then redirect to it
Session.set 'currentItemId', id
'itemPage'
else
# if not, then redirect to the sorry page
'sorryPage'
publications.coffee
Meteor.publish 'item', (id)->
return Items.find({_id: id})
Subscribing to the entire collection will affect performance, right? Is there an easier way to check existence within a collection without subscribing to it? I tried to do a Meteor.call to check it server side, but it didn't work and isn't ideal (router waiting on server call..). Is there a "right" way to do this?
A:
The reason you're getting this "flashing" effect is probably because your router is implemented to be reactive (I'm not sure if this is a right strategy BTW) and since you're using Items.findOne, this method invalidates the current computation as soon as the data requested by Meteor.subscribe arrives to the Items collection.
Also, note that every subscription within an active computation get's cancelled automatically as soon as the computation gets recomputed. However, as it is claimed in the documenation (look here) Meteor should be smart enough to detect when you subscribe to the same data set twice, so this should not have any side effects.
If I were you, I would consider changing my router logic to something like this:
Session.set('currentItemId', id);
var status = Session.get('currentItemStatus');
if (status === 'ready')
return 'itemPage';
if (status === 'missing')
return 'sorryPage';
return 'loadingPage'; // probably status === 'loading'
And then, somewhere else in the project I would do:
Deps.autorun(function () {
Session.set('currentItemStatus', 'loading');
Meteor.subscribe('item', Session.get('currentItemId'), function () {
// onReady callback
var item = Items.findOne({_id:id});
if (item)
Session.set('currentItemStatus', 'ready');
else
Session.set('currentItemStatus', 'missing');
});
});
Please note, that if currentItemId does not change, the computation defined Deps.autorun will not be invalidated, so no unnecessary loadingPage will be shown to the user.
| {
"pile_set_name": "StackExchange"
} |
Q:
Publish bot to Azure
When I published my bot to Azure from Visual Studio and trying it on the web chat, it says can't send the message. Running the bot locally everything works just fine.
The emulator reports HTTP 500 error when trying to chat with the endpoint on azure.
A:
After some discussions in the comment section, I've pulled your code from the repository you've provided. Different to what you were saying, it also crashes locally with HTTP 500 on start. Reading the logs gave me issues with web.config.
This leads me to the following solution:
Your codebase contains a web.config file which doesn't belong there. This is a .net core application and therefore should not rely on web.config and instead use appsettings.json. When this web.config gets deployed, the runtime tries to load certain things and crashes with HTTP 500.
Not sure where this web.config comes from but I assume from previous deployments or some test of yours.
I've send you a PR simply removing this web.config and deployed your bot to Azure.
It works well:
Make sure you've selected remove additional files at destination when you publish it from Visual Studio after removing web.config. This way you're making sure that you not accidentally leave an orphaned web.config there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prometheus won't connect to Synapse metrics
I tried to follow this guide to configure prometheus with synapse metrics: https://github.com/matrix-org/synapse/blob/master/docs/metrics-howto.md
I'm having difficulties though. Here's how i set it up:
$ sudo ufw allow 9090
$ sudo nano /etc/matrix-synapse/homeserver.yaml
# in listeners: list
- type: metrics
port: 9000
bind_addresses:
- '0.0.0.0'
## Metrics ###
# Enable collection and rendering of performance metrics
#
enable_metrics: true
Restarted Synapse, installed Docker.
Create '/etc/prometheus/prometheus.yml' edit it like so:
$ sudo nano /etc/prometheus/prometheus.yml
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ['localhost:9090']
- job_name: "synapse"
metrics_path: "/_synapse/metrics"
scheme: "https"
static_configs:
- targets: ["localhost:9000"]
Attempt to start Prometheus:
$ docker run -p 9090:9090 -v /etc/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml --name prometheus prom/prometheus
level=info ts=2020-05-06T03:42:50.799Z caller=main.go:298 msg="no time or size retention was set so using the default time retention" duration=15d
level=info ts=2020-05-06T03:42:50.799Z caller=main.go:333 msg="Starting Prometheus" version="(version=2.17.2, branch=HEAD, revision=18254838fbe25dcc732c950ae05f78ed4db1292c)"
level=info ts=2020-05-06T03:42:50.799Z caller=main.go:334 build_context="(go=go1.13.10, user=root@9cb154c268a2, date=20200420-08:27:08)"
level=info ts=2020-05-06T03:42:50.800Z caller=main.go:335 host_details="(Linux 4.19.0-8-amd64 #1 SMP Debian 4.19.98-1+deb10u1 (2020-04-27) x86_64 0cf4549b1dcd (none))"
level=info ts=2020-05-06T03:42:50.800Z caller=main.go:336 fd_limits="(soft=1048576, hard=1048576)"
level=info ts=2020-05-06T03:42:50.800Z caller=main.go:337 vm_limits="(soft=unlimited, hard=unlimited)"
level=info ts=2020-05-06T03:42:50.802Z caller=main.go:667 msg="Starting TSDB ..."
level=info ts=2020-05-06T03:42:50.802Z caller=web.go:515 component=web msg="Start listening for connections" address=0.0.0.0:9090
level=info ts=2020-05-06T03:42:50.806Z caller=head.go:575 component=tsdb msg="replaying WAL, this may take awhile"
level=info ts=2020-05-06T03:42:50.806Z caller=head.go:624 component=tsdb msg="WAL segment loaded" segment=0 maxSegment=0
level=info ts=2020-05-06T03:42:50.807Z caller=head.go:627 component=tsdb msg="WAL replay completed" duration=403.999µs
level=info ts=2020-05-06T03:42:50.808Z caller=main.go:683 fs_type=9123683e
level=info ts=2020-05-06T03:42:50.808Z caller=main.go:684 msg="TSDB started"
level=info ts=2020-05-06T03:42:50.808Z caller=main.go:788 msg="Loading configuration file" filename=/etc/prometheus/prometheus.yml
level=info ts=2020-05-06T03:42:50.809Z caller=main.go:816 msg="Completed loading of configuration file" filename=/etc/prometheus/prometheus.yml
level=info ts=2020-05-06T03:42:50.810Z caller=main.go:635 msg="Server is ready to receive web requests."
But it just hangs taking the console away from me. :P I can detach it while running it at least.
I could see Prometheus at 192.168.1.171:9090 but it was not recording/showing synapse metrics. :/
Downloaded synapse-v2.rules from here: https://github.com/matrix-org/synapse/tree/master/contrib/prometheus
Edit: Thanks i edited out the https section, and pointed it to the new rules file, here is my prometheus.yml:
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "/etc/prometheus/synapse-v2.rules"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ['localhost:9090']
- job_name: "synapse"
metrics_path: "/_synapse/metrics"
static_configs:
- targets: ["localhost:9000"]
Then i restarted the Prometheus docker but it still isn't presenting the synapse metrics in the web dropdown.
There are prometheus statistics but no synapse ones.
A:
Tried downloading the compiled package and running that instead, worked well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert factor to float without losing precision in R?
Here is what I have:
tmp[1,]
percentages percentages.1 percentages.2 percentages.3 percentages.4 percentages.5 percentages.6 percentages.7 percentages.8 percentages.9
0.0329489291598023 0.0391268533772652 0.0292421746293245 0.0354200988467875 0.0284184514003295 0.035831960461285 0.0308896210873147 0.0345963756177924 0.0366556836902801 0.0403624382207578
I try converting this to numeric, since the class is factor, but I get:
as.numeric(as.character(tmp[1,]))
[1] 35 36 35 36 31 32 31 34 36 34
Where did these integers come from?
A:
Your problem is that indexing by rows of a data frame gives surprising results.
Reconstruct your object:
tmp <- read.csv(text=
"0.0329489291598023,0.0391268533772652,0.0292421746293245,0.0354200988467875,0.0284184514003295,0.035831960461285,0.0308896210873147,0.0345963756177924,0.0366556836902801,0.0403624382207578",
header=FALSE,colClasses=rep("factor",10))
Inspect:
str(tmp[1,])
## 'data.frame': 1 obs. of 10 variables:
## $ V1 : Factor w/ 1 level "0.0329489291598023": 1
## $ V2 : Factor w/ 1 level "0.0391268533772652": 1
## ... etc.
Converting via as.character() totally messes things up:
str(as.character(tmp[1,]))
## chr [1:10] "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
On the other hand, this (converting to a matrix first) works fine:
as.numeric(as.matrix(tmp)[1,])
## [1] 0.03294893 0.03912685 0.02924217 0.03542010 0.02841845 0.03583196
## [7] 0.03088962 0.03459638 0.03665568 0.04036244
That said, I have to admit that I do not understand the particular magic that makes as.character() applied to a data frame drop the information about factor levels and convert everything first to the underlying numerical codes, and then to character -- I don't know where precisely you would go to read about this. (The bottom line is "don't extract rows of data frames if you can help it; convert them to matrices first if necessary.")
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get more stuff from the wishing well?
When I put my candy in and got more lollipops, it will not let me get anything else. How do I do this and get more stuff from it?
A:
There isn't a way to get more things from the Wishing Well. There are three set defaults:
"Multiply my candies by 5"
"Multiply my lollipops by 8"
"Give me lots of potions and scrolls"
From the Candy Box Wiki:
Take care ! You can use this bonus only once!
When this is done, the well will advise you
"I will grant you one wish! So choose carefully from the list below".
I think that pretty much sums it up. You get one wish, the well warns you to choose carefully because you only get one chance. There is no other way around this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Gtkmm can't open application window on OSX
I've installed gtkmm3 via homebrew. My project links and builds without errors but never opens a window. xQuartz/X11 fires up upon successful build as well. It just seems to hang during the Gtk::Application::create() call. I've included my code below. Building on Xcode 5.1. Any help is much appreciated.
Thanks
#include <iostream>
#include <gtkmm-3.0/gtkmm.h>
int main(int argc, char * argv[])
{
std::cout << "Creating Application" << std::endl;
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "some.thing.here");
std::cout << "Creating Window" << std::endl;
Gtk::Window window;
std::cout << "Setting window title" << std::endl;
window.set_title("Window One");
std::cout << "Running App" << std::endl;
return app->run(window);
}
A:
Gtk::Application::create() seems to hang because X11 isn't responding to it's request for a window. In it's current (default I assume) state only root can request a window.
Ideal solution (what worked best for me):
Go to Product > Scheme > Edit Scheme in the main menu of XCode. Make sure your current scheme (or whatever your dev scheme is) is selected in the fly out menu. On the modal that opens there are a few radio buttons. Select the 'run as root' option. Now X11 should respond to the request for the window.
Another solution:
Compile program and run with sudo.
An even more complex solution but if you intend to eventually let someone use this program via ssh...
Use xhost to add a user and enable ssh forwarding so you can run the compiled version via ssh without sudo. There are many docs explaining how to do this so I won't put the particulars here.
One other Note
XCode generates a main function with const char argv. Gtk::Application::create() won't take a const char argv. Remove const from main's argv and everything works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert my already created application and database to support multiple sites on single db
I have created a custom CMS for one of my clients some years ago and developed it continuously. It has entities, entityGroups and a lot other tables and use LINQ2SQL to access data. I have 4 or 5 base classes who generate custom controls.
Recently, we came up with a need to create another website who use current website membership and authentication provider with same structure, but with different content.
It makes me think about using a single database to store both sites contents, but separate data by adding a field like ApplicationName to web.config of each site and content tables. Something like current design of default membership and roles providers of ASP.net.
But, I am not sure if it is the best solution. I want to know your advice on designing such system.
I want to minimize changes needed by this. For example, it would be more than nice if there be a way to set ApplicationID when creating database context (I create database contexts in my base class, so change would be in a single location), so there would be no need to change existing queries! Or, is there anyway to grab and fix queries just before they got send to database engine? These are my thoughts, do you have any other suggestion?
The question simply is: What is the best solution to use an existing database and application for multiple sites, with minimum changes and effort?
A:
If the sites are separate, I strongly suggest multiple databases; this will:
reduce risk of exposing the wrong data
allow more granular backups/maintenance
avoid excessively large db
allow you to remove sites cleanly when no longer needed
allow you to balance DBs (sites) between database servers
avoid compromising performance (adding an extra filter to every query ever written is a bad thing)
reduce the number of changes you need to make to the app
Basically, I would just have your central "GetConnection()" method worry about the multi-tenancy, serving the right connection for the site/config/user.
Hint: that's what we do here on stackoverflow/stackexchange
| {
"pile_set_name": "StackExchange"
} |
Q:
grouped and stacked bar plots using plotly
I am new to plotly and not very good with R. I am trying to do stack plots and ended up with a very cumbersome code, that I am sure could be simplify using RColorbrewer and perhaps ggplot2 to group my stacked bar plots, but I am unsure on how to do it.
Below is the data I used, which is in a data.frame called data2
Nation glider radar AUV ROV USV corer towed_eq Seismic_eq Drill_rig Manned_sub Other clean
1 Belgium 0 0 1 1 1 3 0 0 0 0 0 6
2 Bulgaria 0 0 0 0 0 0 1 0 0 1 0 2
3 Croatia 0 2 1 2 0 0 0 0 0 0 0 5
4 Cyprus 3 0 0 0 0 0 0 0 0 0 0 3
5 Estonia 0 0 0 1 0 0 0 0 0 0 0 1
6 Finland 1 0 0 0 0 0 0 0 0 0 0 1
7 France 11 2 3 1 0 1 1 3 0 1 0 23
8 Germany 18 3 3 4 0 0 1 4 2 1 0 36
9 Greece 1 0 0 3 0 0 0 0 0 0 0 4
10 Ireland 0 0 0 2 0 0 0 0 0 0 0 2
11 Italy 10 8 3 2 4 0 0 1 0 0 0 28
12 Malta 0 2 0 0 0 0 0 0 0 0 0 2
13 Netherlands 0 2 0 0 0 0 0 0 0 0 0 2
14 Norway 17 3 1 3 0 1 3 1 0 0 1 30
15 Poland 0 0 0 1 0 0 0 0 0 0 0 1
16 Portugal 0 3 6 6 4 2 1 0 0 2 1 25
17 Romania 0 0 0 1 0 0 0 0 0 0 0 1
18 Slovenia 0 1 0 0 0 0 0 0 0 0 0 1
19 Spain 12 17 2 1 0 0 0 2 0 0 0 34
20 Sweden 0 2 1 3 0 0 0 0 0 0 0 6
21 Turkey 0 0 0 0 0 0 0 0 0 2 0 2
22 United Kingdom 0 0 13 4 1 11 4 2 1 0 4 40
23 Unknown 5 0 0 0 0 0 0 0 0 0 0 5
And this is the code I used
fig <- plot_ly(data2, x = ~Nation, y = ~glider, type = 'bar', name = 'Glider')
fig <- fig %>% add_trace(y = ~radar, name = 'Radar', marker=list(color='rgb(26, 118, 255)'))
fig <- fig %>% add_trace(y = ~AUV, name = 'AUV',marker=list(color='rgb(255, 128, 0)'))
fig <- fig %>% add_trace(y = ~ROV, name = 'ROV',marker=list(color='rgb(204, 0, 0)'))
fig <- fig %>% add_trace(y = ~USV, name = 'USV',marker=list(color='rgb(51, 255, 153)'))
fig <- fig %>% add_trace(y = ~corer, name = 'Corer',marker=list(color='rgb(204, 0, 204)'))
fig <- fig %>% add_trace(y = ~towed_eq, name = 'Towed equipment',marker=list(color='rgb(255, 255, 51)'))
fig <- fig %>% add_trace(y = ~Seismic_eq, name = 'Seismic equipment',marker=list(color='rgb(255, 204, 229)'))
fig <- fig %>% add_trace(y = ~Drill_rig, name = 'Drill rig',marker=list(color='rgb(102, 255, 255)'))
fig <- fig %>% add_trace(y = ~Manned_sub, name = 'Manned submersible',marker=list(color='rgb(128, 255, 0)'))
fig <- fig %>% add_trace(y = ~Other, name = 'Other equipment',marker=list(color='rgb(153, 153, 0)'))
fig <- fig %>% layout(xaxis = list(title = "",tickfont = list(size = 14)), yaxis = list(title = 'Number of assets',tickfont = list(size = 14)), barmode = 'stack')
fig
Is there an easier way to code this by using Rcolorbrewer instead of coding each color? and is it possible to group my stacked barplots Group1 (glider, auv, rov, usv), Group 2 (corer,towed_ew, seismic_eq, drill_rig) and Group 3 (radar, manned_sub, Other)?stack_plot
A:
You can try this approach by melting the data:
library(dplyr)
library(plotly)
library(tidyr)
library(RColorBrewer)
#Data
data <- structure(list(Nation = c("Belgium", "Bulgaria", "Croatia", "Cyprus",
"Estonia", "Finland", "France", "Germany", "Greece", "Ireland",
"Italy", "Malta", "Netherlands", "Norway", "Poland", "Portugal",
"Romania", "Slovenia", "Spain", "Sweden", "Turkey", "United Kingdom",
"Unknown"), glider = c(0, 0, 0, 3, 0, 1, 11, 18, 1, 0, 10, 0,
0, 17, 0, 0, 0, 0, 12, 0, 0, 0, 5), radar = c(0, 0, 2, 0, 0,
0, 2, 3, 0, 0, 8, 2, 2, 3, 0, 3, 0, 1, 17, 2, 0, 0, 0), AUV = c(1,
0, 1, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 1, 0, 6, 0, 0, 2, 1, 0, 13,
0), ROV = c(1, 0, 2, 0, 1, 0, 1, 4, 3, 2, 2, 0, 0, 3, 1, 6, 1,
0, 1, 3, 0, 4, 0), USV = c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 0, 4, 0, 0, 0, 0, 0, 1, 0), corer = c(3, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 11, 0), towed_eq = c(0,
1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 3, 0, 1, 0, 0, 0, 0, 0, 4,
0), Seismic_eq = c(0, 0, 0, 0, 0, 0, 3, 4, 0, 0, 1, 0, 0, 1,
0, 0, 0, 0, 2, 0, 0, 2, 0), Drill_rig = c(0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0), Manned_sub = c(0,
1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0,
0), Other = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 4, 0), clean = c(6, 2, 5, 3, 1, 1, 23, 36, 4,
2, 28, 2, 2, 30, 1, 25, 1, 1, 34, 6, 2, 40, 5)), row.names = c(NA,
-23L), class = "data.frame")
Now the code:
#First reshape
df2 <- pivot_longer(data,cols = -Nation)
#Plot
p <- plot_ly(df2, x = df2$Nation,
y = df2$value,
type = 'bar',
name = df2$name,
text = df2$value,
color = df2$name,
colors = brewer.pal(length(unique(df2$name)),
"Paired"))%>%
layout(barmode = 'stack',hoverlabel = list(bgcolor= 'white') ,bargap = 0.5) %>%
layout(xaxis = list(categoryorder = 'array',
categoryarray = df2$Nation), showlegend = T)
The output:
| {
"pile_set_name": "StackExchange"
} |
Q:
Не удалось загрузить файл или сборку "WebKitBrowser
Подключил длл Webkitbrowser и добавил элемент. Но при запуске выдает эту ошибку.
Не удалось загрузить файл или сборку "WebKitBrowser, Version=0.5.0.0, Culture=neutral, PublicKeyToken=b967213f6d29a3be" либо одну из их зависимостей. Была сделана попытка загрузить программу, имеющую неверный формат.
A:
Скорее всего это из-за того, что WebKitBrowser предназначен для 32 битных приложений. Попробуйте сменить целевую платформу для проекта. Для этого правой кнопкой по проекту -> свойства -> сборка -> и выбрать цель платформы "x86".
Подробнее на странице:
Changing the Application Platform
As there is no x64 build of WebKit yet, WebKit .NET is configured to run only as a 32-bit process so that it functions correctly on 64-bit versions of Windows. As a consequence of this, ALL .NET applications which use WebKit .NET must also be configured in this way. By default, C# applications will run as a 64-bit process on Win64, and we will get an error if we try to use a 32-bit library with them. To change the platform, right click the project in the Solution Explorer and select 'Properties'. Select the 'Build' tab and choose 'x86' as the platform (by default it will be set to 'Any CPU').
| {
"pile_set_name": "StackExchange"
} |
Q:
Html Radio button selection
Following is my code,
$(document).ready(function () {
$("#es").hide();
$("#n").hide();
$('input[type="radio"]').click(function () {
if (this.value === "Yes")
$("#es").show();
else if (this.value === "No")
$("#n").show();
});
});
There are 2 radio buttons for yes and no.After selecting yes if select no only no option should be selected but here both buttons are getting selecte.How can i rectify this?
A:
Just provide both of them the same name. You don't need javascript to do that.
<label><input type="radio" name="group" id="es" value="Yes"/>Yes</label>
<label><input type="radio" name="group" id="n" value="No"/>No</label>
Fiddle
A:
try this :
give same name both of radio button like this
<input type="radio" name="radio" value="Yes">Yes
<input type="radio" name="radio" value="no">No
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.