text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Subsetting a vector base on another vector I have 2 input vectors, iv1 and iv2, as shown below. I would like to separate the elements of the second vector according to elements of the first. It works like this: The values in iv2 between the first 2 values of iv1 are stored in ov1, the values in iv2 between the second and third values of iv1 are stored in ov2, and so on. Note: The values in iv1 and iv2 are already in ascending order. Any thoughts please?
Input:
iv1 <- c(100, 200, 300, 400, 435)
iv2 <- c(60, 120, 140, 160, 180, 230, 250, 255, 265, 270, 295, 340, 355, 401, 422, 424, 430)
Desired output:
ov1 = c(120, 140, 160, 180)
ov2 = c(230, 250, 255, 265, 270, 295)
ov3 = c(340, 355)
ov4 = c(401, 422, 424, 430)
A: As @RonakShah suggested, the most efficient way in this case may be this:
split(iv2, cut(iv2, breaks = iv1,labels = paste0('ov',1:4)))
Output:
$ov1
[1] 120 140 160 180
$ov2
[1] 230 250 255 265 270 295
$ov3
[1] 340 355
$ov4
[1] 401 422 424 430
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46167349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to invalidate Asp.Net Session during IdP initiated Single LogOut with WSO2 we are implementing a Single Sign On process using WSO2 Identity Server. We have both Microsoft and Java web applications involved and we are facing a problem during the Single LogOut processing with Microsoft based web apps. The issue is related to session invalidation on Identity Provider initiated SLO.
This is the scenario:
*
*WSO2 Identity Server with a single Identity Provider configured
*an Asp.Net MVC application using ComponentSpace SAML2 assembly and Forms authentication marking controllers with the [Authorize] attribute to ensure that users are authenticated to access them.
*the DEMO Java Web application provided by WSO2 to test SSO
The login process works fine. We get a session ID from WSO2 and the user is authenticated landing on WSO2 login form in the first app, and transparently in the sencond one.
In the Asp.Net webapp, when a successfull login occurs, we authenticate the user to access [Authorize] marked controllers calling FormsAuthentication.SetAuthCookie(userName, false); . When the user logout from one of the apps, WSO2 sends a SLO request to other partecipants on a configured URI. When this request is reveived by the Microsoft one, we call the FormsAuthentication.SignOut(); method but the session is not destroyed. If the user refresh the browser page its User.Authenticated property is still True so he can still access [Authorize] marked controllers. This makes sense in my opinion because the caller is WSO2 and not the user browser.
We performed some investigation in the code of the JAR provided by WSO2 for Java applications and it creates a filter on Tomcat implementing a singleton to store WSO2 Session ID relation with Session objects each time a success login operation occurs. When WSO2 request a SLO the filter gets WSO2 Session ID as parameter, accesses the singleton HashTable to retrieve the Session object and calls the Session.Invalidate() method of the session object. If the user refreshes the browser, he gets redirected to login page. We tryied to implement something similar on Asp.Net side but even if we get the Session object on server side and call the Session.Abandon() method nothing happens when the user refresh the browser. He is still marked as authenticated.
I am not very familiar with Cookies and I have the feeling that is something related to them.
Had anyone faced a similar issue?
Any advice or suggestion will be very appreciated.
Thanks
A: Calling FormsAuthentication.SignOut should clear the authentication cookie. I suggest capturing the HTTP flow and confirming whether the authentication cookie has been deleted. The default name for the authentication cookie is .ASPXAUTH. Alternatively it will be the name specified in your web.config's section. For example, forms name="mycookie" would rename the cookie to mycookie. You shouldn't have to delete the ASP.NET_SessionId session ID cookie.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32884417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add fail to ant macrodef I created a macro to search for a file in a number of directories. That part is working.
Now I'm trying to add fail to the macro if no file is found but this gives me an error
macrodef doesn't support the nested "fail" element.
Is there a way to achieve this ?
<macrodef name="searchfile">
<attribute name="file" />
<attribute name="path" default="${custom.buildconfig},${wst.basedir}" />
<attribute name="name" />
<attribute name="verbose" default="false" />
<sequential>
<first id="@{name}">
<multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
</first>
<property name="@{name}" value="${toString:@{name}}" />
<echo>property @{name} ${@{name}}</echo>
</sequential>
<fail message="${file}was not found in ${custom.buildconfig},${wst.basedir}">
<condition>
<equals arg1="${@{name}" arg2=""/>
</condition>
</fail>
</macrodef>
A: Credits to martin clayton for his comment, moving fail in the sequential fixes the issue.
<macrodef name="searchfile">
<attribute name="file" />
<attribute name="path" default="${custom.buildconfig},${wst.basedir}" />
<attribute name="name" />
<attribute name="verbose" default="false" />
<sequential>
<first id="@{name}">
<multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
</first>
<property name="@{name}" value="${toString:@{name}}" />
<echo>property @{name}=${toString:@{name}}</echo>
<fail message="@{file} was not found in ${custom.buildconfig},${wst.basedir}, customdir=${customdir}">
<condition>
<equals arg1="${toString:@{name}}" arg2=""/>
</condition>
</fail>
</sequential>
</macrodef>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72096205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: POST to https://www.sandbox.paypal.com/cgi-bin/webscr gives 500 error , Classic asp I am working on classic asp to create donation site and payment gateway is paypal.
I have implemented IPN and paypal is sending notification on that notify_url that i pass with form.
Also payment is also working correctly i.e i can get payment history and IPN history in my sandbox paypal account.
Now the problem is in IPN handler file, when i use sandbox.paypal url to post back to paypal, it give 500 error. Same thing is not true for live paypal url.
Below it the code that will explain better.
Test Form
<form action="zPaypalTest.asp" method="POST">
<input name="mc_gross" type="hidden" value="500.00" />
<input name="custom" type="hidden" value="some custom data" />
<input name="address_status" type="hidden" value="confirmed" />
<input name="item_number1" type="hidden" value="6" />
<input name="item_number2" type="hidden" value="4" />
<input name="payer_id" type="hidden" value="FW5W7ZUC3T4KL" />
<input name="tax" type="hidden" value="0.00" />
<input name="address_street" type="hidden" value="1234 Rock Road" />
<input name="payment_date" type="hidden" value="14:55 15 Jan 07 2005 PST" />
<input name="payment_status" type="hidden" value="Completed" />
<input name="address_zip" type="hidden" value="12345" />
<input name="mc_shipping" type="hidden" value="0.00" />
<input name="mc_handling" type="hidden" value="0.00" />
<input name="first_name" type="hidden" value="Jason" />
<input name="last_name" type="hidden" value="Anderson" />
<input name="mc_fee" type="hidden" value="0.02" />
<input name="address_name" type="hidden" value="Jason Anderson" />
<input name="notify_version" type="hidden" value="1.6" />
<input name="payer_status" type="hidden" value="verified" />
<input name="business" type="hidden" value="[email protected]" />
<input name="address_country" type="hidden" value="United States" />
<input name="num_cart_items" type="hidden" value="2" />
<input name="mc_handling1" type="hidden" value="0.00" />
<input name="mc_handling2" type="hidden" value="0.00" />
<input name="address_city" type="hidden" value="Los Angeles" />
<input name="verify_sign" type="hidden" value="AlUbUcinRR5pIo2KwP4xjo9OxxHMAi6.s6AES.4Z6C65yv1Ob2eNqrHm" />
<input name="mc_shipping1" type="hidden" value="0.00" />
<input name="mc_shipping2" type="hidden" value="0.00" />
<input name="tax1" type="hidden" value="0.00" />
<input name="tax2" type="hidden" value="0.00" />
<input name="txn_id" type="hidden" value="TESTER" />
<input name="payment_type" type="hidden" value="instant" />
<input name="last_name=Borduin" type="hidden" />
<input name="payer_email" type="hidden" value="[email protected]" />
<input name="item_name1" type="hidden" value="Rubber+clog" />
<input name="address_state" type="hidden" value="CA" />
<input name="payment_fee" type="hidden" value="0.02" />
<input name="item_name2" type="hidden" value="Roman sandal" />
<input name="invoice" type="hidden" value="123456" />
<input name="quantity" type="hidden" value="1" />
<input name="quantity1" type="hidden" value="1" />
<input name="receiver_id" type="hidden" value="5HRS8SCK9NSJ2" />
<input name="quantity2" type="hidden" value="1" />
<input name="txn_type" type="hidden" value="web_accept" />
<input name="mc_gross_1" type="hidden" value="0.01" />
<input name="mc_currency" type="hidden" value="USD" />
<input name="mc_gross_2" type="hidden" value="0.01" />
<input name="payment_gross" type="hidden" value="0.02" />
<input name="subscr_id" type="hidden" value="PP-1234" />
<input name="test" type="submit" value="test" />
</form>
MY IPN handler File
zPaypalTest.asp
<%@ language="VBScript" %>
<%
Dim Item_name, Item_number, Payment_status, Payment_amount
Dim Txn_id, Receiver_email, Payer_email
Dim objHttp, str
DIM ApplicationRootPath
ApplicationRootPath = Request.ServerVariables("APPL_PHYSICAL_PATH")
' read post from PayPal system and add 'cmd'
str = Request.Form& "&cmd=_notify-validate"
' post back to PayPal system to validate
set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
'Set objHttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
' set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP.4.0")
'set objHttp = Server.CreateObject("Microsoft.XMLHTTP")
'objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false
objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
'objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
'Send response message back to paypal'
'objHttp.open "POST", "https://ipnpb.paypal.com/cgi-bin/webscr", false
'objHttp.open "POST", "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", false
Response.write "IPN-Sand"
Response.write "<br/>"
objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHttp.Send str
Response.write objHttp.status
if (objHttp.status <> 200 ) then
' HTTP error handling
elseif (objHttp.responseText = "VERIFIED") then
Response.write "VERIFIED"
elseif (objHttp.responseText = "INVALID") then
Response.write "INVALID"
else
Response.write "ERROR"
end if
set objHttp = nothing
%>
Above is the example file.
Here is the code sample that i used. https://github.com/paypal/ipn-code-samples
I test it on localhost IIS and it work fine there too.
So only problem is when i use ,
objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
OR
objHttp.open "POST", "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", false
I get 500 server error and this 500 server is only on my server that runs both in http or https, but in localhost IIS it works.
Also
If i change that url to live url
objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false
OR
objHttp.open "POST", "https://ipnpb.paypal.com/cgi-bin/webscr", false
It works.
If i just browse that page in my browser in my server i.e https://myserver.com/zPaypalTest.asp, it gives error when using sandbox url only.
I am not able to think what is the error here. Why it gives 500 error.
I will be very thankful if any one could give me any clue what's wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40311176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unary operators, binary expression tree and shunting yard algorithm I am writing the mathematics expression solver which takes infix expression and solves them, both binary expression tree and shunting-yard are doing good for me (I have even solved the problem of handling unary and ternary operators). Encountered an issue with trigonometric functions. When I write 45sin or (45)sin or (44+1)sin, shunting-yard converts it to valid Reverse Polish Notation(RPN) and evaluation is successful. Though the valid infix expression is sin(44+1) or sin45 + 1. Please suggest to solve this pr1oblem.
Here is the java code from class ExpressionEval which converts infix to RPN.
public String infixToPostFix2(String[] expression)
{
String val = "";
if (expression == null || expression.length <= 0)
return "";
Stack<String> stack = new Stack<String>();
ArrayList<String> exp = new ArrayList<String>();
for (String token : expression)
{
if (OperatorList.isOperator(token))
{
Operator o1 = OperatorList.getOperator(token);
Operator o2 = null;
while (!stack.empty() && OperatorList.isOperator(stack.peek()))
{
o2 = OperatorList.getOperator(stack.peek());
if ( (o1.getAssociativity() == Associativity.LEFT && o1.lessThanEqual(o2))
|| (o1.getAssociativity() == Associativity.RIGHT && o1.lessThan(o2))
)
{
exp.add(stack.pop());
continue;
}
break;
}
stack.push(token);
}
else if(OperatorList.isLeftParenthesis(token))
{
stack.push(token);
}
else if (OperatorList.isRightParentheis(token))
{
while(!OperatorList.isLeftParenthesis(stack.peek()))
{
if (stack.empty())
{
this.error = Error.MISMATCHED_PARANTHESIS;
return ""; //Mismatched paranthesis
}
exp.add(stack.pop());
}
stack.pop();//Pop off the left paranthesis but not move to output
}
else //Operands
{
exp.add(token);
}
}
while(!stack.empty())
{
String s = stack.pop();
if (OperatorList.isParanthesis(s))
{
this.error = Error.MISMATCHED_PARANTHESIS;
return "";
}
exp.add(s);
}
postfixExpression = new String[exp.size()];
int index = 0;
for (String elem : exp)
{
postfixExpression[index++] = elem;
}
CalcDebug.printArray(postfixExpression);
return val;
}
Once we have post-fix expression the evaluation is done in this function of ExpressionEval class
public double evaluateExpression(String[] postfixExpression) {
CalcDebug.Debug("evaluateExpression()");
double val = 0.0;
if (postfixExpression == null || postfixExpression.length <= 0)
return val;
Stack<String> operationStack = new Stack<String>();
CalcDebug.printArray(postfixExpression);
for (String elem : postfixExpression) {
CalcDebug.Debug("elem = " + elem);
if (!OperatorList.isOperator(elem)) {
operationStack.push(elem);
} else {
double arg0 = 0.0;
double arg1 = 0.0;
double arg2 = 0.0;
OperatorType t = OperatorList.getOperatorType(elem);
if (t == OperatorType.BINARY) {
arg1 = Double.parseDouble(operationStack.pop());
arg0 = Double.parseDouble(operationStack.pop());
val = CalculatorBrain.performCalculation(elem, arg0, arg1);
} else if (t == OperatorType.UNARY) {
arg0 = Double.parseDouble(operationStack.pop());
val = CalculatorBrain.performCalculation(elem, arg0);
} else if (t == OperatorType.TERNARY) {
arg2 = Double.parseDouble(operationStack.pop());
arg1 = Double.parseDouble(operationStack.pop());
arg0 = Double.parseDouble(operationStack.pop());
val = CalculatorBrain.performCalculation(elem, arg0, arg1,
arg2);
}
operationStack.push(Double.toString(val));
}
CalcDebug.printStack(operationStack);
}
val = Double.parseDouble(operationStack.pop());
CalcDebug.Debug("val = " + val);
return val;
}
Operator class is somewhat similar to this.
package com.studentscalculator;
import com.studentscalculator.OperatorComparator.OPERATOR_PRIORITY;
public class Operator
{
public enum OperatorType
{
UNARY, BINARY, TERNARY
}
public enum Associativity
{
LEFT, RIGHT
}
private String operator;
public String getOperator(){return operator;}
public void setOperator(String operator){this.operator = operator;}
private int order;
public int getOrder(){return order;}
public void setOrder(int order){this.order = order;}
private OperatorType type;
public OperatorType getType(){ return type; }
public void setType(OperatorType type){ this.type = type; }
private Associativity associativity;
public Associativity getAssociativity(){ return associativity;}
public void setAssociativity(Associativity associativity){ this.associativity = associativity; }
//Constructors
public Operator(String operator)
{
this.setOperator(operator);
this.setOrder(OperatorList.getOperatorOrder(operator));
this.setType(OperatorList.getOperatorType(operator));
this.setAssociativity(OperatorList.getOperatorAssociativity(operator));
}
public Operator(String operator, int order)
{
this.setOperator(operator);
this.setOrder(order);
this.setType(OperatorList.getOperatorType(operator));
}
public Operator(String operator, int order, OperatorType t)
{
init(operator, order, t, Associativity.LEFT);
}
public Operator(String operator, int order, OperatorType t, Associativity a)
{
init(operator, order, t, a);
}
void init(String operator, int order, OperatorType t, Associativity a)
{
this.setOperator(operator);
this.setOrder(order);
this.setType(t);
this.setAssociativity(a);
}
public boolean lessThanEqual(Operator arg0)
{
int val = -(this.order - arg0.order);
if (val <= 0)
return true;
else
return false;
}
public boolean lessThan(Operator arg0)
{
int val = -(this.order - arg0.order);
if (val < 0)
return true;
else
return false;
}
@Override
public String toString()
{
String val = String.format("Operator = %s : Order %s", getOperator(), getOrder());
return val;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35055669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AnimationDrawable Thread skipping frames I am in an Activity which must play an AnimationDrawable (a 'loading' animation) while the rest of the content loads.
I started the animation in another thread since animations tend to give a lot of work to the main thread, however the animation can't be displayed correctly, and the Logcat shows several times to have skipped 40 frames or so.
I'll post the code tomorrow, sorry for the delay.
Meanwhile what can be causing this? all the thread has inside is the start method for the animation drawable.
A: You should not run animation off of the UI thread ("main" thread) - you should load your content in another thread by using a Loader (or something similar) and play the animation on the UI thread. That's what it's for.
Here are official thread guidelines:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
More here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26789955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Has the generic version of HttpResponseMessage been removed from the ASP.NET WebApi? I just finished installing VS 2012 RC and have started working with the ASP.NET Web API. I am basing my work on some tutorials from PluralSight which I've been using as reference.
In every tutorial and article which I've used, I notice that they are using a generic version of HttpResponseMessage in the return type of Action, but to my surprise this object was not available to me while coding. I thought perhaps the issue was just an incorrect namespace reference, but that does not seem to be the case.
Can anyone point me toward some source code or reference material on how to utilize the generic HttpResponseMessage object that PluralSight uses in their videos?
A: yes i was also looking through the same thing.. the generic version of the HttpResponseMessage was remove recently.. because it was not type safe
A: Searching for the answer i found this article
and it states that the generic version has been removed
so now just mention the return type to be of type HttpresponseMessage and when actually returning the response use Request.CreateResponse<T>(params);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11427973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Inconsistent ParseExeption with Data Format in Java I wrote a simple Util method to convert a String in Java to util.Date. What I am not able to figure out is why the method works for the first input, and fails for the second one, given that the inputs are identical:
Code:
package util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate {
public Date getDateFromString(String strDate, String dateFormat) {
DateFormat df = new SimpleDateFormat(dateFormat);
Date date = null;
try {
date = df.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
return date;
}
public static void main(String[] args) {
StringToDate s2d = new StringToDate();
s2d.getDateFromString("12-18-11, 10:36 AM","MM-dd-yy, hh:mm a");
s2d.getDateFromString("02-04-12, 01:17 PM","MM-dd-yy, hh:mm a");
}
}
Output:
Sun Dec 18 10:36:00 CET 2011
null
java.text.ParseException: Unparseable date: "02-04-12, 01:17 PM"
at java.text.DateFormat.parse(DateFormat.java:337)
at util.StringToDate.getDateFromString(StringToDate.java:17)
at util.StringToDate.main(StringToDate.java:33)
Logically, the output should've been Sat Feb 04 13:17:00 CET 2012 going by the first output. Why is the ParseException being thrown?
EDIT: The following two lines work correctly:
s2d.getDateFromString("02-04-12", "MM-dd-yy");
s2d.getDateFromString("01:17 PM", "hh:mm a");
Output:
Sat Feb 04 00:00:00 CET 2012
Thu Jan 01 13:17:00 CET 1970
But the exception happens when I try to parse both date and time together.
A: Do you have a non-breaking space, or some other Unicode space character, somewhere in either your date string or format mask?
I was able to reproduce your error if I replaced one of the spaces in the second of your date strings with a non-breaking space, such as Unicode character 160.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9965238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to import moment.js angular2 I'm trying to import moment.js into my angular2 application.
First of all I have followed this guide, and I've found this answer but even if I've tried to follow the proposed solutions I'm still unable to import moment.js.
The package is present, and in fact my IDE (visual studio) is able to find the moment.d.ts file without any problem, but when I run my application with npm start, I get this two errors in the console:
"NetworkError: 404 Not Found - http://localhost:3000/node_modules/moment/"
/node_m...moment/
Error: patchProperty/desc.set/wrapFn@http://localhost:3000/node_modules/zone.js/dist/zone.js:769:27
Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:356:24
Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:256:29
ZoneTask/this.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:423:29
Error loading http://localhost:3000/node_modules/moment as "moment" from 'my file'
I've tried to import moment in this way
import * as moment from 'moment'
and in this way to
import * as moment from 'moment/moment.d'
but nothing, I'm still get the error. My SystemJs'map property is this one
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'services': 'app/service',
'moment': 'node_modules/moment',//moment.js
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs'
};
If I try to install with typings i get this error:
Typings for "moment" already exist in "node_modules/moment/moment.d.ts". You should let TypeScript resolve the packaged typings and uninstall the copy installed by Typings
so I had uninstalled it, and retype the commands, well I get this error
typings ERR! message Unable to find "moment" ("npm") in the registry.
so is ther a way to get out from this dilemma?
A: Firstly, install the moment package via npm:
npm install moment --save
Secondly change your systemjs config (2 lines):
(function (global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs',
'moment': 'node_modules/moment', <== add this line
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
'moment': { main: 'moment.js', defaultExtension: 'js' } <== add this line
};
Then you can use it:
import * as moment from 'moment';
Typings will be available from node_modules/moment/moment.d.ts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38354048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get dictionary values as List I know this is asked earlier, but I tried but could not help.
I have below dictionary, want to convert to List, What is the best way to convert to List
dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
dList = list(dct.values())
Result:
[['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']]
I need splitted List:
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']
Later, I want to compare list of items in "dList" with another List.
A: If you know that the list is the value associated to the 'result' key, simply call dct['result'].
>>> dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct
{'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct['result']
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']
Converting the values to a list is unneeded, inefficient and might return the wrong value if your dict has more than 1 (key, value) pair.
A: Your dictionary have only one value and that itself is a list of elements. So just call the result key and you will get the list value.
If you want the list from your code add the index [0] like,
dList = list(dct.values())[0]
Hope this helps! Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52552185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to loop between two dates I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.
Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date?
Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.
Help appreciated greatly,
kind regards.
public void DTCalculations()
{
List<string> calculatedDates = new List<string>();
string startDate = "2009-07-27";
string endDate = "2009-07-29";
//Convert to DateTime variables
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);
//Calculate difference between start and end date.
TimeSpan difference = end.Subtract(start);
//Generate list of dates beginning at start date and ending at end date.
//ToDo:
}
A: static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end)
{
for(var day = start.Date; day <= end; day = day.AddDays(1))
yield return day;
}
Edit: Added code to solve your particular example and to demonstrate usage:
var calculatedDates =
new List<string>
(
AllDatesBetween
(
DateTime.Parse("2009-07-27"),
DateTime.Parse("2009-07-29")
).Select(d => d.ToString("yyyy-MM-dd"))
);
A: The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this:
DateTime calcDate = start.Date;
while (calcDate <= end)
{
calcDate = calcDate.AddDays(1);
calculatedDates.Add(calcDate.ToString());
}
Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not.
[Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely]
A: for( DateTime i = start; i <= end; i = i.AddDays( 1 ) )
{
Console.WriteLine(i.ToShortDateString());
}
A: You just need to iterate from start to end, you can do this in a for loop
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);
for(DateTime counter = start; counter <= end; counter = counter.AddDays(1))
{
calculatedDates.Add(counter);
}
A: An alternative method
public static class MyExtensions
{
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
// Remove time info from start date (we only care about day).
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
}
Now in the calling code you can do the following:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1199108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Jest encountered an unexpected token when working with React TypeScript I am building a reusable react component without using react-app and I am very new to Jest. I keep on getting this message. I have tried several post solutions on Stackoverflow but I am stuck at the moment:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
C:\Users\User\Documents\accessible-date-picker\src\__tests__\DatePicker.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { DatePicker } from '../containers/DatePicker';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
I have the following configuration but I cannot figure out why I cannot resolve the problem:
//jest.config.js
module.exports = {
roots: ["<rootDir>/src"],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
coveragePathIgnorePatterns: [
"/node_modules/"
],
moduleNameMapper: {
"\\.(css|less)$": "identity-obj-proxy",
}
};
Here is my tsconfigurations:
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
Here are my dev dependencies:
"devDependencies": {
"@babel/core": "^7.12.7",
"@babel/plugin-transform-runtime": "^7.12.1",
"@babel/preset-env": "^7.12.7",
"@babel/preset-react": "^7.12.7",
"@babel/preset-typescript": "^7.12.7",
"@babel/runtime": "^7.12.5",
"@teamsupercell/typings-for-css-modules-loader": "^2.4.0",
"@types/fork-ts-checker-webpack-plugin": "^0.4.5",
"@types/jest": "^26.0.15",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/webpack": "^4.41.25",
"@types/webpack-dev-server": "^3.11.1",
"@typescript-eslint/eslint-plugin": "^4.8.1",
"@typescript-eslint/parser": "^4.8.1",
"babel-loader": "^8.2.1",
"css-loader": "^5.0.1",
"eslint": "^7.14.0",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"fork-ts-checker-webpack-plugin": "^6.0.3",
"jest": "^26.6.3",
"style-loader": "^2.0.0",
"ts-jest": "^26.4.4",
"ts-node": "^9.0.0",
"typescript": "^4.1.2",
"webpack": "^5.6.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
}
}
Any help will be much appreaciated!
A: Looks like your test file is a js file (src\__tests__\DatePicker.spec.js) instead of ts?x file which means this pattern will never meet "^.+\\.(ts|tsx)$": "ts-jest".
However, you might know tsc can also have capability to transpile your js code as well as long as you set allowJs: true as you already did. So I think your problem would be fixed as you refine your pattern to to transform above including jsx file:
{
transform: {
"^.+\\.(t|j)sx?$": "ts-jest",
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65717630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to reload a entire component with angular when route changes? I want to reload or rerender a sidebar component when route change i have the following code:
constructor(
private auth: AuthService,
private router: Router,
private changeDetector: ChangeDetectorRef
) {
this.auth.currentUser.subscribe(x => this.userData = x);
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.changeDetector.detectChanges();
console.log('enter');
}
});
}
This enter to show the log 'enter' but not reload the component. Anybody can help with an example?
A: Usually component routing doesn't reload because angular works as SPA(single page application) - but you can make your components to load in order to reduce the browser size if that is the only case
Use href and your path name insted of routerLink on your sidebar anchor link - this will make your component to reload everytime when you click - everytime it will load all your js from server - if you are using lazy load this process is not the right way - this will only helps you to reduce the browser RAM usage on every click and doesn't maintain any previous data but routing will work as the same
So href will be the word for your question - but make sure that you really want to load your components
Hope it helps - Happy Coding:)
A: If you want to reload the entire page, just use
window.location.reload();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54174594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: adding items to deep List of KeyValuePairs I wrote a deep list:
public static List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>> ListBoxes = new List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>>();
Anybody has an idea how to add to this list any items?
For example:
("A",LIST("B",LIST("C",true)))
A: Easy:
ListBoxes.Add(
new KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>("A",
new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>
{
new KeyValuePair<string,List<KeyValuePair<string,bool>>>("B",
new List<KeyValuePair<string,bool>>() {
new KeyValuePair<string,bool>("C", true)
}
)
}
)
);
It looks like you could use some helper methods or something.
Edit
If you create a simple extension method, then the task becomes maybe a bit more readable.
public static List<KeyValuePair<TKey, TValue>> AddKVP<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> self, TKey key, TValue value)
{
self.Add(
new KeyValuePair<TKey, TValue>(key, value)
);
// return self for "fluent" like syntax
return self;
}
var c = new List<KeyValuePair<string, bool>>().AddKVP("c", true);
var b = new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>().AddKVP("b", c);
var a = new List<KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>>().AddKVP("a", b);
Edit #2
If you define a simple type, then it helps a bit more:
public class KVPList<T> : List<KeyValuePair<string, T>> { }
public static KVPList<TValue> AddKVP<TValue>(this KVPList<TValue> self, string key, TValue value)
{
self.Add(new KeyValuePair<string, TValue>(key, value));
return self;
}
var ListBoxes = new KVPList<KVPList<KVPList<bool>>>()
.AddKVP("A", new KVPList<KVPList<bool>>()
.AddKVP("B", new KVPList<bool>()
.AddKVP("C", true)));
Edit #3
One more and I promise I'll stop. If you define "Add" on the type, then you can use implicit initialization:
public class KVPList<T> : List<KeyValuePair<string, T>>
{
public void Add(string key, T value)
{
base.Add(new KeyValuePair<string,T>(key, value));
}
}
var abc = new KVPList<KVPList<KVPList<bool>>> {
{ "A", new KVPList<KVPList<bool>> {
{ "B", new KVPList<bool> {
{ "C", true }}
}}
}};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13634094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Python - How to get all possible combinations from nested list I have a nested list like this :
values = [['DNO', 0.2], ['Equinor', 0.4], ['Petoro', 0.2], ['Total', 0.2]]
How to get all possible combinations of elements that will have a sum(2nd element of each sub list) greater than 0.5?
This is what I am using :
def getCombinations(values, min_len):
combo = "\n"
numbers = []
doc = {}
for val in values:
doc[val[0]] = val[1]
numbers.append(val[1])
result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) >= 0.5]
temp = doc.copy()
for r in result:
doc = temp.copy()
if len(r) >= min_len:
for rr in r:
combo = combo + get_key(doc, rr) + " "
doc.pop(get_key(doc, rr))
combo = combo + "\n"
return combo
My algorithm have some problem when there are multiple values like 0.2 in above list.
Currently it is returning this with min_length=3:
Total Equinor Petoro DNO
Total Equinor Petoro
Total Equinor Petoro
Total Petoro DNO
Equinor Total Petoro
A: The following should work:
import itertools
result=[]
for k in range(2,len(values)+1):
temp=[tuple(x[0] for x in i) for i in list(itertools.combinations(values,k))if sum([p[1] for p in i]) >0.5]
result.append(temp)
result=sum(result, [])
print(result)
Output:
[('DNO', 'Equinor'), ('Equinor', 'Petoro'), ('Equinor', 'Total'), ('DNO', 'Equinor', 'Petoro'), ('DNO', 'Equinor', 'Total'), ('DNO', 'Petoro', 'Total'), ('Equinor', 'Petoro', 'Total'), ('DNO', 'Equinor', 'Petoro', 'Total')]
A: You can use a list comprehension like this:
Explanation:
*
*The first for defines the length of the combinations. Every length from 2 to the length of values is used.
*The second for creates the actual combinations
*The if uses a generator method to sum the numbers of the items
from itertools import combinations
combis = [
item
for length in range(2, len(values)+1)
for item in combinations(values, length)
if sum(i[1] for i in item) >= 0.5
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64098059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Does extraction workers in google bigquery save the data into Columnar Storage follows a FIFO pattern? As I understand from bigquery streaming insert lifecycle also shown in the image below. The data goes through streaming buffer before it is available in the Columnar Storage. The work of processing the data is done by the Extraction Workers.
However, in the documentation, it is not mentioned how the extraction workers process the data. Do they follow a random order for processing or it is FIFO processing?
A: The streaming buffer is a queue, and the extraction worker processes rows in order. The extraction workers take from the queue either when it reaches a certain volume of data or when a certain amount of time has elapsed in order to write sufficiently large chunks of data to managed storage. The underlying storage format in BigQuery is Capacitor, which reorders rows as it is persisting them to disk and performs a variety of other optimizations as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51613136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use case for Lock.tryLock() At API docs of Lockinterface for method tryLock(), this code sample is pasted,
A typical usage idiom for this method would be:
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
My question is , does this use case not existed before Java 5 or folks used to implement it via some other techniques?
I am not able to comprehend the need to execute perform alternative actions based on lock availability.
Can somebody please explain real use cases for this?
I am sure this technique is not a straight forward replacement of synchronizedto write deadlock free code.
A: One straight-forward use case is a thread processing a batch of elements, occasionally trying to commit the elements that have been processed. If acquiring the lock fails, the elements will be committed in the next successful attempt or at the final, mandatory commit.
Another example can be found within the JRE itself, ForkJoinTask.helpExpungeStaleExceptions() is a method for performing a task that can be done by an arbitrary thread, but only one at a time, so only the one thread successfully acquiring the lock will perform it, all others will return, as the unavailability of the lock implies that there is already a thread performing the task.
It is possible to implement a similar feature before Java 5, if you separate the intrinsic locking feature, which doesn’t support being optional, from the locking logic, that can be represented as an ordinary object state. This answer provides an example.
A:
My question is, does this use case not existed before Java 5 or folks used to implement it via some other techniques?
The Lock interface was added in Java 5, is that what you mean? Not sure what was there before.
I am not able to comprehend the need to execute perform alternative actions based on lock availability. Can somebody please explain real use cases for this?
Sure. Just wrote one of these today actually. My specific Lock implementation is a distributed lock that is shared among a cluster of servers using the Jgroups protocol stack. The lock.tryLock(...) method makes RPC calls to the cluster and waits for responses. It is very possible that multiple nodes maybe trying to lock and their actions might clash causing delays and certainly one lock to fail. This either could return false or timeout in which case my code just waits and tries again. My code is literally:
if (!clusterLock.tryLock(TRY_LOCK_TIME_MILLIS, TimeUnit.MILLISECONDS)) {
logger.warn("Could not lock cluster lock {}", beanName);
return;
}
Another use case might be a situation where one part of the code holds a lock for a large amount of time and other parts of the code might not want to wait that long and instead want to get other work done.
Here's another place in my code where I'm using tryLock(...)
// need to wait for the lock but log
boolean locked = false;
for (int i = 0; i < TRY_LOCK_MAX_TIMES; i++) {
if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
logger.debug("Lock worked");
locked = true;
break;
} else {
logger.debug("Lock didn't work");
}
}
A: The reason for writing code like that example is if you have a thread that is doing more than one job.
Imagine you put it in a loop:
while (true) {
if (taskA_needsAttention() && taskA_lock.tryLock()) {
try {
...do some work on task A...
} finally {
taskA_lock.unlock();
}
} else if (taskB_needsAttention() && taskB_lock.tryLock()) {
try {
...do some work on task B...
} finally {
taskB_lock.unlock();
}
} else ...
}
Personally, I would prefer not to write code like that. I would prefer to have different threads responsible for task A and task B or better still, to use objects submitted to a thread pool.
A: Use case 1
One use case would be to completely avoid running the thread. Like in the example below, for example a very strict internet hotspot where you can only access one webpage at once, and other requests are cancelled.
With synchronized you cannot cancel it, since it waits until it can obtain the lock. So tryLock just gives you flexibility to cancel something or to run other behavior instead.
package Concurrency;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LimitedHotspotDemo
{
private static Lock webAccessLock = new ReentrantLock();
private static class AccessUrl implements Runnable
{
private String url;
public AccessUrl(String url)
{
this.url = url;
}
@Override
public void run()
{
if(webAccessLock.tryLock()) {
System.out.println("Begin request for url " + url);
try {
Thread.sleep(1500);
System.out.println("Request completed for " + url);
} catch (InterruptedException e) {
webAccessLock.unlock();
return;
} finally {
webAccessLock.unlock();
}
} else {
System.out.println("Cancelled request " + url + "; already one request running");
}
}
}
public static void main(String[] args)
{
for(String url : Arrays.asList(
"https://www.google.com/",
"https://www.microsoft.com/",
"https://www.apple.com/"
)) {
new Thread(new AccessUrl(url)).start();
}
}
}
Output:
Begin request for url https://www.microsoft.com/
Cancelled request https://www.google.com/; already one request running
Cancelled request https://www.apple.com/; already one request running
Request completed for https://www.microsoft.com/
Use case 2
Another use case would be a light sensor which keeps the light on when there is movement in the room (with Sensor thread). There is another thread (TurnOffLights) running to switch the light off when there is no more movement in the room for a few seconds.
The TurnOffLights thread uses tryLock to obtain a lock. If no lock can be obtained, the process is delayed for 500ms. The last Sensor thread is blocking the lock for 5 seconds, after which the TurnOffLights thread can obtain the lock and turn off the lights.
So in this case the TurnOffLights thread is only allowed to turn off the lights when there are no more signals to the Sensor for 5 seconds. The TurnOffLights thread is using tryLock to obtain the lock.
package Concurrency;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LightSensorDemo
{
private static volatile Lock lock = new ReentrantLock();
private static volatile Thread lastSignal = null;
private static Sensor sensor = new Sensor();
private static class Sensor implements Runnable
{
private static Boolean preparing = false;
public static Boolean isPreparing()
{
return preparing;
}
@Override
public void run()
{
System.out.println("Signal send " + Thread.currentThread().getName());
try {
invalidatePreviousSignalsAndSetUpCurrent();
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
//System.out.println("Signal interrupted " + Thread.currentThread().getName());
return;
} finally {
lock.unlock();
}
}
private static synchronized void invalidatePreviousSignalsAndSetUpCurrent() throws InterruptedException
{
preparing = true;
if(lastSignal != null) {
lastSignal.interrupt();
}
lastSignal = Thread.currentThread();
lock.lockInterruptibly();
preparing = false;
}
}
private static class TurnOffLights implements Runnable
{
@Override
public void run()
{
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Interrupted" + this.getClass().getName());
return;
}
if (!Sensor.isPreparing()) {
if(lock.tryLock()) {
try {
System.out.println("Turn off lights");
break;
} finally {
lock.unlock();
}
} else {
System.out.println("Cannot turn off lights yet");
}
} else {
System.out.println("Cannot turn off lights yet");
}
}
}
}
public static void main(String[] args) throws InterruptedException
{
Thread turnOffLights = new Thread(new TurnOffLights());
turnOffLights.start();
//Send 40 signals to the light sensor to keep the light on
for(int x = 0; x < 10; x++) {
new Thread(sensor).start(); //some active movements
new Thread(sensor).start(); //some active movements
new Thread(sensor).start(); //some active movements
new Thread(sensor).start(); //some active movements
Thread.sleep(250);
}
turnOffLights.join();
}
}
Notice also that I use lock.lockInterruptibly(); to interrupt previous signals. So the 5 second countdown always starts from the last signal.
Output is something like:
...
Cannot turn off lights yet
Cannot turn off lights yet
Signal send Thread-19
Signal send Thread-20
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Turn off lights
Process finished with exit code 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41788074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Javascript giving me Uncaught ReferenceError: require is not defined error I have a file structure that looks like this:
My index.js has this code
const THREE = require("three")
var scene = new THREE.scene();
console.log(scene)
My index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="webgl-output">What the hell</div>
<script src="./index.js"></script>
</body>
</html>
I did not use the tag { type : "modules } in my package.json. However, I am still getting the Uncaught ReferenceError: require is not defined error. May I know what is the reason? Thanks!
Error in my live server looks like this
This is my package.json if you are interested
{
"name": "threejs-playground",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"three": "^0.133.1"
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69549742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: problem in making records of a file by perl I'm trying putting a file into records with number starting from record 0 to n and saving it into an output file. my file is starting from AA to // and there are several AA's and // so I'm putting record number for each AA to // as there are 2000 to 3000 AA's so I want to put them in records with number. Could someone please help me.
//
AA r00001
FA tea
OS fskjkterjykjlt
//
AA T00002
FA ACE2
OS coffee
SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
AA T00003
FA Diet coke
OS ewtji34ut893u569
SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
AA T00004
FA coke
OS jgerjgkhjetkh
SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA
//
#!/usr/bin/env perl
use strict;
use warnings;
my $ifh;
my $ofh;
my $line;
my $recnum = 0;
my $ifn = "factor data 1.txt";
my $ofn = "try.txt";
open ($ifh, "<$ifn") || die "can't open $ifn";
open ($ofh, ">$ofn") or die "can't open $ofn";
my $a = "\/\/ ";
while ($line = <$ifh>)
{
chomp $line ;
if ($line =~ m/$a\$/)
{
print "$ofh $line\n";
$recnum++;
}
else
{
print "$ofh $recnum $line\n";
}
}
close ($ifh);
close ($ofh);
A: These types of record I/O problems are simplified if you use the Perl idiom of changing the record separator. Now each record becomes a line and lines are easy to count.
NOTE: I also removed the last // so we don't count the empty record.
Ok... I'm guessing that you may want something like this
#! /usr/bin/env perl
use strict;
use warnings;
my $cntr = 0;
print "Starting\n";
# change record seperator
$/ = '//';
while ((<DATA>))
{
print"============== Record number $cntr ======================\n";
print "$_\n";
print "========================================================\n";
$cntr++;
}
exit 0;
__DATA__
/
AA r00001
FA tea
OS fskjkterjykjlt
//
AA T00002
FA ACE2
OS coffee
SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
AA T00003
FA Diet coke
OS ewtji34ut893u569
SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
AA T00004
FA coke
OS jgerjgkhjetkh
SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA
//
With output like this
Starting
============== Record number 0 ======================
/
AA r00001
FA tea
OS fskjkterjykjlt
//
========================================================
============== Record number 1 ======================
AA T00002
FA ACE2
OS coffee
SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
========================================================
============== Record number 2 ======================
AA T00003
FA Diet coke
OS ewtji34ut893u569
SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
========================================================
============== Record number 3 ======================
AA T00004
FA coke
OS jgerjgkhjetkh
SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6681891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CLLocationManager does not work for non-wireless connection? I have a Mac app and would like to use core location, however, when I am not on wifi but connected using an ethernet cable, core location (CLLocationManager) reports that the operation could not be completed.
The exact error message is
The operation couldn't be completed. (kCLErrorDomain error 0.)
If I am always connected to the same router (ie. either wifi or ethernet cable) why does CLLocationManager only work for wifi and not for the ethernet connection?
Any suggestions would greatly be appreciated.
Thanks.
Edit:
Here is some code.
I define my location manager as an instance variable like so
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:ICMinimumUpdateDistance];
I then monitor the location manager's delegate method like so,
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// Filter out points before the last update
NSTimeInterval timeSinceLastUpdate = [newLocation.timestamp timeIntervalSinceDate:dateOfLastUpdate];
if (timeSinceLastUpdate > 0)
{
//Do stuff
}
}
I also check for errors using the delegate method
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"Location Error:%@", [error localizedDescription]);
}
In the code above, the location manager updates with an invalid newLocation (bad time stamp) and then the location manager calls the delegate error method.
A: For lack of a GPS in your laptop, core-location on OSX uses the (skyhook) service, or something similar.
The service maintains a database of WIFI access-points and their positions (possibly updated by iPhones that do have GPS and wifi enabled) which is queried.
So by feeding a list of access points you can see, and their relative signal strengths the system is able to triangulate roughly where you are.
So you need both wifi enabled, and a working internet link (but internet shouldn't need to be over wifi, you can leave the airport un-associated)
A: I've noticed this too. If you open the Time Zone tab of the Date & Time pane in System Preferences while connected to the internet via ethernet, it says to connect to a wireless network to determine your current location. This leads me to believe that CoreLocation does, in fact, require a wireless connection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5492439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MetaMask RPC error? 'MetaMask - RPC Error: Internal JSON-RPC error.' I'm developing the front-end to an application that I'm trying to test. However, MetaMask keeps giving me this error? I tried changing the gas limit like previously suggested and nothing. Any ideas?
Error:
MetaMask - RPC Error: Internal JSON-RPC error.
code: -32603
data: {code: -32000, message: "gas required exceeds allowance (30000000) or always failing transaction"}
message: "Internal JSON-RPC error."
A: Without seeing the code, it's hard to say for sure but you could try:
*
*Check any code you changed in the front end, specifically in your code you may have something like this:
const contractInstance = new state.web3.eth.Contract(
MyContract.abi,
"0x.....", // contract address
{
from: state.accounts[0],
gasPrice: 1000,
gas: 100000
}
);
Make sure the gas prices are similar to those, you may have to adjust for your case.
*Re-compile and redeploy --> for truffle, run truffle develop first, then compile then migrate --reset for local deployment.
*In Metamask, reset your test account. Metamask > Select Account > Settings > Advanced > Reset account. Only do this for testing accounts
A: Previously it used to happen in older versions due to a gas specification issue which was fixed. rpcErrors.internal` expects a string as the first argument, with arbitrary data being the optional second argument. Passing in a non-
string first argument results in the error being shadowed by an error
from eth-json-rpc-errors.
Please check what you are passing to Metamask.
A: In my case, after trying so many options I have restarted Ganache and re-imported new account from Ganache to Metamask.
I connected this new account with localhost application.
This resoles my issue.
A: Before performing any transaction the sending ETH address must be connected to your own site or UI. So it can get the address of sending account and goes towards the further transaction in the metamask.
Make sure Your sending account address must be connected to your UI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66924776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible for a translucent to have to affect on the items below it? I have kind of a weird situation, while trying to make a simple chrome plugin. The idea of the plugin is that it constantly overlays a half-transparent image on top of the page you are viewing. To accomplish this, I have the plugin inject JavaScript, which appends an tag with the following CSS rules:
img.class#id {
position: absolute;
left: 0;
top: 0;
height: 100%
width: 100%;
opacity: 0.5;
z-index: 9999999;
}
This already works, but it introduces a new problem. Since the z-index of the image is intentionally large, it overrides the left and right click actions of the user, on the elements with a lower z-index. I can't change the z-index to be smaller, since that would defeat the purpose of the plugin, and I can't change the transparency of the other things on the page, since there's too much variability. Is there a way to ensure that the page is still usable, even with the image overlayed on it?
A: set pointer-events: none in css
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
The pointer-events CSS property specifies under what circumstances (if
any) a particular graphic element can become the target of mouse
events.
*
*Note that while only mouse events are stated, it is in fact valid for all kinds of pointer events - mouse, touch.
From the possible values:
none The element is never the target of mouse events; however, mouse
events may target its descendant elements if those descendants have
pointer-events set to some other value. In these circumstances, mouse
events will trigger event listeners on this parent element as
appropriate on their way to/from the descendant during the event
capture/bubble phases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46938946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should I be using static or instance methods? I'm really confused with the concept of static vs instance methods. I have created a BMR calculator. I've seperated the GUI from the calculations using different classes.
public class Calculations {
/**
* If user input is correct, this method will calculate the BMR value of the user given their input and measurement choices.
*
* @param userAge, userHeight, userWeight
* @return BMR Value as a string
*/
public static int calcBMR(int age, String gender, double height, double weight) {
// This is the body of the calculations - different formulas used depending on gender. Conversions to kg and cm done earlier so no conversions needed here.
if (gender.equals("M")) { // Uses male bmr formula if genderMale radiobutton is selected
return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) + 5)); // This is the Miffin St-Jeor formula, calculations done in cm/kg
} else { // else gender.equals("F") - there are only 2 options for gender, M or F.
return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) - 161));
}
}
/**
* If the user selects the TDEE option, this method will be executed after the calcBMR() method.
* A value from the calcBMR() method will be passed down to this method, and is multiplied
* by the activity level parameter passed into this method.
*
* @param selectedActivityLevel
* @return TDEE Value (as a string)
*/
public static int calcTDEE(double activityMultiplier, int bmr) {
System.out.println(activityMultiplier);
return (int) Math.round(bmr * activityMultiplier);
}
}
As you can see, the methods are STATIC, however the variables being passed through (to both methods) are instance variables.
I am only calling these methods through the following lines:
bmrValue = Calculations.calcBMR(userAge, userGender, userHeight, userWeight);
bmrLabel.setText("<html><br /><font size=4>You have a <i><font color=#ce0000>BMR</font></i> of: " + "<font color=#59AF0E>" + bmrValue + "</font></html>");
if (tdeeYes.isSelected()) {
userActivityLevel = activityMap.get(activityLevelBox.getSelectedItem());
// Looks up selected item from combo box, which is the KEY. Then looks up the value to this key from the map - this value is the TDEE multiplier.
tdeeLabel.setText("<html><br /><font size=4>You have a <i><font color=#ce0000>TDEE</font></i> of: " + "<font color=#59AF0E>" + Calculations.calcTDEE(userActivityLevel, bmrValue) + "</font></html>");
}
The variables are defined as:
HashMap<String, Double> activityMap;
String[] activityLevels = {"Sedentary", "Lightly Active", "Moderately Active", "Very Active", "Extra Active"};
int userAge;
String userGender;
double userHeight;
double userWeight;
double userActivityLevel;
int bmrValue;
Am I using static/instance variables correctly? Earlier I had all my parameter variables as static, as I know static methods can only access static variables. I didn't know that the parameters could be instance variables until now.
Any guidance would be appreciated.
A: For starters, the difference between static and instance variables is that, only ONE static variable exists for all the instances of the class, whereas an instance variable exists for EVERY instance of the class.
Now, when you are talking about methods, in most cases you need to make a method static when you are trying to call it from another static method (such as main).
In general this practice is wrong for OOP, and chances are you should rethink the way the program is structured.
If you could provide more details about the code you use to call these methods, I would be able to help you with more details on how to fix this.
EDIT:
In light of the new info you provided:
1) I believe that bmrMain,BMRMain and Calculations can all be merged into one class. The constructor of the new class should be adjusted to read input (as well as getters and setters for each variable for added flexibility - optional)
2) Regarding the calculation of the bmr part, there are many ways to tackle this, so I will go ahead and suggest the one that is best in my opinion.
Add a Button with a text "Click to calculate" or something similar, and implement an ActionListener. The action Listener will in turn call (whenever the button is clicked) the method that calculates everything, and finally it will change the text on the JLabel.
sample code for the action Listener:
JButton button = new JButton("Text Button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Call the methods for the calculation
// bmr and tdee are temporary variables to store the results from the methods
//handle them properly, or remove them if not needed (I just wrote a sample)
int bmr = calcBMR(...); //pass the correct variables as arguments here
int tdee;
if(userHasPickedTDEE) { tdee = calcTDEE(...); } //and here
label.setText(....);
}
});
These 2 steps will take care of your "static" problem.
I recommend that you do some research on event-driven programming
And here is some extra and more in-depth reading on Action Listeners
If you need further help, or clarifications let me know :)
EDIT2:
In general, yes it is a good practice to separate classes in order to keep the code manageable. But in this case I think it is a bit superfluous to create a new class just for 2 methods.
Nevertheless if you would like to keep the current structure, the way to fix the "static" is:
1) remove static from the 2 calculation methods.
2)line 332 should be
Calculations c = new Calculations();
bmrValue = c.calcBMR(userAge, userGender, userHeight, userWeight);
FINAL_EDIT:
Well, these questions can easily be transferred to a thread of their own. But here is a useful link from a quick google search I just did, that will help demistify the static keyword:
Static keyword in Java
A: My thumb rule for using static variables goes somewhat like this:
*
*Do not use static
*When it is needed to use static refer to (1)
For most cases, the above thumb rule works. But then, we have standard idioms popularized by JDK, apache-commons libraries. Looking into them you find that:
*
*It is OK to have utility classes that contain all static methods.
*It is OK to create constants using static fields in classes. Though, for this using Enum might be a better choice.
*It is OK to one off utility functions that work on the same class into the class.
As for the restructuring the code goes, you should be looking at who owns the data. In this case, both the methods from Calculations class looks to be using data from the other class. Move the methods into the other class.
The only reason for existence of Calculations class should be that if you are using the methods from multiple other classes which are not related. If they are related, you try to model their relationship and see where these methods go.
A: I use static whenever my class is just used to call those methods (i.e. my main method calls the static methods to set variables in the main class, etc). I believe that is the "utility" class that KDM mentioned. A small example of when I use static or utility classes:
class Utility {
public static int add(int a, int b) {
// You would, of course, put something besides simple addition here
return a + b;
}
}
class Main {
public static void main(String[] args) {
int a = 2, b = 3;
int sum = Utility.add(a, b);
System.out.println(sum);
}
}
On the other hand, if you have a class that is closer to an actual object, with properties of its own, stay away from static. If you use static, then each instance of the class which you want to be separate objects will end up with same values.
Based on the name and functionality of your class, it appears you have a utility class. Static should be fine, but it may not be necessary. Hypothetically, though, if you wanted to use this class with multiple "people" class instances for which to calculate the BMR (where each instance is unique), then I would put calcBMR() in a person class and make it non-static so that each person has their own calcBMR().
Edit: Maybe this will help too:
Instance -> Instantiate: new Calculations().instanceMethod();
Static -> Class itself, the class's "state": Calculations.staticMethod();
A: If you think in terms of, do I want instance methods or static methods, you're going to be lost. Java isn't method-oriented, it's object-oriented. So for your functionality, decide whether you want an object or a pure function (where pure function means no dependencies and no side-effects, it's strictly a function that given this returns that).
It might be good to model this as an object, since you have information describing some aspect of the User and it may make sense to keep it together:
public class User {
private int age;
private String gender; // todo: use an Enum
private double height;
private double weight;
private String activityLevel; // todo: use an Enum
public User(int age, String gender, double height, double weight,
String activityLevel) {
this.age = age;
this.gender = gender;
this.height = height;
this.weight = weight;
this.activityLevel = activityLevel;
}
public double calculateBmr() {
int offset = gender.equals("M") ? 5 : -161;
return (int) (Math.round((10 * weight)
+ (6.25 * height) - (5 * age) + offset));
}
}
etc. This way we don't have to preface the variables with "user", they're all placed together in one object. Objects are an organizational scheme for collecting related information, the instance methods are functions that use the object's information.
The alternative route is to create a utility class:
public final class UserCalcUtil {
private UserCalcUtil() {} // no point instantiating this
public static int calculateBmr(String gender, double height,
double weight, int age) {
int offset = gender.equals("M") ? 5 : -161;
return (int) (Math.round((10 * weight)
+ (6.25 * height) - (5 * age) + offset));
}
}
Here you're keeping track of the user data separately, and passing it in to the static method when you want to calculate something. The utility class is a dumping ground for separate static methods (which you can think of as functions).
Whether you want to use objects or utility classes depends on how you want to organize your data and do calculations on it. Packing the data for a User together with the methods that act on that data may be more convenient if you always do the calculations on the individual objects, or moving the calculations into a utility class might make sense if there are multiple unrelated classes that you want to do calculations for. Since Java has more support for object-oriented constructs it often makes sense to take the object approach.
And you can use static methods, but avoid static variables for anything but constants (public static final, with a type that's immutable).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32304412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: C++ - Qt QObject::connect GET request usage across classes A quick overview of what's happening: I am trying to do a GET request using Qt's QNetworkAccessManager, but the callback function on my QObject::connect(..) function is not being called. My questions is can I call QObject::connect from one object, but connect to a slot of another object (given that I have a pointer to both the object and the slot) - See below for more details.
My ultimate goal is to POST the data (seeing as it's a login function), I had POST Request code that was ultimately suffering from the same issue - callback function not being called. So I would like to be able to do a simple GET request first, once I have that, I think I'll be fine on my own from there.
I currently have a QMainWindow LoginWindow, with a button that calls a slot doLogin() in the LoginWindow class. This all works as you would expect. LoginWindow also has a public slots function called loginResponse(QNetworkReply* response).
//---LoginWindow.h
...
public slots:
void doLogin();
void loginResponse(QNetworkReply* response)
...
//---LoginWindow.cpp
LoginWindow::LoginWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::LoginWindow)
{
ui->setupUi(this);
ui->username_le->setFocus();
}
void LoginWindow::doLogin()
{
MyProduct::Network network(this);
qDebug() << "Logging in...";
//Here I call network.login from LoginWindow and pass
//references to the Slot I want to use and the LoginWindow itself
network.login(
ui->username_le->text(), //username
ui->password_le->text(), //password
this, //reference to this object (LoginWindow*)
SLOT(loginResponse(QNetworkReply*)) //loginResponse slot
);
}
void LoginWindow::loginResponse(QNetworkReply* response)
{
qDebug() << "Log in complete";
}
Next I have another class, under the MyProduct namespace, called Network. As you can see above, Network has a function called login. Here it is:
void MyProduct::Network login(QString username, QString password, QObject *receiver, const char *slot)
{
QNetworkRequest request(QUrl(API_ROOT + LOGIN_PATH)); //"http://localhost/basic/login.php"
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
//nam = QNetworkAccessManager* declared in the constructor
QObject::connect(nam,SIGNAL(finished(QNetworkReply*)), receiver, slot);
qDebug() << "Posting login data...";
nam->get(request);
}
The goal here is to create a login function in my Network class that can be used and connected in any number of windows (as users may log in from multiple places). But I'm getting no response - LoginWindow::loginResponse is not run.
I see "Logging in..." and "Posting login data" output in the console, but not "Log in complete".
Can anyone please point me in the right direction or tell me I'm crazy or that this is a bad idea?
Thanks in advance!
A: Note that QNetworkAccessManager operates asynchronously. The get() method does not block while the network operation occurs; it returns immediately. (See the Detailed Description section of the documentation for more info.)
This is pretty typical of Qt's network-related APIs, because you usually don't want your application to freeze while waiting for data to move across a network.
What this means is what your instance, nam, isn't alive long enough for the GET request to actually finish. Your instance of the Product::Network class is deleted immediately after the call to login() because it's allocated on the stack. Although I can't see the code, I'm guessing it cleans up the QNetworkAccessManager as well.
If you extend the lifetime of your network object, you may find that your slot will eventually be invoked.
Also, this is more a matter of preference, but I think it would be cleaner to avoid passing a receiver and a slot to your login() function. I'd recommend declaring your own signals in the Network class as part of its API, and to connect to those in the LoginWindow class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13596199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Decode hexadecimal number in IBM/360 column binary format I have this message \1004\1001\2001\1010\0900\0000\0006\2012. It's in IBM column binary format. Reading, and trying to understand, a lot of articles like the below ones can't even put me on track.
https://v8doc.sas.com/sashtml/lrcon/z0695224.htm
http://homepage.divms.uiowa.edu/~jones/cards/codes.html
May I ask for some hint on it? Obviously I want to write a decoder for future use.
A: The IBM/360 column binary format defines how a hexadecimal value is represented on a Hollerith-card (punch card). This is described e.g. in http://www.jwdp.com/colbin1.html and in https://www.masswerk.at/keypunch/
There are several versions of punch cards, see e.g. https://en.wikipedia.org/wiki/Punched_card. The very common IBM 80-column punched card has 80 colums and 12 rows. The rows are labeld from top to bottom Y, X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Using the IBM/360 column binary format it follows for your code:
hex Byte 1 (hex) Byte 2 (hex) Byte 1 (cbf) Byte 2 (cbf) cbf (=column binary format)
\1004 10 04 X 7 X7
\1001 10 01 X 9 X9
\2001 20 01 Y 9 Y9
\1010 10 10 X 5 X5
\0900 09 00 03 0 03
\0000 00 00 0 0 blank
\0006 00 06 0 78 78
\2012 20 12 Y 58 Y58
Next, you have to apply a keypunch to map the punchcard-data to letters, digits and so on. You have not specified a special keypunch. Thus, it makes sense to use the IBM model 029 keypunch which was the most common keypunch, see e.g. https://www.masswerk.at/keypunch/ and your link
http://homepage.divms.uiowa.edu/~jones/cards/codes.html.
cbf 029 keypunch
X7 P
X9 R
Y9 I
X5 N
03 T
blank blank
78 "
Y58 (
Altogether, the result is PRINT "(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52612738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Connecting HTML/DOM with node.js I'm trying to find a way to write to a text file using node.js but I was trying to get the input from the HTML DOM. How do you write the output from the DOM to a text file using fs.writeFile?
Here's some code that doesn't work but thought it might be relevant. Thanks
<h3>A demonstration of how to access a Text Field</h3>
<input id="myText">
<button onclick="myFunction()">Try it</button>
<script>
const fs = require('fs')
function myFunction() {
var content = document.getElementById("myText").value;
}
fs.writeFile('./test.txt', content, err => {
if(err){
console.log(err);
return
}
})
</script>
A: You cannot write file directly from a browser to local computers.
That would be a massive security concern.
*You also cannot use fs on client-side browser
Instead you get inputs from a browser, and send it to your server (NodeJs), and use fs.writeFile() on server-side, which is allowed.
What you could do is:
*
*Create a link and prompt to download.
*Send to server and response with a download.
*Use native environment like Electron to able NodeJs locally to write into local computer.
What I assume you want to do is 1
Is that case you could simply do:
function writeAndDownload(str, filename){
let yourContent = str
//Convert your string into ObjectURL
let bom = new Uint8Array([0xef, 0xbb, 0xbf]);
let blob = new Blob([bom, yourContent], { type: "text/plain" });
let url = (window.URL || window.webkitURL).createObjectURL(blob);
//Create a link and assign the ObjectURL
let link = document.createElement("a");
link.style.display = "none";
link.setAttribute("href", url);
link.setAttribute("download", filename);
//Automatically prompt to download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
writeAndDownload("Text you want to save", "savedData")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67714849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I draw 2 lines with 2 different colors: each set of lines has set Coordinates. the Sets are not connected How do I draw two lines not connected to each other, the two lines must have to different colors, the two lines have points from four set of coordinates. So each line has its own set of coordinates. Using Objective C iOS 7.
Tower Two does not draw right now
if ([deg2 isEqual: @""] ) {
//nil
}else{
//not nil
//Tower Two
//draw line from lat2/long2 to finalLat2/finalLong2
CLLocationCoordinate2D coordinateArray2[2];
coordinateArray2[0] = CLLocationCoordinate2DMake([lat2 doubleValue], [long2 doubleValue]); //tower two
coordinateArray2[1] = CLLocationCoordinate2DMake(finalLat2, finalLong2);
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray2 count:2];
}
Tower One does draw
//tower one
// [self.mapview setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible
//draw line from lat1/long1 to finalLat1/finalLong1
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = CLLocationCoordinate2DMake([lat1 doubleValue], [long1 doubleValue]); //tower one
coordinateArray[1] = CLLocationCoordinate2DMake(finalLat1, finalLong1);
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
[self.mapview setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible
[self.mapview addOverlay:self.routeLine];
}
Here is how Tower One gets the line color
//Tower One Line
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
if(overlay == self.routeLine)
{
if(nil == self.routeLineView)
{
self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
self.routeLineView.fillColor = [UIColor greenColor];
self.routeLineView.strokeColor = [UIColor greenColor];
self.routeLineView.lineWidth = 5;
}
return self.routeLineView;
}
return nil;
}
A: I just needed to add in the .h file
@property (nonatomic, retain) MKPolyline *routeLine1; //ORGINAL LINE
@property (nonatomic, retain) MKPolylineView *routeLineView1; //ORGINAL LINE
@property (nonatomic, retain) MKPolyline *routeLine2; //ADDED LINE
@property (nonatomic, retain) MKPolylineView *routeLineView2; //ADDED LINE
This in the .m
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
if(overlay == self.routeLine1)
{
if(nil == self.routeLineView1)
{
self.routeLineView1 = [[MKPolylineView alloc] initWithPolyline:self.routeLine1];
self.routeLineView1.fillColor = [UIColor greenColor];
self.routeLineView1.strokeColor = [UIColor greenColor];
self.routeLineView1.lineWidth = 5;
}
return self.routeLineView1;
}
if(overlay == self.routeLine2)
{
if(nil == self.routeLineView2)
{
self.routeLineView2 = [[MKPolylineView alloc] initWithPolyline:self.routeLine2];
self.routeLineView2.fillColor = [UIColor orangeColor];
self.routeLineView2.strokeColor = [UIColor orangeColor];
self.routeLineView2.lineWidth = 5;
}
return self.routeLineView2;
}
return nil;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33288708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google maps reverse geocoding returns zero_results I have this code where I try getting address from coords in a google map,but my phone returns status error zero_results.
I am sure my location is available because if I tested via browser and my address location for coordinates is returned.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Geolocation test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
</style>
</head>
<body onload="">
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {lat: -34.397, lng: 150.644},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({map: map});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
map.setCenter(pos);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var geocoder = new google.maps.Geocoder;
geocoder.geocode({'latLng': pos2}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
document.getElementById('msg').innerHTML = results[0].formatted_address;
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="http://maps.google.com/maps/api/js?key=API_KEY&callback=initMap"></script>
</body>
</html>
`
A: the geolocation service is asynchronous, you need to use the data (pos2) in the callback function when/where it is available. Currently you are calling the geocoder before that value is set.
proof of concept fiddle
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
// call reverse geocoder with location returned by geolocation service
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
code snippet:
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.google.com/maps/api/js?callback=initMap"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40683330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display next div only and hide other divs with same class Many versions of this question have already been asked but I can't seem to find a solution.
I'm hoping to have just one div visible at a time and to toggle an 'open' class on the correct trigger.
Here's what I have so far:
<div class="wrap">
<div class="trigger"></div>
<div class="description">
<p>Here's a description</p>
</div>
</div>
<div class="wrap">
<div class="trigger"></div>
<div class="description">
<p>Here's a description</p>
</div>
</div>
<div class="wrap">
<div class="trigger"></div>
<div class="description">
<p>Here's a description</p>
</div>
</div>
And the jQuery:
$(function () {
$(".trigger").click(function (e) {
e.preventDefault();
$(this).next('.description').fadeToggle('fast');$(this).toggleClass('open');
});
});
And that works to get the proper div opened and closed, but what I'm hoping for is some logic to make any other 'description' divs close so only one will be open at a time.
Any help would be much appreciated!
A: Try to hide all .description except the current element's linked .description,
$(function () {
$(".trigger").click(function (e) {
e.preventDefault();
$(".description").not($(this).toggleClass('open').next('.description').fadeToggle("slow")).fadeOut('fast');
});
});
DEMO
A: You need to hide the sibling elements like
$(function() {
$(".trigger").click(function(e) {
e.preventDefault();
$(this).toggleClass('open').siblings('.trigger').removeClass('open');
$(this).next('.description').stop().fadeToggle('fast').siblings('.description').stop().fadeOut('fast');
});
});
.description {
display: none;
}
.open {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trigger">t1</div>
<div class="description">
<p>Here's a description</p>
</div>
<div class="trigger">t2</div>
<div class="description">
<p>Here's a description</p>
</div>
<div class="trigger">t3</div>
<div class="description">
<p>Here's a description</p>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33172592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: getting err_too_many_redirects in laravel when I use Request for validation for validating unique it is my error page
I have used customize Request page for geting value from post request.
in that request I am validating
namespace App\Http\Requests;
use App\Http\Requests\Request;
class TaxclassRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"tax_class"=>'unique:taxes,tax_class'
];
}
}
and my controller is
function insert(TaxclassRequest $request)
{
$n=$request->input('number'); //total number of variable that has been created dyanamic
$tax_class=$request->input("tax_class"); // tax_class
.
.
.
other code
I am getting error
ERR_TOO_MANY_REDIRECTS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36328358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Python 2.7 mechanize library I am trying to use mechanize to access a website and submit form to login. My end goal is to login to a ticketing system, fill in the required fields and submit which in turn would generate a ticket number which I need to grab.
I have the following code.
import urllib
import mechanize
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent','Firefox')]
br.set_handle_robots(False)
jira='jira_link'
br.open(jira)
br.select_form(nr=0)
br.form['os_username'] = 'username'
br.form['os_password']= 'password'
sub=br.submit()
print sub.geturl()
However I get the following error when I run the script
raise BrowserStateError("not viewing HTML")
mechanize._mechanize.BrowserStateError: not viewing HTML
I successfully logged into Facebook using the same code.
Checking browser console it does look like a valid html doc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41973974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to report errors while parsing content in ES6 tagged templates? I'm working with a friend on a small Javascript experiment, which involves a basic HTML parser, implemented as a simple state machine - you can see the code here.
My question is regarding tagged template functions which involve any kind of parser, with regards to error reporting - that is, if the parser detects an invalid state, it needs to report where the error was found in the input.
My problem is tracking and/or explaining where the error was found, in a way that makes sense.
The input to a tagged template function is actually bits of source (in my case HTML) alternating with Javascript values, so you can't simply (as I'm doing now, as you would do in most normal parsers) count characters and report the position, since the alternating Javascript values may not be strings, or may be strings that don't get parsed as literal source.
Is there any way for tagged template functions to discover the source file locations of the alternating input strings/values?
Or am I right in suspecting that a run-time facility of this sort is virtually impossible? Is there literally no useful way to implement this, short of using a Javascript parser, possibly ahead-of-time, to discover and log the source locations?
A: All that can be done here is to output the expected context where the problem took place. Considering that the problem was caused by three:
const three = null;
`one${two}${three}four`
Tag function arguments can be concatenated in error message to the point where they start to make sense, e.g.
Expected a number as an expression at position 2, got `null`,
`one${...}${...}four`
^^^
Stack trace can also be retrieved if needed with new Error().stack.
If more precision is required, a template engine should be used instead of template literals because all necessary data is available during template compilation.
The options for tag function are same as for any other function. If foo function was called with bar variable as an argument that equals 1 (like foo(bar)), it may be impossible to figure out that it was called with bar from inside foo, because all we've got is 1 value. The fact that it was called like foo(bar) can only be found out if we have stack trace and the access to source file - which we don't have under normal circumstances. This method can be used in cases where feedback should be provided on the context, e.g. a test runner - because it is responsible for script loading and has access to source files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46521414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Web Scraping using non-defined tags I'm trying to develop a tool to do some web scraping, I've done this before for specific websites using HTML Agility Pack, but in this case I want the user to be able to specify what information he wants to scrap by selecting the text on the website.
What I don't know is if the user selects "Product 1" is there anyway I can get the HTML tag or something so I can then feed the algorithm so I search for that same type of tag on the entire document?
Product 1
Product description
Price $0.00
A: seems like you want to query your DOM by a specific tag, similar to jquery selectors. Take a look at the project below, it might be what you are looking for.
https://github.com/jamietre/csquery
A: Load the HTML into an HtmlDocument object, then select the first node where the text input appears. The node has everything you might need:
var doc = new HtmlDocument();
string input = "Product 1";
doc.LoadHtml("Your HTML here"); //Or doc.Load(), depends on how you're getting your HTML
HtmlNode selectedNode = doc.DocumentNode.SelectSingleNode(string.Format("//*[contains(text(),'{0}')]", input));
var tagName = selectedNode.Name;
var tagClass = selectedNode.Attributes["class"].Value;
//etc
Of course this all depends on the actual page structure, whether "Product 1" is shown anywhere else, whether other elements in the page also use the same node that contains "Product 1", etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11728682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Textarea not filled with all $_GET data, cuts off at quotation marks I have a text area page which is launched from the previous page:
$message = $_POST['editPost'];
header("location:editPost.php?msg=$message");
The editPost.php retrieves this and fills the text area like so:
echo "<form action='index.php' method='post'>
Your Post:<br/>
<textarea name='comments' cols='100' rows='100'>".$_GET["msg"]."</textarea>
<br/>
<input type=submit value='submit'>
</FORM>";
The problem I'm getting is not all the data of 'msg' seems to get passed across, or the message gets cut of at the point where it reaches a quotation mark e.g. '
The text I want it to fill the textarea with this text:
So this is my second blog post for this assignment, I've progressed a bit since my previous post
however it only add this to the text area this:
So this is my second blog post for this assignment, I
As I say it seems to not contain any more of the string after the quotation mark is reached. Is there anyway around this so I can pass the whole message across?
EDIT
I might add, I'm aware a more simple solution would be to retrieve the message again from the MySQL database as that's what I'm using, but I'm just intrigued as to how this works.
if(isset($_POST['edit'])) {
//$_SESSION['postToEdit'] = $_POST['editPost'];
$message = htmlentities($_POST['editPost'], ENT_QUOTES);
header("location:editPost.php?msg=$message");
That is what I do with the data once it is posted from this form:
foreach($posts as $postid=>$post)
{
echo '<div class="blogPosts">'.$post;
if(isset($_SESSION['username'])) {
if($_SESSION['isAdmin'] == "true") {
echo "<br/><br/><form name='adminTools' action='index.php' method='post'>
<input type='hidden' name='editPost' value='$post'>
<input type='submit' value='Edit' name='edit'/>
<input type='hidden' name='deletePost' value='$postid'>
<input type='submit' value='Delete' name='delete' /></form>
</div>";
A: echo "<form action='index.php' method='post'>
Your Post:<br/>
<textarea name='comments' cols='100' rows='100'>".htmlspecialchars($_GET["msg"])."</textarea>
<br/>
<input type=submit value='submit'>
</FORM>";
textarea seems an odd container for it, but that's your call
A: I think I get it.
header("location:editPost.php?msg=$message"); doesn't smells good.
If you simply want to fix the problem use http://php.net/manual/en/function.urlencode.php and when getting the value http://www.php.net/manual/en/function.urldecode.php
You're getting a post request and then forwarding it using header location. That's definitely a poor way to do it. The problem probably is taking place when you pass the parameter as a query string on ?msg=$message
Since MVC and alike applications (n-layered apps) is the standard now. You should not do that spaghetti code, mixing html and php and using header as your FrontController dispatcher.
I'd suggest you to use for example, the SLIM framework. If you do not want to learn this. You should at least follow the standards described here.
E.g.:
<?php
// index.php
// load and initialize any global libraries
require_once 'model.php';
require_once 'controllers.php';
// route the request internally
$uri = $_SERVER['REQUEST_URI'];
if ($uri == '/index.php') {
list_action();
} elseif ($uri == '/index.php/show' && isset($_GET['id'])) {
show_action($_GET['id']);
} else {
header('Status: 404 Not Found');
echo '<html><body><h1>Page Not Found</h1></body></html>';
}
In short, create a FrontController file that will map to the desired actions (controllers) according to the request without using header() to execute specific actions (the exception is only if actually the headers are needed, in fact).
A: Use addslashes($message) before passing it in querystring and stripslashe($_GET['msg']) function before displaying it.
Click addslashes() and stripslashes() for more references.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9833256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery Slider spacing fubar on ie7 and i6 So ive been trying to debug this friggin spacing issue for the last 4 hours.. and I cant friggin solve it!!!
If you go to http://myurbanlunchbox.com you will see right away what I am refering to. The image slider has spacing issues, but only in IE6 and IE7.. (as usual).
Can anyone point out where im going wrong?
A: It's not the slider which is messing up. Rather, IE isn't displaying the right border of #slider. I think moving the border to #overview would provide the style you're looking for. I have no idea why IE is messing up the border.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1506817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parsing XML inside JSF could anybody tell me how to parse XML file inside a JSF page?
The thing's that I've got XML file and want to put some data from it into my JSF page. My first thought was to include JSTL Core and XML libs and to do something like this:
<c:import var="some-info-doc" src="some-info.xml" />
<x:parse var="some-info-xml" xml="some-info-doc" />
<h:outputText>
<x:out select="$some-info-xml/a-piece-of-data" />
</h:outputText>
However, this code resulted in error. c:import was not recognized. So, I decided to play with a local piece of XML:
<x:parse var="simple">
<child>basic</child>
</x:parse>
<h:outputText>
<x:out select="$simple/child" />
</h:outputText>
This led to the child tag being printed in the result page. And the output came from the x:parse tag, not h:output.
So that, is there any alternative to parse XML inside a JSF page (not including XML being sent as an object from a certain by-me-written module)? Or are there any errors in my code?
A: 1. Don't try to mix JSTL tags and JSF tags; they're chalk and cheese.
2. JSF is an MVP framework, so you're going against the grain by trying to define your data sources in the view.
3. To emit data via an outputText control, bind its value attribute to the model (e.g. a managed bean).
It is probably possible to do something like this:
<!-- other code elided -->
<x:set var="x" select="$simple/child" />
<h:outputText value="#{x}" />
...but, in general, see points 1 and 2.
Just a suggestion: ensure you've added the http://java.sun.com/jsp/jstl/core namespace to the page to use JSTL core.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1640285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Waiting for multiple asynchronous JSON queries to finish before running code I am looking to run multiple different JSON request simultaneously, and then only perform a function once they have either completed or returned an error message (404 etc.). Here's what I have so far, but the function finished doesn't remember the variables from either request. Any ideas?
function socialPosting(a_date,a_title,a_source,a_thumbnail,a_url) {
socialPosts[socialPosts.length] = {date: a_date, title: a_title, source: a_source, thumbnail: a_thumbnail, url: a_url};
//console.log(socialPosts[amount]);
//console.log(amount);
}
function finished(source) {
if (source == "Twitter") {
var Twitter = "True";
}
if (source == "YouTube") {
var YouTube = "True";
}
console.log(source); //diagnostics
console.log(Twitter); //diagnostics
console.log(YouTube); //diagnostics
if (Twitter == "True" && YouTube == "True") {
console.log(socialPosts[0]); //Should return after both requests are complete
}
}
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
socialPosting(Date.parse(data.data.items[i].uploaded),data.data.items[i].title,"YouTube",data.data.items[i].thumbnail.hqDefault,'http://www.youtube.com/watch?v=' + data.data.items[i].id); //Add values of YouTube video to array
}
finished("YouTube");
});
$.getJSON("https://api.twitter.com/1/statuses/user_timeline/twitter.json?count=5&include_rts=1&callback=?", function(data) {
var amount = socialPosts.length;
for(var i=0; i<data.length; i++) {
socialPosting(Date.parse(data[i].created_at),data[i].text,"Twitter"); //Add values of YouTube video to array
}
finished("Twitter");
});
A: try this, in your solution Twitter and Youtube are local variables in the function finished, after the function returns they no longer exist, if the function gets called again they are craeted again but of course they don´t have the value of last time since they are new variables, maybe google for 'javascript variable scope' for more information about this topic.
var Twitter = false;
var YouTube = false;
function finished(source) {
if (source == "Twitter") {
Twitter = true;
}
if (source == "YouTube") {
YouTube = true;
}
console.log(source);
console.log(Twitter);
console.log(YouTube);
if (Twitter && YouTube) {
console.log(socialPosts[0]);
}
}
Also add an error handler to your json-request via
$.getJSON(...).fail(function () {console.log('error');});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16939651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change color of the left aligned text? I'm new to reactjs, i tried to change the color of the left align text using reactjs. Can anybody help me in this?
this would be jsondata in api:
{
"message": "Hello everyone",
"isrespond": true,
},
{
"message": "hi",
"isrespond": false,
}
Can anyone help me in this ?
A: let leftAlignedColor
if(element.isrespond == "left"){
leftAlignedColor = '#000'
}else{
leftAlignedColor = null
}
<Grid.Column floated={ element.isrespond ? "right" : "left"}><p style={{color: `${leftAlignedColor}`}}> {result.message}</p></Grid.Column>
its better to use a <span>,<p> inside a column as a good practice.
Hope this is helpful!
A: You should apply a conditional style. This will enable you even pass a specific class name that styles the component.
let myStyle = element.isrespond ? {float:"right",color:"blue"} : {float:"left",color:"red"};
<Grid.Column style={myStyle}> {result.message}</Grid.Column>
A: <Grid.Column floated={ element.isrespond ? "right" : "left"}><p style={{color: element.isrespond ? "blue" : "green",background:element.isrespond ? "yellow" : "cyan"}}> {result.message}</p></Grid.Column>
I think this will work. change the required colors. I added botj for color and background. In the above one. its "green" for left and "blue" for right
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58850603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to display an image of expo camera in React Native I am working on camera in app, where I have took a picture and have convert into base64 now I want to display an image but did not able to display an image . Could someone please help me how to achieve this goal .
Thanks
takePicture = async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync({
base64: true,
});
this.props.cameraToggle(false);
this.props.image(photo)
console.log('@@@ take picutre', photo)
}
}
Image Code that I want to render
<Image source={{uri:`data:image/png;base64,${cameraImage}`}} style={{width:100,height:100}}/>
A: I assume that you're using class-based components. You can render the image which is captured from camera by setting the response photo to a local state and conditionally rendering it.
import React from "react";
import { Image } from "react-native";
import { Camera } from "expo-camera";
import Constants from "expo-constants";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";
class Cameras extends React.Component(props) {
state = {
captures: "",
};
takePicture = async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync({
base64: true,
});
this.props.cameraToggle(false);
this.setState({ captures: photo.uri });
}
};
render() {
const { captures } = this.state;
return (
<View flex={1}>
{this.state.captures ? (
<Image source={{ uri: captures }} style={{width:50,height:50}} />
) : (
<Camera {...pass in props} />
)}
</View>
);
}
}
export default Cameras;
Note:
A more clean approach would be to pass the state captures as a route param by navigating a different screen and rendering the image on that screen.
A: I am assuming you are storing value of photo in cameraImage.
I am sharing a working solution with you using expo image picker, give it a try
Your component
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';
<TouchableHighlight onPress={this._openCamera}>
<Text>Open Camera</Text>
</TouchableHighlight>
<Image source={this.state.mainImageUrl} />
Your function
_openCamera = async () => {
await Permissions.askAsync(Permissions.CAMERA);
try {
let result: any = await ImagePicker.launchCameraAsync({
base64: true,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
this.setState({
mainImageUrl: { uri: `data:image/jpg;base64,${result.base64}` }
});
}
} catch (E) {
console.warn(E);
}
}
A: Your code:
let photo = await this.camera.takePictureAsync({
base64: true,
});
this.props.image(photo)
The takePictureAsync return an object, so your base64 data is in the field photo.base64.
Solution 2
You can store the URI into the state without base64.
const [photoUri, setPhotoUri] = React.useState(null);
const cameraRef = React.useRef(null);
const takePhoto = async () => {
setPhotoUri(null);
const camera = cameraRef.current;
if(!camera) return;
try {
const data = await camera.takePictureAsync();
setPhotoUri(data.uri);
} catch (error) {
console.log('error: ', error);
}
}
Then use it.
return (
<Image source={{uri: photoUri}} />
);
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63567411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ServiceStack OrmLite Join Issues I'm having a problem with ServiceStack OrmLite for SQL Server in a Visual Studio 2013 C# project. My problem is that I'm trying to use the SqlExpression builder and it's not capturing my table schema and the generated SQL code is not correct. When I run the code, I get a System.Data.SqlClient.SqlException that says "Invalid object name 'ReportPages'."
I'm using the latest NuGet version of ServiceStack.OrmLite, which is version 4.0.24.
Let me start with the table setup. Note that I removed the foreign keys for convenience:
-- Create the report pages table.
CREATE TABLE [MicroSite].[ReportPages](
[ReportPageID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](200) NULL,
[Template] [nvarchar](50) NULL,
[AccessLevel] [int] NOT NULL,
[AssignedEmployeeId] [int] NOT NULL,
[Disabled] [bit] NOT NULL,
[Deleted] [bit] NOT NULL,
[ReportSectionID] [int] NOT NULL,
[Index] [int] NOT NULL,
[Cover] [bit] NOT NULL,
CONSTRAINT [PK_dbo.ReportSections] PRIMARY KEY CLUSTERED
(
[ReportPageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
-- Create the report sections table.
CREATE TABLE [MicroSite].[ReportSections](
[ReportSectionID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NULL,
[ReportID] [int] NOT NULL,
CONSTRAINT [PK_dbo.ReportSectionGroups] PRIMARY KEY CLUSTERED
(
[ReportSectionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
-- Create the report editables table.
CREATE TABLE [MicroSite].[Editables](
[EditableID] [int] IDENTITY(1,1) NOT NULL,
[Index] [int] NOT NULL,
[Content] [nvarchar](max) NULL,
[Styles] [nvarchar](100) NULL,
[Type] [int] NOT NULL,
[ReportPageID] [int] NOT NULL,
CONSTRAINT [PK_dbo.Editables] PRIMARY KEY CLUSTERED
(
[EditableID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
So my tables basically look like this:
Here are my POCOs:
[Alias("ReportPages")]
[Schema("MicroSite")]
public partial class MicrositeReportPage : IHasId<int>
{
[Required]
public int AccessLevel { get; set; }
[Required]
public int AssignedEmployeeId { get; set; }
[Required]
public bool Cover { get; set; }
[Required]
public bool Deleted { get; set; }
[Required]
public bool Disabled { get; set; }
[Alias("ReportPageID")]
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[Required]
public int Index { get; set; }
public string Name { get; set; }
[Alias("ReportSectionID")]
[Required]
public int ReportSectionId { get; set; }
public string Template { get; set; }
}
[Alias("ReportSections")]
[Schema("MicroSite")]
public class MicrositeReportSection : IHasId<int>
{
[Alias("ReportSectionID")]
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
[Alias("ReportID")]
[Required]
public int ReportId { get; set; }
}
[Alias("Editables")]
[Schema("MicroSite")]
public partial class MicrositeEditable : IHasId<int>
{
public string Content { get; set; }
[Alias("EditableID")]
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[Required]
public int Index { get; set; }
[Alias("ReportPageID")]
[Required]
public int ReportPageId { get; set; }
public string Styles { get; set; }
[Alias("Type")]
[Required]
public int TypeId { get; set; }
}
The actual SQL statement I want to generate is this:
SELECT e.EditableID
, e.[Index]
, e.Content
, e.Styles
, e.Type
, e.ReportPageID
FROM
MicroSite.ReportSections AS rs
LEFT JOIN
MicroSite.ReportPages AS rp ON rp.ReportSectionID = rs.ReportSectionID AND rp.[Index] = 24
LEFT JOIN
MicroSite.Editables AS e ON e.ReportPageID = rp.ReportPageID
WHERE
rs.ReportID = 15
Here is my C# code:
var query = db.From<MicrositeReportSection>()
.LeftJoin<MicrositeReportSection, MicrositeReportPage>((section, page) => section.Id == page.ReportSectionId)
.LeftJoin<MicrositeReportPage, MicrositeEditable>((page, editable) => page.Id == editable.ReportPageId && page.Index == 24)
.Where<MicrositeReportSection>(section => section.ReportId == 15);
var sql = query.ToSelectStatement();
var result = db.Select<MicrositeEditable>(query)
The generated SQL statement from the sql variable looks like this (I formatted it for readability):
SELECT
"ReportSectionID",
"Name",
"ReportID"
FROM
"MicroSite"."ReportSections"
LEFT JOIN
"ReportPages" ON ("ReportSections"."ReportSectionID" = "ReportPages"."ReportSectionID")
LEFT JOIN "Editables"
ON (("ReportPages"."ReportPageID" = "Editables"."ReportPageID") AND ("ReportPages"."Index" = 24))
WHERE
("ReportSections"."ReportID" = 15)
First, the left joins are missing the schema name, which makes the SQL statement incorrect. Second, what's going on in the select statement? Those aren't the columns from the MicrositeEditable table. Am I doing this correctly or is this an actual bug with OrmLite?
A: I submitted a ticket with the development team and this is now fixed in version 4.0.25.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25044364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I change user presence status in RingCentral programmatically using C#? I have created as program in C# that is designed to display the users status and availability from RingCentral.
This works brilliantly and I can sort the users by availability, name, etc.
I need to add the functionality to change the status of the user to "Offline". When the users shift ends they would be set to receive calls when they have gone home, we need to stop that.
The problem I have is that the RingCentral SDK I am using is saying it needs a parameter which should be of type PresenceInfoResource. here is the path I am using:
rc.Restapi().Account().Extension().Presence().Put();
I have tried various different types but I cannot seem to get, create or cast to a type of PresenceInfoResource.
Does anyone know what it is looking for, how to change the status in c# or where I am going wrong?
I have looked in the RingCentral documentation on line, but can't find anything, only a link to the update presence page which has nothing about PresenceInfoResource:
https://developers.ringcentral.com/api-reference/Presence/updateUserPresenceStatus
A: I got an answer to this from another site:
var parameters = new PresenceInfoResource();
parameters.userStatus = "Busy";
parameters.dndStatus = "TakeAllCalls";
var resp = await rc.Restapi().Account().Extension().Presence().Put(parameters);
Console.WriteLine("User presence status: " + resp.userStatus);
Console.WriteLine("User DND status: " + resp.dndStatus);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56393678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS Masonry Grid with JQuery .hover hiding images in grid other than hovered image and first column I am building a custom theme for koken based on their Blueprint framework theme and have coded it so the album template loops over all images in the album and outputs the images into a 4 column masonry-like grid using CSS, and a jquery script so that when I hover over an image it changes the opacity of all other images in the grid to 0.4.
The jquery code with the grid works fine in JSFiddle, but when I bring it into the koken theme, whenever an image is hovered, the script works for a second showing all but the hovered image at reduced opacity, but then hiding all the images except for the hovered image and the first column.
The code used for the grid is as follows:
HTML
<main>
<div id="grid">
<ul>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
<li>
<img src="http://placekitten.com/300/200" class="gridimg" />
</li>
</ul>
</div>
CSS
#grid {
/* Prevent vertical gaps */
line-height: 0;
-webkit-column-count: 4;
-webkit-column-gap: 0;
-moz-column-count: 4;
-moz-column-gap: 0;
column-count: 4;
column-gap: 0;
}
#grid img {
/* Just in case there are inline attributes */
width: 100% !important;
height: auto !important;
}
#grid ul li {
display: inline;
}
.gridimg {
opacity:1;
transition: opacity 0.5s;
}
.opaque {
opacity:0.4;
transition: opacity 0.5s;
}
JS
$('img.gridimg').hover(function () {
$('img.gridimg').not(this).each(function () {
$(this).toggleClass("opaque");
});
});
JSFiddle is here: http://jsfiddle.net/jgYY9/3/
Is there something in the koken code that is messing this up? And does anyone know how I can fix it?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23706095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pyplot 3D scatter z axis issue Is there something wrong with the 3d plt.scatter(x,y,z) method?
Plots all z values at zero:
x = [1, 1]
y = [1, 1]
z = [-10, 10]
fig = plt.figure(figsize=(16, 18))
plt.axes(projection ="3d")
plt.scatter(x, y, z, color='k')
plt.show()
Working correctly:
x = [1, 1]
y = [1, 1]
z = [-10, 10]
fig = plt.figure(figsize=(16, 18))
ax = plt.axes(projection ="3d")
ax.scatter(x, y, z, color='k')
plt.show()
A: In your above examples you used the two matplotlib's interfaces: pyplot vs object oriented.
If you'll look at the source code of pyplot.scatter you'll see that even if you are going to provide 3 arguments plt.scatter(x, y, z, color='k'), it is actually going to call the 2D version, with x, y, s=z, s being the marker size.
So, it appears that you have to use the object oriented approach to achieve your goals.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73756160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove a dead lock in the Internet Explorer on Thread.Sleep? I know all browsers are single threaded and impossible implements in JavaScript or Flash Player Thread.sleep. I decided to try using “System.Threading” library implements Thread.Sleep in the Silverlight.
App.xaml.cs
using System.Windows;
using System.Windows.Browser;
using System.Threading;
namespace ThreadSleep
{
public partial class App : Application
{
public App()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("App", this);
}
[ScriptableMember]
public void Sleep(int mlsec)
{
Thread.Sleep(mlsec);
}
}
}
So, from a JavaScript code I can execute a Sleep function, but my Internet Explorer freeze and not responding.
Here is my example:
Index.html
<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
var SleepInterval = 10000;
function pause1(){
window.showModalDialog("PauseWin.html", this, 'dialogWidth:255px; dialogHeight:105px; status:0; scroll:0;');
alert("Resume");
}
function pause2(){
var control = document.getElementById("SleepSL");
control.Content.App.Sleep(SleepInterval);
alert("Resume");
}
function tick(){
var clock = document.getElementById("clock");
if(clock) clock.innerHTML = new Date();
}
setInterval(tick, 1000);
//-->
</SCRIPT>
<INPUT TYPE="button" value="Pause Modal Dialog" onclick="pause1()">
<INPUT TYPE="button" value="Pause Thread Sleep" onclick="pause2()">
<BR><BR>
<!--Youtube Video -->
<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/RWNcGBSP0Wg?autoplay=1" frameborder="0" allowfullscreen></iframe>
<!-- Silverlight Sleep API -->
<object id="SleepSL" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="1" height="1">
<param name="source" value="SleepSL.xap"/>
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50826.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>
<BR><BR>
<DIV ID="clock"/>
</BODY>
</HTML>
PauseWin.html
<html>
<title>Pause Window</title>
<style>body{margin-top:10}</style>
<body scroll="no">
<center style='font-size:14px;font-weight:bold'>
The window will automatically <br> close in <span id="time"></span> second(s).
</center>
<script type="text/javascript">
var ms = window.dialogArguments.SleepInterval;
function wait(){
var span = document.getElementById('time');
span.innerHTML = (ms / 1000);
setInterval(function(){ closeWindow(); }, ms);
setInterval(function(){ ms -= 1000; if(ms > 0) span.innerHTML = (ms / 1000); }, 1000);
}
function closeWindow(){
window.close()
}
wait();
</script>
</body>
</html>
By executing an index.html file I am starting a YouTube video and timer. When I pressed "Pause Modal Dialog" the timer stops, but video continue playing, after 10 seconds the Modal Popup window destroying by JS “window.close()” and in my code I am going to the next line and executing alert(“Resume”). Nothing change the video continues playing. Now if I will press "Pause Thread Sleep" button using a Silverlight Thread.Sleep function. At this time video will hang and by clicking on the Internet Explorer you may get (Not Responded) state in the Process Explorer.
I will prefer to use Thread.Sleep function in the COM, ActiveX or Silverlight objects, but I need to remove that a thread dead lock. Get the same behavior as in JavaScript Modal Dialog or Alert.
Many thanks in advance.
Regards,
David Gofman
Code:
index.html
PauseWin.html
A: Your code is doing exactly what you're telling it to do: it's sleeping your browser's UI thread, which means that your browser can't process any more messages, so it's effectively hanging your browser for the duration of the sleep. Thread.Sleep() in a browser is death: just don't do it, whether in Silverlight or any other framework.
A better approach would be to step back and ask yourself why you want to sleep something, and then figure out a reasonable async way of doing that. Having been thrown into the Silverlight async world several years ago, I realize that this can be disorienting at first, but I can also testify that I've always found reasonably clean ways to do it right.
Another way to put it: if you can't figure out how to do what it is that you actually need to get done, post a question about that, and you'll likely get some help here.
For instance, if you just want to wait 'n' seconds and then perform a callback, you could use a helper class like this one:
public class ThreadingHelper
{
public static void SleepAsync(int millisecondsToSleep, Action action)
{
var timer = new Timer(o => action());
timer.Change(millisecondsToSleep, Timeout.Infinite);
}
public static void SleepAsync(TimeSpan interval, Action action)
{
SleepAsync((int)interval.TotalMilliseconds, action);
}
public static void DispatcherSleepAsync(int millisecondsToSleep, Action action)
{
var interval = TimeSpan.FromMilliseconds(millisecondsToSleep);
DispatcherSleepAsync(interval, action);
}
public static void DispatcherSleepAsync(TimeSpan interval, Action action)
{
var timer = new DispatcherTimer();
EventHandler timerHandler = null;
timerHandler = (s, e) =>
{
timer.Tick -= timerHandler;
if (action != null)
{
action();
}
};
timer.Tick += timerHandler;
timer.Interval = interval;
timer.Start();
}
}
A: You could do this:
function begin() { /* do stuff... */ }
function afterWait() { /* rest of my code...*/ }
begin();
setTimeout(afterWait, 10000);
setTimeout has effectively stopped your javascript for 10 seconds, and the browser can still carry on working
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5302557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Progress bar hangs while deleting large files I have added the loading bar in below snippet.It’s worked fine which I have deleted small amount of data(say 30 to 150 mb). But the problem is when I deleted large size of data, the loading bar doesn't get loaded(approx 190mb).
dispatch_async(dispatch_get_main_queue(), ^{
[self addloading];
if(_isProgress)
return;
_lastDeleteItemIndexAsked = index;
NSInteger catalogue_id =[[[_currentData objectAtIndex:index%[_currentData count]] valueForKey:@"catalogue_id"] integerValue];
BOOL update_avilable = [[[online_date_array objectAtIndex:index%[_currentData count]] valueForKey:@"update_version"] boolValue];
if(update_avilable)
[[self GridViewDelegate] deletecatlogue_for_update:catalogue_id];
else
[[self GridViewDelegate] deletecatlogue:catalogue_id];
[online_date_array replaceObjectAtIndex:index%[online_date_array count] withObject:[NotificationHandler check_online_date_of_catalogue:catalogue_id]];
[_gmGridView reloadObjectAtIndex:index%[_currentData count] withAnimation:GMGridViewItemAnimationFade];
[self stopLoadingfor_delete];
});
A: Is it size or execution time?
I'm going to assume that self is a UI object. If it is, the block should be:
Controller* __weak weakSelf = self;
dispatch_async(queue, ^{
Controller* strongSelf = weakSelf;
if (strongSelf) {
...
}
else {
// self has been deallocated in the meantime.
}
});
Thus you may prefer a MVVC solution, where a view model does the hard work, not the view controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35124320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to publish dependencies into private npm repository I have created a private nexus repository to host my custom nodejs libraries. But when I publish my package, it doesn't publish any of its dependencies.
Steps:
npm set registry <registry url>
npm login
npm publish
package.json
{
"name": "testpackage",
"version": "1.0.0",
"private": false,
"dependencies": {
"request": "^2.87.0",
"safe-access": "0.1.0",
"winston": "^2.4.2"
},
"main": "index.js",
"directories": {
"test": "tests"
},
"devDependencies": {},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
I get this issue when I try to install my package
npm install testpackage
npm ERR! code E404
npm ERR! 404 Not Found: [email protected]
npm ERR! A complete log of this run can be found in:
npm ERR! /<path>/.npm/_logs/2018-10-04T11_25_36_719Z-debug.log
Is there a way to publish node_modules/all transitive dependencies into nexus? (Note: I will not be having internet access in production environment. Hence I need to download all dependencies from private repo itself)
A: No.
What you're describing is exactly what Nexus Repository Manager designed groups for but your internetless scenario removes that from the equation.
Your only recourse is manual upload.
A: I have solved the issue as follows:
I used a npm-group repository and added a npm-hosted repository and a cache enabled npm-proxy (Only this repository has internet access).
Steps to add new packages to the repository:
1) Add the repo to a dummy package.json
2) npm install. (All the required packages get cached)
3) I point proxy-url to some junk url. (To avoid unwanted code to come into my environment).
Steps to use the repository:
1) npm set registry [npm-group-repo url]
2) npm install
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52645771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Solr-Atomic Update changes other fields While running on atomic update,language field is getting changed.We have flow as below.
During indexing object posted is
{
id:"234-567",
fileName:"file1",
content:""
}
In the pipeline we analyse content as part of language detection and create a new field "language" which is working as expected.
But while doing atomic update
{
id:"as above"
fileName:"changed"
}
to change fileName,we make use to "set" operation which is updating field correctly but language field is getting changed to fallback value.
What is happening here?Is it looking for content field to analysis again?Does atomic update also goes through processing pipeline
A: I'm guessing the language detection is run again, and there is no value available for that field for the language detection to actually detect anything for.
Run updates without language detection unless you're including the field you're running language detection on.
You might have to define a second request handler without the language detection settings if you have those defined as static settings in your request handler configuration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45773454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Reactjs production mode, my app does not change url and not rendering component while I use Browser router, but it works fine with hashrouter index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Home from './home'
import {Link,Switch,Route,BrowserRouter} from 'react-router-dom'
ReactDom.render(
<BrowserRouter>
<Link to="/home">Home</Link>
<Switch>
<Route path="/home" exact component={Home}/>
</Switch>
</BrowserRouter>, document.getElementById('root'))
HashRouter works in production mode but BrowserRouter doesn't change urls and not rendering component also
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59711804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: X Error of failed request: GLXBadFBConfig (opengl 4.3 - ubuntu) I'm reading the last version of the OpenGL Programming guide and it is updated for OpenGL 4.3.
The first code they go through is a really simple code to make 2 triangles and of course it is the code I use to test OpenGL on my latop (running kubuntu).
The code runs but this is what happens :
X Error of failed request: GLXBadFBConfig
Major opcode of failed request: 153 (GLX)
Minor opcode of failed request: 34 ()
Serial number of failed request: 34
Current serial number in output stream: 33
RUN FINISHED; exit value 1; real time: 200ms; user: 0ms; system: 0ms
I saw that can happend if you don't have a graphic card that can handel the version of OpenGL you are using.
But on my laptop I have a NVidia 555m so according to the nvidia website I'm good on that side but since I run ubuntu and NVidia are not really good with their drivers I'm sure not that my NVidia-current with bumblebee works for OpenGL 4.3.
How can I check the version supported by my setup ?
Is there anyway for me to make it work or do I need to install Windows :/ ?
A: glxinfo is your friend. It's a command line tool which will report the version numbers and extensions supported for server side GLX, client side GLX, and OpenGL itself.
Do you have the NVIDIA binary (proprietary) driver installed? You'll need it if you want to take advantage of OpenGL versions 3 or 4. Like every software product there are occasional glitches, but over the years I think most 3D programmers / users would agree that the NVIDIA drivers for Linux have been very solid, much better than the alternatives.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17318392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery hyperlinks open a link before my onclick event In my popup page, I have a link with properties:
id="myLink" href="http://..." target="_blank"
when user click the link, it should open the link as default event and then close the popup window.
I have following jquery code in the popup page to close popup window.
$('#myLink').click(function() {
ClosePopupOverlay();
});
Now it works fine in IE, but in firefox and Chrome, it just close the popup window, doesn't open the link at all.
Can we not prevent default event and add custom code in jquery in all browsers? Any ideas on how to fix this issue?
Thanks a lot for any help!
A: Have a look at this thread: event.stopPropagation() not working in chrome with jQuery 1.7
I helped him solve this exact issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8054960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bootstrap CSS transition onhover Hi I'm trying to replicate the beautiful CSS transition dropdown menu onhover of devdojo.com (https://devdojo.com/ebook/laravelsurvivalguide) but can't replicate it. It is the onhover of the 3 dots in the main menu. Maybe I'm missing something? Thanks!
My CSS:
.dropdown-menu-animated {
border: 0 none;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
display: block;
margin-top: 0;
opacity: 0;
transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
transform-origin: 100% 0 0;
transition-delay: 0s, 0s, 0.5s;
transition-duration: 0.5s, 0.5s, 0s;
transition-property: opacity, transform, visibility;
transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
visibility: hidden;
}
.dropdown-menu {
background-clip: padding-box;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
display: none;
float: left;
font-size: 14px;
left: 0;
list-style: outside none none;
margin: 2px 0 0;
min-width: 160px;
padding: 5px 0;
position: absolute;
top: 100%;
z-index: 1000;
}
.open > .dropdown-menu-animated {
visibility: visible;
opacity: 1;
transition: opacity .5s, -webkit-transform .5s;
transition: opacity .5s, transform .5s;
transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
-webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
}
My HTML:
<div id="bs-example-navbar-collapse-1" class="collapse navbar-collapse right">
<ul class="nav navbar-nav navbar-left">
<li class="dropdown">
<a class=" dropdown-toggle" href="#_" data-toggle="dropdown">
HOVER ME
</a>
<ul class="dropdown-menu dropdown-menu-animated" role="menu">
<li>
<a href="/points">Sushi Points</a>
</li>
<li><a href="/points">Two</a></li>
</ul>
</li>
</ul>
</div>
Thanks @chiller .
Updated and edited answer:
JS
$('.dropdown-toggle').hover(function() {
$(this).parent().addClass("open");
});
$('.dropdown').mouseleave(function() {
$(this).removeClass("open");
});
CSS
.dropdown-menu li a {
color: white;
}
.dropdown-menu-animated {
border: 0 none;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
display: block;
margin-top: 0;
opacity: 0;
transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
transform-origin: 100% 0 0;
transition-delay: 0s, 0s, 0.5s;
transition-duration: 0.5s, 0.5s, 0s;
transition-property: opacity, transform, visibility;
transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
visibility: hidden;
}
.dropdown-menu {
background-clip: padding-box;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.176);
/*display: none;*/
float: left;
font-size: 14px;
left: 0;
list-style: outside none none;
margin: 2px 0 0;
min-width: 160px;
padding: 5px 0;
position: absolute;
top: 100%;
z-index: 1000;
}
.open > .dropdown-menu-animated {
visibility: visible;
opacity: 1;
transition: opacity .5s, -webkit-transform .5s;
transition: opacity .5s, transform .5s;
transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
-webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
}
HTML
<div id="bs-example-navbar-collapse-1" class="collapse navbar-collapse right">
<ul class="nav navbar-nav navbar-left">
<li class="dropdown">
<a class="dropdown-toggle" href="#_" data-toggle="dropdown">
HOVER ME
</a>
<ul class="dropdown-menu dropdown-menu-animated" role="menu" style="color:white;background:black;">
<li><a href="#">Bulanching</a></li>
<li><a href="#">Kuya Matmat</a></li>
<li><a href="#">Baby</a></li>
<li><a href="#">Wedding</a></li>
<li><a href="#">Excited</a></li>
</ul>
</li>
</ul>
</div>
A: this actually done with JavaScript and all you have to do is add this jquery code in your script
$('.dropdown-toggle').hover(function() {
$(this).parent().addClass("open");
});
$('.dropdown').mouseleave(function() {
$(this).removeClass("open");
});
and you have to remove display: none; from the class .dropdown-menu for the animation to work
see your example here
you can also make it work with CSS only by adding this code:
.dropdown:hover>.dropdown-menu-animated{
visibility: visible;
opacity: 1;
transition: opacity .5s, -webkit-transform .5s;
transition: opacity .5s, transform .5s;
transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);
-webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
}
See your example with CSS only
A: The following snippet solves your styling issue for the :hover appearance.
Add your transition effect in the .dropdown .dropdown-menu-animated rules and there you go ;)
.dropdown {
float: left;
cursor: pointer;
}
.dropdown .dropdown-menu-animated {
border: 0 none;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
margin-top: 20px;
transform: scale3d(0.95, 0.95, 1) translate3d(0px, -15px, 0px);
transform-origin: 100% 0 0;
transition-delay: 0s, 0s, 0.5s;
transition-duration: 0.5s, 0.5s, 0s;
transition-property: opacity, transform, visibility;
transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);
visibility: hidden;
}
.dropdown:hover .dropdown-menu-animated {
visibility: visible;
}
<div id="bs-example-navbar-collapse-1" class="collapse navbar-collapse right">
<ul class="nav navbar-nav navbar-left">
<li class="dropdown">
HOVER ME
<ul class="dropdown-menu-animated" role="menu">
<li>
<a href="/points">Sushi Points</a>
</li>
<li><a href="/points">Two</a></li>
</ul>
</li>
</ul>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40704000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Safe truncate string contains color tag I have a string which contains color tags.
var myString = "My name is <color=#FF00EE>ABCDE</color> and I love <color=#FFEE00>music</color>";
My string becomes "My name is ABCDE*(pink)* and I love music*(yellow)*"
I want to truncate if the string reaches max length but still keep color tag
var myTruncateString = "My name is <color=#FF00EE>ABCDE</color> and I love <color=#FFEE00>mu</color>";
My string becomes "My name is ABCDE*(pink)* and I love mu*(yellow)*"
Do you have any suggestion?
var stringWithoutFormat = String.Copy(myString);
stringWithoutFormat = Regex.Replace(stringWithoutFormat, "<color.*?>|</color>", "");
var maxLength = 20;
if (stringWithoutFormat.Length > maxLength)
{
// What should I do next?
}
A: Here's a relatively simply and NOT error-handling example of what I think you're trying to accomplish:
*
*Don't count color tags when checking maximum length
*Remove characters from the end, don't destroy color tags
*If you end up with color tags with no text between them, remove those tags
Note: This code is not thoroughly tested. Feel free to use it for whatever you want, but I would write a lot of unit-tests here. In particular I'm scared about the existance of edge-cases that lead to an infinite loop.
public static string Shorten(string input, int requiredLength)
{
var tokens = Tokenize(input).ToList();
int current = tokens.Count - 1;
// assumption: color tags doesn't contribute to *visible* length
var totalLength = tokens.Where(t => t.Length == 1).Count();
while (totalLength > requiredLength && current >= 0)
{
// infinite-loop detection
if (lastCurrent == current && lastTotalLength == totalLength)
throw new InvalidOperationException("Infinite loop detected");
lastCurrent = current;
lastTotalLength = totalLength;
if (tokens[current].Length > 1)
{
if (current == 0)
return "";
if (tokens[current].StartsWith("</") && tokens[current - 1].StartsWith("<c"))
{
// Remove a <color></color> pair with no text between
tokens.RemoveAt(current);
tokens.RemoveAt(current - 1);
current -= 2;
// Since color tags doesn't contribute to length, don't adjust totalLength
continue;
}
// Remove one character from inside the color tags
tokens.RemoveAt(current - 1);
current--;
totalLength--;
}
else
{
// Remove last character from string
tokens.RemoveAt(current);
current--;
totalLength--;
}
}
// If we're now at the right length, but the last two tokens are <color></color>, remove them
if (tokens.Count >= 2 && tokens.Last().StartsWith("</") && tokens[tokens.Count - 2].StartsWith("<c"))
{
tokens.RemoveAt(tokens.Count - 1);
tokens.RemoveAt(tokens.Count - 1);
}
return string.Join("", tokens);
}
public static IEnumerable<string> Tokenize(string input)
{
int index = 0;
while (index < input.Length)
{
if (input[index] == '<')
{
int endIndex = index;
while (endIndex < input.Length && input[endIndex] != '>')
endIndex++;
if (endIndex < input.Length)
endIndex++;
yield return input.Substring(index, endIndex - index);
index = endIndex;
}
else
{
yield return input.Substring(index, 1);
index++;
}
}
}
Example code:
var myString = "My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>";
for (int length = 1; length < 100; length++)
Console.WriteLine($"{length}: {Shorten(myString, length)}");
Output:
1: M
2: My
3: My
4: My n
5: My na
6: My nam
7: My name
8: My name
9: My name i
10: My name is
11: My name is
12: My name is <color=#ff00ee>A</color>
13: My name is <color=#ff00ee>AB</color>
14: My name is <color=#ff00ee>ABC</color>
15: My name is <color=#ff00ee>ABCD</color>
16: My name is <color=#ff00ee>ABCDE</color>
17: My name is <color=#ff00ee>ABCDE</color>
18: My name is <color=#ff00ee>ABCDE</color> a
19: My name is <color=#ff00ee>ABCDE</color> an
20: My name is <color=#ff00ee>ABCDE</color> and
21: My name is <color=#ff00ee>ABCDE</color> and
22: My name is <color=#ff00ee>ABCDE</color> and I
23: My name is <color=#ff00ee>ABCDE</color> and I
24: My name is <color=#ff00ee>ABCDE</color> and I l
25: My name is <color=#ff00ee>ABCDE</color> and I lo
26: My name is <color=#ff00ee>ABCDE</color> and I lov
27: My name is <color=#ff00ee>ABCDE</color> and I love
28: My name is <color=#ff00ee>ABCDE</color> and I love
29: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>m</color>
30: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>mu</color>
31: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>mus</color>
32: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>musi</color>
33: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
34: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
35: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
36: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
37: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
38: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
39: My name is <color=#ff00ee>ABCDE</color> and I love <color=#eeddff>music</color>
... and so on
A: I generate 2 lists :
*
*One that contains the indexes of the real text
*One that contains the staring and ending indexes of tags
Then I take the text until the max length in the first array.
Finally, I check if there was an opening tag and if so, I close it.
N.B. : My code doesn't handle nested tags. You'd have to change the closing tag part.
public static string Truncate(string text, int maxLength)
{
if (text.Length <= maxLength) return text;
var tagIndexes = new List<int>();
var realTextIndexes = new List<int>();
bool isInTag = false;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '<')
{
isInTag = true;
tagIndexes.Add(i);
}
if (!isInTag)
{
realTextIndexes.Add(i);
}
if (text[i] == '>')
{
isInTag = false;
tagIndexes.Add(i);
}
}
if (realTextIndexes.Count <= maxLength) return text;
string truncatedText = text.Substring(0, realTextIndexes[maxLength - 1] + 1);
// Should we close a tag ?
for (int i = 0; i < tagIndexes.Count; i++)
{
if (tagIndexes[i] > realTextIndexes[maxLength - 1])
{
if ((i % 4) == 2) // If the next tag is a closing tag
{
truncatedText += text.Substring(tagIndexes[i], tagIndexes[i + 1] - tagIndexes[i] + 1);
}
break;
}
}
return truncatedText;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67736547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Amazon ec2-get-console-output returns "File not found" I just set up a free instance of an Amazon ec2 server. I'm trying to figure out how to SSH into it. I downloaded the command line tools for ec2 and, following what was written at this page: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#EC2_LaunchInstance_Linux :
.ec2$ ec2-get-console-output [instance id]
File not found: ''
.ec2$
Where [instance id] refers to the id amazon lists in the list of instances I have. Can anyone tell me what's going on?
Edit: I might add it seems to be doing this for any binary I try to run from the command line tools... even if I call them directly.
A: I had the same problem until I specified the key and cert in my .bash_profile file:
export EC2_HOME=~/.ec2
export PATH=$PATH:$EC2_HOME/bin
export EC2_PRIVATE_KEY='ls $EC2_HOME/key.pem'
export EC2_CERT='ls $EC2_HOME/cert.pem'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14805973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get userId for custom action in SharePoint When implementing a List Menu Custom Action in Sharepoint 2013 I have problem getting which user has actually executed the custom action. I would like to do that to check that the user has permission to do this by checking which AD-groups the user is a member of. When I try to resolve the user with the Tokenhelper class it will only return the SharePoint system account sending the query to the Host Web. Is there any way you could attach the userId in the UrlAction parameters like below?
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="77cb35d9-1bf3-4d81-91cf-8a92473a6092.MenuItemCustomAction1"
RegistrationType="List"
RegistrationId="101"
Location="EditControlBlock"
Sequence="10001"
Title="$Resources:TogglePublic"
HostWebDialog="TRUE"
HostWebDialogHeight="250"
HostWebDialogWidth="700">
<UrlAction Url="~remoteAppUrl/CustomActionTarget.aspx?StandardTokens}&SPListItemId={ItemId}&SPListId={ListId}&SPSource={Source}&SPListURLDir={ListUrlDir}&SPItemURL={ItemUrl}&SPUserId={_spPageContextInfo.userId}" />
</CustomAction>
</Elements>
On the Host Web the following code should get the SPUserId:
public partial class CustomActionTarget : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
string userId = this.Request.QueryString["SPUserId"];
}
}
The _spPageContextInfo.userId is a javascript variable that should contain the current user, but I have not found any way to actually resolve and send the userId to the SharePoint App's Host Web using the UrlAction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34719051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Netfilter kernel module packet send I am trying to send a dummy syn packet from netfilter kernel module but i could not succeded does any body has working example or show me where i am doing the mistake
printk(KERN_ALERT "Device a");
struct sk_buff *skb = NULL;
struct iphdr *iph = NULL;
struct tcphdr *tcph = NULL;
printk(KERN_ALERT "Device index");
skb = alloc_skb(sizeof(struct iphdr) + sizeof(struct tcphdr), GFP_ATOMIC); // Allocate a new sk_buff with room for L2 header.
if (skb == NULL){
return;
}
skb->protocol = __constant_htons(ETH_P_IP); // This is an IP packet.
skb->pkt_type = PACKET_OUTGOING; // Its outgoing.
skb->ip_summed = CHECKSUM_NONE; // No need to checksum.
skb_reserve(skb, sizeof(struct iphdr) + sizeof(struct tcphdr)); // Reserve the space for the L3, and L4 headers.
tcph = (struct tcphdr *)skb_push(skb, sizeof(struct tcphdr)); // Setup pointer for the L4 header.
iph = (struct iphdr *)skb_push(skb, sizeof(struct iphdr)); // Setup pointer for the L3 header.
iph->ihl = 5; // IP header length.
iph->version = 4; // IPv4.
iph->tos = 0; // No TOS.
iph->tot_len=htons(sizeof(struct iphdr) + sizeof(struct tcphdr)); // L3 + L4 header length.
iph->id = 0; // What?
iph->frag_off = 0; // No fragmenting.
iph->ttl = 64; // Set a TTL.
iph->protocol = IPPROTO_TCP; // TCP protocol.
iph->check = 0; // No IP checksum yet.
iph->saddr = saddr; // Source IP.
iph->daddr = daddr; // Dest IP.
tcph->check = 0; // No TCP checksum yet.
tcph->source = source; // Source TCP Port.
tcph->dest = dest; // Destination TCP Port.
tcph->seq = htonl(seq - 1); // Current SEQ minus one is used for TCP keepalives.
tcph->ack_seq = htonl( ack_seq - 1); // Ummm not sure yet.
tcph->res1 = 0; // Not sure.
tcph->doff = 5; // TCP Offset. At least 5 if there are no TCP options.
tcph->fin = 0; // FIN flag.
tcph->syn = 0; // SYN flag.
tcph->rst = 0; // RST flag.
tcph->psh = 0; // PSH flag.
tcph->ack = 1; // ACK flag.
tcph->urg = 0; // URG flag.
tcph->ece = 0; // ECE flag? It should be 0.
tcph->cwr = 0; // CWR flag? It should be 0.
//ip_route_input(skb, daddr, saddr, iph->tos, netdevice); // Populate the skb->dst structure.
//ip_send_check(iph); // Calulcate an IP checksum.
//skb->dev = skb->dst->dev; // Populate skb->dev or it wont send.
//printk(KERN_ALERT "SKB device index: %u.\n",skb->dev->ifindex);
//printk(KERN_ALERT "Route device index: %u.\n",skb->dst->dev->ifindex);
printk(KERN_ALERT "Device index2");
struct net_device *dev;
read_lock(&dev_base_lock);
dev = first_net_device(&init_net);
while (dev) {
printk(KERN_INFO "found [%s]\n", dev->name);
if(dev->name=="p1p2"){printk(KERN_INFO "found [%s]\n", dev->name);break;}
dev = next_net_device(dev);
}
read_unlock(&dev_base_lock);
//NF_HOOK(PF_INET, NF_INET_LOCAL_OUT,NULL, NULL, skb, NULL, dev, dst_output);
printk(KERN_ALERT "Device index3");
return;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45971903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DICOM CINE file C#.Net I have read the first frame of a DICOM CINE image, then I want to read the second frame and so on. How much byte should I seek the file pointer to get next frame(If the frame size is width=640, height=480).
A: by DICOM cine image, you mean multi-frame DICOM files right?
May i know :
which platform you are on, which dicom lib/SDK you are using? and for your DICOM image, has it been decompressed? to BMP(32-bit/24-bit)?
If your dicom file is in 24bit(3-bytes) BMP, then your next frame of pixel data would be 640*480*3.
A: Assuming you are dealing with uncompressed (native) multi-frame DICOM. In that case, you need to extract following information before proceeding to calculate the size of each image frame.
*
*Transfer Syntax (0002, 0010) to make sure dataset set is not using
encapsulated/compressed transfer syntax.
*Sample per Pixel (0028, 0002): This represents number of samples
(planes) in this image. As for example 24-bit RGB will have value of
3
*Number of Frames (0028, 0008): total number of frames
*Rows (0028, 0010)
*Columns (0028, 0011)
*Bit Allocated (0028, 0100): Number of bits allocated for each pixel
sample.
*Planar Configuration (0028, 0006): Conditional element that indicates
whether the pixel data are sent color-by-plane or color-by-pixel.
This is required if Samples per Pixel (0028, 0002) has a value
greater than 1.
You would calculate the frame size as follows:
Frame size in bytes = Rows * Columns * (Bit Allocated* Sample per Pixel/8)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5977655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alt tag possible for inline SVG? Is there a way to give an inline SVG an alt tag? Here is the code that I have for my inline SVG, but the alt tag is not showing (and I'm not even sure the way that I coded the alt tag is valid, after searching online for clarification):
<svg version="1.1" id="svg-header-filter" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="27px" height="27px" viewBox="0 0 37 37" enable-background="new 0 0 37 37" xml:space="preserve" alt="Hello world!">
<path class="header-filter-circle" d="M17.796,0C7.947,0,0,7.988,0,17.838s7.947,17.787,17.796,17.787c9.848,0,17.829-7.935,17.829-17.783 C35.625,7.988,27.644,0,17.796,0z"/>
<g>
<path class="header-filter-icon" fill="#FFFFFF" d="M15.062,30.263v-9.935l-8.607-8.703h22.343l-8.744,8.727v5.029L15.062,30.263z M8.755,12.625l7.291,7.389 v7.898l3.025-2.788v-5.086l7.426-7.413H8.755z"/>
</g>
</svg>
And here is the JSFiddle: http://jsfiddle.net/FsCMM
A: With <title> it works nice, the below example shows title (acts like alt for images) for more than one path:
<svg height="200pt" viewBox="0 0 200 200" width="200pt" style="background-color: var(--background);">
<g>
<title>Gray path</title>
<path fill="none" stroke="gray" stroke-width="20" d="M 179.89754857473488 95.95256479386293 A 80 80 0 0 0 100 20">
</path>
</g>
<g>
<title>Red path</title>
<path fill="none" stroke="red" stroke-width="20" d="M 91.90160519334194 179.58904448198567 A 80 80 0 0 0 179.89754857473488 95.95256479386293">
</path>
</g>
<g>
<title>Blue path</title>
<path fill="none" stroke="blue" stroke-width="20" d="M 32.111795102681654 57.67752800438377 A 80 80 0 0 0 91.90160519334194 179.58904448198567">
</path>
</g>
<g>
<title>Green path</title>
<path fill="none" stroke="green" stroke-width="20" d="M 99.99999999999999 20 A 80 80 0 0 0 32.111795102681654 57.67752800438377">
</path>
</g>
</svg>
A: You should use title element, not alt tag, to display tooltips:
<svg version="1.1" id="svg-header-filter" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="27px" height="27px" viewBox="0 0 37 37" enable-background="new 0 0 37 37" xml:space="preserve">
<title>Hello world!</title>
<path class="header-filter-circle" d="M17.796,0C7.947,0,0,7.988,0,17.838s7.947,17.787,17.796,17.787c9.848,0,17.829-7.935,17.829-17.783 C35.625,7.988,27.644,0,17.796,0z"/>
<g>
<path class="header-filter-icon" fill="#FFFFFF" d="M15.062,30.263v-9.935l-8.607-8.703h22.343l-8.744,8.727v5.029L15.062,30.263z M8.755,12.625l7.291,7.389 v7.898l3.025-2.788v-5.086l7.426-7.413H8.755z"/>
</g>
</svg>
for chrome34: wrap graphics by g element and insert title element to this.
<svg version="1.1" id="svg-header-filter" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="27px" height="27px" viewBox="0 0 37 37" enable-background="new 0 0 37 37" xml:space="preserve">
<g>
<title>Hello world!</title>
<path class="header-filter-circle" d="M17.796,0C7.947,0,0,7.988,0,17.838s7.947,17.787,17.796,17.787c9.848,0,17.829-7.935,17.829-17.783 C35.625,7.988,27.644,0,17.796,0z"/>
<g>
<path class="header-filter-icon" fill="#FFFFFF" d="M15.062,30.263v-9.935l-8.607-8.703h22.343l-8.744,8.727v5.029L15.062,30.263z M8.755,12.625l7.291,7.389 v7.898l3.025-2.788v-5.086l7.426-7.413H8.755z"/>
</g>
</g>
</svg>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23146570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Fast associative arrays or maps in Matlab I need to build a fast one-to-one mapping between two large arrays of integers in Matlab. The mapping should take as input an element from a pre-defined array, e.g.:
in_range = [-200 2 56 45 ... ];
and map it, by its index in the previous array, to the corresponding element from another pre-defined array, e.g.:
out_range = [-10000 0 97 600 ... ];
For example, in the case above, my_map(-200) should output -10000, and my_map(45) should output 600.
I need a solution that
*
*Can map very large arrays (~100K elements) relatively efficiently.
*Scales well with the bounds of in_range and out_range (i.e. their min and max values)
So far, I have solved this problem using Matlab's external interface to Java with Java's HashMaps, but I was wondering if there was a Matlab-native alternative.
Thanks!
A: The latest versions of Matlab have hashes. I'm using 2007b and they aren't available, so I use structs whenever I need a hash. Just convert the integers to valid field names with genvarname.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4754181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can't upload images to WordPress I am trying to upload images via the dashboard but it gives me the following error,
Unable to create directory uploads/2015/03. Is its parent directory writable by the server?
I read forum posts online which guided to change the folder permissions to 777. I did so but the error is still there. Please guide me. Thanks.
Note: I have also updated to the latest version of WordPress but that does not solve the problem.
A: Many of the people face this problem this is just a permission Issue
Follow Below Step
1)Open Ftp by filezilla or any ftp client
2)Right Click on Wp_contnet Folder
3) Change Permissions From 755 TO 777(Please Make Sure That 777 permission to all in side folder's under wp_content)
4) Than Try to Upload File Agin and its'done
A: If you checked the permission then try this solution :
Please login to the wordpress dashboard ( http://www.domainname.com/wp-admin ) and access the Miscellaneous settings. Find the uploads path specified, it will most likely be specified as:
"/wp-content/uploads/
Change it to read
"wp-content/uploads/
A: change your wp-content folder's writing permission
Step 1: Open your File Manager and navigate to the file or folder that you need to change.
Step 2: Click on the name of the file or folder.
Step 3: Click on the Change Permissions link in the top menu of the File Manager page.
Step 4: Click on as many check boxes as you require to create the right permission. The permission numbers underneath the check boxes will update automatically.
Step 5: Click on the Change Permissions button when you are ready. The new permission level is saved and the display updated to show the modified file.
A: Some time when you upload image so this issue arise just try to change permission level to 744 but select only for directories and try to change the permission level to 644 this time for files hope this will works for you .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29344200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Thread-safe classes explanation in Java Let's consider this situation:
public class A {
private Vector<B> v = new Vector<B>();
}
public class B {
private HashSet<C> hs = new HashSet<C>();
}
public class C {
private String sameString;
public void setSameString(String s){
this.sameString = s;
}
}
My questions are:
*
*Vector is thread-safe so when a thread calls over it, for instance, the get(int index)method Is this thread the only owner ofHashSeths?
*If a thread call get(int index) over v and it obtains one B object. Then this thread obtains a C object and invoke setSameString(String s) method, is this write thread-safe? Or mechanism such as Lock are needed?
A: First of all, take a look at this SO on reasons not to use Vector. That being said:
1) Vector locks on every operation. That means it only allows one thread at a time to call any of its operations (get,set,add,etc.). There is nothing preventing multiple threads from modifying Bs or their members because they can obtain a reference to them at different times. The only guarantee with Vector (or classes that have similar synchronization policies) is that no two threads can concurrently modify the vector and thus get into a race condition (which could throw ConcurrentModificationException and/or lead to undefined behavior);
2) As above, there is nothing preventing multiple threads to access Cs at the same time because they can obtain a reference to them at different times.
If you need to protect the state of an object, you need to do it as close to the state as possible. Java has no concept of a thread owning an object. So in your case, if you want to prevent many threads from calling setSameString concurrently, you need to declare the method synchronized.
I recommend the excellent book by Brian Goetz on concurrency for more on the topic.
A: In case 2. It's not thread-safe because multiple threads could visit the data at the same time. Consider using read-write lock if you want to achieve better performance. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html#readLock()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27933934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using testthat with more than one expected outcome I wish to check an R function that may output one of two acceptable values using the "testthat" package. Here's a simplified example:
Foo <- function () {
if (uncontrolable_condition) {
matrix(as.raw(0x0c))
} else {
matrix(as.raw(0x03))
}
}
The best solution I could come up with is
result <- Foo()
expect_true(identical(result, matrix(as.raw(0x0c))) ||
identical(result, matrix(as.raw(0x03))))
But this loses the functionality of waldo::compare: if I fail the test,
I have to manually run waldo::compare(Foo(), matrix(as.raw(0x0c))) to see how the output differs from the expectation.
A: I think you're going to need a custom expectation. Based on the testthat pkgdown site, it might look something like this:
expect_options <- function(object, options) {
# 1. Capture object and label
act <- quasi_label(rlang::enquo(object), arg = "object")
# 2. Call expect()
compResults <- purrr::map_lgl(options, ~identical(act$val, .x))
expect(
any(compResults),
sprintf(
"Input (%s) is not one of the accepted options: %s",
toString(act$val),
paste(purrr::map_chr(options, toString), collapse = ", ")
)
)
# 3. Invisibly return the value
invisible(act$val)
}
expect_options(result, list(matrix(as.raw(0x0c)), matrix(as.raw(0x03))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71082379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to uniquely identify email addresses, phones, etc. with Microsoft Graph API? Trying to set up a 2-way sync with Graph contacts. When I receive a response from Graph for a specific contact I can't seem to find a way to uniquely identify the phone/email attributes.
In my use case, each email address and phone number are separate entities with a unique id identifying them. This solves for the edge case of having multiple addresses or numbers of the same type (i/e home, work, school, mobile).
In a perfect world, I would like to be able to send metadata along with each phone/email entity that uniquely identifies it on creation in Graph. That way when I set up a subscription or even query the contact, I can directly map the returned contact objects phone/email to our specific phone/email.
Is this possible? I know Google has ids that solve for this.
A: Outlook Contacts are structured a little differently than Google Contacts. Rather than having a single gd:phoneNumber property with distinct rel values, Outlook uses distinct phone number properties.
It's also important to keep in mind that some phone number properties are collections rather than single values (i.e. homePhones). These collections are ordered so these collections can be maps back to Outlook's UI pretty easily. For example, homePhones[0] holds the "Home Phone" value while homePhones[1] holes "Home Phone 2".
In terms of a 1:1 mapping:
*
*http://schemas.google.com/g/2005#home == homePhones[0]
*http://schemas.google.com/g/2005#work == businessPhones[0]
*http://schemas.google.com/g/2005#mobile == mobilePhone
Finally, Microsoft Graph only returns a limited set of phone numbers by default. In my experience, the set returned by Graph is almost always sufficient but there are certainly some edge cases (the healthcare sector still makes use of pagers for example).
You can access these additional phone numbers using Extended Properties. This is done by requesting specifically requesting a given property using the MAPI tag name.
For example, if you need to retrieve the Pager property, you can request the MAPI identifier 0x3A21 as an extended property:
/v1.0/me/contacts?$expand=singleValueExtendedProperties($filter=id eq 'String 0x3A21')
You can find the complete list of MAPI properties here.
A: "homePhones": [],
"mobilePhone": "124124124124",
"businessPhones": [
"+86 (510) 12114142"
],
"spouseName": null,
"personalNotes": "",
"children": [],
"emailAddresses": [
{
"name": "Charles Test([email protected])",
"address": "[email protected]"
}
],
"homeAddress": {},
"businessAddress": {
"city": "Wuxi"
},
"otherAddress": {}
As you know, the phone reference is not unique, user can share same phone number, so it cannot be used as uniquely identify in all MS Authentication API, unless the phone reference is user's id. So it is not possible for your perfect world.
For the same reason, user can share the same address reference, so it is cannot be used as uniquely identify in all MS Authentication API. So it is not possible for your perfect world too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52107136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to extract a variable sub-string from a string I want to extract a sub-string from a string using javascript, then replace as set of characters by another character.
I know the prefix and postfix of the string. Between the prefix and postfix is the variable sub-string that I want to extract and replace set of characters on it.
For example, this string represents error URL. I need to extract the URL from it which in this example is: https%3A//revoked.badssl.com/ then replace %3A with :
The logic is that, the prefix is: about:neterror?e=nssFailure2&u= and the postfix is &c=UTF* as I do not care about the rest of the string after the & character.
I probably need to use Regex. However, I know how to use Regex to compare whether a string matches a specific pattern or not. But I wonder how to use Regex to extract a sub-string?
about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&
f=regular d=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.
%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code
%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE
%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A
EDIT:
When I try this script:
var myString="about:neterror?e=nssFailure2&u=https%3A//abcde.somethig/&c=UTF-8&f=regular&d=An%20error%20occurred%20during%20a%20connection%20to%20abcde.somethig.\
%0A%0ACannot%20communicate%20securely%20with%20peer%3A%20no%20common%20encryption%20algorithm%28s%29.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20\
title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A";
console.log(myString.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&c=UTF8.*$/, "$1:$2"));
NOTE: I used \ at the end of the line just to break the string in the editor. But it is not part of the original string.
I get output identical to the input.
NOTE2:
What about if I want to just use & as mark of strat for the postfix? I used console.log(myString.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&.*$/, "$1:$2")); but it prints: https://abcde.somethig/&c=UTF-8&f=regular and I want: https://abcde.somethig/
A: Simplest I can think of without using some complex regex and assuming the &c and &u are static, is this - first decoding the string as suggested by Jedi
var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"
var url = decodeURIComponent(str).split("&u=")[1].split("&c")[0];
console.log(url)
And here is why I close as duplicate:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"
var url = getParameterByName("u",str);
console.log(url);
A: What you are trying to do is to retrieve a query parameter from a URL, and then decode it. For this, you should use libraries build for the purpose, not regexp. For example, many regexp approaches will depend on the precise order of the query params, which is something you cannot really (or should not) rely on.
Here's an example using the URL API, which is stable and widely supported (other than IE11, and a bug in Firefox for non-http-type URLs such as about:neterror currently in the process of being fixed):
var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A";
var url = new URL(str);
console.log(url.searchParams.get('u'));
A: You can capture the sub string you need and then use back reference to extract and reformat it:
var s = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regular d=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"
var url = s.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&c=UTF[\s\S]*$/, "$1:$2")
console.log(url)
Using decodeURIComponent:
var s = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regular d=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"
var url = decodeURIComponent(s).replace(/^about:neterror\?e=nssFailure2&u=(.*)&c=UTF[\s\S]*$/, "$1")
console.log(url)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44872776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I create separate endpoint for public user and current user in rails api I am building a rails api with a User model. My app will have a public profile for every user with basic attributes like username, avatar and bio. When you are logged in and you visit your profile, you see more information like which email newsletters you are subscribed to and private app data.
Which way should I implement it in my API:
*
*Should I have one GET user/:id endpoint? If the user is not authorized (if they are not requesting their own data) then they receive the basic attributes back. If they are authorized (requesting their own user data) they will receive a response with the private app data.
Is it bad to have an endpoint that returns different properties based on the authorization?
*Should I have both a GET /user/:id endpoint which does not require authentication or authorization and only responds with basic info AND a GET /profile endpoint which responds only with the current users private app data?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65727281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: java.io.FileNotFoundException: /jacoco.exec: open failed: EROFS (Read-only file system) Facing this problem while trying to implement JaCoCo Offline Instrumentation.
W/System.err( 1733): java.io.FileNotFoundException: /jacoco.exec: open failed: EROFS (Read-only file system)
W/System.err( 1733): at libcore.io.IoBridge.open(IoBridge.java:456)
W/System.err( 1733): at java.io.FileOutputStream.<init>(FileOutputStream.java:89)
--
W/System.err( 1733): at libcore.io.IoBridge.open(IoBridge.java:456)
W/System.err( 1733): at java.io.FileOutputStream.<init>(FileOutputStream.java:89)
W/System.err( 1733): at org.jacoco.agent.rt.internal_14f7ee5.output.FileOutput.openFile(FileOutput.java:67)
W/System.err( 1733): at org.jacoco.agent.rt.internal_14f7ee5.output.FileOutput.startup(FileOutput.java:49)
W/System.err( 1733): at org.jacoco.agent.rt.internal_14f7ee5.Agent.startup(Agent.java:122)
W/System.err( 1733): at org.jacoco.agent.rt.internal_14f7ee5.Agent.getInstance(Agent.java:50)
W/System.err( 1733): at org.jacoco.agent.rt.internal_14f7ee5.Offline.<clinit>(Offline.java:31)
A: The solution is well-documented in jacoco but for Android people, what you need is to add the file in /src/androidTest/resources/jacoco-agent.properties with the contents output=none so jacoco can startup without failing, and coverage will be written as normal and transferred correctly later by the android gradle plugin coverage implementation.
A: I think it's safe to ignore that offline instrumentation warning, because the path should be something alike: executionData = files("${project.buildDir}/jacoco/${testTaskName}.exec") (on the PC - so there is no need to save it on the device and then pull the file).
On Android this will add the JaCoCo agent into the APK:
buildTypes {
debug {
testCoverageEnabled = true
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56115583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to read and write to ElasticSearch with SparkR? Begineer SparkR and ElasticSearch question here!
How do I write a sparkR dataframe or RDD to ElasticSearch with multiple nodes?
There exists a specific R package for elastic but says nothing about hadoop or distributed dataframes. When I try to use it I get the following errors:
install.packages("elastic", repos = "http://cran.us.r-project.org")
library(elastic)
df <- read.json('/hadoop/file/location')
connect(es_port = 9200, es_host = 'https://hostname.dev.company.com', es_user = 'username', es_pwd = 'password')
docs_bulk(df)
Error: no 'docs_bulk' method for class SparkDataFrame
If this were pyspark, I would use the rdd.saveAsNewAPIHadoopFile() function as shown here, but I can't find any information about it in sparkR from googling. ElasticSearch also has good documentation, but only for Scala and Java
I'm sure there is something obvious I am missing; any guidance appreciated!
A: to connect your SparkR session to Elasticsearch you need to make the connector jar and your ES configuration available to your SparkR session.
1: specifiy the jar (look up which version you need in the elasticsearch documentation; the below version is for spark 2.x, scala 2.11 and ES 6.8.0)
sparkPackages <- "org.elasticsearch:elasticsearch-spark-20_2.11:6.8.0"
2: specify your cluster config in your SparkConfig. You can add other Elasticsearch config here, too (and, of course, additional spark configs)
sparkConfig <- list(es.nodes = "your_comma-separated_es_nodes",
es.port = "9200")
*initiate a sparkR session
sparkR.session(master="your_spark_master",
sparkPackages=sparkPackages,
sparkConfig=sparkConfig)
*do some magic that results in a sparkDataframe you want to save to ES
*write your dataframe to ES:
write.df(yourSparkDF, source="org.elasticsearch.spark.sql",
path= "your_ES_index_path"
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49141042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Validation Question I get the following error when using the w3c validator why?
Line 54, Column 9: No li element in list scope but a li end tag seen.
</li><!-- LI Close -->
Code
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $name; ?> : Nationwide Housemovers</title>
<link href="<?php echo base_url()?>includes/css/adminstyle.css" rel="stylesheet" type="text/css" media="screen" />
<link href='http://fonts.googleapis.com/css?family=Josefin+Slab' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="<?php echo base_url() ?>includes/js/ckedit/ckeditor.js"></script>
</head>
<body>
<div id ="wrapper">
<div id="header">
<h1 id="companyName">Housemovers Ltd </h1>
<h4 id="companyQuote">""</h4>
</div>
<div id ="leftCol">
<nav>
<ul>
<?php if($this->session->userdata('logged_in')): ?>
<li><?php echo anchor('admin/dashboard', 'Dashboard');?></li>
<li><a>Edit Pages</a>
<?php if(is_array($cms_pages)): ?>
<ul>
<?php foreach($cms_pages as $page): ?>
<li><a href="<?=base_url();?>admin/editpage/index/<?= $page->id ?>/<?php echo url_title($page->name,'dash', TRUE); ?>"><?=$page->name?></a></li>
<?php endforeach; ?>
</ul> <!-- UL Close -->
<?php endif; ?>
</li> <!-- Edit Close -->
<li><a>Gallery</a>
<ul>
<li><?php echo anchor('admin/addimage','Add Image');?></li>
<li><?php echo anchor('admin/deleteimage','Delete Image');?></li>
</ul>
</li> <!-- Gallery Close -->
<li><a>Sales</a>
<ul>
<li><?php echo anchor('admin/addsale','Add Sale');?></li>
<li><a>Edit Sale</a>
<?php if(is_array($sales_pages)): ?>
<ul>
<?php foreach($sales_pages as $sale): ?>
<li><a href="<?=base_url();?>admin/editsale/index/<?= $sale->id ?>/<?php echo url_title($sale->name,'dash', TRUE); ?>"><?=$sale->name?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li><!-- LI Edit Sale Close -->
</li><!-- LI Close -->
<li><?php echo anchor('#','Delete Sale');?></li>
</ul><!-- UL Close -->
<li><?php echo anchor('admin/home/logout','Log Out');?></li>
<?php else: ?>
<?php redirect('admin/home'); ?>
<?php endif; ?>
</ul>
</nav>
</div><!--leftCol End -->
<section id="content">
<?=$content?>
</section>
<footer>
<p>© Houses LTD <?php echo date('Y');?></p>
</footer>
</div>
</body>
</html>
A: There's an extra </li>
<li><a>Edit Sale</a>
<?php if(is_array($sales_pages)): ?>
<ul>
<?php foreach($sales_pages as $sale): ?>
<li>
<a href="<?=base_url();?>admin/editsale/index/<?= $sale->id ?>/<?php echo url_title($sale->name,'dash', TRUE); ?>"><?=$sale->name?></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li><!-- LI Edit Sale Close -->
<!-- Right here you have two closing end tags for <li>-->
</li><!-- LI Close -->
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5838875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting rid of SettingWithCopyWarning in Python pandas I am loading a bunch of csvs and processing certain columns if they exist, after loading the csv with pandas
data = pd.read_csv('Test.csv', encoding = "ISO-8859-1", index_col=0)
this dataframe will be used in the example
import pandas as pd
data = pd.DataFrame({'A': [1, 2.1, 0, 4.7, 5.6, 6.8],
'B': [0, 1, 0, 0, 0, 0],
'C': [0, 0, 0, 0, 0, 1],
'D': [5, 5, 6, 5, 5.6, 6.8],
'E': [2, 4, 1, 0, 0, 5],
'F': [0, 0, 1, 0, 0, 0],
'G': [0, 0, 0, 0, 0, 0],})
Next I check and select specific columns that are going be processed
coltitles = ['A', 'B','C', 'D', 'E']
columns = []
for name in coltitles:
if name in data.columns:
columns.append(name)
else:
print (name, 'is missing')
df = data[columns]
if 'A' in df.columns:
#perform some processing, I will put print to simplify it
print ('Exist')
The code works if I use a dataframe for data, but If I load the data from a csv I get a Warning:
<module3>:74: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
The warning is caused by the line where df = data[columns].
The code still works with the warning but how do I get rid of this warning without suppressing it?
A:
The chained assignment warnings / exceptions are aiming to inform the
user of a possibly invalid assignment. There may be false positives;
situations where a chained assignment is inadvertantly reported.
The purpose of this warning is to flag to the user that the assignment is carried out on a copy of the DataFrame slice instead of the original Dataframe itself.
You generally want to use .loc (or .iloc, .at, etc.) type indexing instead of 'chained' indexing which has the potential to not always work as expected.
To make it clear you only want to assign a copy of the data (versus a view of the original slice) you can append .copy() to your request, e.g.
df = data[columns].copy()
See the documentation for more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29725890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Reassigning a React Components prop value using let I understand that a components prop value cannot be reassigned, but what if you destructure props using let and then reassign their value? I don't see any negative side effect when using this approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62518416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Show different partial in Controller#show I have 3 different partials, each representing a different step of this process: "_overview.slim", "_setup.slim", and "_submit.slim". I want to show these 3 different partials all in "show.slim" only one at a time, and one after another as the user clicks on "Go to next step". How can I accomplish this in the show action of my controller?
A: Let say in your show,have a 'Next' button to trigger the next partial.
In the 'Next' button, I can pass a param[:page1] and all the necessary param when click.
In the 'Show', if there is param[:page1] ,then display _partial1.html.erb
its goes all the same.
A: So if I were you, I would put render all three partials in your show view, and use Javascript, and CSS to manage when each one was shown. If you drop each of those partials in a div, its easy to use JQuery's hide and show methods, linked to the click event of the "Go To Next Step" button. To do it this way you wouldn't have to touch your Controller at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16086743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to publish Office add-in to Marketplace? Has anything changed about the way we publish Office.js add-in to Office Store? I'm following the documentation (which is pretty recent) and in there they ask me to go to Partner Store, then Office Store tab and choose New Offer > Office add-in:
But in my Partner Center there is no Office Store tab. There is a New Offer dropdown but it doesn't contain Office add-in option.
I hear that they have merged the two (Marketplace and Office Store), but it doesn't seem to be the case right now. Or am I looking in the wrong place?
A: Found my answer from Microsoft support guys. Office Store enrollment is still separate from Marketplace enrollment. You must be enrolled in Office Store program to see Office add-in option in the Offers dropdown.
If you've already signed up for Partner Center, you can find information about creating a Developer account for Microsoft Office Store on the following page:
https://learn.microsoft.com/en-in/azure/marketplace/open-a-developer-account#create-an-account-using-an-existing-partner-center-enrollment
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74860037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deleting of DSpace Collection fails As Administrator in DSpace 5.3 I try to remove (delete) a collection that is not needed anymore, but I get the message:
ERROR: update or delete on table "item" violates foreign key constraint "workspaceitem_item_id_fkey" on table "workspaceitem" Detail: Key (item_id)=(70) is still referenced from table "workspaceitem".
The collection does not contain any archived document.
And although I added myself to all the workflow-steps and made me also Collection-adminstrator of this collection, I don't see any submitted item.
Is there another possibility to remove a collection?
A: I think this is due to the fact one (or more) item(s) is (are) being submitted in the collection you're trying to delete.
To check that, you can run the following PSQL query:
select workspace_item_id, item.item_id, submitter_id, handle from workspaceitem, item, handle where workspaceitem.item_id = item.item_id and handle.resource_type_id = '3' and handle.resource_id = workspaceitem.collection_id;
If the "handle" column corresponds to the handle of the collection you're trying to delete, check the submitter ID for that item. If the login as feature is enabled, you can login as that user (their IDs are listed in the "People" admin menu together with their names and emails), go to his / her submissions page, and cancel the submission. If not, you may have to contact that user to do it himself / herself.
If none of these approaches are possible, I assume it would be possible to delete the item directly from the database, but I would advise you against that approach (or at least make sure that you also remove all dependencies from all tables in the database).
Cheers,
Benoît
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37925630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creting a graphical process control panel Dear Professor Hedengren and community:
I was wondering if Gekko (or Python as a bigger entity) has any way to convert simulations into a graphical control panel.
Say we have a Combined Cycle, and we want to calculate the net efficiency by altering the process parameters, such as pressure levels, stack temperature, air/fuel ratio at the combustor...
Please find attached a sketch on what I mean with this.
This would be especially interesting for non-experienced users, for them to grasp an insight on how these parameters affect the output, without diving into the formalities of coding / Thermodynamics.
Thanks in advance for your valuable time.
Best regards,
Enrique Garcia - Spain
A: One way to create this graphical panel is through IPython widgets if you are running in a Jupyter notebook. Here is an example with Python and APM although you could just as easily create this with Gekko.
A built-in option for Gekko is the GUI interface that can be accessed with m.solve(GUI=True). There is more information on the GUI interface in the Gekko paper.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59768072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Polkadot: Weird Transaction Hash using JS API with Westend chain I’m using the Polkadot JS API to send transactions on Westend.
For that, the snippet is something like this:
const hash = await api.tx.balances
.transfer(to, amount)
.signAndSend(from, { tip, nonce: -1 })
.catch(e => {
throw e;
});
I’m getting a hash just fine and balances are being updated as expected. But the hash I get is nowhere to be found on Subscan. When I fetch the account’s history of transactions, I see a different hash there, not the one I got from executing the above function. That hash I get from querying Subscan directly (at https://westend.subscan.io/api/scan/transfers), is the correct one. It can be found on Subscan both via the API and using Subscan’s UI.
Example:
I've just sent a new transaction on Westend. I got the hash 0xdc2605ef0f21c77aa09f4e2df762a729bb2ecb5bb5602fe7a0858be2515c085c;
If I search for that hash on Subscan, it’s not there.
Now, I get the account's history of transactions and find out that my last transaction is this one:
{
"from": "5Ec2BnQhmoM7anBrXi2wvgPKBUrTDS1ELmcR3j68cgXZxCuo",
"to": "5HeRXojbvrsgk3x37haUJgxZhFZy8hvsBo9zDGsEsU8XhRRh",
"extrinsic_index": "6089109-2",
"success": true,
"hash": "0xf026f07bf8736e7b9a664d08529ef88466f5d52a7237d202560cad680865c5a5",
"block_num": 6089109,
"block_timestamp": 1623872502,
"module": "balances",
"amount": "0.000000010014",
"fee": "15700001585",
"nonce": 20,
"asset_symbol": "",
"from_account_display": {
"address": "5Ec2BnQhmoM7anBrXi2wvgPKBUrTDS1ELmcR3j68cgXZxCuo",
"display": "",
"judgements": null,
"account_index": "",
"identity": false,
"parent": null
},
"to_account_display": {
"address": "5HeRXojbvrsgk3x37haUJgxZhFZy8hvsBo9zDGsEsU8XhRRh",
"display": "",
"judgements": null,
"account_index": "",
"identity": false,
"parent": null
}
}
The hash we see there (0xf026f07bf8736e7b9a664d08529ef88466f5d52a7237d202560cad680865c5a5) is the right one. And the previous hash (0xdc2605ef0f21c77aa09f4e2df762a729bb2ecb5bb5602fe7a0858be2515c085c) is not even referenced, I have no idea what it is, nor why the function signAndSend returned it. I’m trying to fetch how many confirmations a given tx has, but I can’t, since the hash I’m getting when I make the transaction is (apparently) useless - and I'm storing on my database the hash that I get when I make the transaction.
Can anyone please shed some light here?
Thanks!
A: Found it!
The variable hash is not in hexadecimal format - well, it actually is, but not in the way the system wants it. I don't understand why, but the fact is that you have to do a hash.toHex() in order to get the right value. So, the solution is something like this:
const hash = await api.tx.balances
.transfer(to, amount)
.signAndSend(from, { tip, nonce: -1 })
.catch(e => {
throw e;
});
return hash.toHex();
It was in the docs, I didn't pay attention to it: https://polkadot.js.org/docs/api/examples/promise/make-transfer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68009452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ARM Cortex M7: can a cache clean overwrite changes made by DMA device? I am developing a driver for a DMA bus master device in the STM32H743 SoC, powered by a Cortex M7 CPU. Suppose I have two memory locations, x and y, which map to the same cache line, which is in normal, write-back cacheable memory, and suppose the following sequence of events:
*
*Start with x = x1, y = y1, cache line invalid.
*CPU reads y
*DMA device sets x = x2, in memory
*CPU sets y = y2
*CPU cleans the cache line.
After 5. completes, from the point of view of the DMA device, x = ?
I think the DMA will see x = x1, here is my reasoning:
*
*When CPU reads y in 2., the cache line gets pulled in cache. It reads x = x1, y = y1, and is marked as valid.
*The DMA then updates x in memory, but the change is not reflected in the cache line.
*When the CPU sets y = y2, the cache line is marked as dirty.
*When the CPU cleans the cache line, as it is dirty it gets written back to memory.
*When it gets written back to memory, it reads x = x1, y = y2, thus overwriting the
change made by the DMA to x.
Does that sound like a good reasoning?
A: Shortly, if I get your question right, than yes, your description is correct.
It's not very clear from question what "two memory locations, x and y".
Based on how you put them in use in description, I'd presume that it's something like 2 pointers.
int* x, y;
and "Start with x = x1, y = y1" means assigning addresses to that pointers, eg
x = (int*)(0x2000); // x = x1
y = (int*)(0x8000); // y = y1
Now to your question: "After 5. completes, from the point of view of the DMA device, x = ?"
So after step 3, x = x2, y = y1 in memory, x = x1, y == y1 in cache.
After step 4, x = x2, y = y1 in memory, x = x1, y = y2 in cache.
DMA access values of x/y pointers in memory, CPU access value of x/y pointers in cache. Because cache and memory are not in sync (cache is dirty) at that stage CPU and DMA would get different values.
And finally after step 5...
It depends. Cache controller operates by cache lines, an area of memory of some size, something like 32Bytes, 64Bytes, etc (could be bigger or smaller). So when CPU does clean/flush cache line containing some address it flushes a content of a whole cache line to memory. Whatever was in memory is overwritten.
There are basically 2 situations:
*
*x and y pointers are both in same cache line. That means values from cache would override memory and, you are correct, that x = x1, y == y2 would finish in memory and cache after that.
*x and y pointers are in different cache lines. That simple, only one variable would be affected, another cache line still is dirty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68459164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel spreadsheet: Find lowest character value and from specific cells, not specific cell range I have a range of cell {B15:G15) with the following values.
B15 B16 B17 B18 B19 B20
C D B C D F
I would like to use a formula to find the lowest value character from few specific cells (only B15, B17, B19), not from the range (B15:G15).
In the above example, the answer should be “B”.
What could be the formula, any suggestion ?
Thank you.
Regards,
w
A: Find the lowest value character in cells B15, B17 and B19 only
Input data housed in B15:B20
In D15, enter formula :
=CHAR(MIN(CODE(T(OFFSET(B14,{1,3,5},0)))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59656847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Some HTTPS connections failing in Chromium-based/IE browsers, but not Firefox Overnight, on two of my machines (Windows 10, which live on the same network but otherwise don't interact with my network), stopped loading static.twitchcdn.net and id.getmailspring.com in any Chromium-based browser and also Internet Explorer. updates.getmailspring.com appears as insecure. So far these are the only ones I've discovered and the greater internet appears to be loading just fine. My Apple/Android products appear to be unaffected.
Chrome, Edge, and Mailspring (just a NWJS mail client which I discovered was no longer working) stopped being able to load these sites. Issue persists in incognito/private mode (extensions disabled).
The weird part is that Firefox continues to load websites just fine.
My understanding is that Chromium browsers and IE both use Windows-built in certificates to validate connections, but Firefox carries its own certificate store so I believe the issue could be certificate related.
Weirder, enabling a VPN (external IP still within the US) resolves the issue in all browsers and both machines. Any insight as to specifically what might be happening?
My DNS servers are 1.1.1.1 (as primary) and 8.8.8.8 (as secondary) if it matters.
Btw in case this might matter: My ISP is AT&T and I live in Texas. And tomorrow we have a major election day. Although I would be very surprised if this mattered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74358093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: App with data at launch I'm currently working on an app which needs data. Exemple: A list of books. What is the best way to create a data base pre populated at first launch ?
Or do we need to populate a core data base at its first launch ?
Thanks in advance for your help :)
A: You can store the "seed data" any way you like, text files, plists etc. and even in a database (presumably sqlite).
Then when starting up your app, check if the data already exists in your core data store. If not, import the file into your database.
You could also have a preconfigured database and copy that to the application documents directory to make it writable. This is a somewhat more involved approach, as you will have to regenerate this seed database each time your seed data or model changes.
A: In my apps I have a DB which I only use to read from (no writing), I include it in my bundle that is distributed. I then update the AppDelegate->persistentStoreCoordinator method to point to the correct location for my DB.
If I needed to write to the DB, then I would need to move it to the Documents directory prior to accessing it. And the changes to AppDelegate->persistentStoreCoordinator would not be needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11951619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add a Path, that has been defined in the XAML ResourceDictionary, multiple times to a WPF form at runtime? I have a defined path in XAML:
<UserControl.Resources>
<ResourceDictionary>
<Path x:Key="N44" Width="20" Height="80" Stretch="Fill" Fill="#FF000000" Data="M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z "/>
</ResourceDictionary>
</UserControl.Resources>
I want to add it to a WPF Gird & doing it once like this works:
System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
aPath = (System.Windows.Shapes.Path)this.Resources["N44"];
LayoutRoot.Children.Add(aPath);
However if I add this code on a button click event and then click the button twice, an error is thrown stating
"Specified Visual is already a child
of another Visual or the root of a
CompositionTarget."
I then attempted to create two instances of the resource but I have continued to receive the same error. Below is the code that I used for this test:
private void cmbTest_Click(object sender, System.Windows.RoutedEventArgs e)
{
System.Windows.Shapes.Path aPath = new System.Windows.Shapes.Path();
aPath = (System.Windows.Shapes.Path)this.Resources["N44"];
if (LayoutRoot.Children.Contains(aPath) == true){
System.Windows.Shapes.Path bPath = (System.Windows.Shapes.Path)this.Resources["N44"];
LayoutRoot.Children.Add(bPath);
}else{
aPath.Name = "a";
aPath.Tag = "a";
LayoutRoot.Children.Add(aPath);
}
}
As such, how can I add an XAML Path, which has been defined in the ResourceDictionary, multiple times to a WPF form at runtime?
A: Just create style for Path, and apply it.
A: There's an easier, built-in way to do this.
Set x:Shared="False" on the resource. This will allow it to be reused. Then use it as many times as you want.
<UserControl.Resources>
<ResourceDictionary>
<Path x:Shared="False" x:Key="N44" Width="20" Height="80" Stretch="Fill" Fill="#FF000000" Data="..."/>
</ResourceDictionary>
</UserControl.Resources>
A: I've since found that I had missed an important part of the documentation from MSDN:
Shareable Types and UIElement Types:
A resource dictionary is a technique for
defining shareable types and values of
these types in XAML. Not all types or
values are suitable for usage from a
ResourceDictionary. For more
information on which types are
considered shareable in Silverlight,
see Resource Dictionaries.
In particular, all UIElement derived
types are not shareable unless they
come from templates and application of
a template on a specific control
instance. Excluding the template case,
a UIElement is expected to only exist
in one place in an object tree once
instantiated, and having a UIElement
be shareable would potentially violate
this principle.
Which I will summarise as, that's not the way it works because it’s not creating a new instance each time I execute that code – it’s only creating a reference to the object – which is why it works once but not multiple times.
So after a bit more reading I’ve come up with 3 potential ways for a resolution to my problem.
1) Use a technique to create a deep copy to a new object. Example from other StackOverflow Question - Deep cloning objects
2) Store the XAML in strings within the application and then use the XAML reader to create instances of the Paths:
System.Windows.Shapes.Path newPath = (System.Windows.Shapes.Path)System.Windows.Markup.XamlReader.Parse("<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Width='20' Height='80' Stretch='Fill' Fill='#FF000000' Data='M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z ' HorizontalAlignment='Left' VerticalAlignment='Top' Margin='140,60,0,0'/>");
LayoutRoot.Children.Add(newPath);
3) Only store the Path data in the Resource Dictionary. Create a new instance of a Path in code, apply the Path data to the new Path and then add the other properties I am interested in manually.
The XAML - The Path data is stored as a StreamGeometry:
<UserControl.Resources>
<ResourceDictionary>
<StreamGeometry x:Key="N44">M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z</StreamGeometry>
</ResourceDictionary>
</UserControl.Resources>
The C# code to then create an instance and apply the other values:
System.Windows.Shapes.Path bPath = new System.Windows.Shapes.Path();
bPath.Data = (System.Windows.Media.Geometry)this.FindResource("N44");
bPath.Width = 20;
bPath.Height = 80;
bPath.VerticalAlignment = System.Windows.VerticalAlignment.Top;
bPath.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
left = left + 40;
System.Windows.Thickness thickness = new System.Windows.Thickness(left,100,0,0);
bPath.Margin = thickness;
bPath.Fill = System.Windows.Media.Brushes.Black;
LayoutRoot.Children.Add(bPath);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1377658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Unable to assign id to items fetched from firebase database I am using react and redux to make a social media app. I'm storing all the data regarding posts in the firebase realtime-database. But when I fetch it I'm unable to assign firebase name property as an id to each and every post.
This is the action responsible for fetching data from firebase.
export const FetchPostStart = () => {
return {
type: actionTypes.Fetch_Post_Start
};
};
export const FetchPostSuccess = (fetchedData) => {
return {
type: actionTypes.Fetch_Post_Success,
payload: fetchedData
}
}
export const FetchPostError = (error) => {
return {
type: actionTypes.Fetch_Post_Error,
error: error
}
}
export const FetchPost = () => {
return dispatch => {
dispatch(FetchPostStart());
axios.get('/Data.json')
.then(response => {
const fetchedData = [];
for(let key in response.data){
fetchedData.push({
...response.data[key],
id: response.data.name
});
}
dispatch(FetchPostSuccess(fetchedData));
})
.catch(error => {
dispatch(FetchPostError(error));
});
}
}
This is the reducer function
case actionTypes.Fetch_Post_Start:
return {
...state,
loading:true
}
case actionTypes.Fetch_Post_Error:
return {
...state,
loading:false
}
case actionTypes.Fetch_Post_Success:
return {
...state,
loading: false,
Data: action.payload
}
The id remains undefined.
EDIT
This is how I'm trying to store id for new posts.
These are the action functions for adding a new post and to delete a post. The firebase name property is getting set as id here. But when I try to delete a post it passes a null value instead of the id.
export const NewPostSuccess = (id, postData) => {
return {
type: actionTypes.New_Post_Success,
payload: {
data: postData,
index: id
}
}
}
export const NewPostError = (error) => {
return {
type: actionTypes.New_Post_Error,
error: error
}
}
export const NewPost = (postData) => {
return (dispatch) => {
axios.post('/Data.json', postData)
.then(response => {
dispatch(NewPostSuccess(response.data.name, postData));
})
.catch(error => {
dispatch(NewPostError(error));
})
}
}
export const DeletePostSuccess = (id) => {
return {
type: actionTypes.Delete_Post_Success,
ID: id
}
}
export const DeletePost = (ID) => {
return (dispatch) => {
axios.delete('/Data/'+ ID + '.json')
.then(response => {
console.log(response.data);
dispatch(DeletePostSuccess(ID));
})
.catch(error => {
dispatch(DeletePostError(error));
})
}
}
THis is the reducer
case actionTypes.New_Post_Success:
const {Comment, ImageUrl, Date, User} = action.payload.data;
const id = action.payload.index;
console.log(id+"Reducer function")
return {
...state,
loading: false,
Data: [
...state.Data,
{Comment, ImageUrl, Date, User},
id
],
}
case actionTypes.Delete_Post_Success:
return {
...state,
loading: false,
}
A: .then(response => {
const fetchedData = [];
for(let key in response.data){
fetchedData.push({
...response.data[key],
id: response.data[key].name //made a small change here
});
}
dispatch(FetchPostSuccess(fetchedData));
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69808868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I close open OLE dialogs I have a function that closes all the forms in the application apart from the main form
procedure CloseOpenForms(const Component: TComponent);
var
i: Integer;
begin
for i := 0 to pred(Component.ComponentCount) do
begin
CloseOpenForms(Component.Components[i]);
if Component.Components[i] is TForm then
begin
TForm(Component.Components[i]).OnCloseQuery := nil;
TForm(Component.Components[i]).Close;
end;
end;
end;
Called from the main form:
CloseOpenForms(Self);
It works fine as long as there are no active OLE dialogs (e.g. TJvObjectPickerDialog).
How can I force these non modal OLE dialogs to close?
A: JVCL passes the application handle to 'hwndParent' parameter of IDSObjectPicker.InvokeDialog, hence the dialog is owned (not like 'owner' as in VCL, but more like popup parent) by the application window. Then you can enurate windows to find out the ones owned by the application window and post them a close command.
procedure CloseOpenForms(const AComponent: TComponent);
function CloseOwnedWindows(wnd: HWND; lParam: LPARAM): BOOL; stdcall;
begin
Result := TRUE;
if (GetWindow(wnd, GW_OWNER) = HWND(lParam)) and (not IsVCLControl(wnd)) then
begin
if not IsWindowEnabled(wnd) then // has a modal dialog of its own
EnumWindows(@CloseOwnedWindows, wnd);
SendMessage(wnd, WM_CLOSE, 0, 0);
end;
end;
procedure CloseOpenFormsRecursive(const RecComponent: TComponent);
var
i: Integer;
begin
for i := 0 to pred(RecComponent.ComponentCount) do
begin
CloseOpenFormsRecursive(RecComponent.Components[i]);
if RecComponent.Components[i] is TForm then
begin
TForm(RecComponent.Components[i]).OnCloseQuery := nil;
TForm(RecComponent.Components[i]).Close;
end;
end;
end;
begin
EnumWindows(@CloseOwnedWindows, Application.Handle);
CloseOpenFormsRecursive(AComponent)
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10294392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to reference parent component data object I'm sure it's something simple but I can't figure this out.
I'm trying to reference a JSON object (or any props at this point) in the function body of a child component. I tested whether I was able to reference data in the JSON by typing out the full expression in a variable in the function body of the child component but autocomplete isn't working for any of the properties passed through props.
Note, I removed much of the structure of the JSON object to keep this post concise but it does contain more data.
My code:
Parent Component:
export default function SproutStudioSvgContainer() {
const initialCanvasDataModel = {
"data": {}
}
// const [canvasDataModel, dispatchCanvasDataModel] = useReducer(SproutReducer, initialCanvasDataModel);
// Utility: getCanvasRootNodeFromUrl()
// This will either be a userId or branchId
const [canvasRootNode, setCanvasRootNode] = useState({ nodeId: '1' });
const [windowRootNode, setWindowRootNode] = useState({ nodeId: '1' });
const [allowedBloomLevel, setAllowedBloomLevel] = useState(3);
return (
< Fragment >
<svg id='sprout-root-svg' height='100%' width='100%' viewBox='0 0 1000 1000'>
<g id='root-node-container'>
{/* Positioned by default to the bottom-center of the SVG canvas. */}
<g id='root-sprout-node'>
<RootContainer myData={initialCanvasDataModel} />
</g>
</g>
</svg>
</Fragment >
)
}
Child component:
const RootContainer = (props) => {
let s = props.myData
console.log(s) // returns JSON data but doesn't autocomplete any properties in the JSON
console.log(props) // returns props passed, but doesn't autocomplete any of them.
return (
<Fragment>
{/* <RootNode
// title={rootNodeTitle} nodeId={props.nodeId}
nodeType='root'
x={props.initialCanvasDataModel}
y={props.y}
height={props.height}
width={props.width}
/> */}
{/* <CollectionNodeContainer branchId={props.branchId} /> */}
{/* <SubBranchesContainer
parentNodeId={props.nodeId}
canvasDataModel={props.canvasDataModel}
/> */}
</Fragment>
)
}
export default RootContainer;
A: This is because that a type has not been attached to the object. If you create a type and attach it it should work. The type in your case could be:
type myType = {
data: object
}
And the object you are using as props needs to be declared to be this type:
const initialCanvasDataModel: myType = {
And then you can extend the type when there are more children. For this to work i do not believe you can use props, but you can get the props like this:
const RootContainer = ({myData}: {myData: myType}) => {
Now you should be able to use autocomplete as normal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75245563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails 5 Paperclip Save Image from URL I'm a total Rails newbie so apologies if this is a simple question, but I've been unable to find a clear answer. I'm trying to allow a user to attach an image to a post either by uploading a file or entering the URL of an image using the Paperclip gem.
File upload works fine, but using the URL method I receive a 'No handler defined' error
link.rb
require "open-uri"
class Link < ApplicationRecord
attr_reader :image_from_url
has_attached_file :image, styles: { medium: "600x600>", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
def image_from_url=(url)
self.image = URI.parse(url)
@image_from_url = url
end
end
_form.html.erb
<%= form_with(model: link, local: true) do |form| %>
<%= form.file_field :image, id: :link_image %>
<%= form.text_field :image, id: :link_image_url %>
<% end %>
links_controller.erb
def create
@link = current_user.links.build(link_params)
end
def link_params
params.require(:link).permit(:title, :url, :description, :image, :slug)
end
I must confess that I don't fully understand what is happening at each stage of the process which is why I'm struggling to debug it.
A: I am recommending carrierwave gem over paperclip. Easier to parse from link.
Carrierwave
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48976361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to calculate means and confidence intervals for different sample sizes automatically? I have a sample of a population (n=670), where I want to investigate how the sample size affects the results. I have calculated the "true mean" of the population, and want to compare this to the mean when n=20, n=30, n=40, etc. Is there a way where R could randomly sample x number of individuals from my dataset, and calculate mean and confidence interval, for each sample size?
Would also like to plot this somehow, where the x-axis show the "accumulated" mean. The hypothesis is that the larger the sample size, the closer to the "true mean", where I want to investigate how large the sample size must be in order to get close to the true mean.
I have figured out how to sample random rows with sample_n(data, size), and how to do the calculations (using lm() and confint()). But is it possible to avoid doing everything manually? Not only is the dataset of 670 individuals, but I have to do the same for two more populations (in total app 1500 individuals).
A: I would do a for loop with the sample sizes I am interested in, as follows:
sizes <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
results <- c()
for (size in sizes) {
subset <- sample_n(data, size)
lm_fit <- lm(subset$response ~ subset$predictor)
conf <- confint(lm_fit, level = 0.95)
results <- rbind(results, c(size, lm_fit$coefficients[1], conf[1,1], conf[1,2]))
}
You may plot the results as follows:
library(ggplot2)
ggplot(data = results, aes(x = size, y = mean)) +
geom_point() +
geom_errorbar(aes(ymin = lower, ymax = upper))
where geom_errorbar helps to show the confidence interval.
A: Thank you! This sent me in the right direction. New to RStudio, so it is not always easy to know where to look for solutions. I ended up with the code below.
calculate_mean_ci_M <- function(data, subset_sizes){
mean <- mean(RandomM$Value[1:subset_sizes])
sem <- sd(RandomM$Value[1:subset_sizes]) /sqrt(subset_sizes)
ci <- sem * qt(c(0.025, 0.975), df = subset_sizes-1)
return(data.frame(subset_sizes = subset_sizes, mean = mean, ci_lower = mean - ci[1],
ci_upper = mean + ci[1]))
}
subset_sizes <- c(20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140,
150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370,
380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500,
510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630,
640, 650, 660, 670, 672)
mean_ci_data_M <- map(subset_sizes, calculate_mean_ci_M, data = data) %>%
bind_rows()`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74851120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I make a button that removes contacts once someone clicks on them, in Android? So I saw two tutorials about removing contacts in Android Studio, but one was an entire project with "selecting features", which I don't have enough space to add in my app, and in the other one I was suppose to create databases and other variables.
My question is if there's any easy solution to make a button that once pressed has the option to select any of the contacts in the list and, upon clicking them, show a message that asks if the person is sure they want to delete it.
Another nice feature would be to make the contacts a different color so the person is sure they're in "delete mode".
What my activity_main looks like:
I also made a class just to remove contacts, but I don't know if it's necessary (this is just the MainActivity):
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<ContactModel> arrayList = new ArrayList<>();
MainAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
checkPermission();
}
private void checkPermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this
, Manifest.permission.READ_CONTACTS)
!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS}, 100);
}else{
getContactList();
}
Button add_btn = findViewById(R.id.add_btn);
add_btn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, Add_Contact.class)));
Button rem_btn = findViewById(R.id.rem_btn);
rem_btn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, Remove_Contact.class)));
}
And as you can see, the "Remove Contact" Button is connected to the rem_btn, which in itself is connected to the class "Remove_Contact".
Again, I don't know if it's necessary to make an entire class for it, but I would assume that, because most of the contact list is done, a lot of the code is not necessary.
I'm also learning the various implements in Android Studio, and, as I'm working on this, I also have a limited amount of time to work on this project.
Any help would be greatly appreciated!
A: Here is a solution that shows you how to delete all contacts in a loop. how to delete all contacts in contact list on android mobile programatically You just need some of the contacts information to tell which one to delete which you already have from the list.
You may need the WRITE_CONTACTS permission.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70250502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VM101:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.xhr.onload (app.js:134) I have some problems with my code in JS. When I want to detect if a person presses the button to eliminate, The console should show me an id with the register, but it shows me that error.
I have looked for a lot of information. For example, some people say that I have problems in my HTML code, but I looked and the code is good.
function eliminarContacto(e) {
if(e.target.parentElement.classList.contains('btn-borrar')) {
const id = e.target.parentElement.getAttribute('data-id');
//console.log(id);
const respuesta = confirm('Estas seguro?');
if(respuesta) {
const xhr = new XMLHttpRequest();
xhr.open('GET', `inc/modelos/modelo-contactos.php?id=${id}&accion=borrar`, true);
xhr.onload = function() {
if(this.status == 200) {
const resultado = JSON.parse(xhr.responseText);
console.log(resultado);
}
}
//enviar la peticion
xhr.send();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56566372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OAuth2: What is the difference between the JWT Authorization Grant and Client Credentials Grant with JWT client authentication? The OAuth2 JWT Profile introduces the possibility to use JWTs both as authorization grant and as client authentication.
The JWT client authentication feature is independent of a certain grant type, and can be used with any grant type, also the client credentials grant.
However, using the JWT grant type seems to do exactly the same as using the client credentials grant with JWT client authentication, except that the syntax is slightly different.
In both cases the client contacts the token endpoint to get an access token:
POST /token.oauth2 HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=[JWT]
vs
POST /token.oauth2 HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=[JWT]
A: A slightly different perspective on the great answer by Josh C: as it happens both the client authentication and the grant credentials can be expressed as JWTs but the semantics behind them are different.
It is about separation of concerns: clients authenticate with a credential that identifies them i.e. they are the so-called subject whereas they use grants that were issued to them i.e. they are the so-called audience. Or as version 12 of the draft spec (https://datatracker.ietf.org/doc/html/draft-ietf-oauth-jwt-bearer-12) says:
*The JWT MUST contain a "sub" (subject) claim identifying the
principal that is the subject of the JWT. Two cases need to be
differentiated:
A. For the authorization grant, the subject typically
identifies an authorized accessor for which the access token
is being requested (i.e., the resource owner or an
authorized delegate), but in some cases, may be a
pseudonymous identifier or other value denoting an anonymous
user.
B. For client authentication, the subject MUST be the
"client_id" of the OAuth client.
A: Probably very little. The way a client is identified and the way auth grants are requested are two different notions in OAuth, so the questions address those notions separately:
*
*Can a client authenticate with an authorization server using a JWT? Yes.
*Can a client make a grant request using a JWT? Yes.
The spec seems to hint that the separation is simply a design decision, deferring to policy makers to find what scenarios are valuable to them:
The use of a security token for client authentication is orthogonal to and separable from using a security token as an authorization grant. They can be used either in combination or separately. Client authentication using a JWT is nothing more than an alternative way for a client to authenticate to the token endpoint and must be used in conjunction with some grant type to form a complete and meaningful protocol request. JWT authorization grants may be used with or without client authentication or identification. Whether or not client authentication is needed in conjunction with a JWT authorization grant, as well as the supported types of client authentication, are policy decisions at the discretion of the authorization server.
One concrete possibility: The separation could allow for an authorization server to set up different policies along client types. For example, in the case of a public client (like a mobile app), the server should not accept the client creds grant type. Instead, the server could accept the JWT grant type for public clients and issue a token of lesser privilege.
Other than that, I would suppose that the design simply offers a degree of freedom for clients and servers to pivot around--keep this part of the existing handshake the same while migrating this part--as the need arises.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29696728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: unfortunately app has stopped error when Changing the graphical layout I'm new to android development. I created a simple app that adds two numbers Using eclipse. It worked fine. But when I run the app after changing the positions of buttons and textViews, using graphical layout without directly editing xml files, "unfortunately app has stopped" error shown in Emulator. This happens to me few times. Please can someone figure why is that?
logCat
06-10 16:51:36.690: E/Trace(1343): error opening trace file: No such file or directory (2)
06-10 16:51:36.886: D/AndroidRuntime(1343): Shutting down VM
06-10 16:51:36.886: W/dalvikvm(1343): threadid=1: thread exiting with uncaught exception (group=0xa624b288)
06-10 16:51:36.890: E/AndroidRuntime(1343): FATAL EXCEPTION: main
06-10 16:51:36.890: E/AndroidRuntime(1343): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a/com.example.a.MainActivity}: java.lang.ClassCastException: android.widget.RadioGroup cannot be cast to android.widget.Button
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.ActivityThread.access$600(ActivityThread.java:130)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.os.Looper.loop(Looper.java:137)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-10 16:51:36.890: E/AndroidRuntime(1343): at java.lang.reflect.Method.invokeNative(Native Method)
06-10 16:51:36.890: E/AndroidRuntime(1343): at java.lang.reflect.Method.invoke(Method.java:511)
06-10 16:51:36.890: E/AndroidRuntime(1343): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-10 16:51:36.890: E/AndroidRuntime(1343): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-10 16:51:36.890: E/AndroidRuntime(1343): at dalvik.system.NativeStart.main(Native Method)
06-10 16:51:36.890: E/AndroidRuntime(1343): Caused by: java.lang.ClassCastException: android.widget.RadioGroup cannot be cast to android.widget.Button
06-10 16:51:36.890: E/AndroidRuntime(1343): at com.example.a.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:75)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.Activity.performStart(Activity.java:5018)
06-10 16:51:36.890: E/AndroidRuntime(1343): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
06-10 16:51:36.890: E/AndroidRuntime(1343): ... 11 more
fagment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#EB7474"
tools:context="com.example.a.MainActivity$PlaceholderFragment" >
<EditText
android:id="@+id/n1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="119dp"
android:ems="10"
android:background="#FFE9E9"
android:hint="num2" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/n2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/n1"
android:layout_alignBottom="@+id/n1"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:ems="10"
android:background="#FFE9E9"
android:hint="num2" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/radioGroup1"
android:layout_marginTop="99dp"
android:layout_toRightOf="@+id/n1"
android:text="Answer" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/b1"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp"
android:background="#FFE9E9"
android:text="@string/hello_world" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/n1"
android:layout_centerHorizontal="true"
android:layout_marginTop="132dp"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/r0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="+" />
<RadioButton
android:id="@+id/r1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<RadioButton
android:id="@+id/r2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" />
<RadioButton
android:id="@+id/r3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/" />
</RadioGroup>
</RelativeLayout>
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.a.MainActivity"
tools:ignore="MergeRootFrame" />
mainActivity.java
package com.example.a;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
Button A;
TextView B;
EditText n1;
EditText n2;
RadioGroup radioButtonGroup;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
A = (Button) rootView.findViewById(R.id.b1);
B = (TextView) rootView.findViewById(R.id.tv1);
n1 = (EditText) rootView.findViewById(R.id.n1);
n2 = (EditText) rootView.findViewById(R.id.n2);
radioButtonGroup = (RadioGroup) rootView.findViewById(R.id.radioGroup1);
A.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
int num1 = Integer.parseInt(n1.getText().toString());
int num2 = Integer.parseInt(n2.getText().toString());
int total = 0;
switch (idx)
{
case 0:
total = num1+num2;
break;
case 1:
total = num1-num2;
break;
case 2:
total = num1*num2;
break;
case 3:
total = num1/num2;
break;
case -1:
break;
}
String ttl = String.valueOf(total);
B.setText(ttl);
}
});
return rootView;
}
}
}
A: I usually get this error when all I am doing is swapping view in xml layout. It is a ecllipse bug(sometimes) when and as a result your resource is not synced with the adt builder. When I get his error first thing I do is close ecllipse, end process adb.exe from task manager(windows) and then start ecllipse again. If this doesnot help then Android tools -> fix project properties and project -> clean.
A: android.widget.RadioGroup cannot be cast to android.widget.Button
*
*Your XML contains a RadioGroup item
*Your Fragment class is getting that item with findViewById and tries to cast it as a Button. Like that for instance:
Button btn = (Button) getView().findViewById(r.id.myRadioButton);
You'll need to either change your XML to make that a element or to change your fragment to get a RadioGroup variable:
RadioGroup grp = (RadioGroup) getView().findViewById(r.id.myRadioButton);
A: The problem is that you are trying to cast a RadioGroup to a Button, which you can't do. This is happening in MainActivity.
Post the code for MainActivity if you can't find the problem.
A: As I suspected, I don't see any invalid casting going on. My guess is that you're receiving this error because there is some disconnect between what has been deployed and what you've got built in your IDE. R.java is probably stale. You need to clean (remove bin, gen, lib, obj directories) and rebuild your project.
Here's a similar post where this same thing happened: Android ClassCastException for RadioGroup into RadioButton
Their issue was resolved by shutting down the emulator and restarting the IDE.
A: this is simple one!
I had came across this once. It seems quite baffling & frustrating at first, but the only thing you need to do is help eclipse get aware of the fact that the position and layout of a few (or all) components have been modified/altered.
And this you are supposed to achieve by building the work space from scratch.
For that all you need to do is close and restart eclipse.
That'll do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24146706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I change the background color of table cell (td) using two buttons for different colors? My HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Wolf and Rabbit Game</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="wolf&rabbit_game.css">
<script src="wolf&rabbit_game.js"></script>
</head>
<body>
<table>
<tr>
<td id="tableCell"></td>
</tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColorRed">
<input id="button2" type="button" value="I'm green" onclick="setColorGreen">
</body>
</html>
My CSS file:
table{
text-align: center;
margin: auto;
}
td{
border: 1px black solid;
width: 25px;
height: 25px;
}
#button1,#button2{
text-align: center;
margin-top: 20px;
font-size: 1em;
font-family: Myriad Pro;
font-weight: semibold;
color: white;
border-radius: 15px;
padding: 1%;
}
#button1{
background: red;
}
#button2{
background: green;
}
body{
text-align: center;
}
img{
width: 25px;
height: auto;
}
My JavaScript file:
function setColor(){
if ("#button1").click {
document.getElementById("#tableCell").style.backgroundColor="red";
};
if ("#button2").click {
document.getElementById("#tableCell").style.backgroundColor="green";
};
};
A: Check this JS Fiddle
JsFiddle link
There is no need of calling two different methods on two different buttons, a single method to accept the color parameter and change the desired element's color is good enough.
You have to modify your code like this and make sure javascript code comes before your button markup.
<script>
function setColor(color){
document.getElementById("tableCell").style.backgroundColor=color;
};
</script>
<table>
<tr>
<td id="tableCell">test</td>
</tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColor('red')">
<input id="button2" type="button" value="I'm green" onclick="setColor('green')">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26554237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Efficient Way to Replace Unicode Hex Character Codes in Snowflake String I currently have an issue where text I am importing includes Unicode Hex Character Codes in item descriptions.
For example, may appear for a no-break space, ê may appear for the French language "ê", etc.
I am wanting the text returned in a view to show the actual characters, rather than the hex character codes.
The best solution I have found so far involves doing something like the below:
CREATE OR REPLACE FUNCTION ENTITY_TO_SYMBOL(STRING VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
return STRING.replace(/À/g, "À").replace(/Á/g, "Á").replace(/Â/g, "Â").replace(/Ã/g, "Ã").replace(/Ä/g, "Ä").replace(/Å/g, "Å").replace(/à/g, "à").replace(/â/g, "â").replace(/ã/g, "ã").replace(/ä/g, "ä").replace(/å/g, "å").replace(/Æ/g, "Æ").replace(/æ/g, "æ").replace(/ß/g, "ß").replace(/Ç/g, "Ç").replace(/ç/g, "ç").replace(/È/g, "È").replace(/É/g, "É").replace(/Ê/g, "Ê").replace(/Ë/g, "Ë").replace(/è/g, "è").replace(/é/g, "é").replace(/ê/g, "ê").replace(/ë/g, "ë").replace(/ƒ/g, "ƒ").replace(/Ì/g, "Ì").replace(/Í/g, "Í").replace(/Î/g, "Î").replace(/Ï/g, "Ï").replace(/ì/g, "ì").replace(/í/g, "í").replace(/î/g, "î").replace(/ï/g, "ï").replace(/Ñ/g, "Ñ").replace(/ñ/g, "ñ").replace(/Ò/g, "Ò").replace(/Ó/g, "Ó").replace(/Ô/g, "Ô").replace(/Õ/g, "Õ").replace(/Ö/g, "Ö").replace(/ò/g, "ò").replace(/ó/g, "ó").replace(/ô/g, "ô").replace(/õ/g, "õ").replace(/ö/g, "ö").replace(/Ø/g, "Ø").replace(/ø/g, "ø").replace(/Œ/g, "Œ").replace(/œ/g, "œ").replace(/Š/g, "Š").replace(/š/g, "š").replace(/Ù/g, "Ù").replace(/Ú/g, "Ú").replace(/Û/g, "Û").replace(/Ü/g, "Ü").replace(/ù/g, "ù").replace(/ú/g, "ú").replace(/û/g, "û").replace(/ü/g, "ü").replace(/µ/g, "µ").replace(/×/g, "×").replace(/Ý/g, "Ý").replace(/Ÿ/g, "Ÿ").replace(/ý/g, "ý").replace(/ÿ/g, "ÿ").replace(/°/g, "°").replace(/†/g, "†").replace(/‡/g, "‡").replace(/</g, "<").replace(/>/g, ">").replace(/±/g, "±").replace(/«/g, "«").replace(/»/g, "»").replace(/¿/g, "¿").replace(/¡/g, "¡").replace(/·/g, "·").replace(/•/g, "•").replace(/™/g, "™").replace(/©/g, "©").replace(/®/g, "®").replace(/§/g, "§").replace(/¶/g, "¶").replace(/Α/g, "Α").replace(/Β/g, "Β").replace(/Γ/g, "Γ").replace(/Δ/g, "Δ").replace(/Ε/g, "Ε").replace(/Ζ/g, "Ζ").replace(/Η/g, "Η").replace(/Θ/g, "Θ").replace(/Ι/g, "Ι").replace(/Κ/g, "Κ").replace(/Λ/g, "Λ").replace(/Μ/g, "Μ").replace(/Ν/g, "Ν").replace(/Ξ/g, "Ξ").replace(/Ο/g, "Ο").replace(/Π/g, "Π").replace(/Ρ/g, "Ρ").replace(/Σ/g, "Σ").replace(/Τ/g, "Τ").replace(/Υ/g, "Υ").replace(/Φ/g, "Φ").replace(/Χ/g, "Χ").replace(/Ψ/g, "Ψ").replace(/Ω/g, "Ω").replace(/α/g, "α").replace(/β/g, "β").replace(/γ/g, "γ").replace(/δ/g, "δ").replace(/ε/g, "ε").replace(/ζ/g, "ζ").replace(/η/g, "η").replace(/θ/g, "θ").replace(/ι/g, "ι").replace(/κ/g, "κ").replace(/λ/g, "λ").replace(/μ/g, "μ").replace(/ν/g, "ν").replace(/ξ/g, "ξ").replace(/ο/g, "ο").replace(/&piρ;/g, "ρ").replace(/ρ/g, "ς").replace(/ς/g, "ς").replace(/σ/g, "σ").replace(/τ/g, "τ").replace(/φ/g, "φ").replace(/χ/g, "χ").replace(/ψ/g, "ψ").replace(/ω/g, "ω").replace(/•/g, "•").replace(/…/g, "…").replace(/′/g, "′").replace(/″/g, "″").replace(/‾/g, "‾").replace(/⁄/g, "⁄").replace(/℘/g, "℘").replace(/ℑ/g, "ℑ").replace(/ℜ/g, "ℜ").replace(/™/g, "™").replace(/ℵ/g, "ℵ").replace(/←/g, "←").replace(/↑/g, "↑").replace(/→/g, "→").replace(/↓/g, "↓").replace(/&barr;/g, "↔").replace(/↵/g, "↵").replace(/⇐/g, "⇐").replace(/⇑/g, "⇑").replace(/⇒/g, "⇒").replace(/⇓/g, "⇓").replace(/⇔/g, "⇔").replace(/∀/g, "∀").replace(/∂/g, "∂").replace(/∃/g, "∃").replace(/∅/g, "∅").replace(/∇/g, "∇").replace(/∈/g, "∈").replace(/∉/g, "∉").replace(/∋/g, "∋").replace(/∏/g, "∏").replace(/∑/g, "∑").replace(/−/g, "−").replace(/∗/g, "∗").replace(/√/g, "√").replace(/∝/g, "∝").replace(/∞/g, "∞").replace(/&OEig;/g, "Œ").replace(/œ/g, "œ").replace(/Ÿ/g, "Ÿ").replace(/♠/g, "♠").replace(/♣/g, "♣").replace(/♥/g, "♥").replace(/♦/g, "♦").replace(/ϑ/g, "ϑ").replace(/ϒ/g, "ϒ").replace(/ϖ/g, "ϖ").replace(/Š/g, "Š").replace(/š/g, "š").replace(/∠/g, "∠").replace(/∧/g, "∧").replace(/∨/g, "∨").replace(/∩/g, "∩").replace(/∪/g, "∪").replace(/∫/g, "∫").replace(/∴/g, "∴").replace(/∼/g, "∼").replace(/≅/g, "≅").replace(/≈/g, "≈").replace(/≠/g, "≠").replace(/≡/g, "≡").replace(/≤/g, "≤").replace(/≥/g, "≥").replace(/⊂/g, "⊂").replace(/⊃/g, "⊃").replace(/⊄/g, "⊄").replace(/⊆/g, "⊆").replace(/⊇/g, "⊇").replace(/⊕/g, "⊕").replace(/⊗/g, "⊗").replace(/⊥/g, "⊥").replace(/⋅/g, "⋅").replace(/&lcell;/g, "⌈").replace(/&rcell;/g, "⌉").replace(/⌊/g, "⌊").replace(/⌋/g, "⌋").replace(/⟨/g, "⟨").replace(/⟩/g, "⟩").replace(/◊/g, "◊").replace(/'/g, "'").replace(/&/g, "&").replace(/"/g, "\"").replace(/é/g,"é").replace(/'/g,"'").replace(/ê/g,"ê").replace(/à/g,"à").replace(/ /g," ").replace(/°/g,"°").replace(.replace(/±/g,"±");
$$;
This is obviously a nightmare to read, and in order for it to truly be inclusive I would likely need to write a script to generate all the replaces needed.
While I could do this, it does not necessarily seem like the most efficient way to essentially manually replace each character.
I had seen on a different site someone recommending using a lookup table to do this. I could figure out how to do something like this in Python, but was not sure if there was an easy approach for this in Snowflake.
The idea would be having a table where one column is the code, another is the value, and then the UDF would basically replace all instances of any codes with their corresponding values.
This seems like it would be a common problem, but I have not come across any specific solutions.
Any advice regarding how to do this and whether it would be best practice would be appreciated. I know ideally we would parse before loading, but due to the nature of our platform I need to do these transformations in Snowflake.
A: You can do this easily with a Python UDF:
create or replace function py_unescape(X string)
returns string
language python
handler = 'x'
runtime_version = 3.8
as $$
import html
def x(s):
return html.unescape(s)
$$
;
select py_unescape('À makes me feel Á');
-- À makes me feel Á
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73491711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Element implicitly has type 'any', because expression of type 'any' cannot be used to index type '{}' I'm trying to solve the duplicateCount() function.
Here is my code :
export const duplicateCount = (text: string): number => {
let countObj = {}
if (text.length === 0) return 0
let allLetters = text.toLowerCase().split("")
allLetters.forEach(letter => {
if(countObj[letter]) {
countObj[letter] ++
}else {
countObj[letter] = 1
}
})
}
I get an error that says Element implicitly has type 'any', because expression of type 'string' cannot be used to index type '{}'. I don't really understand what it mean, can someone explain how to solve it?
A: I finally end up with this solution code:
export const duplicateCount = (text: string): number => {
let countObj: Record<string, number> = {}
let count: number = 0
if (text.length === 0) return 0
let allLetters = text.toLowerCase().split("")
allLetters.forEach((letter) => {
if (countObj[letter]) {
countObj[letter]++
} else {
countObj[letter] = 1
}
})
for (const key in countObj) {
if (countObj[key] > 1) {
count++
}
}
return count
}
I'm open for any suggestion refactoring
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70563995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parse v. TryParse What is the difference between Parse() and TryParse()?
int number = int.Parse(textBoxNumber.Text);
// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);
Is there some form of error-checking like a Try-Catch Block?
A: The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.
As a footnote, passing in null to most TryParse methods will throw an exception.
A: TryParse and the Exception Tax
Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.
A: If the string can not be converted to an integer, then
*
*int.Parse() will throw an exception
*int.TryParse() will return false (but not throw an exception)
A: Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.
TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.
In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.
A: TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).
A: For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.
if (!Int32.TryParse(txt,out tmpint)) {
tmpint = 0;
}
and:
try {
tmpint = Convert.ToInt32(txt);
} catch (Exception) {
tmpint = 0;
}
For c#, the best option is to use tryparse because try&Catch alternative thrown the exception
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.
A: I know its a very old post but thought of sharing few more details on Parse vs TryParse.
I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.
Old Code:
dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");
New Code:
DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);
Have to declare another variable and used as Out for TryParse.
A: double.Parse("-"); raises an exception, while
double.TryParse("-", out parsed); parses to 0
so I guess TryParse does more complex conversions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/467613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "118"
} |
Q: How to show the preview of the input photo in page? I have an img tag and an input type file,
Functionality
The functionality is i will input one jpg file using input type file, i need to show this image in the image tag.
How is it possible in angular 2 ?
My tries
I tried to get the file path on change event of input button and assign it to the src of image file.
Tried to solve it using an external js file.
but both these tries are failure, whats the solution for this.
Code
HTML
<img [src]="imagePath" width="100px">
<input type="file" multiple (change)="onUpload(input)" #input >
Component.ts
import { Component, OnInit, NgModule } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
})
export class FormComponent implements OnInit {
//DECLARATION
imagePath:string;
constructor() {
this.onInitial();
}
ngOnInit() {}
onInitial(){
this.imagePath="../../assets/images/1.jpg"
}
onUpload(event){
console.log(event);
}
}
What the code i need to write inside the onUpload() to assign the path of the input image to the variable imagePath.
Please help me.
A: Have not tried Angular2. Though you should be able to set img src to Blob URL of first File object of input.files FileList.
At chromium, chrome you can get webkitRelativePath from File object, though the property is "non-standard" and possibly could be set to an empty string; that is, should not be relied on for the relative path to the selected file at user filesystem.
File.webkitRelativePath
This feature is non-standard and is not on a standards track. Do not
use it on production sites facing the Web: it will not work for every
user. There may also be large incompatibilities between
implementations and the behavior may change in the future.
File
The webkitRelativePath attribute of the File interface must return
the relative path of the file, or the empty string if not specified.
4.10.5.1.18. File Upload state (type=file)
EXAMPLE 16 For historical reasons, the value IDL attribute
prefixes the file name with the string "C:\fakepath\". Some legacy
user agents actually included the full path (which was a security
vulnerability). As a result of this, obtaining the file name from the
value IDL attribute in a backwards-compatible way is non-trivial.
See also How FileReader.readAsText in HTML5 File API works?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="" width="100px" alt="preview">
<input type="file" multiple onchange="onUpload(this)" id="input" accepts="image/*" />
<br><label for="input"></label>
<script>
let url;
function onUpload(element) {
console.log(element)
let file = element.files[0];
if (url) {
URL.revokeObjectURL(url);
}
url = URL.createObjectURL(file);
if ("webkitRelativePath" in file
&& file.webkitRelativePath !== "") {
element.labels[0].innerHTML = file.webkitRelativePath;
} else {
element.labels[0].innerHTML = element.value;
}
element.previousElementSibling.src = url;
element.value = null;
}
</script>
</body>
</html>
A: At last i got the answer my self,
https://github.com/ribizli/ng2-imageupload
this will work for you. It may help you for this issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40431758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JavaMail with gmail SMTP - How to handle an unexisting email addresses In my project I'm using a JavaMail implementation to send emails through GMAIL's SMTP server.
The general concept is ok, my custom validators checks whether the e-mail was correctly formulated etc...
Everything is fine, however I am not able to catch anything what should be considered, as unsent email. I went deeper into JavaMail docs, and they advised to catch SendMailException and MessageException, but based on the code, it handles only an incorrectly formulated e-mail addresses or an empty Strings. If the user will come up with an unexisting email, but well formulated, the API will not inform that anything happened.
Did anyone handle with the similar issue and knows how to go forward?
Thanks in advance for your help.
@Bean
public JavaMailSender javaMailSender(EmailProperties prop) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(prop.getHost());
mailSender.setPort(prop.getPort());
mailSender.setUsername(prop.getUsername());
mailSender.setPassword(prop.getPassword());
mailSender.setDefaultFileTypeMap(FileTypeMap.getDefaultFileTypeMap());
mailSender.setJavaMailProperties(getProperties(prop));
mailSender.setProtocol(prop.getProtocol());
mailSender.setDefaultEncoding("UTF-8");
return mailSender;
}
private Properties getProperties(EmailProperties prop) {
Properties props = new Properties();
props.put("mail.transport.protocol", prop.getProtocol());
props.put("mail.smtp.auth", prop.getAuth());
props.put("mail.smtp.starttls.enable", prop.getStarttls());
props.put("mail.debug", prop.getDebug());
return props;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58564389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Retrieve multiple data from firebase database in one cloud function I am faced with the problem of retrieving two data values of a single node from my firebase database and reference it in my javascript file but don't know how to go about it. I have been able to retrieve just one data value from a node (in this case "message") but I would like to add "from" as well. Most tutorials just reference one so I am really confused. So how do I get multiple data values?
This is my code...
JS file
exports.sendNotification7 = functions.database.ref('/GroupChat/{Modules}/SDevtChat/{SDevtChatId}/message')
.onWrite(( change,context) =>{
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();
var str = "New message from System Development Group Chat: " + eventSnapshot;
console.log(eventSnapshot);
var topic = "Management.Information.System";
var payload = {
data: {
name: str,
click_action: "Student_SystemsDevt"
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
return;
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
A: You can read from however many nodes you want in a Cloud Function. However, only one can trigger the function to run.
To read from your database use the following code:
admin.database().ref('/your/path/here').once('value').then(function(snapshot) {
var value = snapshot.val();
});
You will probably want to read from the same place that the Cloud Function was triggered. Use context.params.PARAMETER to get this information. For the example you posted your code would turn out looking something like this:
admin.database().ref('/GroupChat/'+context.params.Modules+'/SDevtChat/'+context.params.SDevtChatId+'/from').once('value').then(function(snapshot) {
var value = snapshot.val();
});
A: Just trigger your function one level higher in the JSON:
exports.sendNotification7 =
functions.database.ref('/GroupChat/{Modules}/SDevtChat/{SDevtChatId}')
.onWrite(( change,context) =>{
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();
console.log(eventSnapshot);
var str = "New message from System Development Group Chat: " + eventSnapshot.message;
var from = eventSnapshot.from;
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51029101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extracting Multiple Elements with same html criteria in python I'm novice with python and beautiful so this answer may be obvious.
I'm using beautiful soup to parse the following html and extract the Date.
html='''
<p><strong>Event:</strong>Meeting</p>
<p><strong>Date:</strong> Mon, Apr 25, 2016, 11 am</p>
<p><strong>Price:</strong>$20.00</p>
<p><strong>Event:</strong>Convention</p>
<p><strong>Date:</strong> Mon, May 2, 2016, 11 am</p>
<p><strong>Price:</strong>$25.00</p>
<p><strong>Event:</strong>Dance</p>
<p><strong>Date:</strong> Mon, May 9, 2016, 11 am</p>
<p><strong>Price:</strong>Free</p>
'''
I parsed the date when there is only one date using the following code but having a hard time when encountering multiple dates (only gets one date).
date_raw = html.find_all('strong',string='Date:')
date = str(date_raw.p.nextSibling).strip()
Is there a way to do this in bs4 or should I use regular expressions. Any other suggestions?
Desired list output:
['Mon, Apr 25, 2016, 11 am','Mon, May 2, 2016, 11 am','Mon, May 9, 2016, 11 am']
A: I would probably iterate of every found element and append it to a list. Something like this maybe (untested):
date_list = []
date_raw = html.find_all('strong',string='Date:')
for d in date_raw:
date = str(d.p.nextSibling).strip()
date_list.append(date)
print date_list
A: Rookie mistake...fixed it:
for x in range(0,len(date_raw)):
date_add = date_raw[x].next_sibling.strip()
date_list.append(date_add)
print (date_add)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35947754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to split strings based on "/n" in Java I have got a string
$key1={331015EA261D38A7}
$key2={9145A98BA37617DE}
$key3={EF745F23AA67243D}
How do i split each of the keys based on "$" and the "next line" element?
and then place it in an Arraylist?
The output should look like this:
Arraylist[0]:
$key1={331015EA261D38A7}
Arraylist[1]:
$key2={9145A98BA37617DE}
Arraylist[2]:
$key3={EF745F23AA67243D}
A: If you just want to split by new line, it is as simple as :
yourstring.split("\n"):
A: yourstring.split(System.getProperty("line.separator"));
A: Don't split, search your String for key value pairs:
\$(?<key>[^=]++)=\{(?<value>[^}]++)\}
For example:
final Pattern pattern = Pattern.compile("\\$(?<key>[^=]++)=\\{(?<value>[^}]++)\\}");
final String input = "$key1={331015EA261D38A7}\n$key2={9145A98BA37617DE}\n$key3={EF745F23AA67243D}";
final Matcher matcher = pattern.matcher(input);
final Map<String, String> parse = new HashMap<>();
while (matcher.find()) {
parse.put(matcher.group("key"), matcher.group("value"));
}
//print values
parse.forEach((k, v) -> System.out.printf("Key '%s' has value '%s'%n", k, v));
Output:
Key 'key1' has value '331015EA261D38A7'
Key 'key2' has value '9145A98BA37617DE'
Key 'key3' has value 'EF745F23AA67243D'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39931342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-8"
} |
Q: Disable weaker TLS ciphers for a Linux hosted ASP.NET Core app I am looking at disabling RC4 and 3DES TLS ciphers in my application and wondering how to implement this?
The application is Angular/ASP.NET Core currently in the latest versions of both technologies. The application is hosted on a Red Hat 7 server.
A: Application level
You may try to force your app to only support TLS 1.3.
TLS 1.3 supports only ciphers thought to be secure.
This post explains how to do it for TLS 1.2, you would just have to change the
s.SslProtocols = SslProtocols.Tls12;
to
s.SslProtocols = SslProtocols.Tls13;
More informations here
Feel free to test it with SSL Labs
You can stay on TLS 1.2 and manually choosing your ciphers by doing this.
Proceed with absolute caution when doing this. You want to do this only if you absolutely know what you're doing.
var ciphersArray = new TlsCipherSuite[]
{
TlsCipherSuite.TLS_AES_256_GCM_SHA384, // etc
};
var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder.ConfigureKestrel(kestrelServerOptions =>
{
kestrelServerOptions.ConfigureHttpsDefaults(w =>
{
w.OnAuthenticate = (x, s) =>
{
var ciphers = new CipherSuitesPolicy(ciphersArray);
s.CipherSuitesPolicy = ciphers;
};
});
});
});
OS Level
It's not your OS version but this RHEL 8 doc could be interesting to you. As you can see the DEFAULT option doesn't allow RC4 and 3DES
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71550920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular 2: How to render a multiple event in fullcalndar I am using FullCalendar in angular 2, Events for fullcalendar coming from other source, problem is how should i render the events which contain only multiple event on the day,need to hide or not clickable which show only single event.
Please help me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47709958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: problems populating list view from text file Android Ok so I am trying to populate a list view in android from a linked list of objects. I am reading lines from a text file, splitting out two values from each line of the text file separated by a "," storing each of these values into a linked list of objects. Then I'm pulling the name field of each object to populate a list view. I know it's sloppy I'm just starting with Android :E It won't run at all at this point but there are no errors in the code.
here's my activity.java file
package com.pkuCalc.pkuCalc;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Bundle;
public class PkuCalcActivity extends Activity {
private ListView lv;
List<Food> foodlist = new LinkedList<Food>();
int numFoodItems = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView) findViewById(R.id.listView1);
try{
InputStream inputStream = getResources().openRawResource(R.raw.food);
if (inputStream != null) {
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader r = new BufferedReader(inputreader);
String strLine;
while (( strLine = r.readLine()) != null) {
int z = 0;
int length = strLine.length();
int ind = strLine.indexOf( ',' );
String name = "";
for (int i = 0; i < ind; i++) {
name = name + strLine.charAt(i);
}
String sphe = "";
for (int i = ind + 2; i < length; i++) {
sphe = sphe + strLine.charAt(i);
}
int phe = Integer.parseInt(sphe);
Food newFood = new Food(name, phe);
foodlist.add(newFood);
numFoodItems = z;
z++;
}
}
inputStream.close();
} catch (IOException e){ //Catch exception if any
e.printStackTrace();
}
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i <= numFoodItems; i++) {
values.add((foodlist.get(i)).getName());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
lv.setAdapter(arrayAdapter);
setContentView(R.layout.main);
}
}
A: You cannot find a view by it's ID until AFTER the call to
setContentView(R.layout.main);
Put the above line as the 2nd line of your onCreate function and it will work.
A: As a suggestion, a handy java function is String.split(String pattern). Still assuming that each line in your text will always be: string, integer. We can re-write you reader loop:
while (( strLine = r.readLine()) != null) {
String[] pair = strLine.split(",");
Food newFood = new Food(pair[0], Integer.parseInt(pair[1]));
foodlist.add(newFood);
}
I'm not too sure what z nor numFoodItems are doing since they are set to zero on each loop so I left them out. If you want to know how many food items you have in foodlist you can always call foodlist.size();
You can condense this loop even more, but at some point you start to lose readability so it's up to you.
Addition
Aha, that is what you are trying to do with numFoodItems. Let's change the loop you use to build values:
for (Food foodItem : foodlist) {
values.add(foodItem.getName());
}
For-Each loops like these are faster, according to Oracle, and as a bonus they are shorter to type. Now you might get more than one row in your ListView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10375300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits