text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Java equivalent for Oracle INSTR function I need to write the Java equivalent for INSTR Oracle function.
Example in Oracle:
select INSTR('vivek Srinivasamoorthy','a',14) from DUAL
Output:15
How can I do this in Java?
A: String.indexOf() is your friend. Keep in mind that in Oracle counting start at 1, in Java at 0 (zero), so result in Java for your Oracle example will be 14. For docu see at Oracle DB server and Java.
In your specific case you can test it with System.out.println("is on index: " + "vivek Srinivasamoorthy".indexOf("a", 13));
A:
getInstring(String input, String substr, int start, int occurence) {
char[] tempstring = input.substring(start).replaceAll(substr, "-").toCharArray();
int occurindex = 0;
int counter = 0;
for (int i = 0; i < tempstring.length; i++) {
if (":-".equals(":" + tempstring[i])) {
occurindex++;
counter = i;
}
if (occurindex == occurence) {
break;
}
}
return counter == 0 ? -1 : counter + start + 1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36127866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to start mongodb in read only mode? I need to disable writes for a mongodb replicaset, is that possible? Something like 'FLUSH WITH READ LOCK' in mysql?
A: If you connect to secondary directly, not as part of the replica set, then you will not be able to write.
Or you can turn on authentication and create read-only users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27049658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Reduce calls of DBI::common::Fetch (Perl) I have been trying to reduce the runtime of a program I've created.
I used a Profiler, which told me that 63% of the time was spent was on DB::st::execute. I then ran a DBI Profiler, and found which of my calls were taking the longest:
+ 1 SELECT Gene FROM genotypegene WHERE Genotype like ?
= 754 0.163602352142334 0 0 0.0156009197235107 1332756184.24322 1332756184.74384
I changed the amount of calls from 754 down to 14:
+ 1 SELECT Gene FROM genotypegene WHERE Genotype like ?
= 14 0.00399994850158691 0 0 0.00100016593933105 1332923220.99416 1332923221.70477
The program speed hasn't increased significantly however, and my profiler now says that 100% is spent on DBI::common::FETCH. I'm not sure what method this is referring to.
Before I edited my program to cut down the number of calls of 'SELECT Gene', it said DBI::common::FETCH was taking 0.000003 sec/call, whereas now it is taking 4.467... sec/call. Why would DBI::common::FETCH now be taking so much longer sec/call than previously? ( The only other thing I have noticed between the two profiles is that the original profile had a call to which the new profile no longer has. If I look at the Profile as the program is running, it only has one call to but this increases in time as the program runs)
Thanks!
Edit: Here is the table I am selecting from (put in here for easier reading than in the comment part) :
CREATE TABLE genotypegene
(
Genotype VARCHAR(20),
Gene VARCHAR(20),
FOREIGN KEY (Genotype) REFERENCES genotype(Genotype),
FOREIGN KEY (Gene) REFERENCES gene(Gene)
)ENGINE=InnoDB;
Edit 2:
The fields for the DBI Profile are here: http://metacpan.org/pod/DBI::Profile#Report-Format
The reason I was able to go from 700~ to 14 is because of my inexperience as a programmer (self taught, only started using perl 3 months ago). I was originally calling the information from the database every time I needed it (so was calling the same information more than once). Once I saw that this was slowing the program down I changed it so it called the information I needed at the start of the program then stored it in a hash. I was then expecting this to speed the program up, which it has, but not as much as expected. This is why I was surprised at the 4.4secs for the DBI::common::Fetch as it was never this slow before, and to my knowledge I didn't change anything in the program that should make this call this slow
This is the Devel Profile for the program once edited:
%Time Sec. #calls sec/call F name
100.00 386198925.3409 86442494 4.467698 DBI::common::FETCH
0.00 15263.1450 21928855 0.000696 DBI::st::execute
(many other functions listed too, just selected the ones of interest)
and here it is before it was edited:
%Time Sec. #calls sec/call F name
65.01 8767.3435 21766318 0.000403 DBI::st::execute
2.29 309.2408 86510899 0.000004 DBI::common::FETCH
11.52 1554.1823 0 1554.182323 * <other>
(discrepancy between 65% and 63% is because this is a different run of the program than the one I mentioned at the start, but it is roughly the same)
A: After seeing your database design, I would suggest 2 things based on your queries.
i) You are using LIKE queries to match strings, so create a INDEX on your GENOTYPE column, that will give performance boost.
ii) Try using MyIsam engine, and a FULL TEXT engine on GENOTYPE column , based on what kind of matches you are doing on your column strings.
Are your queries like:
a) SELECT Gene FROM genotypegene WHERE Genotype like 'YYY%' (starts with )
or
b) SELECT Gene FROM genotypegene WHERE Genotype like '%YY%' (contains )
Please share an exact query, that would help more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9903952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How are role cookies encrypted? FormsAuthentication has an encrypt and decrypt method to push and pull the Authentication Ticket. Roles has a lot of the same methods, but it does not tell you what type of encryption is being used, or how to decrypt it. Can anyone point me in the right direction? I need to be able to mock up a Role Cookie for a test.
EDIT 1:
Here is an example of the problem that I'm still having.
SetLoggedInUserInHttpContext(User, Roles.GetRolesForUser(User.UserID.ToString()));
RQUserMembership member = new RQUserMembership();
QUserMembership mem = member.GetByUserAndPass(User.Username, User.Password);
FormsAuthentication.SetAuthCookie(mem.UserId.ToString(), true);
QGlobals.expireLoginProxyID();
RQLoginAttempt.LogSuccessfulAttempt(User.Username);
Here is the setting of the user
public static bool SetLoggedInUserInHttpContext(QUser User, string[] roles = null) {
if (HttpContext.Current != null) {
if (roles == null) {
roles = Roles.GetRolesForUser(User.UserID.ToString());
}
GenericIdentity genericIdentity = new GenericIdentity(User.UserID.ToString());
RolePrincipal genericUser = new RolePrincipal(genericIdentity); //rolesToSet
HttpContext.Current.User = genericUser;
return (User.UserID == QGlobals.GetLoggedInUserID());
} else {
return false;
}
}
My attempt to get the byte[]:
HttpContext blah = HttpContext.Current;
string blah2 = HttpContext.Current.Request.Cookies[".ASPXROLES"].Value;
byte[] bytes = new byte[blah2.Length * sizeof(char)];
System.Buffer.BlockCopy(blah2.ToCharArray(), 0, bytes, 0, bytes.Length);
byte[] blah3 = MachineKey.Unprotect(bytes);
var str = System.Text.Encoding.Default.GetString(blah3);
I'm now getting an error on blah3 = MachineKey.Unprotect(bytes);
Error occurred during a cryptographic operation.
at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input)
at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData)
at System.Web.Security.MachineKey.Unprotect(ICryptoServiceProvider cryptoServiceProvider, Byte[] protectedData, String[] purposes)
at System.Web.Security.MachineKey.Unprotect(Byte[] protectedData, String[] purposes)
at Quorra.Repositories.RQUser.GetUserHomePageStats(Int32 UserID, Int32 HourInterval) in e:\Code\quorra\Quorra.Domain\Repositories\RQUser.cs:line 133
at Quorra.Admin.Controllers.HomeController.Home(Nullable`1 refreshBasketCount) in e:\Code\quorra\Quorra.Admin\Controllers\HomeController.cs:line 31
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41()
Any direction would be appreciated.
Edit 2:
To clarify I need to be able to set up a role cookie for a user so that Roles.IsUserInRole(); works. Right now if I pass the userId it works, because it goes to the role provider and runs that method, but to check the logged on user, it just tests the cookie. I don't actually need to be able to decrypt it, if I can encrypt it, that will be enough.
A: The encryption used for Forms Authentication is based on the <machineKey> element under <system.web>. Effectively you reconfigure the <machineKey> element to control the encryption.
See here for further information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25730905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Program/Script that runs autonomously without interaction from user I need to know whether it is possible to create a program/script that runs autonomously once initiated by an event (usually a mouse click) without any further interactions from the user ie. even if he closes his browser the script continues to run on the server
Scenario
lets say that I've got a video sharing site whose permissions,login access and all other relevant credentials are given to me .I've created a crawler in PHP that crawls the entire site and writes the video src's of all the videos on the site in a file called log_file.txt. Now i want to know whether it is possible to create a program that,once i initiate it , downloads the videos from the site's server onto my server using the src's in the log_file.txt, and this continues to work even if i shut down my computer ie. runs on the server continuously until all the videos have downloaded or otherwise
NOTE : this question is not intended to perform piracy of any sorts. Its just that i have a site that has got some basic video hosting and i want to perform server to server video migration without having to download it on my pc and then reuploading it to new server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36014014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Airflow Docker Unhealthy trigerrer Im trying to setup airflow on my machine using docker and the docker-compose file provided by airflow here : https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html#docker-compose-yaml
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d4d8de8f7782 apache/airflow:2.2.0 "/usr/bin/dumb-init …" About a minute ago Up About a minute (healthy) 8080/tcp airflow_airflow-scheduler_1
3315f125949c apache/airflow:2.2.0 "/usr/bin/dumb-init …" About a minute ago Up About a minute (healthy) 8080/tcp airflow_airflow-worker_1
2426795cb59f apache/airflow:2.2.0 "/usr/bin/dumb-init …" About a minute ago Up About a minute (healthy) 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp airflow_airflow-webserver_1
cf649cd645bb apache/airflow:2.2.0 "/usr/bin/dumb-init …" About a minute ago Up About a minute (unhealthy) 8080/tcp airflow_airflow-triggerer_1
fa6b181113ae apache/airflow:2.2.0 "/usr/bin/dumb-init …" About a minute ago Up About a minute (healthy) 0.0.0.0:5555->5555/tcp, :::5555->5555/tcp, 8080/tcp airflow_flower_1
b6e05f63aa2c postgres:13 "docker-entrypoint.s…" 2 minutes ago Up 2 minutes (healthy) 5432/tcp airflow_postgres_1
177475be25a3 redis:latest "docker-entrypoint.s…" 2 minutes ago Up 2 minutes (healthy) 6379/tcp airflow_redis_1
I followed all steps as described in this URL, every airflow component is working great but the airflow trigerrer shows an unhealthy status :/
Im kinda new to docker i just know the basics and i don't really know how to debug that, can anyone help me up ?
A: Try to follow all steps on their website including mkdir ./dags ./logs ./plugins echo -e "AIRFLOW_UID=$(id -u)\nAIRFLOW_GID=0" > .env.
I don't know but it works then, but still unhealthy,
airflow.apache.org/docs/apache-airflow/stable/start/docker.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69538129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dialogflow Messenger -- Selecting Environment How does one select an environment for the Dialogflow Messenger? We have 3 different environments (dev, QA, prod) and want to select Prod for the Dialogflow Messenger we deploy on our site.
There doesn't seem to be any setting where you can select the environment?
A: In Dialogflow CX, we can select environment before enabling Dialogflow Messenger.
Like the picture below, select the environment in the dropdown when connect Dialogflow Messenger integration so that the it will work with selected environment.
If you already enabled it, then disable it to select environment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74342285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why if did not execute right condition i have a code, like this
public static Response updateDataFiles(String id, String checksum){
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction trans = session.beginTransaction();
Files files = (Files) session.get(Files.class, id);
System.out.println("checksum "+checksum);
System.out.println("checksum file "+files.getChecksumFile());
String checksumFile = files.getChecksumFile();
if(checksum == checksumFile){
System.out.println("upload success");
files.setStatusUpload(EnumStatusUpload.statusUpload.UPLOADED_AND_SUCCESS.toString());
}else{
System.out.println("upload success but checksum error");
files.setStatusUpload(EnumStatusUpload.statusUpload.UPLOADED_BUT_ERROR_CHECKSUM.toString());
}
session.update(files);
trans.commit();
session.flush();
session.close();
Response respon = new Response();
respon.status = 200;
return respon;
}
at if(checksum == checksumFile) there's something wrong, the checksum variable and checksumFile have a same value, but if did not execute the right condition, if executed else condition.
In my log i had seen the value of checksum variable, and checksumFile like this
checksum 9d73d945294d5488056bb5da54f62e8f
checksum file 9d73d945294d5488056bb5da54f62e8f
i don't know what's wrong in my code. Can anyone help me? and sorry for my bad English
A: You want to compare the values of the two strings using .equals()
checksum.equals(checksumFile)
Using == compares the references and basically asks whether the two references point to the same object, which they don't.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17915305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Plotting Multiple Argument Function in Matlab How can i plot
f(x,y) = xsin(xy)
function on the intervals
0 < x < 5 and π < y < 2π
A: You could use this for a 3d plot:
ezsurf('x*sin(x*y)', [0,5,pi,2*pi])
You can also use ezmesh with the same arguments to draw the mesh only (with a transparent surface)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23967076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MV4 Application with EF5 model first, without ViewModels or Repositories I'm building a MVC4 app, I've used EF5 model first, and kept it pretty simple. This isn't going to a huge application, there will only ever be 4 or 5 people on it at once and all users will be authenticated before being able to access any part of the application, it's very simply a place order - dispatcher sees order - dispatcher compeletes order sort of application.
Basically my question is do I need to be worrying about repositories and ViewModels if the size and scope of my application is so small. Any view that is strongly typed to a domain entity is using all of the properties within that entity. I'm using TryOrUpdateModel in my controllers and have read some things saying this can cause a lot of problems, but not a lot of information on exactly what those problems can be. I don't want to use an incredibly complicated pattern for a very simple app.
Hopefully I've given enough detail, if anyone wants to see my code just ask, I'm really at a roadblock here though, and could really use some advice from the community. Thanks so much!
A: In my experience, the requirements on a software solution tend to evolve over time well beyond the initial requirement set.
By following architectural best practices now, you will be much better able to accommodate changes to the solution over its entire lifetime.
The Respository pattern and ViewModels are both powerful, and not very difficult or time consuming to implement. I would suggest using them even for small projects.
A: Yes, you still want to use a repository and view models. Both of these tools allow you to place code in one place instead of all over the place and will save you time. More than likely, it will save you copy paste errors too.
Moreover, having these tools in place will allow you to make expansions to the system easier in the future, instead of having to pour through all of the code which will have poor readability.
Separating your concerns will lead to less code overall, a more efficient system, and smaller controllers / code sections. View models and a repository are not heavily intrusive to implement. It is not like you are going to implement a controller factory or dependency injection.
A: ViewModels: Yes
I only see bad points when passing an EF Entities directly to a view:
*
*You need to do manual whitelisting or blacklisting to prevent over-posting and mass assignment
*It becomes very easy to accidentally lazy load extra data from your view, resulting in select N+1 problems
*In my personal opinion, a model should closely resembly the information displayed on the view and in most cases (except for basic CRUD stuff), a view contains information from more than one Entity
Repositories: No
The Entity Framework DbContext already is an implementation of the Repository and Unit of Work patterns. If you want everything to be testable, just test against a separate database. If you want to make things loosely coupled, there are ways to do that with EF without using repositories too. To be honest, I really don't understand the popularity of custom repositories.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14568657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add a "Copy Button" to SSRS? The users of my SSRS report always select the entire text in the report, then right-click and copy it (then they paste it elsewhere). So, it would be of great benefit if I could add a copy button that would simply copy the entire content of the report - ready for pasting. So they can just click the button, and go elsewhere and simply paste it. Is this possible in SSRS?
A: This is not possible. It is possible to copy all text from a textbox but there are no viable options to only copy selected text to clipboard.
How can I click a button in VB and highlight a text box and copies conent to clipboard?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29210759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get 3 rows with the most recent dates, starting with most recent I have this table:
postID | postTitle | date
1 | example1 | 04/06/2014 ***15:00***
2 | example2 | 04/06/2014 ***14:00***
3 | example3 | 04/06/2014 ***14:20***
3 | example4 | 04/06/2014 ***10:00***
3 | example5 | 04/06/2014 ***09:00***
Current time: 16:00
How can I do three queries where for example query 1 selects the most recent row, query 2 selects the second most recent row and query 3 selects the third most recent row?
A: Just use an order desc, and limit
select *
from yourTable
order by `date` desc
limit 3
Limit with 1 argument : argument = number of rows.
Limit with 2 argument : first = offset, second = number (offset starting at 0, not 1)
first row
limit 1 -- or limit 0, 1
second row
limit 1, 1
third row
limit 2, 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24040329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating new DDM type I'm using Liferay 7 and I need to create a custom DDM type, which I'd like to use in structure creation. Can you please guide me how can I achieve that?
What I've read so far, all types are self-contained modules, so I've took dynamic-data-mapping-type-select from modules/apps/forms-and-workflow/dynamic-data-mapping and created a new project based on them. After deploying a new type is visible in the new form page, but not in structure form. What should I do, to make it visible in case of structures?
A: I have a quick guess that I'll try to flesh out if I get time today.
I suspect that the Forms App was built expecting to need to find any custom ddm-type modules and display them in the UI for selection. The Structures JSP is probably not updated to automatically expect to need to to find new types. So, I'm going to guess that there's a JSP that you need to modify somewhere in a dynamic-data-mapping-*-web module. Once you find what you need to modify and where it is, you'll be able to do that with a JSP override fragment. see here: https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/overriding-a-modules-jsps
Hopefully that at least helps you direct your research into this matter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40105836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generate and commit a file in the context of a post-receive hook I need to create a git hook whose responsibility is to compile a handlebars file to .js after a push. So, for every new .hbs file pushed, I must generate a corresponding .js file and for every modified .hbs, I need to update the corresponding .js. The .js file must then be added and committed to the repo.
The requirements state that it HAS to be done server side, so I cannot use any client side hooks.
I am planning to use a post-receive hook to implement this scenario.
I am a not very experimented using git (and even less hooks), so my question is: how can I add a file and create a new commit in a bare repository (in the context of a post-receive hook) if I don't have the files tree?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57661275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to insert data from a select query using php I wan to insert data to mysql table from another database which is connected via ODBC.But I cannot enter into the while loop, here is my code -
N.B: For security I dont provide db name, user and pass.
ODBC connection declared as 'connStr'
<?php
$connStr = odbc_connect("database","user","pass");
$conn = mysqli_connect("server","user","pass","database");
//$result_set=mysqli_query($conn,$datequery);
//$row=mysqli_fetch_array($result_set);
echo "<br>";
echo "<br>";
$query="select cardnumber, peoplename, creditlimit, ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'" ;
$rs=odbc_exec($connStr,$query);
$i = 1;
while(odbc_fetch_row($rs))
{ //echo "Test while";
$cardnumber=odbc_result($rs, "cardnumber");
$peoplename=odbc_result($rs, "peoplename");
$creditlimit=odbc_result($rs, "creditlimit");
$cbalance=odbc_result($rs, "cbalance");
$minpay=odbc_result($rs, "minpay");
$conn = mysqli_connect("server","user","pass","database");
$sql= "INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay) VALUES ('cardnumber', 'peoplename', 'creditlimit', 'cbalance', 'minpay') ";
if(!(mysqli_query($conn,$sql))){
//echo "Data Not Found";
echo "<br>";
}
else{
echo "Data Inserted";
echo "<br>";
}
echo $i++ ;
}
echo "<br>";
odbc_close($connStr);
?>
How can I solve this?
A: If you really want to understand why you can't enter while() {...}, you need to consider the following.
First, your call to odbc_connect(), which expects database source name, username and password for first, second and third parameter. It should be something like this (DSN-less connection):
<?php
...
$connStr = odbc_connect("Driver={MySQL ODBC 8.0 Driver};Server=server;Database=database;", "user", "pass");
if (!$connStr) {
echo 'Connection error';
exit;
}
...
?>
Second, check for errors after odbc_exec():
<?php
...
$rs = odbc_exec($connStr, $query);
if (!$rs) {
echo 'Exec error';
exit;
}
...
?>
A: you can do it with just SQL check it here, like:
INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay)
SELECT cardnumber, peoplename, creditlimit,
ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
where cardnumber not like '5127%'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53168912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tkinter focus on popup window I have a question regarding a popup window from the main window. How do I ensure that when there's a popup window (to set date & time), the main window cannot be touched (i.e closed or press anything) until the user close the popup window.
I have tried using grab_set but the main window can still be closed which result in error message:
bgerror failed to handle background error.
grab_set_global work for me but I won't be able to move the popup window around.
# Main window
root = Tk()
root.title("Restaurants")
root.geometry("800x500")
lines of codes..... where user will select if they want to set the date
and time
# Popup window
def date_time():
popup = Tk()
popup.title("Set Date and Time")
popup.geometry("500x500")
popup.grab_set() # Not working
lines of codes to run
I want it to focus on the popup window and the main window under it will not be able to close until the popup window is closed/destroyed.
A: You can use popup.focus_force, but probably first check if root is in focus. But that seems to be similar to cheating.
A: Ok, I have managed to solve my problem by changing the popup = Tk() to popup = Toplevel() and popup.grab_set works on the popup window. The main window can't be touched till the popup window is closed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58709452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use Coffeescript and shellJS to write executable shell scripts? I've installed coffeescript and shellJS, using NPM. I have a test script, shtest.coffee:
#!/usr/local/bin/coffee
require 'shelljs/global'
echo 'hello'
exit 1
Running the script with coffee works fine:
$ coffee shtest.coffee
hello
Or with shjs:
$ shjs shtest.coffee
hello
But not directly:
$ chmod u+x shtest.coffee
$ ./shtest.coffee
./shtest.coffee: line 2: require: command not found
hello
Changing the shebang to point to /usr/local/bin/js doesn't help.
It looks like the script is being run as a bash script. What am I doing wrong? OS X Snow Leopard.
A: Try using
#!/usr/bin/env coffee
as your shebang line. That works for me at least, though I'm not sure why exactly (apart from it having to do with the ENV somehow)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19129686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Tab character in SSRS Expression I have a requirement in SSRS report, wherein I need to write an expression which replaces a string having Chr(9) with a tab character. The data is fetched from stored procedure and it has tab characters [Chr(9)] which needs to be replaced with a tab in SSRS. I have tried various solutions(like adding spaces, vbTab, etc.) from different forums, but none seem to work.
For a newline, we use a vb constant ‘vbcrlf’. Similarly I am looking something for tab. Can someone please help?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33868260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python concatenate values in rows till empty cell and continue I am struggling a little to do something like that:
to get this output:
The purpose of it, is to separate a sentence into 3 parts to make some manipulations after.
Any help is welcome
A: Select from the dataframe only the second line of each pair, which is the line
containing the separator, then use astype(str).apply(''.join...) to restrain the word
that can be on any value column on the original dataframe to a single string.
Iterate over each row using split with the word[i] of the respective row, after split
reinsert the separator back on the list, and with the recently created list build the
desired dataframe.
Input used as data.csv
title,Value,Value,Value,Value,Value
Very nice blue car haha,Very,nice,,car,haha
Very nice blue car haha,,,blue,,
A beautiful green building,A,,green,building,lol
A beautiful green building,,beautiful,,,
import pandas as pd
df = pd.read_csv("data.csv")
# second line of each pair
d1 = df[1::2]
d1 = d1.fillna("").reset_index(drop=True)
# get separators
word = d1.iloc[:,1:].astype(str).apply(''.join, axis=1)
strings = []
for i in range(len(d1.index)):
word_split = d1.iloc[i, 0].split(word[i])
word_split.insert(1, word[i])
strings.append(word_split)
dn = pd.DataFrame(strings)
dn.insert(0, "title", d1["title"])
print(dn)
Output from dn
title 0 1 2
0 Very nice blue car haha Very nice blue car haha
1 A beautiful green building A beautiful green building
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62985724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CheckBoxGroup Bokeh Python New in Bokeh, I'm trying to build a html page with boxgroupcheck.
Below is df
UC_Month dep_delayed_15min_count dep_delayed_15min_sum dep_delayed_15min_Percent UC
AA-01 797 153 0.192 AA
AA-02 708 128 0.181 AA
AA-03 799 157 0.196 AA
I create a plot with bokeh using the following code
# Call once to configure Bokeh to display plots inline in the notebook.
output_notebook()
def plot_col(data, col, long, larg):
# Output file
output_file("bar_stacked_split.html")
# Define Labels
group = data[col].unique()
target = ['Flight on Time', 'Flight Delayed']
colors = ['blue', 'red']
# Define Values
val = {'Group': group,
'Flight on Time' : 1 - data['dep_delayed_15min_Percent'],
'Flight Delayed' : data['dep_delayed_15min_Percent']}
# Define plots
p1 = figure(plot_width = long, plot_height = larg, y_range = group,
tools=["box_zoom", "wheel_zoom", "lasso_select", "reset", "save"], tooltips= "$name @Group: @$name")
p1.hbar_stack(target, y= 'Group', height=0.9, color=colors, source= val, legend_label= target)
val2 = {'Group': group,
'Flight on Time' : data['dep_delayed_15min_count'] - data['dep_delayed_15min_sum'],
'Flight Delayed' : data['dep_delayed_15min_sum'] }
p2 = figure(plot_width= long, plot_height= larg, y_range= group,
tools=["box_zoom", "wheel_zoom", "lasso_select", "reset", "save"], tooltips= "$name @Group: @$name")
p2.hbar_stack(target, y='Group', height=0.9, color=colors, source= val2, legend_label= target)
return show(row(p1, p2))
Then I apply the plot function
plot_col(train_ucmonth, 'UC_Month', 750, 5550)
Which gives me this output
So, what I'm trying to do after that is to create a checkbox with train_ucmonth.UC.unique() and update the html output
I have found many ressources on internet regarding the checkboxgroup such as this one
However, my problem is that I already have a 'target' that I have 'flight delayed' and 'flight not delayed'.
Thus, my question is how can I add a filter box with column 'UC' and keeping my target like in my plot.
Edit
How can I add in the above plot a checkbox with the following values?
*
*WN
*AA
*UA
*OO
*OA
By selecting only one unique carrier, the plot should be updated.
Thanks for anyone helping!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62282926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Execute JavaScript with Cucumber/Capybara tests I am looking to execute some JavaScript within a after hook in my cucumber tests, what I'm looking to do is capture any JavaScript errors and output the errors within my console.
What I am having trouble with at the moment is using the method execute_script to run a piece of JavaScript
I get the error
undefined method `execute_script' for #<Cucumber::Ast::Scenario:0x5878608> (NoMethodError)
This is my setup so far
Capybara.register_driver :firefox do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
# see https://github.com/mguillem/JSErrorCollector
profile.add_extension "./lib/firefox_extensions/JSErrorCollector.xpi"
profile.native_events = false
Capybara::Selenium::Driver.new(app, :browser => :firefox)
end
(Am I adding the extension correctly by specifying the path correctly? using . to start at root?)
My After Hook
After do |page|
errors = page.execute_script("return window.JSErrorCollector_errors.pump()")
if errors.any?
STDOUT.puts '-------------------------------------------------------------'
STDOUT.puts "Found #{errors.length} javascript #{pluralize(errors.length, 'error')}"
STDOUT.puts '-------------------------------------------------------------'
errors.each do |error|
puts " #{error["errorMessage"]} (#{error["sourceName"]}:#{error["lineNumber"]})"
end
raise "Javascript #{pluralize(errors.length, 'error')} detected, see above"
end
end
Is there anything I'm doing here that looks incorrect or does anyone do this in a different way?
A: The After passes a Scenario object (the scenario that just ran) to the block, you've just happened to name the variable page. Frequently, this variable will be called scenario. The undefined_method line is showing what object type (#<Cucumber::Ast::Scenario:0x5878608>) the NoMethodError is coming from in the error message.
You should be able to execute code in an After block like you would in any other Cucumber step.
After do |scenario|
errors = page.execute_script("return window.JSErrorCollector_errors.pump()")
if errors.any?
STDOUT.puts '-------------------------------------------------------------'
STDOUT.puts "Found #{errors.length} javascript #{pluralize(errors.length, 'error')}"
STDOUT.puts '-------------------------------------------------------------'
errors.each do |error|
puts " #{error["errorMessage"]} (#{error["sourceName"]}:#{error["lineNumber"]})"
end
raise "Javascript #{pluralize(errors.length, 'error')} detected, see above"
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29341469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Undefined variable in blade after redirect I am using Laravel 7 and PHP 7.4.
I have form in my project. User can submit the form and I can generate report on values the user provided with. Initial issue was that the form was resubmitting on page refresh that was undesirable. I tried to prevent it with redirect-> but the issue is I'm unable to fetch the variable from controller into my view.
This is error on my blade.
Undefined variable: seller
Controller
$seller = Sellers::take(1)->latest()->get();
return redirect()->route('private_seller_report')->with(['seller' => $seller]);
Blade
@php
$seller = Session::get('seller');
@endphp
@foreach($seller as $row)
<a href="#">{{$row->seller_name}}</a>
@endforeach
So my ultimate goal is to prevent the form submission on refresh.
A: Here is an example of how you can do it. The ->with() method is not intended for this use, but you can just pass data in the route method instead, like so:
Route::get('/first-route', static function() {
return redirect()->route('second-route', ['data' => [1, 2, 3]]);
});
Route::get('/second-route', static function(\Illuminate\Http\Request $request) {
return view('test-view', ['data' => $request->input('data')]);
})->name('second-route');
Keep in mind that you are redirecting to another route, so you need the route you redirected to, to pass the data into the view. In this example, you can see that I pass [1, 2, 3] into second-route and then get the data via the request object. Then I pass that into the view in the second-route.
If I do a dd($request->input('data'); in second-route, I will get:
array:3 [
0 => "1"
1 => "2"
2 => "3"
]
So my best guess is that you never pass the data into the view, after the first route redirects to the next.
UPDATE:
Take a second and read the documentation about the ->with() method https://laravel.com/docs/7.x/redirects#redirecting-with-flashed-session-data and look at the PHPDoc of the code in RedirectResponse.php: Flash a piece of data to the session.
You can see here what the "flash" is used for: https://www.itsolutionstuff.com/post/laravel-5-implement-flash-messages-with-exampleexample.html
A: first time you need to call sellerPage method using this route.
Route::get('/seller/page','SellerController@sellerPage')->name('private_seller_report');
public function sellerPage()
{
$seller = Sellers::take(1)->latest()->get()->toArray();
return view('your.blade')->with(['seller' => $seller]);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63412014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Embedded YouTube video views on iOS app are not counted I added embedded Youtube video to my iOS app. It's work, but not counted as view counts!
I couldn't find its access on YouTube studio.
The video is YouTube Live Stream.
Doesn't playing via API consider as right view counts?
I feel the criteria is blackbox.
Selected library is below:
YoutubePlayer-in-WKWebView
My code is below:
private let youtubePlayer = WKYTPlayerView()
private func loadInline() {
youtubePlayer.load(withVideoId: videoID,
playerVars: ["playsinline": 1, "controls": 1])
}
func startInline() {
youtubePlayer.playVideo()
}
I could find my access from YouTube App.
Perhaps mobile access via API is not counted, but official YouTube app is counted.
I cannot find related documents.
A: I have read YouTube Documents in Japanese, but its translation is somehow misunderstood. The comments on the question helped me understand that.
Clearly YouTube declares they count only play via a native play button.
It means playback via API call is ignored.
(I guess it means user tap action would be counted.
A play button on my app is not "native")
Note: A playback only counts toward a video's official view count if it is initiated via a native play button in the player.
Playback controls and player settings
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63112614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Neural network with a single out with tensorflow I want to make a neural network that has one single output neuron on the last layer that tells me the probability of there being a car on an image (the probability going from 0 - 1).
I'm used to making neural networks for classification problems, with multiple output neurons, using the tf.nn.softmax_cross_entropy_with_logits() and tf.nn.softmax() methods. But these methods don't work when there is only one column for each sample in the labels matrix since the softmax() method will always return 1.
I tried replacing tf.nn.softmax() with tf.nn.sigmoid() and tf.nn.softmax_cross_entropy_with_logits() with tf.nn.sigmoid_cross_entropy_with_logits(), but that gave me some weird results, I might have done something wrong in the implementation.
How should I define the loss and the predictions on a neural network with only one output neuron?
A: Just use the sigmoid layer as the final layer. There's no need for any cross entropy when you have a single output, so just let the loss function work on the sigmoid output which is limited to the output range you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48003535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Testing Android Activity with Robolectric, duplicated Otto provider I have a little problem figuring out how to test my Activity using Robolectric 2.2. I am probably not correctly setting up the lifecycle or the entire test...
In my Activity, I have a Otto producer like this:
@Produce public GetAlarmList produceAlarmList() {
Log.v(this, "Producing GetAlarmList event.");
return new GetAlarmList(mAlarmList);
}
The following is my test.
@RunWith(RobolectricTestRunner.class)
public class GLarmListFragmentTests {
//GLarmMain mActivity;
ActivityController<GLarmMain> mController;
@Before
public void setUp() throws Exception {
mController = Robolectric.buildActivity(GLarmMain.class);
}
@After
public void tearDown() throws Exception {
mController = mController.destroy();
}
@Test
public void shouldHaveListFragment() {
GLarmMain activity = mController.create().start().resume().visible().get();
GLarmListFragment listFragment = (GLarmListFragment) activity.getSupportFragmentManager().findFragmentById(R.id.main_list_frag);
assertNotNull(listFragment);
}
@Test
public void shouldHaveListAdapter() {
GLarmMain activity = mController.create().start().resume().visible().get();
GLarmListFragment listFragment = (GLarmListFragment) activity.getSupportFragmentManager().findFragmentById(R.id.main_list_frag);
FuncAlarmListAdapter listAdapter = (FuncAlarmListAdapter)listFragment.getListAdapter();
assertNotNull(listAdapter);
}
}
Every time I launch it, I receive:
java.lang.IllegalArgumentException: Producer method for type class ar.android.app.glarm.events.GetAlarmList found on type class ar.android.app.glarm.ui.GLarmMain, but already registered by type class ar.android.app.glarm.ui.GLarmMain.
at com.squareup.otto.Bus.register(Bus.java:198)
at ar.android.app.glarm.ui.GLarmMain.onResume(GLarmMain.java:461)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
at android.app.Activity.performResume(Activity.java:5082)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.util.ActivityController$6.run(ActivityController.java:216)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256)
at org.robolectric.util.ActivityController.invokeWhilePaused(ActivityController.java:214)
at org.robolectric.util.ActivityController.resume(ActivityController.java:152)
at ar.android.app.glarm.test.GLarmListFragmentTests.shouldHaveListAdapter(GLarmListFragmentTests.java:51)
Does someone have the same issue? How can I solve it?
A: Found the problem, leaving it here for reference.
I was not handling the pause()/onPause() life-cycle step and therefore never calling:
@Override
protected void onPause() {
super.onPause();
Log.v(this, ".onPause()");
mBus.unregister(this); // unregisters.
}
Changing the above code as following solved:
@After
public void tearDown() throws Exception {
mController = mController.pause().stop().destroy();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20929572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How would I get the top role of a bot(client) in discordpy So right now my setup is
if memb.id != 'EzLife#9391' and memb.id != message.guild.owner.id and memb.top_role < client.top_role:
but the issue is that the client is a bot and the bot has no top role. I tried to get the member of the bot by doing client.me.top_role but I dont get any top role. any fixes?
A: As of right now, in the latest version of discord.py, there is no client.me
Here's something you can do though (using discord.ext's commands):
member = ctx.guild.get_member(client.user.id)
top_role = member.top_role
top_role will return discord.Role, so you can do top_role.name, top_role.id, etc.
You can check out the documentation here: https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.top_role
You can also join the discordpy discord for more help: https://discord.com/invite/r3sSKJJ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64442236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to show add to cart button after hover through product box in woocommerce? I have a problem when making a wordpress theme integrated with woocommerce like cannot show "add to cart" button when hovering a cursor in product box and only show when hovering a cursor to bottom in product box like GIF below:
woocommerce.css
.woocommerce ul.products li.product .button {
margin: 1em 0 3px 0.3em;
}
.woocommerce a.button {
/* font-size: 100%; */
/* margin: 0; */
/* line-height: 1; */
/* cursor: pointer; */
position: relative;
font-family: inherit;
text-decoration: none;
overflow: visible;
padding: 0.618em 1.75em;
font-weight: 700;
/* border-radius: 3px; */
/* left: auto; */
color: transparent;
background-color: transparent;
/* border: 0; */
/* white-space: nowrap; */
/* display: inline-block; */
/* background-image: none; */
/* box-shadow: none; */
/* -webkit-box-shadow: none; */
/* text-shadow: none; */
}
.woocommerce a.button:hover {
background-color: #f37020;
text-decoration: none;
color: #fff;
background-image: none;
}
.woocommerce ul.products li:hover {
border: 3px solid;
border-color: #f37020;
}
How I can fix it?
UPDATED (Dec 11,2015):
Its my URL link: http://dev.galerigadget.com/shop/
A: Obviously your "add to cart" button is only displaying when you hover the lower part of the box. That indicates only the bottom area is linked. Your "a" element might need to be "display:block" so it covers the entire block inside the brown rule. Hard to tell without seeing the actual site. Can you post URL?
AFTER EXAMINING YOUR CODE, HERE IS WHAT IS HAPPENING
The add-to-cart link is there, even when not hovered.
You do not see it b/c the CSS includes:
color: transparent;
background-color: transparent;
I would remove those parameters so the button is visible in gray and white. Looks nice and tells the user where to click to purchase the item.
You still have the hover effect that changes the button color to brown, but now the user clearly sees where to put their cursor.
If you want the button 'hidden' until the box is hovered, and then turn brown when hovering the box, add this to your CSS:
li:hover a.add_to_cart_button {
background-color: #f37020;
text-decoration: none;
color: #fff;
background-image: none;
}
A: Here is an example
$(document).ready(function () {
$(document).on('mouseenter', '.divbutton', function () {
$(this).find(":button").show();
}).on('mouseleave', '.divbutton', function () {
$(this).find(":button").hide();
});
});
.divbutton {
height: 140px;
background: #0000ff;
width:180px;
}
button{
padding: 4px;
text-align: center;
margin-top: 109px;
margin-left: 7px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divbutton" ">
<button type="button" style="display: none;">ADD TO CART</button>
</div>
Or If you want to use only CSS
button {
display: none; /* Hide button */
}
.divbutton:hover button {
display: block; /* On :hover of div show button */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34205282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you add a permission to a cmake target without repeating the default permissions? I would like to turn on the setuid bit for a program I'm installing using install(TARGETS... in cmake.
I can do this using the PERMISSIONS clause and specify SETUID. But when I do this, I lose all the default permissions unless I specify all of those, too.
For example, if this were bash, it would be like running chmod u=s,g=,o= file instead of chmod u+s file -- all the existing permissions are turned off instead of just masking in the one permission you want to add.
Is there a mechanism in cmake to add a permission to an installed target without repeating all the default permissions?
A: CMake has no other ways for set permissions for installed files except PERMISSIONS option for install command. But there are many ways for simplify permissions settings.
For example, you can define variable, contained default permissions set:
set(PROGRAM_PERMISSIONS_DEFAULT
OWNER_WRITE OWNER_READ OWNER_EXECUTE
GROUP_READ GROUP_EXECUTE
WORLD_READ WORLD_EXECUTE)
and use it as base for add new permissions:
install(TARGETS myexe ... PERMISSIONS ${PROGRAM_PERMISSIONS_DEFAULT} SETUID)
If some set of permissions is used in many places, you can define variable, contained that set, and use it when needed:
set(PROGRAM_PERMISSIONS_BY_ROOT ${PROGRAM_PERMISSIONS_DEFAULT} SETUID)
...
install(TARGETS myexe ... PERMISSIONS ${PROGRAM_PERMISSIONS_BY_ROOT})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32914041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to automatically test classes that use C# System Class Methods? I want to run Unit Tests on some C# classes that call methods from the System Classes. Specifically, in this case, Image.FromFile(); When I build my main project, everything compiles and runs smoothly, but when I try to run these automated tests, it says it can't find the System Classes. How do I help it "find" these System classes that my main project finds so easily?
I've tried adding References to the Test Project through the Solution Explorer, but the Assembly classes are mysteriously absent from the list of dependencies to choose from.
Here's the unit test:
[TestMethod]
public void initTest1()
{
Assert.IsNotNull(new Managers());
}
Here's the Managers constructor:
public Managers()
{
//...//
Image image = Image.FromFile("exit.png");
//...//
}
I expected the test to run, but instead it gave me this error:
Message: Test method ManagersTest.initTest1 threw exception:
System.IO.FileNotFoundException: Could not load file or assembly 'System.Drawing.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57683668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java inner class access outer class variable I have a question about inner class access. I am not experienced in Java, so please bear with me.
Below is the code i wrote:
public class MainFrame extends JFrame {
...
private String selectedNodeString = NULL; //outer class variable
private JPanel createControlPanel() {
...
parseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
tree.addTreeSelectionListener(new MyTreeSelectionListener());
}
});
class MyTreeSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
selectedNodeString = //compile error, can not resolve type
}
}
}
Below is an example from "thinking in java" explaining inner class access, where inner class can access outer class variable.
interface Selector {
...
}
public class Sequence {
private Object[] items;
private class SequenceSelector implements Selector {
...
private int i = 0;
public boolean end() { return i == items.length; }
public Object current() { return items[i]; }
public void next() { if(i < items.length) i++; }
}
}
So what is wrong with my code, is it more than 1 layer of inner class, and how to fix it?
Thanks
A: You are missing a curly brace after the method createControlpanel.
private JPanel createControlPanel() {
...
parseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
tree.addTreeSelectionListener(new MyTreeSelectionListener());
}
});
} // missing this one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25985956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i display my firebase data on my text? Flutter how can i display my firebase data on my text view in flutter? i have made a database where i store the users name in. What i want to do now is display that name from my database in firebase to my textview. i can't seem to figure it out.
this is my code for the textview
return Scaffold(
body: Stack(
children: <Widget>[
Container(
height: size.height * 1,
decoration: BoxDecoration (gradient: LinearGradient(colors: [
hexStringToColor("FFBEC8"),
hexStringToColor("fe98a8"),
hexStringToColor("FC98A7"),
hexStringToColor("#FF8799")
]
))),
SafeArea(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
Container(
height: 64,
margin: EdgeInsets.only(bottom: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
CircleAvatar(
radius: 29,
backgroundImage: AssetImage(
'assets/logo.png'),
),
SizedBox(
width: 16,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'gfffff',
style: TextStyle(
fontFamily: "Montserrat Medium",
color: Colors.white,
fontSize: 20),
),
],
)
],
),
),
i don't know if this is enought code for you to know how i stored it
FirebaseFirestore.instance.collection("Userdata").doc(value.user!.uid).set({"name": _userNameTextController.text});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74142402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF not deserializing JSON - Parameters in web service are null I am having the same issues as per this question: WCF not deserializing JSON input
I am at a loss and desperate for a solution. I have scoured the net for answers, but I have found only this question that matches my exact problem. My datacontract parameter is also nothing when the service starts.
I have tried the points of the answer in the question above, but they provide me with no clues (The web service executes OK -I am not getting any exceptions - and I can't see what the deserializer is doing - or not doing as the case may be).
I am using POST, due to the size of the nested JSON.
Could some WCF wizard, or the original poster of that question, please enlighten me?
If more detailed information is needed, I will provide it on request. My issue is so very similar to that question I was hoping the OP could pass on how he resolved the problem.
Updated
Code snippets - I'm under NDA, so can't post specifics.
"In-Page JS":
var settings = {
a: $("#a").val(),
b: $("#b").val(),
c: $("#c").val(),
d: $("#d").val(),
e: $("#e").val(),
f: $("#f").prop("checked").toString(),
g: $("#g").prop("checked").toString()
};
var data= {
a: [1011,1012,1013],
b: JSON.stringify(settings),
c: "01/01/2011 23:59:59"
};
Library.Services.Post("path/to/service/Service.svc/SaveSettings", data, true, function (result) {
if (result.Succeeded) {
ShowSuccess("Success.");
}
else {
ShowError("Failure.");
}
});
"Library.Services.Post":
Post: function (serviceUrl, data, async, successHandler, errorHandler) {
var continueOperation = true;
if (!data) {
data = "{}";
}
try {
var obj = $.parseJSON(data);
obj = null;
}
catch (err) {
continueOperation = false;
JS.ShowError("Data attribute is not a valid JSON object");
}
if (typeof (data) !== "string") {
data = JSON.stringify(data);
}
if (continueOperation) {
Library.Services._ajax("POST", serviceUrl, data, async, successHandler, errorHandler);
}
continueOperation = null;
}
"Library.Services._ajax":
_ajax: function (method, serviceUrl, data, async, successHandler, errorHandler) {
if (!typeof (successHandler) === "function") {
continueOperation = false;
ShowError("Success handler must be a function");
}
try {
$.ajax({
async: async,
cache: false, // don't cache results
type: method,
url: Library.Services.baseUrl + serviceUrl,
contentType: "application/json; charset=utf-8",
data: data,
dataType: "json",
processData: false, // data processing is done by ourselves beforehand
success: function (data, statusText, request) {
if (data != null) {
if (data.d && data.d.__type) {
data = data.d;
}
else {
// Wrapped message: return first property
$.each(data, function (name, value) {
data = value;
return false;
});
}
}
successHandler(data, statusText, request);
},
error: function (request, statusText, error) {
//debugger;
var res = request.responseText;
if (request.status != 200) {
if (!request.isResolved()) {
ShowError(request.status + " " + request.statusText);
}
else {
ShowError("Request could not be resolved.");
}
}
else {
ShowError("Unknown error status.");
}
if (typeof (errorHandler) === "function") {
errorHandler();
}
}
});
}
catch (err) {
ShowError("AJAX call failed");
}
}
"Service.svc":
<DataContract()>
Public Class SaveSettingsContract
<DataMember(Order:=1)>
Public a() As String
<DataMember(Order:=2)>
Public b()() As String
<DataMember(Order:=3)>
Public c As String
End Class
<OperationContract()>
<WebInvoke(BodyStyle:=WebMessageBodyStyle.Wrapped,
RequestFormat:=WebMessageFormat.Json,
ResponseFormat:=WebMessageFormat.Json)>
Public Function SaveSettings(ByVal settings as SaveSettingsContract) As WebServiceResults.BaseResult
' At this point in debugging, settings is Nothing
End Function
A: It is hard to say without knowing whole your code but perhaps there can be some help with diagnosing your issue.
Create small test application (console is enough) which will use DataContractJsonSerializer directly. Once you have this helper tool you can try to deserialize captured JSON message to your data contracts (use Fiddler to capture JSON) or you can try to create data contract you expect and serialize it and compare serialized and incoming message (they must be same).
A: I believe I found the answer to this question.
I think the reason the parameter was null was because this:
var data= {
a: [1011,1012,1013],
b: JSON.stringify(settings),
c: "01/01/2011 23:59:59"
};
should be this:
var data = {
settings: {
a: [1011,1012,1013],
b: JSON.stringify(settings),
c: "01/01/2011 23:59:59"
}
}
The data I wanted needed to be wrapped in a settings variable that matched the name of the parameter of the SaveSettings method. The service doesn't automatically put the data you send up into the settings parameter.
It sounds blindingly obvious now I look back at it, but for some reason I missed this when I was creating the service originally.
Edit: I believe I missed this because with the old asmx services, you could pass in the data in the same order as the parameters and the service automatically populated the parameters with the correct values. In WCF, however, that is not the case and you have to explicitly specify them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6384504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ruby: CSV.open with encoding fallback option When opening a CSV file in Ruby with CSV.open, is there a way to set encoding fallback similar to how it's set in String.encode?
Example:
CSV.open('file.csv', encoding: 'windows-1252:utf-8')
I would like to set something like this:
CSV.open('file.csv', encoding: 'windows-1252:utf-8', fallback: {
"\u0080" => "\x80",
"\u0081" => "\x81"
})
I couldn't find this in the docs, but maybe it's hidden somewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55102576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: neo4j & .NetCore Docker setup I want to setup my neo4j database and my .NetCore Web Api with Docker. I created the following docker-compose file :
version: '3.4'
services:
server:
image: ${DOCKER_REGISTRY-}server
network_mode: "bridge"
build:
context: .
dockerfile: Server/Dockerfile
stdin_open: true
tty: true
environment:
- CHOKIDAR_USEPOLLING=true
depends_on:
- neo4j
neo4j:
image: "neo4j:latest"
network_mode: "bridge"
ports:
- "7474:7474"
- "7687:7687"
volumes:
- $HOME/neo4j/data:/data
- $HOME/neo4j/logs:/logs
- $HOME/neo4j/import:/var/lib/neo4j/import
- $HOME/neo4j/plugins:/plugins
environment:
- NEO4J_AUTH=neo4j/admin
Within my .NetCore Server I check whether I can reach the neo4j address (172.17.0.3:7474), which works. Connecting to the Neo4J Database does not work with the following code :
_client = new GraphClient(new Uri("http://172.17.0.3:7474/db/data/"), "neo4j", "admin");
_client.Connect();
The error message is :
System.Exception: 'Received an unexpected HTTP status when executing the request.
The response status was: 404 Not Found
A: The library doesn't fully support Neo4j 4.x yet -still in development-.
You can either use an older image of Neo4j (using Neo4j:3.5.19 connects successfully), or you can use a different driver.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62516069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: EntityList / EntityCollection - MVVM Example I'm working with the new EntityList in the April toolkit to expose a collection in a ViewModel. I also have FK exposed as EntityCollections.
I thought I would expose the collection as IEnumerable, which handles the exposure of a collection using generic interfaces. That leaves the FK that I bind to grids/list .... can I create an enumerable with an embeded object using EntityCollection? Is this the "right" way?
I've also built a number of user controls, each with their own viewmodel. Does this mean the page should have a viewmodel, with the other viewmodels aggregated within it? Should each control stand on it's own, instanciating it's own viewmodel when the user control is embedded in a page?
I know that I could also jump over to POCO classes, but I'm on a tight deadline, and would like to minimize all the plumbing code.
I'm also a newbie on testing code, but I'm hoping that when I have more time, I can go back and fill that in.
So much to learn, so little time!
Thanks in advance...
A: You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to combine the Entity Framework 4 with MVVM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5959223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XSLT How to add Logic I have the following collection in an XML document:
<events>
<event>
<type>Downloaded</type>
<result>Sucess</result>
</event>
<event>
<type>Processed</type>
<result>Sucess</result>
</event>
</events>
Now in my XSLT I have a table with a TD - I want the value of this TD to represent the status of the events. If an event exists for processed and result is true, then I want the value of this TD to be Processed, likewise, if processed doesn't exist, then if downloaded exists and status is success, then I want the value of the TD to be downloaded...
Don't expect full code, just a sample on how to add some programming logic to XSLT.
What I really need to check for ... is
Does Element Event Exist with type = "Processed".... if not... then.... I'll figure the rest out.....
A: You can add if/else if logic to XSLT with <xsl:if>
There is also the ability to have something like a switch statement with <xsl:choose>, which includes the capability do do 'else' behaviour.
These constructs take a test attribute, in which you specify the condition. Here's a nice writeup on useful getting-started tests.
It's really something you have to play with to get used to, but these website links will give you a great start.
Example: given your document a template like:
<xsl:template match="/">
<xsl:for-each select="events/event">
<xsl:choose>
<xsl:when test="type/text() = 'Processed'">
<xsl:value-of select="result"></xsl:value-of>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:template>
Will produce the text 'Sucess'.
A: Untested, and I'm a bit confused by the logic you're trying to implement, but try starting with this:
<xsl:template match="/">
<table>
<xsl:apply-templates select="events/event" />
</table>
</xsl:template>
<xsl:template match="event">
<xsl:if test="type = 'Processed'">
<tr>
<td>
<xsl:value-of select="result" />
</td>
</tr>
</xsl:if>
</xsl:template>
A: xsl:choose is another option. From that link:
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 10">
<td bgcolor="#ff00ff">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="artist"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
The xsl:if doen't have an else functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1461839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert php array into a comma separated list of strings I have the following array:
$arr = [
0 => 'value1',
1 => 'value2',
2 => 'value3'
];
The select function of my db class takes arguments in the following format:
DB::table('users')->select('value1', 'value2', 'value3')
How can I convert my array to pass those values in my select function?
I tried implode(',', $arr) and it gives one string with comma separated values, but what I want is not a single string, it's a list of comma separated strings like in the example above.
Thanks for any help.
A: select() can accept an array, so try:
DB::table('users')->select($arr);
This is source code of select() method:
public function select($select = null)
{
....
// In this line Laravel checks if $select is an array. If not, it creates an array from arguments.
$selects = is_array($select) ? $select : func_get_args();
A: You can do this in Laravel 5.8 as follows:
DB::table('users')->select('username')->pluck('username')->unique()->flatten();
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39208705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use Google API in flutter? I want to use Google Cloud Natural Language in my Flutter app,I got Google API package
This works for flutter and theGoogle API_AUTH dependence is working for 0.2.1.
How do I implement them ?
A: The accepted answer is most likely written towards an older version of the SDK I just couldn't get it to work. This is what works for me as of now.
As an example, the following allow us to access files in Google Drive which is part of googleapis.
Dependencies
pubspec.yaml:
dependencies:
google_sign_in: any
googleapis: any
(I just put any here as a example, but you should specific the version(s) for you actual app.)
How it works
Necessary imports:
import 'package:googleapis/drive/v3.dart' as drive;
import 'package:google_sign_in/google_sign_in.dart' as signIn;
Step 1, sign in the user and ask for access permission (scope) to google drive:
final googleSignIn = signIn.GoogleSignIn.standard(scopes: [drive.DriveApi.DriveScope]);
final sign.GoogleSignInAccount account = await googleSignIn.signIn();
Step 2, build a AuthenticateClient:
class AuthenticateClient extends http.BaseClient {
final Map<String, String> headers;
final http.Client client;
AuthenticateClient(this.headers, this.client);
Future<http.StreamedResponse> send(http.BaseRequest request) {
return client.send(request..headers.addAll(headers));
}
}
As suggested in http, this is using the BaseClient with extra authentication headers (being composable).
Step 3, create a authenticated http client with from step 1 and 2 and access google drive API.
final baseClient = new Client();
final authenticateClient = AuthenticateClient(authHeader, baseClient);
final driveApi = drive.DriveApi(authenticateClient);
Checkout How to Use the Google Drive API With Flutter Apps for details.
A: This worked for me:
Logging in using package google_sign_in and then get auth headers from it:
import 'package:google_sign_in/google_sign_in.dart'
show GoogleSignIn, GoogleSignInAccount;
import 'package:googleapis/people/v1.dart'
show ListConnectionsResponse, PeopleApi;
useGoogleApi() async {
final _googleSignIn = new GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
await _googleSignIn.signIn();
final authHeaders = _googleSignIn.currentUser.authHeaders;
// custom IOClient from below
final httpClient = GoogleHttpClient(authHeaders);
data = await PeopleApi(httpClient).people.connections.list(
'people/me',
personFields: 'names,addresses',
pageToken: nextPageToken,
pageSize: 100,
);
}
This is a custom IOClient implementation that automatically adds the auth headers to each request. The googleapis call support passing a custom HTTP client to be used instead of the default (see above)
import 'package:http/io_client.dart';
import 'package:http/http.dart';
class GoogleHttpClient extends IOClient {
Map<String, String> _headers;
GoogleHttpClient(this._headers) : super();
@override
Future<StreamedResponse> send(BaseRequest request) =>
super.send(request..headers.addAll(_headers));
@override
Future<Response> head(Object url, {Map<String, String> headers}) =>
super.head(url, headers: headers..addAll(_headers));
}
A: Update to the accepted answer
Along with google_sign_in and googleapis packages, now you can use extension_google_sign_in_as_googleapis_auth package (provided by flutter.dev) to get configured http client. So the accepted answer can be simplified to below. No implementation of GoogleHttpClient is necessary.
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/people/v1.dart';
useGoogleApi() async {
final _googleSignIn = new GoogleSignIn(
scopes: [
'email',
PeopleServiceApi.contactsReadonlyScope,
],
);
await _googleSignIn.signIn();
// custom IOClient
final httpClient = await _googleSignIn.authenticatedClient();
data = await PeopleApi(httpClient!).people.connections.list(
'people/me',
personFields: 'names,addresses',
pageToken: nextPageToken,
pageSize: 100,
);
}
A: I can't add comments yet, so I'll just post it as an answer.
I kept trying to make a GoogleHttpClient as per the top answer, but on the import, it says "The library 'package:http/http.dart' doesn't export a member with the shown name 'IOClient'."
I found the answer here https://pub.dartlang.org/packages/http#-changelog-tab-, which says you should import IOClient separately as such: import 'package:http/io_client.dart';
I thought this might help out others who are new to flutter and its implementation of Google APIs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48477625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Linker script: insert absolute address of the function to the generated code I have a question related to gcc's linker.
I'm working with embedded stuff (PIC32), but PIC32's compiler and linker are based on gcc, so, main things should be common for "regular" gcc linker and PIC32 linker.
In order to save flash space (which is often insufficient on microcontrollers) I need to put several large functions in the bootloader, and application should call these functions just by pointers.
So, I need to create vector table in the generated code.
I'm trying to get absolute address of the function and write it to the generated code, but still getting errors.
In the example below I'm trying to get address of the function _formatted_write.
Code:
.user_addr_table _USER_ADDR_TABLE_ADDR :
{
KEEP(*(.user_addr_table))
LONG((ABSOLUTE(_formatted_write))); /* _formatted_write is a name of my function */
} > user_addr_table
Linker returns error: "unresolvable symbol '_formatted_write' referenced in expression".
I have noticed that if I write some garbage instead of _formatted_write, then it returns error "undefined symbol .....", so, _formatted_write is known by linker.
It makes me think I should perform some additional steps to make it "resolvable". But still no idea how to do that.
A: For the case that someone has the same problem (like me some hours ago), there is a still better solution:
Let "bootloader.out" be the bootloader-binary. Then we can generate with
nm -g bootloader.out | grep '^[0-9,a-e]\{8\} T' | awk '{printf "PROVIDE(%s = 0x%s);\n",$3,$1}' > bootloader.inc
a file that we can include in the linker script of the application with
INCLUDE bootloader.inc
The linker knows now the addresses of all bootloader-functions and we can link against it without to have the actual function code in the application. All what we need there is a declaration for every bootloader-function which we want to execute.
A: The way I found around this was to use function pointers, i.e.
void (*formatted_write)( int a, char * b, struct mystruct c );
then, in the code somewhere at boot set the address of this function, i.e.
formatted_write = 0xa0000;
you can then call your function using the normal convention.
Additionally, you can use the -Wl,--just-symbols=symbols.txt flag when compiling. You can set the address of your symbols as follows:
formatted_write = 0xa0000;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18173045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Android - Cannot connect to external IP address over mobile 3G/4G network using sockets Right now, I am writing a server/client program to allow a user to control different parts of their computer from an android phone on the fly. The server runs on the computer and the client runs from the android phone. I am using socket programming to do this, WinSocket on the computer and Android/Java sockets on the phone.
What Works:
*
*The server on the computer end works.
*When on the same wifi network, the client on the phone can send and
receive commands to/from the server.
*The server is accessible from outside the local wireless network it is connected to. I
tested this by using this open port checking tool to send a request
to the server. The server can successfully receive the request, and
the port checking website reports that the port I am using is
properly forwarded.
*When using an app on my android phone that tests open ports, my
server gets the connection request over 3G/4G.
Now for my problem. When I try to connect to the server running on the computer from the client on the phone, when the phone is connected to the internet through 3G or 4G, the socket does nothing and throws a socket timeout exception, and the server does not receive any connection request from the phone. I don't understand this because, like the 4th thing above, the port checking app I used can get through to my server program, but the code I'll post below doesn't do anything when running on 3G/4G.
String hostName = "SERVER_NETWORK_EXTERNAL_IP_HERE";
int port = 58587;
SocketAddress address = new java.net.InetSocketAddress(hostName, port);
sock = new Socket();
sock.connect(address, 5000);
The network activity indicator in the status bar at the top of the screen does not report outbound network activity when running this code, however if I am connected to wifi, everything works correctly. Anyone got any ideas?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18292815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MS SQL Temporary table looping Need help on sql looping query
my table :
my expecting output:
I am able to get 1 line only..
declare @ID nvarchar(50) = (select EMP_ID from HRS_WORKFLOW01);
CREATE TABLE #TEMP(EMP_ID NVARCHAR(200),EMP_L1 NVARCHAR(200),EMP_L2 NVARCHAR(200),EMP_L3 NVARCHAR(200),EMP_L4 NVARCHAR(200))
DECLARE @L1 NVARCHAR(50);
DECLARE @L2 NVARCHAR(50);
DECLARE @L3 NVARCHAR(50);
DECLARE @L4 NVARCHAR(50);
SET @L1 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@ID)
INSERT INTO #TEMP (EMP_ID,EMP_L1)VALUES(@ID,@L1)
SET @L2 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L1)
UPDATE #TEMP SET EMP_L2=@L2 WHERE EMP_ID=@ID
SET @L3 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L2)
UPDATE #TEMP SET EMP_L3=@L3 WHERE EMP_ID=@ID
SET @L4 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L3)
UPDATE #TEMP SET EMP_L4=@L4 WHERE EMP_ID=@ID
SELECT * FROM #TEMP
A: You need to use Recursive CTE
;WITH DATA
AS (SELECT *
FROM (VALUES ('ALI','ABU'),
('JOSH','LIM'),
('JAMES','KAREN'),
('LIM','JERRY'),
('JERRY','GEM')) TC(EMP_ID, EMP_L1)),
REC_CTE
AS (SELECT EMP_ID,
EMP_L1,
Cast(EMP_L1 AS VARCHAR(8000)) AS PARENT,
LEVEL = 1
FROM DATA
UNION ALL
SELECT D.EMP_ID,
D.EMP_L1,
Cast(RC.PARENT + '.' + D.EMP_L1 AS VARCHAR(8000)),
LEVEL = LEVEL + 1
FROM DATA D
JOIN REC_CTE RC
ON RC.EMP_ID = D.EMP_L1)
SELECT TOP 1 WITH TIES EMP_ID,
EMP_L1 = COALESCE(Parsename(PARENT, 1), ''),
EMP_L2 = COALESCE(Parsename(PARENT, 2), ''),
EMP_L3 = COALESCE(Parsename(PARENT, 3), ''),
EMP_L4 = COALESCE(Parsename(PARENT, 4), '')
FROM REC_CTE
ORDER BY Row_number()OVER(PARTITION BY EMP_ID ORDER BY LEVEL DESC)
OPTION (MAXRECURSION 0)
Result :
╔════════╦════════╦════════╦════════╦════════╗
║ EMP_ID ║ EMP_L1 ║ EMP_L2 ║ EMP_L3 ║ EMP_L4 ║
╠════════╬════════╬════════╬════════╬════════╣
║ ALI ║ ABU ║ ║ ║ ║
║ JAMES ║ KAREN ║ ║ ║ ║
║ JERRY ║ GEM ║ ║ ║ ║
║ JOSH ║ LIM ║ JERRY ║ GEM ║ ║
║ LIM ║ JERRY ║ GEM ║ ║ ║
╚════════╩════════╩════════╩════════╩════════╝
Note : This considers there can be maximum of 4 levels. To split the data into different columns I have used PARSENAME function which will not work if you more then 4 levels.
If you dont want to split the parents into different columns remove the PARSENAME and select the PARENT column alone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39951299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Angular UI Router Loading View, But Not Controller I'm getting very odd behavior from a very simple angular app using ui-router. All the templates are being loaded and displayed properly, but only 1 of the controllers is ever called, the DashboardCtrl. I can't explain this at all.
var adminPanel = angular.module('adminPanel', [
'ui.router',
'adminPanel.controllers'
])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardCtrl'
})
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
});
$urlRouterProvider.otherwise('/login');
});
adminPanel.controllers = angular.module('adminPanel.controllers', [])
.controller('LoginCtrl', function ($scope, $state, AuthService) {
console.log("hello!"); // never called
$scope.user = {
username: null,
password: null
};
$scope.submitLogin = function(loginForm) {
// never called
};
})
.controller('DashboardCtrl', ['$scope', function ($scope) {
console.log("Dashboard"); // this one is called for unkown reason
}])
.controller('HomeCtrl', [ '$scope', '$http', function ($scope, $http) {
console.log("HomeCtrl"); // never called
}]);
Markup is super simple:
<html>
<body ng-app="adminPanel">
<div ui-view></div>
<script src="js/vendor.js" type="text/javascript"/></script>
<script src="js/app.js" type="text/javascript"/></script>
</body>
</html>
The templates:
dashboard.html
<h1>Dashboard</h1>
home.html
<h1>Home</h1>
login.html
<h1>Login</h1>
<form name="loginForm" class="login-form" ng-submit="submitLogin(loginForm)">
<input type="text" name="username" ng-model="user.username"/>
<input type="password" name="password" ng-model="user.password"/>
</form>
A: I believe there was an issue with how I was attaching the controllers to the base angular module, but I still can't say for sure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33636332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: x86 How to add all the positive integers in an array I have this code below, and this seems to be adding up ALL the integers in an array, instead of taking ONLY the positive. I'm kind of confused how to fix this problem as I am new to x86 Assembly Programming. Thank you for your help!
int addpos(int* X, int length){
__asm{
PUSH ebx
PUSH ecx
PUSH edx
PUSH esi
PUSH edi
MOV ebx, X
MOV ecx, length
xor eax, eax
L1:
cmp ecx, 0
add eax, [ebx]
add ebx, 4
loop L1
POP edi
POP esi
POP edx
POP ecx
POP ebx
}
}
A: There are probably more efficient variations, but the following should do:
xor eax, eax ; total = 0
L1:
mov esi, [ebx] ; X[i]
add ebx, 4 ; or: lea ebx, [ebx + 4]
test esi, esi
js L2 ; jump if sign (most significant) bit set.
add eax, esi ; total += X[i]
L2:
loop L1
This may not be the best way to structure the loop - and it assumes that: length (ecx) != 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21464976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Electron Fetches Resources of React From Root Dir I spent the last week trying some of recipes to glue Electron + React, but, each of them has its cons.
Today, thought to do it by:
*
*create-react-app ...
*npm install electron --save-dev
*Put all Electron logic into build dir of React (must do some work to keep theme there after the coming step 5, because it will clear build dir)
*Using Electron's window.loadURL('file://.../index.html') (index.html) is react built HTML
*npm run build (will build react app)
*npx electron ./build/main.js
Wow! it worked like charm. But, there is only one conflict I need to know how to fix, which is:
React is writing links and sources as /../.. which Electron understands as root directory of the system, and I have to add the dot manually before each src to be ./../.., which fixed the conflict.
But, that would be almost impossible to do by hand for all the links in app! So, please, how can this done automatically.
A: Solved it today..
Just add property "homepage" : "./" to package.json,
check this issue comment on create-react-app
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52322648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to show small and large image in fixed height and width light box 2 Run the snippet will clear the actual issue raised here snippets contains two link images by clicking on image you will find the size difference.i want to show that images in fixed size instead of showing in their original sizes
// Uses Node, AMD or browser globals to create a module.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('jquery'));
} else {
// Browser globals (root is window)
root.lightbox = factory(root.jQuery);
}
}(this, function ($) {
function Lightbox(options) {
this.album = [];
this.currentImageIndex = void 0;
this.init();
// options
this.options = $.extend({}, this.constructor.defaults);
this.option(options);
}
// Descriptions of all options available on the demo site:
// http://lokeshdhakar.com/projects/lightbox2/index.html#options
Lightbox.defaults = {
albumLabel: 'Image %1 of %2',
alwaysShowNavOnTouchDevices: false,
fadeDuration: 600,
fitImagesInViewport: true,
imageFadeDuration: 600,
// maxWidth: 800,
// maxHeight: 600,
positionFromTop: 50,
resizeDuration: 700,
showImageNumberLabel: true,
wrapAround: false,
disableScrolling: false,
/*
Sanitize Title
If the caption data is trusted, for example you are hardcoding it in, then leave this to false.
This will free you to add html tags, such as links, in the caption.
If the caption data is user submitted or from some other untrusted source, then set this to true
to prevent xss and other injection attacks.
*/
sanitizeTitle: false
};
Lightbox.prototype.option = function (options) {
$.extend(this.options, options);
};
Lightbox.prototype.imageCountLabel = function (currentImageNum, totalImages) {
return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
};
Lightbox.prototype.init = function () {
var self = this;
// Both enable and build methods require the body tag to be in the DOM.
$(document).ready(function () {
self.enable();
self.build();
});
};
// Loop through anchors and areamaps looking for either data-lightbox attributes or rel attributes
// that contain 'lightbox'. When these are clicked, start lightbox.
Lightbox.prototype.enable = function () {
var self = this;
$('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function (event) {
self.start($(event.currentTarget));
return false;
});
};
// Build html for the lightbox and the overlay.
// Attach event handlers to the new DOM elements. click click click
Lightbox.prototype.build = function () {
var self = this;
$('<div id="lightboxOverlay" class="lightboxOverlay"></div><div id="lightbox" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /><div class="lb-nav"><a class="lb-prev" href="" ></a><a class="lb-next" href="" ></a></div><div class="lb-loader"><a class="lb-cancel"></a></div></div></div><div class="lb-dataContainer"><div class="lb-data"><div class="lb-details"><span class="lb-caption"></span><span class="lb-number"></span></div><div class="lb-closeContainer"><a class="lb-close"></a></div></div></div></div>').appendTo($('body'));
// Cache jQuery objects
this.$lightbox = $('#lightbox');
this.$overlay = $('#lightboxOverlay');
this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
this.$container = this.$lightbox.find('.lb-container');
this.$image = this.$lightbox.find('.lb-image');
this.$nav = this.$lightbox.find('.lb-nav');
// Store css values for future lookup
this.containerPadding = {
top: parseInt(this.$container.css('padding-top'), 10),
right: parseInt(this.$container.css('padding-right'), 10),
bottom: parseInt(this.$container.css('padding-bottom'), 10),
left: parseInt(this.$container.css('padding-left'), 10)
};
this.imageBorderWidth = {
top: parseInt(this.$image.css('border-top-width'), 10),
right: parseInt(this.$image.css('border-right-width'), 10),
bottom: parseInt(this.$image.css('border-bottom-width'), 10),
left: parseInt(this.$image.css('border-left-width'), 10)
};
// Attach event handlers to the newly minted DOM elements
this.$overlay.hide().on('click', function () {
self.end();
return false;
});
this.$lightbox.hide().on('click', function (event) {
if ($(event.target).attr('id') === 'lightbox') {
self.end();
}
return false;
});
this.$outerContainer.on('click', function (event) {
if ($(event.target).attr('id') === 'lightbox') {
self.end();
}
return false;
});
this.$lightbox.find('.lb-prev').on('click', function () {
if (self.currentImageIndex === 0) {
self.changeImage(self.album.length - 1);
} else {
self.changeImage(self.currentImageIndex - 1);
}
return false;
});
this.$lightbox.find('.lb-next').on('click', function () {
if (self.currentImageIndex === self.album.length - 1) {
self.changeImage(0);
} else {
self.changeImage(self.currentImageIndex + 1);
}
return false;
});
/*
Show context menu for image on right-click
There is a div containing the navigation that spans the entire image and lives above of it. If
you right-click, you are right clicking this div and not the image. This prevents users from
saving the image or using other context menu actions with the image.
To fix this, when we detect the right mouse button is pressed down, but not yet clicked, we
set pointer-events to none on the nav div. This is so that the upcoming right-click event on
the next mouseup will bubble down to the image. Once the right-click/contextmenu event occurs
we set the pointer events back to auto for the nav div so it can capture hover and left-click
events as usual.
*/
this.$nav.on('mousedown', function (event) {
if (event.which === 3) {
self.$nav.css('pointer-events', 'none');
self.$lightbox.one('contextmenu', function () {
setTimeout(function () {
this.$nav.css('pointer-events', 'auto');
}.bind(self), 0);
});
}
});
this.$lightbox.find('.lb-loader, .lb-close').on('click', function () {
self.end();
return false;
});
};
// Show overlay and lightbox. If the image is part of a set, add siblings to album array.
Lightbox.prototype.start = function ($link) {
var self = this;
var $window = $(window);
$window.on('resize', $.proxy(this.sizeOverlay, this));
$('select, object, embed').css({
visibility: 'hidden'
});
this.sizeOverlay();
this.album = [];
var imageNumber = 0;
function addToAlbum($link) {
self.album.push({
link: $link.attr('href'),
title: $link.attr('data-title') || $link.attr('title')
});
}
// Support both data-lightbox attribute and rel attribute implementations
var dataLightboxValue = $link.attr('data-lightbox');
var $links;
if (dataLightboxValue) {
$links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
for (var i = 0; i < $links.length; i = ++i) {
addToAlbum($($links[i]));
if ($links[i] === $link[0]) {
imageNumber = i;
}
}
} else {
if ($link.attr('rel') === 'lightbox') {
// If image is not part of a set
addToAlbum($link);
} else {
// If image is part of a set
$links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
for (var j = 0; j < $links.length; j = ++j) {
addToAlbum($($links[j]));
if ($links[j] === $link[0]) {
imageNumber = j;
}
}
}
}
// Position Lightbox
var top = $window.scrollTop() + this.options.positionFromTop;
var left = $window.scrollLeft();
this.$lightbox.css({
top: top + 'px',
left: left + 'px'
}).fadeIn(this.options.fadeDuration);
// Disable scrolling of the page while open
if (this.options.disableScrolling) {
$('body').addClass('lb-disable-scrolling');
}
this.changeImage(imageNumber);
};
// Hide most UI elements in preparation for the animated resizing of the lightbox.
Lightbox.prototype.changeImage = function (imageNumber) {
var self = this;
this.disableKeyboardNav();
var $image = this.$lightbox.find('.lb-image');
this.$overlay.fadeIn(this.options.fadeDuration);
$('.lb-loader').fadeIn('slow');
this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
this.$outerContainer.addClass('animating');
// When image to show is preloaded, we send the width and height to sizeContainer()
var preloader = new Image();
preloader.onload = function () {
var $preloader;
var imageHeight;
var imageWidth;
var maxImageHeight;
var maxImageWidth;
var windowHeight;
var windowWidth;
$image.attr('src', self.album[imageNumber].link);
$preloader = $(preloader);
$image.width(preloader.width);
$image.height(preloader.height);
if (self.options.fitImagesInViewport) {
// Fit image inside the viewport.
// Take into account the border around the image and an additional 10px gutter on each side.
windowWidth = $(window).width();
windowHeight = $(window).height();
maxImageWidth = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - 120;
// Check if image size is larger then maxWidth|maxHeight in settings
if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
maxImageWidth = self.options.maxWidth;
}
if (self.options.maxHeight && self.options.maxHeight < maxImageWidth) {
maxImageHeight = self.options.maxHeight;
}
// Is the current image's width or height is greater than the maxImageWidth or maxImageHeight
// option than we need to size down while maintaining the aspect ratio.
if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
imageWidth = maxImageWidth;
imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
$image.width(imageWidth);
$image.height(imageHeight);
} else {
imageHeight = maxImageHeight;
imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
$image.width(imageWidth);
$image.height(imageHeight);
}
}
}
self.sizeContainer($image.width(), $image.height());
};
preloader.src = this.album[imageNumber].link;
this.currentImageIndex = imageNumber;
};
// Stretch overlay to fit the viewport
Lightbox.prototype.sizeOverlay = function () {
this.$overlay
.width($(document).width())
.height($(document).height());
};
// Animate the size of the lightbox to fit the image we are showing
Lightbox.prototype.sizeContainer = function (imageWidth, imageHeight) {
var self = this;
var oldWidth = this.$outerContainer.outerWidth();
var oldHeight = this.$outerContainer.outerHeight();
var newWidth = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;
function postResize() {
self.$lightbox.find('.lb-dataContainer').width(newWidth);
self.$lightbox.find('.lb-prevLink').height(newHeight);
self.$lightbox.find('.lb-nextLink').height(newHeight);
self.showImage();
}
if (oldWidth !== newWidth || oldHeight !== newHeight) {
this.$outerContainer.animate({
width: newWidth,
height: newHeight
}, this.options.resizeDuration, 'swing', function () {
postResize();
});
} else {
postResize();
}
};
// Display the image and its details and begin preload neighboring images.
Lightbox.prototype.showImage = function () {
this.$lightbox.find('.lb-loader').stop(true).hide();
this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);
this.updateNav();
this.updateDetails();
this.preloadNeighboringImages();
this.enableKeyboardNav();
};
// Display previous and next navigation if appropriate.
Lightbox.prototype.updateNav = function () {
// Check to see if the browser supports touch events. If so, we take the conservative approach
// and assume that mouse hover events are not supported and always show prev/next navigation
// arrows in image sets.
var alwaysShowNav = false;
try {
document.createEvent('TouchEvent');
alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
} catch (e) { }
this.$lightbox.find('.lb-nav').show();
if (this.album.length > 1) {
if (this.options.wrapAround) {
if (alwaysShowNav) {
this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
}
this.$lightbox.find('.lb-prev, .lb-next').show();
} else {
if (this.currentImageIndex > 0) {
this.$lightbox.find('.lb-prev').show();
if (alwaysShowNav) {
this.$lightbox.find('.lb-prev').css('opacity', '1');
}
}
if (this.currentImageIndex < this.album.length - 1) {
this.$lightbox.find('.lb-next').show();
if (alwaysShowNav) {
this.$lightbox.find('.lb-next').css('opacity', '1');
}
}
}
}
};
// Display caption, image number, and closing button.
Lightbox.prototype.updateDetails = function () {
var self = this;
// Enable anchor clicks in the injected caption html.
// Thanks Nate Wright for the fix. @https://github.com/NateWr
if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
this.album[this.currentImageIndex].title !== '') {
var $caption = this.$lightbox.find('.lb-caption');
if (this.options.sanitizeTitle) {
$caption.text(this.album[this.currentImageIndex].title);
} else {
$caption.html(this.album[this.currentImageIndex].title);
}
$caption.fadeIn('fast')
.find('a').on('click', function (event) {
if ($(this).attr('target') !== undefined) {
window.open($(this).attr('href'), $(this).attr('target'));
} else {
location.href = $(this).attr('href');
}
});
}
if (this.album.length > 1 && this.options.showImageNumberLabel) {
var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
} else {
this.$lightbox.find('.lb-number').hide();
}
this.$outerContainer.removeClass('animating');
this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function () {
return self.sizeOverlay();
});
};
// Preload previous and next images in set.
Lightbox.prototype.preloadNeighboringImages = function () {
if (this.album.length > this.currentImageIndex + 1) {
var preloadNext = new Image();
preloadNext.src = this.album[this.currentImageIndex + 1].link;
}
if (this.currentImageIndex > 0) {
var preloadPrev = new Image();
preloadPrev.src = this.album[this.currentImageIndex - 1].link;
}
};
Lightbox.prototype.enableKeyboardNav = function () {
$(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
};
Lightbox.prototype.disableKeyboardNav = function () {
$(document).off('.keyboard');
};
Lightbox.prototype.keyboardAction = function (event) {
var KEYCODE_ESC = 27;
var KEYCODE_LEFTARROW = 37;
var KEYCODE_RIGHTARROW = 39;
var keycode = event.keyCode;
var key = String.fromCharCode(keycode).toLowerCase();
if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
this.end();
} else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
if (this.currentImageIndex !== 0) {
this.changeImage(this.currentImageIndex - 1);
} else if (this.options.wrapAround && this.album.length > 1) {
this.changeImage(this.album.length - 1);
}
} else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
if (this.currentImageIndex !== this.album.length - 1) {
this.changeImage(this.currentImageIndex + 1);
} else if (this.options.wrapAround && this.album.length > 1) {
this.changeImage(0);
}
}
};
// Closing time. :-(
Lightbox.prototype.end = function () {
this.disableKeyboardNav();
$(window).off('resize', this.sizeOverlay);
this.$lightbox.fadeOut(this.options.fadeDuration);
this.$overlay.fadeOut(this.options.fadeDuration);
$('select, object, embed').css({
visibility: 'visible'
});
if (this.options.disableScrolling) {
$('body').removeClass('lb-disable-scrolling');
}
};
return new Lightbox();
}));
/* Preload images */
body:after {
content: url(../images/close.png) url(../images/loading.gif) url(../images/prev.png) url(../images/next.png);
display: none;
}
body.lb-disable-scrolling {
overflow: hidden;
}
.lightboxOverlay {
position: absolute;
top: 0;
left: 0;
z-index: 9999;
background-color: black;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
opacity: 0.8;
display: none;
}
.lightbox {
position: absolute;
left: 0;
width: 100%;
z-index: 10000;
text-align: center;
line-height: 0;
font-weight: normal;
}
.lightbox .lb-image {
display: block;
height: auto;
max-width: inherit;
max-height: none;
border-radius: 3px;
/* Image border */
border: 4px solid white;
}
.lightbox a img {
border: none;
}
.lb-outerContainer {
position: relative;
*zoom: 1;
width: 250px;
height: 250px;
margin: 0 auto;
border-radius: 4px;
/* Background color behind image.
This is visible during transitions. */
background-color: white;
}
.lb-outerContainer:after {
content: "";
display: table;
clear: both;
}
.lb-loader {
position: absolute;
top: 43%;
left: 0;
height: 25%;
width: 100%;
text-align: center;
line-height: 0;
}
.lb-cancel {
display: block;
width: 32px;
height: 32px;
margin: 0 auto;
background: url(../images/loading.gif) no-repeat;
}
.lb-nav {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 10;
}
.lb-container > .nav {
left: 0;
}
.lb-nav a {
outline: none;
background-image: url('data:image/gif;base64,R0lGODlhAQABAPAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
}
.lb-prev, .lb-next {
height: 100%;
cursor: pointer;
display: block;
}
.lb-nav a.lb-prev {
width: 34%;
left: 0;
float: left;
background: url(../images/prev.png) left 48% no-repeat;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
opacity: 0;
-webkit-transition: opacity 0.6s;
-moz-transition: opacity 0.6s;
-o-transition: opacity 0.6s;
transition: opacity 0.6s;
}
.lb-nav a.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
}
.lb-nav a.lb-next {
width: 64%;
right: 0;
float: right;
background: url(../images/next.png) right 48% no-repeat;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
opacity: 0;
-webkit-transition: opacity 0.6s;
-moz-transition: opacity 0.6s;
-o-transition: opacity 0.6s;
transition: opacity 0.6s;
}
.lb-nav a.lb-next:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
}
.lb-dataContainer {
margin: 0 auto;
padding-top: 5px;
*zoom: 1;
width: 100%;
-moz-border-radius-bottomleft: 4px;
-webkit-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-moz-border-radius-bottomright: 4px;
-webkit-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.lb-dataContainer:after {
content: "";
display: table;
clear: both;
}
.lb-data {
padding: 0 4px;
color: #ccc;
}
.lb-data .lb-details {
width: 85%;
float: left;
text-align: left;
line-height: 1.1em;
}
.lb-data .lb-caption {
font-size: 13px;
font-weight: bold;
line-height: 1em;
}
.lb-data .lb-caption a {
color: #4ae;
}
.lb-data .lb-number {
display: block;
clear: left;
padding-bottom: 1em;
font-size: 12px;
color: #999999;
}
.lb-data .lb-close {
display: block;
float: right;
width: 30px;
height: 30px;
background: url(../images/close.png) top right no-repeat;
text-align: right;
outline: none;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=70);
opacity: 0.7;
-webkit-transition: opacity 0.2s;
-moz-transition: opacity 0.2s;
-o-transition: opacity 0.2s;
transition: opacity 0.2s;
}
.lb-data .lb-close:hover {
cursor: pointer;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<a href="https://4.img-dpreview.com/files/p/TS200x100~sample_galleries/5712229318/5425314683.jpg" data-lightbox="Image-Set" data-title="">
<img class="img-responsive center-block" src="https://4.img-dpreview.com/files/p/TS200x100~sample_galleries/5712229318/5425314683.jpg" alt="Image 1" style="width:auto;margin-top: 15px;height:270px;" />
</a>
<a href="https://4.img-dpreview.com/files/p/TS600x450~sample_galleries/5712229318/5716495176.jpg" data-lightbox="Image-Set" data-title="">
<img class="img-responsive center-block" src="https://4.img-dpreview.com/files/p/TS600x450~sample_galleries/5712229318/5716495176.jpg" alt="Image 1" style="width:auto;margin-top: 15px;height:270px;" />
</a>
I am using Light Box 2 and need to know that how can i fixed the
size of image for large as well as small image.i already tried code
given below but nothing happened.
img {
max-width: 400px;
max-height: 400px;
}
.lb-outerContainer, .lb-dataContainer {
max-width: 420px;
width: auto!important;
height: auto!important;
}
A: I don't know if this is the lightbox way to do it, but it seems to do the trick:
.lightbox .lb-image {
height : 400px !important;
width : 400px !important;
display: block;
height: auto;
border-radius: 3px;
/* Image border */
border: 4px solid white;
}
fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43593192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read banned words from a text file I am currently trying to build a moderator-bot that automatically scans a chat for banned words and then times people out when saying them.
Currently I have those banned words in a string-list but I'd want the bot to actually take the words out of a .txt file so I can easily have a bigger list of words without having to write a huge part of the code only containing bad words.
Currently my (part of the) code that does this looks like this:
List<string> BannedWords = new List<string> { "dog", "kitten", "bird" };
private bool BannedWordFilter(string username, string message)
{
foreach(string word in BannedWords)
{
if (message.Contains(word))
{
string command = "/timeout " + username + " 10";
irc.sendChatMessage(command);
irc.sendChatMessage(username + "no banned words allowed!");
return true;
}
}
return false;
}
So for now the bot times out people saying the words I put up as test.
But I am not really sure how I could built it so that the bot takes words out of a .txt file.
A: If you have a text with one banned word per line, e.g. like this:
dog
kitten
bird
...then you can read it using
BannedWords = System.IO.File.ReadAllLines("bannedWords.txt")`;
This returns an array of strings, each containing a line of the text file. See here for more information.
BTW: if you have lots of banned words, then it might be better to put then into a lookup, as this will make the lookup faster, e.g:
// read banned words
private ILookup<string, string> BannedWords;
// ...
BannedWords = File.ReadAllLines("bannedWords.txt").ToLookup(w => w);
// check message for banned words
if (message.Split(' ').Any(w => bannedWords.Contains(w))
{
// message contains a banned word
}
A: This should do it:
var wordsFile = File.ReadAllLines(BANNEDWORDS_PATH);
List<string> BannedWords = new List<string>(wordsFile);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39926943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: ByPass jQuery Plug-in OnClick Function I am using the following jQuery plug-in, i.e:
http://flowplayer.org/tools/scrollable.html
The issue I am having though is that, as part of the call to the api, it seems to make us of the onClick() function within the plug-in js file.
I actually want to use the onClick function as your normal javascript onClick() function but I am not able to as it seems to be overridden with the following code:
// assign onClick events to existing entries
} else {
// find a entries first -> syntaxically correct
var els = nav.children();
els.each(function(i) {
var item = $(this);
item.attr("href", i);
if (i === 0) { item.addClass(conf.activeClass); }
item.click(function() {
nav.find("." + conf.activeClass).removeClass(conf.activeClass);
item.addClass(conf.activeClass);
self.setPage(item.attr("href"));
});
});
}
});
// item.click()
if (conf.clickable) {
self.getItems().each(function(index, arg) {
var el = $(this);
if (!el.data("set")) {
el.bind("click.scrollable", function() {
self.click(index);
});
el.data("set", true);
}
});
}
Is there anyway of bypassing this, so that I can use the standalone onClick() function?
A: You can define your own click event handler and stop propagation of the event there.
$('your selector').click(function (e) {
e.stopPropagation();
});
A: Seems that they haven't given a callback function to call back to. You can modify their JS code to do this -
item.click(function() {
nav.find("." + conf.activeClass).removeClass(conf.activeClass);
item.addClass(conf.activeClass);
self.setPage(item.attr("href"));
if(typeof(clickCallback) != "undefined") clickCallback();
});
So, if you have a function called clickCallback defined on your page, you'll now be able to handle the click event after their click event code has been executed -
function clickCallback() {
//This is the function on your page. This will be called when you click the item.
}
You don't have to call the clickCallback function, the library will itself call that function if its been defined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1253327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enabling asp-prerender-module in ASP.NET CORE giving error I'm getting this error on enabling asp-prerender-module in ASP.NET CORE:
NodeInvocationException: Prerendering failed because of error:
TypeError: Cannot read property 'document' of undefined at
Rb.object.module.exports.module.exports at
Function.FusionChartsService.resolveFusionChartsCore at
Function.FusionChartsModule.fcRoot
A: The only solution I've reached is change your index.cshtml
<!-- remove this line
<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
-->
<!-- replace with -->
<app>Loading...</app>
<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}
A: In my case with ASP.NET Core 2 and Angular, this worked.
<app asp-ng2-prerender-module="ClientApp/dist/main-server">Loading...</app>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48556728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass values to IN operator in a Worklight SQL adapter I have started to work with SQL adapters in Worklight, but I do not understand how can I pass values to an IN condition when invoking my adapter procedure.
A: You will need to edit your question with your adapter's XML as well as implementation JavaScript...
Also, make sure to read the SQL adapters training module.
What you need to do is have your function get the values:
function myFunction (value1, value2) { ... }
And your SQL query will use them, like so (just as an example how to pass variables to any SQL query, doesn't matter if it contains an IN condition or not):
SELECT * FROM person where name='$[value1]' or id=$[value2];
Note the quotation marks for value1 (for text) and lack of for value2 (for numbers).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16012017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: function still working after global variable change Ok I have the code:
$(document).ready(function(){
if(selected == 0){
$(".color").mouseover(function(){
var image = $(this).children('img').attr('src');
$(this).children('img').css("border", "2px solid #000000");
$("#itemMainImg").attr("src", image);
});
$(".color").mouseout(function(){
$(this).children('img').css("border", "none");
})
$(".color").click(function(){
var image = $(this).children('img').attr('src');
console.log("worked");
$("#itemMainImg").attr("src", image);
$(this).children('img').css("border", "2px solid #000000");
selected = 1;
console.log(selected);
colorSelected = $(this).children('img').attr('src');
});
}
else{
$(".color").click(function(){
var image = $(this).children('img').attr('src');
if(image == colorSelected){
$("#itemMainImg").attr("src", image);
if($(this).children('img').css("border") == "none"){
$(this).children('img').css("border","2px solid #000000");
}
else{
$(this).children('img').css("border", "none");
selected = 0;
}
}
});
}
});
I have a global variable assigned var selected = 0;
and var colorSelected = "";
The html looks like this:
<div id="itemHead">
<div id="itemMain">
<h1 id="itemH1">Demo Item by Demo</h1>
<img id="itemMainImg" src="photos/Carpets/ApolloBoxwood - Copy.jpg">
</div>
<div id="itemColors">
<div>
<p id="colorsP">Available Colours</p>
</div>
<div>
<div class="color">
<img class="colorImg" src="photos/Carpets/ApolloBoxwood - Copy.JPG" alt="Apollo Plus Boxwood">
<p class="colorPara">Boxwood</p>
</div>
<div class="color">
<img class="colorImg" src="photos/Carpets/ApolloCinderGrey - Copy.JPG" alt="Apollo Plus Cinder Grey">
<p class="colorPara">Cinder Grey</p>
</div>
<div class="color">
<img class="colorImg" src="photos/Carpets/ApolloCorkOak - Copy.JPG" alt="Apollo Plus Cork Oak">
<p class="colorPara">Cork oak</p>
</div>
</div>
</div>
for some reason when I click on the .color divs the selected value is changed to 1, but the function still acts like the value is 0. So on page var selected gets set to 1, but the first part of the if statement still works. I don't think it should as I've changed the global variable with the click.
A: You are binding your click events on document ready based on the value of selected - only the first click event in your code will ever be bound to the element as the initial value is zero. You need to move the logic in to the click function so that the value is checked every time the function runs:
$(document).ready(function(){
$(".color").click(function(){
if(selected == 0){
/* do something if value is zero */
} else {
/* do something if value is NOT zero */
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34253730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: sql left join issue not giving result of non matching from right table i want all records from left table and matching record from right table but below query not giving correct result:
select a.date,b.amt,b.code,c.type
from (select date from t where date is between '2017-04-01' and '2018-09-30')a
on a.date = b.date and a.name = b.name left join
c on c.date = b.date and c.name = b.name or c.name is null
group by a.date,b.amt,b.code,c.type
I cant see value for all code from table b.Its returning only matching from table c
A: When you do a LEFT JOIN, you are taking all the rows from the first table and if there are no matches for the first join condition, the resulting records for table x will be a NULL record which is why you're using the AND operator 'c.name IS NULL' but I think you have some issues with your query. It's been a while for me so I'm trying not to make an error here but you don't appear to have a table name in your FROM clause and your select can't be in the from clause (i don't think)...maybe I'm wrong but I had to clean up the statement to understand what you are doing better...so please clarify and I can improve my answer.
SELECT
[a].[date] AS 'Date'
,[b].[amt] AS 'Amount'
,[b].[code] AS 'Code'
,[c].[type] AS 'Type'
FROM [table].[name] (NOLOCK)
LEFT JOIN [table].[name] (NOLOCK) date ON [c].[date] = [b].[date]
LEFT JOIN [table].[name] (NOLOCK) name ON [c].[name] = [b].[name]
WHERE (SELECT date
FROM [t]
WHERE DATEADD (hh,-6, DATEADD (ss,[table].[name],'1970')) BETWEEN '2017-04-01' AND '2018-09-30')
AND [a].[date] = [b].[date] //Not sure if this is what you meant
AND [a].[name] = [b].[name]
AND [c].[name] IS NULL
GROUP BY [a].[date],[b].[amt],[b].[code],[c].[type]
A: With some guesswork involved, I could imagine you want:
SELECT DISTINCT
t.date,
b.amt,
b.code,
c.type
FROM t
LEFT JOIN b
ON b.date = t.date
AND b.name = t.name
LEFT JOIN c
ON c.date = b.date
AND (c.name = b.name
OR c.name is null)
WHERE t.date BETWEEN '2017-04-01'
AND '2018-09-30';
*
*Your subquery from t isn't really needed, that check on date can be moved in the WHERE clause. But it wasn't strictly wrong. It depends on what the optimizer makes of it what's better.
*Though your GROUP BY has the same effect, I changed it to a DISTINCT, which might be more clear to understand at a glance.
*And I'm not sure about your join condition for c.
*
*I guessed you want the date to match but allow c.name to be null if it doesn't match. That means you have to use parenthesis to counter the higher precedence of AND over OR.
*You probably want to change the b.s in the join condition to t.s, if record from c should also be added if no matching record from b exists for a record from t. Like it is right now, no record from c is joined for a record from t without a matching record from b.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51312636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: My custom slide doesnt go in a row Please take a look at this
http://jsfiddle.net/CztkH/6/
I want to run my slide in a row (like how we play films). But i cant make it slide in a row :(. Please help me Q.Q
Here is my javascript that run the slide:
function doDoubleSlide(obj1, obj2){
obj1.hide("slide", {direction:"left"},1000);
obj2.show("slide", {direction:"right"},1000);
setTimeout(function(){doDoubleSlide(obj2,obj1);}, 3000);
}
doDoubleSlide($("#sl01"), $("#sl02"));
Thanks for your time.
A: The way you've structured your slider with JavaScript and CSS has a few different problems, I don't think there's any easy fix for what you're putting together here.
*
*you're animating the slides in a way that's problematic from a CSS point of view - the should be floated inline
*and you should be animating one main container rather than animating the elements inside of their separate containers.
The best advice I could give you is to use a different approach.
I see you're using the jQuery UI library for the animations - I don't think that's the best fit for what you're trying to achieve here - those plugins are better suited to effects and require more work to adapt and re-skin.
There's lots of better suited, existing plugins out there specifically for slideshows like this and work well out of the box:
http://jquerytools.org/demos/scrollable/index.html
http://www.woothemes.com/flexslider/
http://jquery.malsup.com/cycle/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13233915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenCV make on Ubuntu with opencv_contrib fails due to opencv_xphoto I'm trying to build OpenCV on Ubuntu 15.10 with opencv_contrib (to use the nonfree modules). I did the following:
cmake -D CMAKE_BUILD_TYPE=RELEASE -DOPENCV_EXTRA_MODULES_PATH=/home/myname/Downloads/opencv_contrib-master/modules -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D BUILD_opencv_ximgproc=ON ..
but I tried also with
BUILD_opencv_ximgproc=OFF
CMake goes well but it fails during the make step:
CMakeFiles/Makefile2:8403: recipe for target 'modules/xphoto/CMakeFiles/opencv_xphoto.dir/all' failed
make[1]: *** [modules/xphoto/CMakeFiles/opencv_xphoto.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
and then:
Makefile:136: recipe for target 'all' failed
make: *** [all] Error 2
Do you have any suggestions?
Thanks.
A: I solved it by deleting and re-downloading both opencv and opencv_contrib. Then I built everything again:
git clone https://github.com/Itseez/opencv.git
git clone https://github.com/Itseez/opencv_contrib.git
cd opencv
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -DOPENCV_EXTRA_MODULES_PATH=/home/myname/Downloads/opencv_contrib/modules -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D BUILD_opencv_ximgproc=ON ..
make -j7
sudo make install
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35825391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: is comparison on various objects in python When I do the is comparison on a list is acts differently than on a number or string. For example:
>>> a=[1,2,3] # id = 4344829768
>>> b=[1,2,3] # id = 4344829960
>>> a is b
False
>>> c=1 # id = 4304849280
>>> d=1
>>> c is d
True
Why is this so?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58469563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Typescript groupBy "Cannot be used to index type '{}'" when trying to add key to reduce object I'm trying to get the following function to compile without TS erros:
function groupBy<Item>(items: Item[], key: keyof Item) {
return items.reduce((acc, item) => {
(acc[item[key]] = acc[item[key]] || []).push(item);
return acc;
}, {});
}
But assigning to acc results in Type 'Item[keyof Item]' cannot be used to index type '{}'.
I've tried a lot of other things like playing with Extract and Record but just results in more errors e.g.
export function groupBy<Item extends Record<string, object>, K extends Extract<keyof Item, string>>(
items: Item[],
key: K
) {
return items.reduce((acc: Record<K, Item[]>, item: Item) => {
(acc[item[key]] = acc[item[key]] || []).push(item);
return acc;
}, {});
}
P.S the functionality is like lodash groupBy e.g.
groupBy(['one', 'two', 'three'], 'length');
// Result: { '3': ['one', 'two'], '5': ['three'] }
How can I fix that? Thanks
A: I'd type it like this:
function groupBy<T extends Record<K, PropertyKey>, K extends keyof T>(
items: readonly T[],
key: K
) {
return items.reduce((acc, item) => {
(acc[item[key]] = acc[item[key]] || []).push(item);
return acc;
}, {} as Record<T[K], T[]>);
}
The important bits are: mutually constraining K and T so that K is a key of T where the property T[K] is itself suitable to be a key of an object; and asserting that the accumulator will eventually be of type Record<T[K], T[]>, an object whose keys are the same as T[K] and whose values are an array of T.
Then you can test that it works:
const g = groupBy(['one', 'two', 'three'], 'length');
// const g: Record<number, string[]>
console.log(
Object.keys(g).map(k => k + ": " + g[+k].join(", ")).join("; ")
); // 3: one, two; 5: three
The type of g is inferred as {[k: number]: string[]}, an object with a numeric index signature whose properties are string arrays. As another example, to make sure it works:
interface Shirt {
size: "S" | "M" | "L"
color: string;
}
const shirts: Shirt[] = [
{ size: "S", color: "red" },
{ size: "M", color: "blue" },
{ size: "L", color: "green" },
{ size: "S", color: "orange" }];
const h = groupBy(shirts, "size");
// const h: Record<"S" | "M" | "L", Shirt[]>
console.log(JSON.stringify(h));
//{"S":[{"size":"S","color":"red"},{"size":"S","color":"orange"}],"M":[{"size":"M","color":"blue"}],"L":[{"size":"L","color":"green"}]}
Here we see that a Shirt has a size property from a limited selection of string literals, and groupBy(shirts, "size") returns a value inferred to be of type {S: Shirt[], M: Shirt[], L: Shirt[]}.
Okay, hope that helps; good luck!
Playground link to code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62134312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IOS how to POST GET DELETE PUT Rest Api I am building my App conected to a Rest API and until now I only made a GET request with the following code :
//Start login process
NSString *emailstring = email.text;
NSString *passstring = pass.text;
// Create the URL from a string.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.myserver.com/Rest/API/users?format=json&email=%@&password=%@",emailstring,passstring]];
NSLog(@"%@",url);
// Create a request object using the URL.
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Prepare for the response back from the server
NSHTTPURLResponse *response = nil;
NSError *error = nil;
// Send a synchronous request to the server (i.e. sit and wait for the response)
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Reponse from web:%@", response);
// Check if an error occurred
if (error != nil) {
NSLog(@"%@", [error localizedDescription]);
// Do something to handle/advise user.
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Login error"
message:@""
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[message show];
}
else {
// Convert the response data to a string.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// View the data returned - should be ready for parsing.
NSLog(@"%@", responseString);
// Add data to a Plist file for next time
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"login.plist"];
NSArray *values = [[NSArray alloc] initWithObjects:emailstring,passstring,@"IDtest",nil];
[values writeToFile:path atomically:YES];
[values release];
[self dismissModalViewControllerAnimated:YES];
}
This code work fine just for a GET request. I saw it is there a lot of framework (e.g RestKit, ....). But I am getting a bit lost with other request ! So what is the best solution to make POST DELETE PUT request for an IOS App ?
A: It's similar code, but using the class NSMutableRequest. You can set the httpbody and other parameters to communicate with the server.
check the documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html
to post something, just put setHTTPMethod:@"POST"and assign the data to post using setHTTPBody:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12047717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: propriety: opacity into my background color in css I would like to use the propriety: opacity into my background color. However, when I use this propriety, all the elements become transparent. I just want to change the background color.
Thank you for your help.
body{
margin: 0px;
padding: 0px;
}
header{
background-color: #B1DBE8;
height: 98px;
opacity: 0.8;
}
.header-block{
font-size: 11px;
text-transform: uppercase;
padding-top: 8px;
font-weight: 700;
color: #777;
line-height: 20px;
}
.page-left{
display: inline-block;
margin-left: 430px;
}
.page-left-languages{
display: inline-block;
margin-left: 30px;
}
.page-right{
display: inline-block;
float: right;
margin-right: 134px;
}
.page-right-login{
display: inline-block;
float: right;
margin-right: -100px;
}
nav{
position: relative;
top: 6px;
float: right;
right: 92px;
}
nav ul{
list-style: none;
}
nav ul li{
display: inline-block;
font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif;
font-size: 14px;
font-weight: bold;
text-transform: uppercase;
line-height: 27px;
}
nav ul li a{
padding: 8px 16px;
text-decoration: none;
color: #FFF;
text-decoration: center;
border-radius: 3px
}
nav ul li a:hover{
background-color: #FFF;
color: black;
}
.active{
background-color: #cd2122;
color: #FFF;
padding: 8px 16px;
border-radius: 3px;
}
<body>
<header>
<div class="header-block">
<div class="page-left">Portfolio</div>
<div class="page-left-languages">Languages</div>
<div class="page-right">Support</div>
<div class="page-right-login">Login</div>
</div>
<nav>
<ul>
<li><a class="active"><href="#">Home</a></li>
<li><a href="#"> Plan</a></li>
<li><a href="#">Commission</a></li>
<li><a href="#">About us</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Register</a></li>
<li><a href="#">Pages</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</nav>
</header>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60790642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read PNG file with c I want to read a PNG image file with C without any library. From PNG (Portable Network Graphics) Specification Version 1.0 any PNG file has a signature that distinguishes it from other image formats. The signature is the first 8 bytes of the image.
Some sources like the above RFC mentioned the signature as:
137 80 78 71 13 10 26 10 (decimal)
Or like Not able to read IHDR chunk of a PNG file mentioned the signature as:
89 50 4E 47 0D 0A 1A 0A (ASCii)
So, I write a simple code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE (8)
int main(int argc, char **argv){
if(argc != 2) {
printf("Usage: %s <png file>\n", argv[0]);
return 1;
}
char *buf = (char *)malloc(MAX_SIZE);
if(!buf) {
fprintf(stderr, "Couldn't allocate memory\n");
return 1;
}
FILE *f = fopen(argv[1], "r");
if(!f) {
perror("fopen");
printf("Invalid file\n");
free(buf);
return 1;
}
int size = fread(buf, 1, MAX_SIZE, f);
printf(%c\n", buf[1]);
printf(%c\n", buf[2]);
printf(%c\n", buf[3]);
printf(%c\n", buf[4]);
printf(%c\n", buf[5]);
printf(%c\n", buf[6]);
printf(%c\n", buf[7]);
printf(%c\n", buf[8]);
fclose(f);
free(buf);
system("pause");
return 0;
}
When I print the bytes by printf, the output is not like the above.
This is what it shows:
ëPNG→►v@,
Can someone describe what happened and what can I do to modify it?
A: You need to print each value with the correct format specifier. Here we want numerical representations, not character ones.
From the documentation on printf:
*
*%c writes a single character
*%d converts a signed integer into decimal representation
*%x converts an unsigned integer into hexadecimal representation
%02X prints a hexadecimal with a minimum width of two characters, padding with leading zeroes, using ABCDEF (instead of abcdef).
See also implicit conversions.
An example:
#include <stdio.h>
#define SIZE 8
int main(int argc, char **argv) {
unsigned char magic[SIZE];
FILE *file = fopen(argv[1], "rb");
if (!file || fread(magic, 1, SIZE, file) != SIZE) {
fprintf(stderr, "Failure to read file magic.\n");
return 1;
}
/* Decimal */
for (size_t i = 0; i < SIZE; i++)
printf("%d ", magic[i]);
printf("\n");
/* Hexadecimal */
for (size_t i = 0; i < SIZE; i++)
printf("%02X ", magic[i]);
printf("\n");
fclose(file);
}
Output:
137 80 78 71 13 10 26 10
89 50 4E 47 0D 0A 1A 0A
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70098489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bash: recursively write a line to a file from column maximum Linking back to my previous question, I found the problem not to be entirely solved. Here's the problem:
I have directories named RUN1, RUN2, and RUN3
Each directory has some files. Directory RUN1 has files mod1_1.csv, mod1_2.csv, mod1_3.csv. Directory RUN2 has files mod2_1.csv, mod2_2.csv, mod3_3.csv, etc.
The contents of mod1_1.csv file look like this:
5.71 6.66 5.52 6.90
5.78 6.69 5.55 6.98
5.77 6.63 5.73 6.91
And mod1_2.csv looks like this:
5.73 6.43 5.76 6.57
5.79 6.20 5.10 7.01
5.71 6.21 5.34 6.81
In RUN2, mod2_1.csv looks like this:
5.72 6.29 5.39 5.59
5.71 6.10 5.10 7.34
5.70 6.23 5.23 6.45
And mod2_2.csv looks like this:
5.72 6.29 5.39 5.69
5.71 6.10 5.10 7.32
5.70 6.23 5.23 6.21
My goal is to obtain the line with the smallest value of column 4 for each RUN* directory, and write that and the model which gave it to a new .csv file. Right now, I have this code:
#!/bin/bash
resultfile="best_results_mlp_2.txt"
for d in $(find . -type d -name 'RUN*' | sort);
do
find $d -type f -name 'mod*' -exec sort -k4 {} -g \; | head -1 >> "$resultfile"
done
But it doesn't always return the smallest value of column 4 (I went through the files and checked), and it doesn't include the file name that contains the smallest number. To clarify, I would like a .csv file with these contents:
5.73 6.43 5.76 6.57 mod1_2.csv
5.72 6.29 5.39 5.59 mod2_1.csv
A: If you would like to get the smallest value from all files, you will have to sort all their content at once. The command currently sorts file by file, so you get the smallest value in the first sorted file.
Check the difference between
find "$d" -type f -name 'mod*' -exec sort -k4 -g {} +
and
find "$d" -type f -name 'mod*' -exec sort -k4 -g {} \;
Also it is recommended to use -n instead of -g unless you really need to.
Check --general-numeric-sort section of info coreutils 'sort invocation' for more details why.
Edit: Just checked the link to your previous question and I see now that you need to use --general-numeric-sort
That said, here's a way to get the corresponding filename into the lines, so that you have it in the output:
find "$d" -type f -name 'mod*' -exec awk '{print $0, FILENAME}' {} \;|sort -k4 -g |head -1 >> "$resultfile"
Essentially awk is invoked for each file separately. Awk print each line of the file, appending the corresponding file name to it. Then all those lines are passed for sorting.
Note: The above will print the filename with its path under which find found it. If you are looking to get only the file's basename, you can use the following awk command instead (the rest stays the same as above):
awk 'FNR==1{ cnt=split(FILENAME, arr, "/"); basename=arr[cnt] } { print $0, basename}'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42709021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Devise and rvm having issues I am trying to run:
rails generate devise User
and I am getting the following error:
/home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/inflector/methods.rb:238:in `const_get': uninitialized constant User (NameError)
from /home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/inflector/methods.rb:238:in `block in constantize'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/inflector/methods.rb:236:in `each'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/inflector/methods.rb:236:in `inject'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/inflector/methods.rb:236:in `constantize'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise.rb:297:in `get'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/mapping.rb:77:in `to'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/mapping.rb:72:in `modules'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/mapping.rb:89:in `routes'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/mapping.rb:156:in `default_used_route'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/mapping.rb:66:in `initialize'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise.rb:331:in `new'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise.rb:331:in `add_mapping'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/rails/routes.rb:221:in `block in devise_for'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/rails/routes.rb:220:in `each'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/devise-3.2.4/lib/devise/rails/routes.rb:220:in `devise_for'
from /home/zach/HandCoOp/project/HandCo-op/config/routes.rb:2:in `block in <top (required)>'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/routing/route_set.rb:337:in `instance_exec'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/routing/route_set.rb:337:in `eval_block'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/routing/route_set.rb:315:in `draw'
from /home/zach/HandCoOp/project/HandCo-op/config/routes.rb:1:in `<top (required)>'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:40:in `each'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:40:in `load_paths'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:16:in `reload!'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:26:in `block in updater'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/file_update_checker.rb:75:in `call'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.4/lib/active_support/file_update_checker.rb:75:in `execute'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:27:in `updater'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/routes_reloader.rb:7:in `execute_if_updated'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application/finisher.rb:71:in `block in <module:Finisher>'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `instance_exec'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `run'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/initializable.rb:55:in `block in run_initializers'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:226:in `block in tsort_each'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:427:in `each_strongly_connected_component_from'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:347:in `block in each_strongly_connected_component'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:345:in `each'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:345:in `call'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:345:in `each_strongly_connected_component'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:224:in `tsort_each'
from /home/zach/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/tsort.rb:205:in `tsort_each'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/initializable.rb:54:in `run_initializers'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application.rb:300:in `initialize!'
from /home/zach/HandCoOp/project/HandCo-op/config/environment.rb:5:in `<top (required)>'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/application.rb:276:in `require_environment!'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:147:in `require_application_and_environment!'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:133:in `generate_or_destroy'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:51:in `generate'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /home/zach/.rvm/gems/ruby-2.1.2/gems/railties-4.1.4/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
I am not quite sure exactly what is going wrong here and I will keep looking into the issue. Thanks anyone who knows what my problem here is. I am following the guide here : https://github.com/plataformatec/devise but am defiantly having issues.
A: Unfortunately, I don't have enough karma to comment, so I'll do the best I can to provide a solution here.
Have you made sure to run 'rails generate devise:install' before attempting to generate the devise model? Also make sure that you ran 'bundle install' before you attempt either of installing Devise or generating a model.
A: hope u followed these steps:-
*
*Add gem 'devise' to gemfile
*Run the bundle command to install it.
*After you install Devise and add it to your Gemfile, you need to run the generator:
rails generate devise:install
The generator will install an initializer which describes ALL Devise's configuration options and you MUST take a look at it.
4. When you are done, you are ready to add Devise to any of your models using the generator:
rails generate devise MODEL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25277103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get_terms() order not follow hierarchy Here is how I get all terms, including children, of a custom hierarchical taxonomy:
$args = array(
'taxonomy' => 'obra_tema',
);
$themes = get_terms($args);
Very simple. But instead the list look like that:
*
*Books
*Cars
*Others
*DVD (child of Others)
The function return
*
*Books
*Cars
*DVD (child of Others)
*Others
How can I show terms in the same order of dashboard?
A: Have not tried this, but it should be something like this
$args = array(
'taxonomy' => 'obra_tema',
'orderby' => 'id',
'order' => 'DESC',
);
$themes = get_terms($args);
You might have to adjust the order field or the order by direction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54554283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 4 font files added but only 2 styles displayed I'm trying to manually add a custom font to my localhost installation of WP, what I did so far:
*
*download the font (Computer Modern) from fontsquirrel in .woff format
*take the 4 files needed (Serif): Roman (cmunrm), Bold (cmunbx), Oblique (cmunti), Bold Oblique (cmunbi)
*put the 4 files in the folder C:\xampp\htdocs\sitename\wp-includes\fonts\latex
*write the following in style.css
CSS code
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunrm.woff');
font-style: normal;
}
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunbx.woff');
font-weight: bold;
}
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunti.woff');
font-style: italic, oblique;
}
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunbi.woff');
font-weight: bold;
font-style: italic, oblique;
}
body {
font-family: "Computer Modern", serif;
}
*
*write the following in the WP editor
HTML code
This is normal text
<strong>This is bold text</strong>
<em>This is oblique text</em>
<em><strong>This is bold and oblique text</strong></em>
but the result is this
It seems that only Bold and Oblique have been loaded, in fact by replacing cmunti with cmunrm (Oblique with Roman) and cmunbi with cmunbx (Bold Oblique with Bold) in the CSS file this is showed
What is this due to, and how to solve it?
A: Does it help to be explicit with font-weight and font-style in each definition? That's what this answer does. It also adds css that makes strong/em associated to font-weight/font-style explicitly (which may be unneeded).
A: Don't know why but this solved the problem
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunrm.woff');
}
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunti.woff');
font-style: italic;
}
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunbx.woff');
font-weight: bold;
}
@font-face {
font-family: "Computer Modern";
src: url('http://localhost/sitename/wp-includes/fonts/latex/cmunbi.woff');
font-weight: bold;
font-style: italic;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57934933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: webapp doesnt start after spring-boot update to 1.3.1 I hope you can help me with this problem and couldn't find a solution.
I am working on a Webapplication with gradle 2.4, Java 8, Spring-boot and a H2-DB. We started with Spring-Boot 1.2.2 a while ago and decided to update Spring-Boot to 1.3.1. But with this Version the Server doesnt start anymore. It throws a NullPointerException when I start the Project (gradle bootRun)
2016-01-14 17:39:22.472 ERROR 8304 --- [ main] o.s.boot.SpringApplication : Application startup failed
java.lang.NullPointerException: null
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.onApplicationEvent(DataSourceInitializer.java:100) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.onApplicationEvent(DataSourceInitializer.java:47) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:163) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:136) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:119) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.registerListeners(AbstractApplicationContext.java:809) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:535) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at com.infinit.organization.config.Application.main(Application.java:46) [main/:na]
The build.gradle:
buildscript {
// The buildscript closure is executed at the beginning of gradle's configuration phase.
// It defines dependencies on gradle plugins that are used in the remaining configuration phase
// and in the execution phase.
// Note that spring-boot registers a custom Gradle ResolutionStrategy that allows to omit version numbers
// when declaring dependencies. Only the plugin version must be set.
ext {
springBootVersion = '1.3.1.RELEASE'
}
// repositories used to resolve gradle plugins
repositories {
maven { url "http://download.osgeo.org/webdav/geotools/"}
mavenCentral()
maven { url "http://repo.spring.io/libs-snapshot" }
maven { url "http://dl.bintray.com/infinit/infinit-opensource" }
maven { url "http://dl.bintray.com/letteral/opensource" }
maven { url 'https://repo.gradle.org/gradle/plugins-releases'}
}
// dependent gradle plugins
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "net.saliman:gradle-cobertura-plugin:2.3.0"
classpath "com.letteral:letteral-gradle-plugin:0.0.5"
}
}
// repositories used for satisfying project's configuration dependencies (e.g. compile, runtime)
repositories {
maven { url "http://download.osgeo.org/webdav/geotools/"}
mavenCentral()
maven { url "http://repo.spring.io/libs-snapshot" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots" } // cobertura snapshots
maven { url "http://dl.bintray.com/infinit/infinit-opensource" }
maven { url "http://dl.bintray.com/letteral/opensource" }
maven { url 'https://repo.gradle.org/gradle/plugins-releases'}
}
// plugins needed in the build process
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'war'
apply plugin: 'net.saliman.cobertura'
apply plugin: 'spring-boot'
apply plugin: 'letteral'
apply from: 'gensrc.gradle'
apply from: 'liquibase.gradle'
// check coverage limits locally with command '../gradlew cobertura coberturaCheck'
cobertura {
coberturaVersion = '2.1.1' // cobertura 2.1.x depends on asm-5 required for Java 8
coverageCheckHaltOnFailure = true // fail if coverage is below limits
coverageIgnoreTrivial = true // ignore simple getters and setters
coverageCheckBranchRate = 0 // minimum acceptable branch coverage rate (percent) needed by each class
coverageCheckLineRate = 0 // minimum acceptable line coverage rate (percent) needed by each class
coverageCheckTotalBranchRate = 50 // minimum acceptable branch coverage rate (percent) needed by the whole project
coverageCheckTotalLineRate = 50 // minimum acceptable line coverage rate (percent) needed by the whole project
coverageCheckRegexes = [
// more fine grained limits per package
[regex: 'com.infinit.atobcarry.config.*', branchRate: 0, lineRate: 0],
[regex: 'com.infinit.atobcarry.entity.*', branchRate: 0, lineRate: 0]
]
//exclude the fixture files in order to get a realistic view of the coverage
coverageExcludes = [
'.*\\.DevelopmentFixtures.*',
'.*\\.Fixtures.*'
]
}
letteral {
username = 'username'
password = 'pass'
organization = 'org'
repos = files('mail')
apiUrl = 'http://letteral-dev.elasticbeanstalk.com/api'
}
configurations {
webapp // configuration used to hold the build result of the client project
}
dependencies {
// spring boot dependencies
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.boot:spring-boot-starter-web"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.boot:spring-boot-starter-websocket"
compile "org.springframework:spring-context-support"
compile "org.springframework:spring-messaging"
//compile("org.springframework.boot:spring-boot-devtools")
// modelmapper
compile "org.modelmapper.extensions:modelmapper-spring:0.7.3"
// swagger
compile "com.mangofactory:swagger-springmvc:1.0.0"
// database dependencies
compile 'com.h2database:h2:1.4.190'
// runtime 'org.postgresql:postgresql:9.4-1201-jdbc41'
// liquibase
runtime 'org.liquibase:liquibase-core:3.3.2'
// Joda
compile 'joda-time:joda-time:2.7'
compile 'org.jadira.usertype:usertype.spi:3.2.0.GA'
compile 'org.jadira.usertype:usertype.core:3.2.0.GA'
compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda';
// Apache commons
compile 'org.apache.commons:commons-lang3:3.3.2'
compile 'org.apache.commons:commons-io:1.3.2'
// java melody dependencies
compile 'net.bull.javamelody:javamelody-core:1.55.0'
runtime 'com.thoughtworks.xstream:xstream:1.4.8'
runtime 'org.jrobin:jrobin:1.5.9'
// Atmosphere SSE / Websockets
compile 'org.atmosphere:atmosphere-runtime:2.2.6'
// Jackson
compile 'com.fasterxml.jackson.core:jackson-core'
// letteral
compile 'com.letteral:letteral-client-java:0.0.17'
// tomtom
compile(group: 'com.tomtomworker.webfleet.connect', name: 'webfleet-connect-client', version: '1.1')
//google maps
compile 'com.google.maps:google-maps-services:0.1.7'
//quartz
compile(group: 'org.quartz-scheduler', name: 'quartz', version: '2.2.1')
compile(group: 'org.quartz-scheduler', name: 'quartz-jobs', version: '2.2.1')
//itext pdf generation
compile('com.itextpdf:itextpdf:5.5.6')
//xdocreport templating over freemarker
compile('fr.opensagres.xdocreport:xdocreport:1.0.3')
compile('fr.opensagres.xdocreport:fr.opensagres.xdocreport.template:1.0.3')
compile('fr.opensagres.xdocreport:fr.opensagres.xdocreport.template.freemarker:1.0.3')
//unfortuately we also need to include the velocity templates without using them
compile('fr.opensagres.xdocreport:fr.opensagres.xdocreport.template.velocity:1.0.3')
compile('fr.opensagres.xdocreport:fr.opensagres.xdocreport.converter.odt.odfdom:1.0.3')
//pdf signing with bouncy castle, must be 1.49 for now as itext 5.5.6 only supports BC 1.49
compile('org.bouncycastle:bcpkix-jdk15on:1.49')
//jts to create the tunnel
compile('com.vividsolutions:jts:1.13')
compile('org.geotools:gt-shapefile:14.0')
//compile('org.geotools:gt-swing:13.3')
compile('org.geotools:gt-epsg-hsql:14.0')
//javaxmail
compile 'javax.mail:mail:1.4.1'
//hazelcast
compile("com.hazelcast:hazelcast-all:3.5") {
exclude group: 'org.freemarker'
}
// testing dependencies
testCompile("org.springframework.boot:spring-boot-starter-test") {
// the following artifacts are excluded since spock is used:
exclude group: 'org.mockito', module: 'mockito-core'
}
testCompile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
testCompile 'com.jayway.jsonpath:json-path:0.9.1'
testCompile 'cglib:cglib-nodep:3.1'
testCompile 'org.dbunit:dbunit:2.4.9'
testCompile 'com.github.springtestdbunit:spring-test-dbunit:1.2.1'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
// web resources from client project
webapp project(path: ':atobcarry-client', configuration: 'webapp')
}
// configure the war task to deploy on conventional servlet container (e.g. tomcat)
war {
// let war task depend on webapp configuration
// hereby start relevant tasks in the client project;
// when the war task runs execute the closure
// hereby unzip the client project's build result
// and add it to the resources path of the war
// This folder is exposed as static content by spring boot.
dependsOn(configurations.webapp)
from { zipTree(configurations.webapp.singleFile) }
baseName = 'atobcarry'
//version = '0.1.0'
}
// docker packaging requires a jar file that is configured similarly to the war
jar {
dependsOn(configurations.webapp)
from(zipTree(configurations.webapp.singleFile)) {
into 'META-INF/resources'
}
baseName = 'atobcarry'
//version = '0.1.0'
}
The application config:
mail.host=localhost
[email protected]
organization.serverURL=http://localhost:8080
organization.enableTomTomTracking=false
organization.disableQuartzJobsInDebugMode=false
organization.restUrlTrackingPositions=http://localhost:8080/api/v1/trackingPositions/
organization.gracePeriodExpiredRequestsMinutes=1
organization.gracePeriodExpiredOffersMinutes=1
organization.keystorePath=security/atobcarry
organization.truststorePath=security/cacerts
organization.keyPassword=password
organization.keyAlias=organization
organization.keystorePassword=changeit
organization.pdfHashingAlgorithm=SHA-256
liquibase.changeLog=classpath:/db/changelog/db.changelog-master.xml
liquibase.enabled=false
management.security.enabled:false
letteral.enabled=false
[email protected]
letteral.apiKey=123456
letteral.apiUrl=http://letteral-dev.elasticbeanstalk.com/api
letteral.hoursTokenValid=24
letteral.organization=organization
letteral.repository=mail
letteral.release=not used
letteral.releaseVersion=not used
letteral.requestMailName=request
# google maps properties
googleMaps.directionsApiKey=xxxxx
googleMaps.mode=car
# for debugging letteral requests
# logging.level.org.apache.http.wire=DEBUG
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.password=
spring.datasource.url=jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;MODE=PostgreSQL
spring.datasource.username=dbuser
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.id.new_generator_mappings=true
#spring.jpa.show-sql=false
spring.jpa.open-in-view=true
spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true
spring.jpa.properties.jadira.usertype.databaseZone=UTC
spring.jpa.properties.jadira.usertype.javaZone=jvm
spring.jackson.dateFormat=yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
spring.messages.basename=com/infinit/atobcarry/messages
multipart.maxFileSize=10Mb
That should be all relevant Information I hope. Please tell me if it isnt enought.
update: here are some more related files. What might be important: The Project contains 2 "subprojects": server and client. The Client is pure Javascript and works fine. The build.gradle above is the one from the server, I just added the main build.gradle and some other files as well.
application class:
@Configuration
@EnableJpaRepositories("com.infinit.atobcarry.repository")
@EnableAutoConfiguration
@EnableConfigurationProperties
@ComponentScan("com.infinit.atobcarry")
@EntityScan(basePackages = {"com.infinit.atobcarry.entity"})
@EnableJpaAuditing
@EnableAspectJAutoProxy
public class Application implements EmbeddedServletContainerCustomizer {
public final static String API_PREFIX = "/api/v1";
public final static String FRONTEND_PREFIX = "/#";
// As a default it is assumed that the document root is the app folder of the client project.
// Relative to the root of the project this is located in the following path:
private final static String CLIENT_DOCUMENT_ROOT = "../atobcarry-client/app";
/**
* An embedded container is started, when the application is run via the main method.
* It can be started with the gradle command bootRun
*
* @param args start parameters
* @throws Exception
*/
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(Application.class);
app.run(args);
}
/**
* When running with an embedded servlet container additional configurations can be applied.
*
* @param container that is subject of the configuration
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
// The embedded servlet container shall use the resources from the client project
configureDocumentRoot(container);
// send charset in Content-Type response header to improve performance
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("html", "text/html;charset=utf-8");
container.setMimeMappings(mappings);
}
/**
* Sets the document root to the resource folder of the client project if available.
* This allows for instant reloading when developing the app.
*/
private void configureDocumentRoot(ConfigurableEmbeddedServletContainer container) {
String documentRootPath = CLIENT_DOCUMENT_ROOT;
File documentRoot = new File(documentRootPath);
if (documentRoot.isDirectory() && documentRoot.canRead()) {
container.setDocumentRoot(documentRoot);
}
}
}
A: here are some more information:
this class might be interesting as well:
/**
* Servlet 3.0+ environments allow to replace the web.xml file with a programmatic configuration.
* <p/>
* Created by owahlen on 01.01.14.
*/
public class Deployment extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
/**
* This method is copied from SpringBootServletInitializer.
* Only the registration of the ErrorPageFilter is omitted.
* This was done since errors shall never be sent as redirects but as ErrorDto
* @param servletContext
* @return
*/
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
SpringApplicationBuilder builder = new SpringApplicationBuilder();
ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
builder.initializers(new ParentContextApplicationContextInitializer(parent));
}
builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
builder = configure(builder);
SpringApplication application = builder.build();
if (application.getSources().isEmpty()
&& AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) {
application.getSources().add(getClass());
}
Assert.state(application.getSources().size() > 0,
"No SpringApplication sources have been defined. Either override the "
+ "configure method or add an @Configuration annotation");
// Error pages are handled by the ExceptionHandlerController. No ErrorPageFilter is needed.
// application.getSources().add(ErrorPageFilter.class);
return run(application);
}
private ApplicationContext getExistingRootWebApplicationContext(ServletContext servletContext) {
Object context = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (context instanceof ApplicationContext) {
return (ApplicationContext) context;
}
return null;
}
}
and another configuration - class:
@Configuration
public class H2Console {
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Define the H2 Console Servlet
*
* @return ServletRegistrationBean to be processed by Spring
*/
@Bean(name= "h2servlet")
public ServletRegistrationBean h2servletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet());
registration.addInitParameter("webAllowOthers", "true"); // allow access from URLs other than localhost
registration.addUrlMappings("/console/*");
return registration;
}
}
main build.gradle:
import java.util.concurrent.CountDownLatch
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.0'
}
}
apply plugin: 'org.asciidoctor.gradle.asciidoctor'
ext {
applicationVersion = 'UNDEFINED'
appBackend = null
}
asciidoctor {
sourceDir = file('asciidoc')
options = [
doctype : 'book',
attributes: [
'source-highlighter': 'coderay',
toc : '',
idprefix : '',
idseparator : '-'
]
]
}
def defaultEnvironment() {
def environment = ["PATH=${System.env.PATH}"]
environment += "HOME=${System.env.HOME}"
return environment
}
def execAsync(command, printStdOutput, dir, expectedOutput) {
println("Starting async command $command")
final CountDownLatch condition = new CountDownLatch(1)
def commandEnvironment = defaultEnvironment()
def proc = command.execute(commandEnvironment, new File(dir as String))
Thread.start {
try {
proc.in.eachLine { line ->
if (printStdOutput) {
println "$line"
}
if (expectedOutput != null && line?.contains(expectedOutput)) {
condition.countDown()
}
}
}
catch (ignored) {
}
}
Thread.start {
try {
proc.err.eachLine { line ->
if (printStdOutput) {
println line
}
}
}
catch (ignored) {
}
}
return [proc, expectedOutput != null ? condition : null]
}
task startServer() {
doLast {
def condBackend
(appBackend, condBackend) = execAsync(["./gradlew", "run"], true, "$projectDir", "Started Application")
condBackend.await()
}
}
task stopProcesses << {
appBackend?.destroy()
}
task e2eReport(dependsOn: [startServer, ':atobcarry-client:clean', ':project-client:e2eTest'])
tasks.getByPath(':project-client:e2eTest').mustRunAfter(startServer)
stopProcesses.mustRunAfter(':project-client:e2eTest')
startServer.finalizedBy(stopProcesses)
e2eReport.finalizedBy(stopProcesses)
tasks.getByPath(':project-client:e2eTest').finalizedBy(stopProcesses)
task validate(dependsOn: [':project-client:grunt_default', ':project-server:cobertura', ':project-server:coberturaCheck'])
the settings.gradle:
// This file includes the gradle subprojects of project project
include 'project-server' // REST webserver backend (WAR)
include 'project-client' // AngularJS frontend (JAR)
include 'project-tracking' // TomTom tracking server (WAR)
include 'project-tracking-commons' // Shared code between tracking and server
querydsl.graddle (from project-server)
configurations {
// configuration to hold the build dependency on the querydsl generator
querydslapt
}
String queryDslVersion = '3.5.1'
dependencies {
querydslapt "com.mysema.querydsl:querydsl-apt:$queryDslVersion"
compile "com.mysema.querydsl:querydsl-jpa:$queryDslVersion"
}
task generateQueryDSL(type: JavaCompile, group: 'build', description: 'Generate the QueryDSL query types.') {
// only process entity classes and enums to avoid compilation errors from code that needs the generated sources
source = fileTree('src/main/java/com/infinit/atobcarry/entity') + fileTree('src/main/java/com/infinit/project/enums')
// include the querydsl generator into the compilation classpath
classpath = configurations.compile + configurations.querydslapt
options.compilerArgs = [
"-proc:only",
"-processor", "com.mysema.query.apt.jpa.JPAAnnotationProcessor"
]
options.warnings = false
// the compiler puts the generated sources into the gensrcDir
destinationDir = gensrcDir
}
gensrc {
// extend the gensrc task to also generate querydsl
dependsOn generateQueryDSL
}
liquibase.graddle (from server)
configurations {
liquibase
}
dependencies {
liquibase 'org.liquibase:liquibase-core:3.3.2'
liquibase 'org.liquibase.ext:liquibase-hibernate4:3.5'
// liquibase 'org.yaml:snakeyaml:1.14'
liquibase 'org.postgresql:postgresql:9.3-1103-jdbc41'
liquibase 'org.springframework:spring-beans'
liquibase 'org.springframework:spring-orm'
liquibase 'org.springframework:spring-context'
liquibase 'org.springframework.boot:spring-boot' // contains the SpringNamingStrategy
liquibase 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final'
}
[
'status' : 'Outputs count (list if --verbose) of unrun change sets.',
'validate' : 'Checks the changelog for errors.',
'changelogSync' : 'Mark all changes as executed in the database.',
'changelogSyncSQL' : 'Writes SQL to mark all changes as executed in the database to STDOUT.',
'listLocks' : 'Lists who currently has locks on the database changelog.',
'releaseLocks' : 'Releases all locks on the database changelog.',
'markNextChangesetRan' : 'Mark the next change set as executed in the database.',
'markNextChangesetRanSQL': 'Writes SQL to mark the next change set as executed in the database to STDOUT.',
'dropAll' : 'Drops all database objects owned by the user. Note that functions, procedures and packages are not dropped (limitation in 1.8.1).',
'clearChecksums' : 'Removes current checksums from database. On next run checksums will be recomputed.',
'generateChangelog' : 'generateChangeLog of the database to standard out. v1.8 requires the dataDir parameter currently.',
'futureRollbackSQL' : 'Writes SQL to roll back the database to the current state after the changes in the changeslog have been applied.',
'update' : 'Updates the database to the current version.',
'updateSQL' : 'Writes SQL to update the database to the current version to STDOUT.',
'updateTestingRollback' : 'Updates the database, then rolls back changes before updating again.',
'diff' : 'Writes description of differences to standard out.',
'diffChangeLog' : 'Writes Change Log XML to update the base database to the target database to standard out.',
'updateCount' : 'Applies the next <liquibaseCommandValue> change sets.',
'updateCountSql' : 'Writes SQL to apply the next <liquibaseCommandValue> change sets to STDOUT.',
'tag' : 'Tags the current database state with <liquibaseCommandValue> for future rollback',
'rollback' : 'Rolls back the database to the state it was in when the <liquibaseCommandValue> tag was applied.',
'rollbackToDate' : 'Rolls back the database to the state it was in at the <liquibaseCommandValue> date/time.',
'rollbackCount' : 'Rolls back the last <liquibaseCommandValue> change sets.',
'rollbackSQL' : 'Writes SQL to roll back the database to the state it was in when the <liquibaseCommandValue> tag was applied to STDOUT.',
'rollbackToDateSQL' : 'Writes SQL to roll back the database to the state it was in at the <liquibaseCommandValue> date/time to STDOUT.',
'rollbackCountSQL' : 'Writes SQL to roll back the last <liquibaseCommandValue> change sets to STDOUT.'
].each { String taskName, String taskDescription ->
String prefixedTaskName = 'dbm' + taskName.capitalize()
task(prefixedTaskName, type: JavaExec) { JavaExec task ->
initLiquibaseTask(task)
args += taskName
String liquibaseCommandValue = project.properties.get("liquibaseCommandValue")
if (liquibaseCommandValue) {
args += liquibaseCommandValue
}
}
}
void initLiquibaseTask(JavaExec task) {
String changeLogFile = 'src/main/resources/db/changelog/db.changelog-master.xml'
task.main = 'liquibase.integration.commandline.Main'
task.classpath = configurations.liquibase + sourceSets.main.runtimeClasspath
task.args = [
// "--logLevel=debug",
"--changeLogFile=${changeLogFile}",
"--url=jdbc:postgresql://localhost:15432/roject",
"--username=project",
"--password=project",
"--referenceUrl=hibernate:spring:com.infinit.atobcarry?dialect=org.hibernate.dialect.PostgreSQL9Dialect&hibernate.ejb.naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy&hibernate.enhanced_id=true",
]
task.group = 'liquibase'
}
jreleaseinfo.gradle
configurations {
// configuration to hold the build dependency on the jreleaseinfo ant task
jreleaseinfo
}
dependencies {
jreleaseinfo 'ch.oscg.jreleaseinfo:jreleaseinfo:1.3.0'
}
task generateJReleaseInfo(group: 'build', description: 'Generate the VersionInfo class.') { Task task ->
Map<String, ?> parameters = [
buildKey: project.hasProperty('buildKey') ? project.buildKey : '',
buildResultKey: project.hasProperty('buildResultKey') ? project.buildResultKey : '',
buildNumber: project.hasProperty('buildNumber') ? project.buildNumber : '',
buildResultsUrl: project.hasProperty('buildResultsUrl') ? project.buildResultsUrl : '',
gitBranch: project.hasProperty('gitBranch') ? project.gitBranch : '',
gitCommit: project.hasProperty('gitCommit') ? project.gitCommit : ''
]
task.inputs.properties(parameters)
task.inputs.property('version', project.version)
task.outputs.file( new File(gensrcDir, 'com/infinit/atobcarry/config/VersionInfo.java') )
task.doLast {
// gradle properties that can be passed to the JReleaseInfoAntTask task
ant.taskdef(name: 'jreleaseinfo', classname: 'ch.oscg.jreleaseinfo.anttask.JReleaseInfoAntTask', classpath: configurations.jreleaseinfo.asPath)
ant.jreleaseinfo(targetDir: gensrcDir, className: 'VersionInfo', packageName: 'com.infinit.atobcarry.config', version: project.version) {
parameters.each { String key, String value ->
parameter(name: key, type: 'String', value: value)
}
}
}
}
gensrc {
// extend the gensrc task to also generate JReleaseInfo
dependsOn generateJReleaseInfo
}
gensrc.gradle
// register directory where generated sources are located with the project
ext.gensrcDir = file('src/main/generated')
// create a wrapper task for source generation that the generators can depend upon
task gensrc(group: 'build', description: 'Execute all tasks that generate source code.')
// include the source code generators
apply from: 'querydsl.gradle'
apply from: 'jreleaseinfo.gradle'
// add the gensrcDir to the sourceSets
sourceSets {
generated
}
sourceSets.generated.java.srcDirs = [gensrcDir]
// extend the conventional compileJava task to also compile the generated sources
compileJava {
dependsOn gensrc
source gensrcDir
}
clean {
delete gensrcDir
}
orm.xml
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener"/>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34795548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to pass multiple variables in foreach php I'd like to pass multiple variables in a foreach loop to add the value from $array_sma[] into my database. But so far I can only insert the value from $short_smas, while I'd also like to insert the values from $mid_smas. I have tried nested foreach but it's multiplying the values.
$period = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$sma = array(6,9);
foreach ($sma as $range) {
$sum = array_sum(array_slice($period, 0, $range));
$result = array($range - 1 => $sum / $range);
for ($i = $range, $n = count($period); $i != $n; ++$i) {
$result[$i] = $result[$i - 1] + ($period[$i] - $period[$i - $range]) / $range;
}
$array_sma[] = $result;
}
list($short_smas,$mid_smas)=$array_sma;
foreach ($short_smas as $short_sma) {
$sql = "INSERT INTO sma (short_sma)
VALUES ('$short_sma') ";
if ($con->query($sql) === TRUE) {
echo "New record created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
The code in my question works fine i.e. the value from the first sub array ($short_smas) of $array_sma[] gets inserted into the column short_sma of my msql database. The problem I have is when I try to insert the second sub array $mid_smas (see list()) from $array_sma[] in my second column of my database call mid_sma.
I think this is closed to what I want to achieve but still nothing gets inserted in the DB, source: php+mysql: insert a php array into mysql
I don't have any mysql syntax error.
$array_sma[] = $result;
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
foreach ($array_sma as $item) {
$sql .= "('".$item[0]."','".$item[1]."'),";
}
$sql = rtrim($sql,",");
A: Main problem is that $short_smas and $mid_smas have different size. Moreover they are associative arrays so either you pick unique keys from both and will allow for empty values for keys that have only one value available or you pick only keys present in both arrays. Code below provides first solution.
// first lets pick unique keys from both arrays
$uniqe_keys = array_unique(array_merge(array_keys($short_smas), array_keys($mid_smas)));
// alternatively we can only pick those present in both
// $intersect_keys = array_intersect(array_keys($short_smas),array_keys($mid_smas));
// now lets build sql in loop as Marcelo Agimóvel sugested
// firs we need base command:
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
// now we add value pairs to coma separated list of values to
// insert using keys from prepared keys array
foreach ($uniqe_keys as $key) {
$mid_sma = array_key_exists($key, $mid_smas)?$mid_smas[$key]:"";
$short_sma = array_key_exists($key, $short_smas)?$short_smas[$key]:"";
// here we build coma separated list of value pairs to insert
$sql .= "('$short_sma', '$mid_sma'),";
}
$sql = rtrim($sql, ",");
// with data provided in question $sql should have string:
// INSERT INTO sma (short_sma, mid_sma) VALUES, ('3.5', ''), ('4.5', ''), ('5.5', ''), ('6.5', '5'), ('7.5', '6'), ('8.5', '7'), ('9.5', '8'), ('10.5', '9'), ('11.5', '10'), ('12.5', '11')
// now we execute just one sql command
if ($con->query($sql) === TRUE) {
echo "New records created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
// don't forget to close connection
Marcelo Agimóvel also suggested that instead of multiple inserts like this:
INSERT INTO tbl_name (a,b,c) VALUES (1,2,3);
its better to use single:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
That's why I append value pairs to $sql in foreach loop and execute query outside loop.
Also its worth mentioning that instead of executing straight sql its better to use prepared statements as they are less prone to sql injection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49454647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Github's JIRA ticket integration: add comment I've set up the JIRA plugin that github provides and it works well, with a commit message like this:
I made the thing work! [#PROJ-57 transition:21]
It'll do that transition (In my case it's a 'close issue' transition) but I'd really like it to also post a commend to the ticket saying something like "Closed by via github: I made the thing work!"
How can I make this happen?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15431106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a vector by combining rows of a data frame in R? I have a data frame say 'a'
qq ee rr tt
1 2 3 4
2 44 66 77
9 0 0 4
I want a create a vector like:
vec <- c(1,2,3,4,2,44,66,77,9,0,0,4)
how do I do this?
A: Take the transpose which also converts it to a matrix, and then convert to vector:
as.vector(t(a))
[1] 1 2 3 4 2 44 66 77 9 0 0 4
A: Use James' answer.
Here is another alternative: unlist and sort.
unlist(a)[order(rep(seq_len(nrow(a)),ncol(a)))]
#qq1 ee1 rr1 tt1 qq2 ee2 rr2 tt2 qq3 ee3 rr3 tt3
# 1 2 3 4 2 44 66 77 9 0 0 4
That way you retain information in names, which could be useful. If you don't want the names, use unlist with use.names=FALSE.
A: For fun, here's another alternative:
> scan(textConnection(do.call(paste, a)))
Read 12 items
[1] 1 2 3 4 2 44 66 77 9 0 0 4
Where "a" is:
a <- read.table(textConnection("qq ee rr tt
1 2 3 4
2 44 66 77
9 0 0 4"), header=T)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17693390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing different UIButtons through a general Method. Are Selectors/Senders the answer? I have about 20 buttons added from Interface Builder, and when pressed they change colour like so:
-(IBAction)button1:(id)sender
{
if(playerTurn == YES)
{
button1.backgroundColor = [UIColor redColor];
}
}
But to shorten things it seems like I could just have a general method, so that every button when pressed runs the method. Something like:
-(IBAction)button1:(id)sender
{
//Go to method and make this button red
}
-(void)changeColour
{
if(playerTurn == YES)
{
buttonThatWasSent.backgroundColor = [UIColor redColor];
}
}
Unfortunately I can't figure out how to do that. It seems selectors/senders are the answer? But I've not managed to make any tutorials I've found work.
A: You were pretty close!
- (IBAction)myActionWithAnArbitraryName:(UIButton *)sender
{
if(playerTurn == YES) {
[sender setBackgroundColor:[UIColor redColor]];
}
}
A: You can link all the 20 buttons of a single action.
The sender knows which button was pressed, so directly channge the backgroundColor of sender.
-(IBAction)changeColour:(id)sender
{
if (playerTurn == YES)
sender.backgroundColor = [UIColor redColor];
}
Note:This is not tested code. But i guess it should work, if wont they try do this way:
UIButton *button=(UIButton *)sender;
button.backgroundColor = [UIColor redColor];
A: You can actually use a single IBAction for all your buttons and just cast the sender as a UIButton:
- (IBAction)buttonPressed:(id)sender {
UIButton *button = (UIButton *)sender;
if (playerTurn == YES) {
button.backgroundColor = [UIColor redColor];
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13893228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: After submit i get an Error trying to diff '[object Object]'. Only arrays and iterables are allowed Error Explaination
After i click the submit button the data is save successfully to database but the above error shows.Ill share my related code below. Is there any way to solve this issue
my api data format
this my api data format
{
"expires_in": 0,
"data": [
{
"patientPastHistoryCatID": 1,
"phCatName": "Cardiovascular",
"patientPastMedicalHistorys": [
{
"patientPastHistoryCatID": 1,
"phCatName": "Cardiovascular",
"patientPastHistorySubID": 1,
"phSubCatName": "Heart Attack",
"isActive": true,
"isDeleted": false,
"createdDate": "2022-05-09T00:00:00",
"createdBy": 1,
"updatedBy": 1,
"updatedDate": "2022-05-09T00:00:00"
},
]
}
formbuilder
this.patientPastHistoryForm = this.formBuilder.group({
'patientID': new FormControl(this.clientId),
'patientPastMedicalHistoryModelLists': this.formBuilder.array([]),
'phSubCatName': ['', Validators.required],
});
api call
this code is used to call the data from api.
getPatientPastMedicalHistoryList() {
this.clientsService.getPatientPastMedicalHistoryList(this.clientId)
.subscribe(
(response: ResponseModel) => {
if (response.statusCode == 200) {
//debugger
this.patientPastMedicalHistory = response.data ;
const formArray = this.patientPastHistoryForm.get("patientPastMedicalHistoryModelLists") as FormArray;
response.data.forEach(item => {
item.patientPastMedicalHistorys.forEach(element => {
formArray.push(this.formBuilder.group({
catId:element.patientPastHistoryCatID,
catName:element.phCatName,
subCatId:element.patientPastHistorySubID,
SubCatName:element.phSubCatName,
itemvalue:[]
}))
})
})
}
else {
this.patientPastMedicalHistory=[];
}
});
}
OnSubmit code
this is the code for submit the error comes here after the data is save successfully.
onSubmit(event: any) {
debugger
if (!this.patientPastHistoryForm.invalid) {
this.submitted = true;
this.patientPastMedicalHistory = this.patientPastHistoryForm.value;
this.clientsService.createPatientPastHistory(this.patientPastMedicalHistory).subscribe((response: any) => {
//debugger
if (response.statusCode == 200) {
//alert(response.message);
this.notifier.notify('success', response.message);
} else {
this.notifier.notify('error', response.message);
}
});
}
}
Html code
<div class="col-lg-12 readmin-panel">
<form id="patientPastHistoryForm" [formGroup]="patientPastHistoryForm">
<div *ngFor="let pmhx of patientPastMedicalHistory;let i = index;">
<div class="lineheader" id="{{pmhx.patientPastHistoryCatID}}"><p><a>{{pmhx.phCatName}}</a></p></div>
<div class="row ppm ppd">
<div *ngFor="let item of pmhx.patientPastMedicalHistorys;let j = index;" class="col-sm-4 fsize">
<section> <div id="left">
<label id="{{item.phSubCatName}}_{{item.patientPastHistorySubID}}" class="bpading">{{item.phSubCatName}}:</label></div>
<div id="right">
<mat-radio-group id="{{item.patientPastHistoryCatID}}_{{item.patientPastHistorySubID}}" matInput formControlName="phSubCatName" required class="bposi">
<mat-radio-button color="primary" class="lbl-wrap-radio bsize bpading" (click)="onButtonClick('Yes',item.patientPastHistorySubID,j)" value="Yes" checked="{{item.valueItem==='Yes'}}">YES</mat-radio-button>
<mat-radio-button color="primary" class="lbl-wrap-radio bsize" (click)="onButtonClick('No',item.patientPastHistorySubID,j)" value="No" checked="{{item.valueItem==='No'}}">NO</mat-radio-button>
</mat-radio-group></div>
</section>
<!-- <mat-error *ngIf="submitted && formControls.{{item.phSubCatName}}.errors?.required"> Please select {{item.phSubCatName}} </mat-error> -->
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 d-sm-flex justify-content-sm-end pt-3 actions-btn">
<button name="Save" mat-raised-button color="primary" (click)="onSubmit($event)" form="patientPastHistoryForm"
class="text-uppercase" [disabled]="submitted" cdkFocusInitial>{{submitted ? 'Saving...' : 'Save'}}</button>
</div>
</div>
</form>
</div>
A: Use console.log() to inspect your object behavior and view it on your browser's console (F12)
Example:
onSubmit(event: any) {
// debugger
if (!this.patientPastHistoryForm.invalid) {
this.submitted = true;
this.patientPastMedicalHistory = this.patientPastHistoryForm.value;
console.log(this.patientPastMedicalHistory); // check what you send in payload. this.clientsService.createPatientPastHistory(this.patientPastMedicalHistory).subscribe((response: any) => {
//debugger
console.log(response); // check what you got
if (response.statusCode == 200) {
//alert(response.message);
this.notifier.notify('success', response.message);
} else {
this.notifier.notify('error', response.message);
}
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72210610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Not able to select text in textbox I've got this here wizard step with a couple of text boxes. For some reason I cannot highlight/select the text in the textbox in IE or FF and I have no idea why, not even after spending a couple of hours googling the problem. I could really use another set of eyes on this. Let me know if you need more code to help.
<asp:WizardStep ID="wsPlanInfo" runat="server" Title="" StepType="Step">
<div style="width:100%; height:290px; margin-top:150px ">
<table border="0" style="margin:0 auto;">
<tr>
<td colspan="2" class="title">
Placeholder text here?
</td>
</tr>
<tr>
<td colspan="2"><asp:TextBox runat="server" ID="txtLearningPlanName" Width="300px" CssClass="input-text" /> <asp:RequiredFieldValidator runat="server" ID="rflLearningPlanName" ControlToValidate="txtLearningPlanName" ErrorMessage="*" CssClass="validator" /><br /><br /></td>
</tr>
<tr>
<td colspan="2" class="title">
placeholder text here?
</td>
</tr>
<tr>
<td> </td>
<td>
<table border="0"><tr><td><asp:RadioButton runat="server" ID="rbSpecificDate" GroupName="DeadlinePicker" Checked="true" /></td><td><UC:DatePicker runat="server" ID="ucSpecificDatePicker" RequiredField="false" /></td></tr></table>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:RadioButton runat="server" ID="rbCustomUserFieldPlusDays" GroupName="DeadlinePicker" /> <asp:DropDownList runat="server" ID="ddlUserCustomFields" CssClass="input-text" /> plus <Telerik:RadNumericTextBox runat="server" SkinID="Normal" ID="rntbUserCustomFieldOffset" ShowSpinButtons="true" DataType="System.Int32" NumberFormat-DecimalDigits="0" Width="60px" Value="365" /> days
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:RadioButton runat="server" ID="rbPlusDays" GroupName="DeadlinePicker" /> <Telerik:RadNumericTextBox runat="server" SkinID="Normal" ID="rntbPlusDays" ShowSpinButtons="true" DataType="System.Int32" NumberFormat-DecimalDigits="0" Width="60px" Value="365" /> days from today
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:RadioButton runat="server" ID="rbNone" GroupName="DeadlinePicker" /> None
</td>
</tr>
</table>
</div>
</asp:WizardStep>
A: Try:
((TextBox)wsPlanInfo.FindControl("txtLearningPlanName")).Text
It will search the Wizard Step's Control list for a textbox with that ID name. It then casts it as a TextBox and so you can then use the Text property.
A: Removing disableSelection(document.body) in my javascript solved my problem. Note to self, post entire code when asking a question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6268653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing underline from a part of the link I have some hyperlinks with content before it . Like in picture.
This is the code I am using .
a {
font-size: 14px;
text-decoration: none;
color: $grey;
font-weight: bold;
text-decoration: underline;
&:hover {
cursor: pointer;
}
&:before {
content: '\1F847';
color: $green;
padding-right: 8px;
text-decoration: none;
}
&:after {
text-decoration: none;
}
}
I need the arrow that is added as a content to not have underline as a text decoration but the text needs to keep it . As you can see , i tried to add text-underline:none to both before and after , but it didn't work. I can use JS/Query if needed , but still have no idea how to do this .
A: Change the :before pseudo element so that it displays as an inline-block:
&:before {
content: '\1F847';
color: $green;
padding-right: 8px;
text-decoration: none;
display: inline-block;
}
A: You can apply text-decoration: none to the a, but insert a span into it with the link text inside the span - then put text-decoration: underline of the a span. Notethat I had to rejig your css a little since we don't have a preprocessor.
a {
font-size: 14px;
text-decoration: none;
color: grey;
font-weight: bold;
text-decoration: none;
}
a span {
text-decoration: underline;
}
a:hover {
cursor: pointer;
}
a:before {
content: '\1F847';
color: green;
padding-right: 8px;
text-decoration: none;
}
<a href="#"><span>2015 Highlights</span></a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53097991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's the wrong with this code? I'm new in SSMS, and I'm trying to execute this code:
use master
create database SQL20145Db2
on primary
( name = Sql2015Data2, filename='C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Sql2015Data2',
size=4MB, MaxSize=15, FileGrowth= 20%
)
log on
(Name=Sql2015Log2, filename='C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Sql2015Log2',
size= 1MB,MaxSize=5Mb,filegrowth=1MB
)
But the messages pane displays this error:
Msg 5123, Level 16, State 1, Line 2
CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file 'C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Sql2015Data2'.
Msg 1802, Level 16, State 4, Line 2
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
A: This error happen because the registry value DefaultData and DefaultLog (which correspond to default data directory) are either empty or does not exists.
See documentation for more information.
Most of the time, these registry values does not exists because they actually need to be accessed as Admin. So, to fix this issue, simply run whatever application you are using to execute the sql as an administrator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28459204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best practice architecture, for multiple websites with commonality We are looking to build multiple custom websites for different customer contracts, with tailored functionality, but all around the same theme and concept.
There will be about 70% commonality in functionality across all websites, but enough difference that building a CMS is a bad choice. Also customers dont want their DB to have properties that are not relevant to them.
The DB tables will be mostly the same, with a few different properties in each table per site. ie a customer table might be 80% the same, but in one project in might also ask for hair-color, eye-color, etc. whereas in another in might also ask for height and weight....
I'm ok with my other layers, but what is the best practise for the MVC presentation layer?
I want to create as many inherited functions/controllers/actions/resx/etc as possible via base classes (which will be the same project referenced by each website), but MVC does not seem to lend itself as well to this as webforms.
Any thoughts would be really appreciated, thanks
A: I would focus my efforts on the web config and building my presentation layer around config settings stored at server side. Also, I'm not entirely sure how logically different your pages will be, but having different CSS styles can dramatically change the look of your websites. This post was kinda vague, I hope I helped spurn some ideas...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19911992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Moving android device to another access point programatically Im looking for a way to move an android device to another access point on the network if the access point is being overloaded with devices. I wish to do this programatically if possible. Thanks in advance.
My thinking was that I could write something with php which would move the IP address onto the other access point thus switch the device to the other access point...I'm just looking for any pointers.
Thanks in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24336171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Listview - clickable items with youtube links? I've already created a listview, that has 40 names of songs, and a standard adapter for it. Do you have any idea about how I can make the items clickable with links?
Edit: Thank you all :)
A: If the order / items are static you can store the links as strings in an array and then access the array to get the corresponding string and navigate to it using an Intent.
Here is an example of an intent to a web address
String url = "http://www.youtube.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
A: If I understand correctly, you should use a onItemClickListener!
http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
Then use this code in it!
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27065114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hive - Count number of occurrences of character I am trying to count number of occurrences of pipe symbol in Hive - (6)
select length(regexp_replace('220138|251965797?AIRFR?150350161961|||||','^(?:[^|]*\\|)(\\|)','')) from smartmatching limit 10
This is what I am trying and I am not getting it right.
A: This will work
SELECT LENGTH(regexp_replace('220138|251965797?AIRFR?150350161961|||||','[^|]',''))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36736022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQLite Exception: no such column I am using a SQLite database and I got this this error:
Caused by: android.database.sqlite.SQLiteException: no such column: coin (code 1): , while compiling: SELECT _id, name, age, coin, log FROM person_tb1 WHERE name = ?
I have no idea why it show me this!
I have tried it before its working fine!
Here is my code:
public ArrayList<Person> getPersons (){
persons.clear();
SQLiteDatabase dba = this.getReadableDatabase();
Cursor cursor = dba.query(Constants.TABLE_NAME,
new String[]{Constants.KEY_ID, Constants.NAME, Constants.AGE , Constants.COIN , Constants.LOG},null,null,null,null,null);
if(cursor.moveToFirst()){
do {
Person p = new Person();
p.setName(cursor.getString(cursor.getColumnIndex(Constants.NAME)));
p.setAge(cursor.getInt(cursor.getColumnIndex(Constants.AGE)));
p.setCoin(cursor.getInt(cursor.getColumnIndex(Constants.COIN)));
p.setLog(cursor.getInt(cursor.getColumnIndex(Constants.LOG)));
p.setPersonId(cursor.getInt(cursor.getColumnIndex(Constants.KEY_ID)));
persons.add(p);
}while (cursor.moveToNext());
cursor.close();
dba.close();
}
return persons;
}
and here the select method :
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "(" +
Constants.KEY_ID + " INTEGER PRIMARY KEY, " + Constants.NAME + " TEXT, "+
Constants.AGE + " INT, " + Constants.COIN + " INT, " + Constants.LOG + " INT);";
db.execSQL(CREATE_TABLE);
}
// EDIT : (OnUpgrade)
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + Constants.TABLE_NAME);
onCreate(db);
}
A: Wild guess: You added the column after running the app once.
If so (i have tried it before its working fine !), just unistall and reinstall your app.
OR you can simply increment your DATABASE_VERSION constant.
[EDIT]
But the second method won't work, since your current onUpgrade() method is buggy.
db.execSQL("DROP TABLE IF EXISTS" + Constants.TABLE_NAME);
Won't delete the table. And so, it won't be recreated, even.
You need to insert a space before the table name:
db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_NAME);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33442385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VBA iterating over rows of range to create a dictionary of string to array? I have a excel workbook with the third sheet looks like this:
A B C D E F
1 test test test test test
1 test1 test1 test1 test1 test1
1 test2 test2 test2 test2 test2
2 test test test test test
3 test test test test test
4 test test test test test
5 test test test test test
6 test test test test test
And I want to create a dictionary where the first column is the key and the value is a collection of 5 arrays
key: 1
Value: [
[test1 test1 test1 test1 test1]
[test2 test2 test2 test2 test2]
[test test test test test]
["" "" "" "" ""]
["" "" "" "" ""]
]
key: 2
Value: [
[test test test test test]
["" "" "" "" ""]
["" "" "" "" ""]
["" "" "" "" ""]
["" "" "" "" ""]
]
etc.
I want to store this in a global variable before opening the form so that I can use it in functions like onclick():
Public donationDict As Scripting.Dictionary
Option Explicit
Sub ouvrir()
Dim constData As Range
Set constData = Range("thirdSheet!A:F")
Dim rw As Range
For Each rw In constData.rows
If donationDict.Exists(rw(0)) Then
donationDict(rw(0)).Add New Collection
Else
donationDict.Add rw(0), New Collection
End If
Next rw
UserForm1.Show
End Sub
A: Try this out:
Option Explicit
Public donationDict As Scripting.Dictionary
Sub ouvrir()
Dim data As Range, id, ws As Worksheet
Dim rw As Range, arr(), numArrCols As Long
Set ws = ThisWorkbook.Worksheets("thirdSheet")
Set data = ws.Range("A1:F" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
Set donationDict = New Scripting.Dictionary
numArrCols = data.Columns.Count - 1
ReDim arr(1 To numArrCols) 'empty array
For Each rw In data.Rows
id = rw.Cells(1).Value
If Not donationDict.Exists(id) Then
donationDict.Add id, New Collection 'new key: add key and empty collection
End If
donationDict(id).Add _
OneDimension(rw.Cells(2).Resize(1, numArrCols).Value) 'add the row value as 1D array
Next rw
For Each id In donationDict.Keys
Do While donationDict(id).Count < 5
donationDict(id).Add arr 'add empty array
Loop
Next id
ShowDict donationDict 'dump to Immediate window for review
End Sub
'convert a 2D [row] array to a 1D array
Function OneDimension(arr)
OneDimension = Application.Transpose(Application.Transpose(arr))
End Function
Sub ShowDict(dict)
Dim k, e
For Each k In dict.Keys
Debug.Print "Key: " & k
Debug.Print "------------------------"
For Each e In dict(k)
Debug.Print , Join(e, ",")
Next e
Next k
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71430420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the switch statement below to polymorphism in javascript and also how to access the different classes let type = document.querySelector('#productType');
type.addEventListener('change', function() {
switch (type.value) {
case 'DVD':
document.querySelector('.DVD').classList.add('visible');
document.querySelector('.Furniture').classList.remove('visible');
document.querySelector('.Book').classList.remove('visible');
break;
case 'Furniture':
document.querySelector('.Furniture').classList.add('visible');
document.querySelector('.DVD').classList.remove('visible');
document.querySelector('.Book').classList.remove('visible');
break;
case 'Book':
document.querySelector('.Book').classList.add('visible');
document.querySelector('.Furniture').classList.remove('visible');
document.querySelector('.DVD').classList.remove('visible');
break;
}
})
A: You could take an array of ids and update the wanted value with a single loop
ids = ['DVD', 'Furniture', 'Book'];
// update
ids.forEach(id => document.querySelector(id).classList[id === value
? 'add'
: 'remove'
]('visible'));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74041010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: KitKat: Service is null after exiting main activity I have a service and I need to check if it's still running after some time from a static context.
[I noticed this happens only on Android KitKat]
What I did:
My service:
public class Servizio extends Service {
public static Service servizio;
[...Other things...]
@Override
public void onCreate() {
super.onCreate();
servizio = this;
scheduleMyAlarmToDoSomethingAfterSomeTime();
}
[...Other things...]
}
Then I launch the service from the main Activity in onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
[...]
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ServizioUtility.toggleService(this, true);
[...]
}
Then I check if it's null after a minute (with an alarm receiver whose alarm was launched by the service. Note that the receiver works fine and the following code is called):
if (Servizio.servizio!=null) {// FIXME
[...]
//THIS IS NOT CALLED IN THE 2ND SCENARIO
}
There are 2 scenario:
*
*I run the activity, wait for the alarm to be launched and Servizio.servizio is not null.
*I run the activity, "kill" it using the , wait for the alarm receiver to be called, Servizio.servizio is now null. Note that the service, on the other hand, is still running (checked from Settings->App->Running menu).
What's happening in the 2nd scenario?
A: I found out this is an issue with Android KitKat, if you want to check it out:
https://code.google.com/p/android/issues/detail?id=63793
https://code.google.com/p/android/issues/detail?id=63618
A: My simple workaround:
It sets the alarm with a 1 sec delay and stops the service by calling stopForeground().
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (Build.VERSION.SDK_INT >= 19) {
Intent serviceIntent = new Intent(this, MessageHandlerService.class);
serviceIntent.setAction(ACTION_REFRESH);
serviceIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
manager.set(AlarmManager.RTC, System.currentTimeMillis()+1000, PendingIntent.getService(this, 1, serviceIntent, 0)); //1 sec delay
stopForeground(true);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21073136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Returning an event from a jQuery function How do I return an event to the calling function to do something once the function has completed running.
jQuery Function
$.fn.myFunction(){
this.each(function(){
var it = $(this)
setTimeout(function(){
/* Return an event */
}, 3000);
}
}
Call jQuery Function
$('div.specific').myFunction({
'finish': function(element){
/* Do something with element.
}
});
A: I don't understand the "return an event" but I'm guessing you want to call finish function whenever something is finished.
I am not sure this is the best way, but it's something you can start with.
$.fn.myFunction = function (object) {
const _self = $(this);
const init = () => {
if (object.hasOwnProperty('myCallback') && typeof object.myCallback === 'function') {
_self.on('myEvent', object.myCallback)
}
_self.on('click', triggerCustomEvent)
};
const triggerCustomEvent = () => _self.trigger('myEvent')
init();
}
$('#c').myFunction({
myCallback: () => alert(123),
})
$('#d').myFunction({
myCallback: () => alert(1234),
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="banner-message">
<button id="c">Color</button>
<button id="d">Dollar</button>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59032158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble with python regex matching I am tying to write a regular expression to match the dates in a string.
timeStamps = '25-12-2017 25:12:2017 25.12.2017'
pattern = r'(\d{2}(?:-|:|.)){2}\d{4}'
[ re.search(pattern,ts) for ts in timeStamps.split()]
re.search is working without any problem and works exactly the way wanted.
[<_sre.SRE_Match object; span=(0, 10), match='25-12-2017'>,
<_sre.SRE_Match object; span=(0, 10), match='25:12:2017'>,
<_sre.SRE_Match object; span=(0, 10), match='25.12.2017'>]
When i change the re.search to re.findall, The result was different.
[ re.findall(pattern,ts) for ts in timeStamps.split()]
[['12-'], ['12:'], ['12.']]
Why the two functions are giving two different output?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44355538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does the Testcafe Roles work behind the scenes I am curious about behind the scenes logic of Roles. I do understand they do some cookies and local storage magic and I am guessing there is some window magic involved as well
I am guessing that because in one of our tests one of our window properties is disappearing, however without any code actively removing it. So I assume the Roles after login will create a snapshot which is then being reapplied on top of every test case using useRole()
Any idea where could I find more details about this behavior, and how to instruct the testcafe to wait for a particular action to finish before taking that snapshot?
All the examples are finishing the test by clicking on signInButton, I was thinking about waiting for an element to appear using something like t.expect(element.visible).ok(); which however seems a bit odd (running assertion in the beforeEach statement.
A: TestCafe Roles reload a page and apply previously stored cookies and local storage values or perform the initialization steps if there are no stored values. They do not store or change window properties. However, scripts from your page can produce different results due to different local storage values. I think you can create an issue in the TestCafe repository and provide a sample page that can be used to reproduce this behavior.
You can add t.wait or a ClientFunction that returns a Promise to the end of a Role initialization function to postpone creating local storage snapshots.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56024493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Concatenate Column and value as property To existing JSON object in another column In SQL Server Let's say I have the following table Product
A: You can use a nested FOR JSON subquery, which breaks open the original JSON using OPENJSON and re-aggregates it
SELECT
p.ProductID,
p.ProductName,
(
SELECT
p.ProductID,
p.ProductName,
j.Price,
j.Shipper
FROM OPENJSON(p.Results, '$.Results')
WITH (
Price int,
Shipper varchar(100)
) j
FOR JSON PATH, ROOT('Results')
) AS Results
FROM Product p;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71223725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python3, hmac returns wrong output?! ARM71, 32bit I've asked another question here recently, regarding python, flask with a badsignature exception for sessions (https://stackoverflow.com/questions/37158432/python-flask-session-cookie-bad-signature-exception) , and I've been working with this problem now for a while, an seen another problem.
When signing a client-side session for my flask application hmac is used to hash the signature. On my personal computer this works fine, but when moving this to the embedded device built for this application hmac occasionally fails to hash the key (wrong output), which makes the session data invalid.
I made a small test program running the hmac.new() & .update() multiple times(10000) without any errors (on the target machine). But when the call is made inside the flask application the error occur in about 60% of the calls.
The call is made inside the "derive_key" method of itsdangerous.py and it looks like this:
def derive_key(self):
"""This method is called to derive the key. If you're unhappy with
the default key derivation choices you can override them here.
Keep in mind that the key derivation in itsdangerous is not intended
to be used as a security method to make a complex key out of a short
password. Instead you should use large random secret keys.
"""
salt = want_bytes(self.salt)
if self.key_derivation == 'concat':
return self.digest_method(salt + self.secret_key).digest()
elif self.key_derivation == 'django-concat':
return self.digest_method(salt + b'signer' +
self.secret_key).digest()
elif self.key_derivation == 'hmac':
mac = hmac.new(self.secret_key, digestmod=self.digest_method)
print("mac1:", binascii.hexlify(mac.digest())) #1
mac.update(salt)
print("mac2:", binascii.hexlify(mac.digest())) #2
return mac.digest()
elif self.key_derivation == 'none':
return self.secret_key
else:
raise TypeError('Unknown key derivation method')
digestmod = hashlib.sha1
With the secret_key = b'testing' and salt=b'cookie-session' the expected output is:
mac1: b'6ab6fc891eefd3b78743ea28b1803811561a7c9b'
mac2: b'd58bd52b4ced54374ea5baca0b6aa52b0e03af74'
But many times these values differ.
I've also seen that the output of mac1 & mac2 is equal! like the salt did not modify the result.
I have also asked this question here:
https://github.com/pallets/flask/issues/1808
This application is running on an ARM7, 32bit.
All libraries installed using yocto.
UPDATE:
For every call to derive_key() I also print salt and key: The output for a couple of requests is the following:
...: OPEN THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION NOT OKAY!!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'\xc8D\xf0\x95\xc5R\x9f\xe3n\xc7\xa2 `7\xa9\xdb\xdd\xd8F\x85'
...: mac2: b'\x156\xbf\xb6\x97}m\xe9[\xe0\xea\xd15\xb4\xff\x00\xf9\x14B\x0c'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION NOT OKAY!!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'D\xdaR}\xa0\xf2\x9awpP\xa0\x018b\xfcfH}\xcau'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION NOT OKAY!!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'=\xcc\x01\xee"\x0ed\xde\xf4z\run\rMm\x98\xcb\x0e\xba'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: OPEN THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
...: SAVES THE SESSION OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
...: mac2: b'\xd5\x8b\xd5+L\xedT7N\xa5\xba\xca\x0bj\xa5+\x0e\x03\xaft'
...: .-.-.-.-.-.-.
I added the "OK!" and "NOT OKAY!" so that it is easier for you to see which executions went wrong.
(I also see that it, in this example, is not 60% fails. )
In the output above, Only the "Open session"-event failed. So i tried it again to see if it is only when saving the session, but it happens for Save-session also..
...: SAVES THE SESSION NOT OK!
...: DERIVE KEY:
...: Salt: b'cookie-session'
...: Key: b'testing'
...: mac1: b'\xc8D\xf0\x95\xc5R\x9f\xe3n\xc7\xa2 `7\xa9\xdb\xdd\xd8F\x85'
...: mac2: b'\xc8D\xf0\x95\xc5R\x9f\xe3n\xc7\xa2 `7\xa9\xdb\xdd\xd8F\x85'
I finally found a small example program that reproduces the error.
#!/usr/bin/env python
async_mode = "eventlet"
if async_mode is None:
try:
import eventlet
async_mode = 'eventlet'
except ImportError:
pass
if async_mode is None:
try:
from gevent import monkey
async_mode = 'gevent'
except ImportError:
pass
if async_mode is None:
async_mode = 'threading'
print('async_mode is ' + async_mode)
if async_mode == 'eventlet':
import eventlet
eventlet.monkey_patch()
elif async_mode == 'gevent':
from gevent import monkey
monkey.patch_all()
import hmac
import hashlib
import time
from threading import Thread
thread = None
def background_thread():
time.sleep(0.5)
error_mac = ""
while True:
error_mac = ""
time.sleep(0.1)
counter = 0
for i in range(0, 40):
time.sleep(0.001)
mac = hmac.new(b'testing', digestmod=hashlib.sha1).digest() # == b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b':
if not mac == b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b':
counter = counter + 1
error_mac = mac
if error_mac:
print("Example of the wrong hmacs calculated:")
print(error_mac)
print("--------------------------------------")
print("{} - {}".format(time.time(), counter))
def index():
global thread
if thread is None:
thread = Thread(target=background_thread)
thread.daemon = True
thread.start()
for i in range(0,40):
print(hmac.new(b'testing', digestmod=hashlib.sha1).digest())
thread.join()
return "ok"
if __name__ == '__main__':
index()
Usually if there is an error of the first 20 hashes (created by the main thread) also the second thread will get the wrong hash. If no error occur in the main thread, and the second thread outputs only timestsamp and zeros, then restart the program.
It async_mode is set to "threading" everything works fine. But when set to "gevent" or "eventlet" this error occur.
Output with error:
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
b'D\xb4V\r9$gy\xe1 \x13\xd8\xc4f\x93O\x9e\xfa\x02\xff'
Example of the wrong hmacs calculated:
b"\x19\xd2}YU\xfeyX\x87\xee\xf5\x96\x94\xc1'\xa3tP\xb3\x96"
--------------------------------------
1463462121.3955774 - 40
Example of the wrong hmacs calculated:
b"\x19\xd2}YU\xfeyX\x87\xee\xf5\x96\x94\xc1'\xa3tP\xb3\x96"
--------------------------------------
1463462121.6040413 - 40
Example of the wrong hmacs calculated:
b"\x19\xd2}YU\xfeyX\x87\xee\xf5\x96\x94\xc1'\xa3tP\xb3\x96"
--------------------------------------
1463462121.8342147 - 40
Example of the wrong hmacs calculated:
b"\x19\xd2}YU\xfeyX\x87\xee\xf5\x96\x94\xc1'\xa3tP\xb3\x96"
Output with no error:
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
b'j\xb6\xfc\x89\x1e\xef\xd3\xb7\x87C\xea(\xb1\x808\x11V\x1a|\x9b'
1463462453.3856905 - 0
1463462453.5910842 - 0
1463462453.8242626 - 0
1463462454.0677884 - 0
1463462454.2900438 - 0
1463462454.5460255 - 0
1463462454.7883186 - 0
(On my ubuntu machine, this example works perfeclty. It is only on the ARM7 device that we have this problem..)
A: When I changed the arguments to gevetn patch all:
...
elif async_mode == 'gevent':
from gevent import monkey
monkey.patch_all(ssl=False)
...
It seems to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37209712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In LINQ, what is the main difference/usefulness between .Any<> and .Where<> to test for records existance For example, if I had a Linq to SQL data context, or if I had ADO.NET Entity Framework entities that mapped to a database table, and I want to test for a single Customer...
Is there much difference between:
MyDatabaseContext.Customers.Any(c => c.CustomerId == 3)
and
MyDatabaseContext.Customers.Where(c => c.CustomerId == 3)
.Any<> - return type bool
.Where<> - return type IQueryable
EDIT: Corrected question wording after accepting answer from Fredrik Mörk - thanks.
A: Any returns a bool while Where returns an IQueryable. Being lazy, one would expect Any to terminate as soon as one satisfying element is found (returning true) while Where will search them all.
If you want to select a single customer, Single is what you are looking for.
A: Any() returns a bool. I.e. are there any elements matching the condition. Use Any() if you just want to know if you have elements to work with. E.g. prefer Any() over Count() == 0 for instance as the latter will possible enumerate the entire sequence to find out if it is empty or not.
Where() returns a sequence of the elements matching the condition.
A: Any<> checks whether any items satisfy the criterion, i.e. returns bool, meaning that it only has to find the first item, which can be very fast. Whereas Where<> enumerates all the items that satisfy the condition, meaning that it has to iterate the whole collection.
A: Check the documentation again:
*
*Any<> returns a bool indicating whether at least one item meets the criteria
*Where<> returns an IEnumerable containing the items that meet the criteria
There may be a performance difference in that Any stops as soon as it can determine the result (when it finds a matching item), while Where will need to always loop over all items before returning the result. So if you only need to check whether there are any matching items, Any will be the method for the job.
A: Any tests the lambda/predicate and returns true/false
Where returns the set of objects for which lambda/predicate holds true as IQueryable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1404039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Fetching the lineitem field from item table when adding the item as lineitem in SO - Netsuite I am Learning netsuite,
I am trying to fetch the Customfield "custitem_celigo_sfnc_salesforce_id" from item, on sales order module when adding that item in SO line items
here is my sample
/**
*@NApiVersion 2.x
*@NScriptType ClientScript
*/
define(['N/record', 'N/search', 'N/url', 'N/https', 'N/runtime'], function(record, search, url, https, runtime) {
function fieldChanged(context) {
var currentRecord = context.currentRecord;
var sublistName = context.sublistId;
var sublistFieldName = context.fieldId;
var line = context.line;
var SFID = context.custitem_celigo_sfnc_salesforce_id;
var descriptionValue = currentRecord.getCurrentSublistValue({
sublistId: sublistName,
fieldId: "custitem_celigo_sfnc_salesforce_id"
})
alert(JSON.stringify(currentRecord));
alert(JSON.stringify(test));
return true;
}
var exports = {};
exports.fieldChanged = fieldChanged;
return exports;
});
It is not fetching the custom field , what is the way to do that.
Thanks in advance,
A: Try this one
var descriptionValue = currentRecord.getCurrentSublistValue({
sublistId: item,
fieldId: "custitem_celigo_sfnc_salesforce_id",
line:line
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69276570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Failed to decode downloaded font" when using gulp-iconfont I'm using gulp-iconfont v4 to generate fonts from SVGs in a folder.
I'm using a swig template to generate a .scss file and include that in my app.scss.
When I serve the files I get the following error in the console: Failed to decode downloaded font and the icons appear as [].
When I navigate to the file in the url, it downloads fine. What could be causing the browser to not decode them?
I've looked at the following with no resolution:
*
*Failed to decode downloaded font
*FontAwesome - Failed to decode downloaded font
*Failed to decode downloaded font: ..../font-family/bariol/bariol_regular-webfont.woff
Sometimes the warning comes from the .html page but sometimes it will come from Modernizr or most recently in jquery-1.7.2.min.js which isn't actually included anywhere :/
Everything 'works' so I'm not sure what code would be of use.
Here's the response from the file request:
When I look at the files in the resource panel it just shows the normal A-Z and not any glyphs. Not sure what the expected result is.
EDIT:
I've validated the font using Font Book and all looks well.
However, the info indicates there are two glyphs (when there should be only one currently) and also doesn't display them at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32190878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS transform: How can I make transform value a combination of two different classes? HTML:
<a class="button">TEST</a>
CSS:
.button{transform: translateY(-50%)}
.scale{transform: scale(1.1)}
JS:
$(document).ready(function(){
setTimeout(function(){
$('.button').addClass('scale');
setTimeout(function(){
$('.button').removeClass('scale');
},1000)
},1000);
})
The above is a simplified instance of my real project. I am trying to enlarge the button after page loads so it is more impressive to the users. The problem is, the two CSS won't work together, the transform will override one another. Is there any workaround for this if I don't want to make .scale like this:
.scale{transform: scale(1.1) translateY(-50%)}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71489896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loan calculator alteration I created a program that calculates loans, but it doesn't go under the guidelines of what my professor asked. Can show me the correct alteration. Source Code would be awesome and time saving, but you don't have to.
Heres the problem:
Write a program that lets the user enter the loan amount and the loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8. Heres a sample run:
Loan amount: 10000 [Enter]
Numbers of Years: 5: [Enter]
Interest rate Monthly Payment Total Payment
5% 188.71 11322.74
5.125% 189.28 11357.13
Heres my previous code:
# include <iostream>
# include <iomanip>
# include <cmath>
using namespace std;
int main ()
{
double loanAmountA;
double annualRate;
double paymentAmount;
double amountInterest;
double ratePeriod;
double balanceAfter;
double amountApplied;
double balance;
double paymentPeriod;
int paymentsPerYear;
int totalPayments;
int loanCount = 1;
int paymentCount = 1;
bool anotherLoan = true;
char response;
while (anotherLoan == true)
{
cout<<"Enter amount of loan A:$ ";
cin>>loanAmountA;
cout<<endl;
cout<<"Enter annual percentage rate (APR): "<<"%";
cin>>annualRate;
cout<<endl;
cout<<"Enter the number of payments per year: ";
cin>>paymentsPerYear;
cout<<endl;
cout<<"Enter the total number of payments: ";
cin>>totalPayments;
cout<<endl;
cout<<"Payment Payment Amount Amount to Balance after";
cout<<endl;
cout<<"Number Amount Interest Principal This Payment";
cout<<endl;
cin.ignore(80,'\n');
while (paymentCount <=totalPayments)
{
annualRate = annualRate / 100;
balance = loanAmountA - totalPayments * paymentAmount;
ratePeriod = balance * annualRate;
paymentAmount = loanAmountA * (totalPayments / paymentsPerYear * annualRate) / totalPayments;
balanceAfter = balance - paymentAmount;
balance = loanAmountA - (paymentCount * paymentAmount);
cout<<left<<setprecision(0)<<setw(3)<<paymentCount;
cout<<setw(13)<<left<<fixed<<setprecision(2)<<paymentAmount;
cout<<setw(26)<<left<<fixed<<setprecision(2)<<ratePeriod;
cout<<setw(39)<<left<<fixed<<setprecision(2)<<balance;
cout<<setw(42)<<left<<fixed<<setprecision(2)<<balanceAfter;
if (paymentCount % 12 == 0)
{
cout<<endl;
cout<<"Hit <Enter> to continue: "<<endl;
cin.ignore(80,'\n');
cin.get();
}
paymentCount++;
loanCount++;
cout<<endl;
}
cout<<"Would you like to calculate another loan? y/n and <enter>";
cin>>response;
if (response == 'n')
{
anotherLoan = false;
cout<<endl<<endl;
cout<<"There were"<<loanCount<< "loans processed.";
cout<<endl<<endl;
}
}
return 0;
}
A: Did you try to use the debugger, and find the point of failure?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3329632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to search text from page with next and previous functionality in jquery I am implementing the Text search functionality on page .I found lot of links .But i need more functionality .
Here is good example
http://jsfiddle.net/z7fjW/137/
function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {
//var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
//var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
var selector = selector || "body"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = $(selector).text().match(searchTermRegEx);
if(matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));
if($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
But I need it only search first word(present first) then using next it goes to next (go to next position).Then previous (go to previous position).as in note pad ?
Is this possible in query?
A: instead of directly highligt them add class "match" and work with it
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
//to highlighted specific index
$('.match:first').addClass('highlighted');
//to work with index you need you var matches to know what indexes exist
$('.match').eq(3).addClass('highlighted');
demo
A: I looked at http://jsfiddle.net/ruddog2003/z7fjW/141/, and it was a great starting point. I modified the logic a bit to allow both next and previous, and to be a bit more robust. Its not perfect, but here follows my code in AJAX format
HTML
> <div data-role="content">
> <div id="fulltext-search">
> <input type="text" name="search-input" value="" placeholder="Type text here..."/>
> <input type="button" name="search-action" value="Search"/>
> <button id="searchPrevious"> << </button>
> <button id="searchNext"> >> </button>
> </div>
> </div>
CSS
#document_fulltext [data-role="content"] #fulltext-search {
width: 100%;
text-align: center;
position: fixed;
top: 0px;
background-color: rgba(255,255,255, 0.8);
z-index: 10000;
border-bottom: 1px solid #000;
}
.highlighted {
color: white;
background-color: rgba(255,20,0,0.5);
padding: 3px;
border: 1px solid red;
-moz-border-radius: 15px;
border-radius: 15px;
}
JAVASCRIPT EVENT
$(document).ready(function( ) {
loadFulltext();
//Load full text into the designated div
function loadFulltext(searchString){
//reset
$("#fulltext").html('');
filePath = 'http://localhost/income_tax_act_58_of_1962.html';
$.ajax({
url: filePath,
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/html; charset=UTF-8;" );
},
cache: false,
success: function(html){
$("#fulltext").html(html);
// if search string was defined, perform a search
if ((searchString != undefined) && (searchString != '') && (searchString != null)){
if(!searchAndHighlight(searchString, '#fulltext')) {
alert("No results found");
}
}
},
fail: function(){
alert('FAIL');
}
});
}
/* ------------------------------ CLICK - REFRESH DOCUMENTS LIST --- */
$(document).on('click', 'input[name="search-action"]', function ( event ){
// load fresh copy of full text into the div and perform a search once it is successfully completed
loadFulltext($('input[name="search-input"]').val());
});
});
JAVASCRIPT FUNCTION
function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$('.match').removeClass('match'); //Remove old matches
//var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
//var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
var selector = selector || "body"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = $(selector).text().match(searchTermRegEx);
// count amount of matches found
if(matches) {
alert('['+matches.length+'] matches found');
// replace new matches
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
// add highligt to first matched class
$('.match:first').addClass('highlighted');
// keep track of next and previous. Start at one because on SEARCH the forst one was already highlightes
var matchIndex = 1;
// look out for user click on NEXT
$('#searchNext').on('click', function() {
//Re-set match index to create a wrap effect if the amount if next clicks exceeds the amount of matches found
if (matchIndex >= matches.length){
matchIndex = 0;
}
var currentMatch = $('.match');
currentMatch.removeClass('highlighted');
var nextMatch = $('.match').eq(matchIndex);
matchIndex += 1;
nextMatch.addClass('highlighted');
// scroll to the top of the next found instance -n to allow easy viewing
$(window).scrollTop(nextMatch.offset().top-30);
});
// look out for user click on PREVIOUS
$('#searchPrevious').on('click', function() {
//Re-set match index to create a wrap effect if the amount if next clicks exceeds the amount of matches found
if (matchIndex < 0){
matchIndex = matches.length-1;
}
var currentMatch = $('.match');
currentMatch.removeClass('highlighted');
var previousMatch = $('.match').eq(matchIndex-2);
matchIndex -= 1;
previousMatch.addClass('highlighted');
// scroll to the top of the next found instance -n to allow easy viewing
$(window).scrollTop(previousMatch.offset().top-30);
});
// if match found, scroll to where the first one appears
if($('.highlighted:first').length) {
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17520307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "could not find/install babel plugin 'proposal-decorators':" codesandbox I am working with a react app locally and when i deploy it to codesandbox it appears this error:
could not find/install babel plugin 'proposal-decorators': Cannot find plugin 'proposal-decorators' or 'babel-plugin-proposal-decorators'
I already tried to add the dependency but it doesn't let me.
this is really important, does anybody know what might be happening?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71474224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i make cmd prompt not show "echo is off" when i type @echo off I have a problem. I'm coding a batch file in Notepad, and when I type "@echo off" (without the quotes) it turns off echo but also displays "ECHO is off" (again, without the quotes) in the CMD Prompt window. Please help me!!
A: You could try doing
"@echo off>nul" (without quotes)
Which might stop it from displaying anything.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22578913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove .php extension from live website url I referred alexcican website and put the code in my htaccess.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
It works in my localhost, but doesn't work in thesvn link or live website. Please help.
A: Are you using apache server? Check if you have mod_rewrite enabled.
A: Just in case, if you have created any folder on you live website for your code, than try using below line
RewriteBase /yourFolderName/
keep above code just below RewriteEngine On
A: This one worked for me:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]
## hide .php extension snippet
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36495869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Swagger express sequelize I'm trying to set up a swagger, but I'm running into an error
Resolver error at paths./projects.post.parameters.0.schema.$ref
Could not resolve reference: #/models/Projects
Below is my project code
routes/projects.js
const Projects = require("../models").Projects;
module.exports = (app) => {
/**
* @swagger
* /projects:
* post:
* tags:
* - Projects
* name: Create Project
* summary: Create Project
* consumes:
* - application/json
* parameters:
* - name: body
* in: body
* schema:
* $ref: '#/models/Projects'
* type: object
* properties:
* authorFirstName:
* type: string
* authorLastName:
* type: string
* responses:
* 200:
* description: Project add successfully
*/
app.post("/projects", (req, res) => {});
};
models/Projects.js
"use strict";
module.exports = (sequelize, DataTypes) => {
const Projects = sequelize.define("Projects", {
authorFirstName: DataTypes.STRING,
authorLastName: DataTypes.STRING
});
return Projects;
};
This is a test project for swagger configuration. I use node.js express and sequelize
Here is swagger
var swaggerDefinition = {
info: {
title: "TETS MySQL api",
version: "1.0.0",
description: "Endpotions"
},
host: "localhost:4000",
basePath: "/",
securityDefinitions: {
bearerAuth: {
type: "apiKey",
name: "Authorization",
schema: "bearer",
in: "header"
}
}
};
const options = {
swaggerDefinition,
apis: ["./routes/*.js"]
};
const swaggerSpec = swaggerJSDoc(options);
app.get("/swagger.json", function(req, res) {
res.setHeader("Content-Type", "application/json");
res.send(swaggerSpec);
});
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56235214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Merging two digitally signed PDFs with Zend_Pdf Scenario: I have a webservice that signs PDFs, I'm using PHP, the Zend framework, and TCPDF. A PDF is to be submitted to the webservice, where a signature page is created, then merged with the incoming PDF, and then the merged document is signed. I've got TCPDF to create and sign the second document, but I'm not able to merge the two documents while preserving the signature.
My questions: Can TCPDF add pages to an existing PDF, then sign? Can Zend_Pdf merge two PDFs where one is already signed? Can signed PDFs even be merged? Is there a better way?
A: Afaik no, signed pdfs can't be merged, cause the signature is applied to the document, not to its range. Changing the document invalidates the signature.
A: If you are not concerned about invalidating the signature you can always print to Adobe PDF again and then combine with other PDFs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10955659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL statement using WHERE AND OR I try to execute the following, what am I missing here ?
DELETE FROM escrow WHERE host = '$name' OR challenger = '$name' AND id='$match_id'
A: When you use AND and OR together in any circumstances in any programming language ALWAYS use brackets. There is an implicit order which gets evaluated first (the AND or the OR condition) but you usually don't know the order and shouldn't be in need to look it up in the manual
Also use Prepared statements for SQL queries which depends on variables.
In your case you either write
... WHERE (host = ? OR challenger = ?) AND id = ?
or
... WHERE host = ? OR (challenger = ? AND id = ?)
depending on what condition you want.
Also, when a SQL query fails for whatever reason check the error message you get from the database. It will tell you whats wrong with the query. However, a valid query which returns no rows (because the WHERE condition don't match for any row) is still a valid query and not an error, the result is just empty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33448553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the font / typeface of a button in RemoteViews of an Android Widget? How can I change the font / typeface of a button in an Android widget? When working with normal view is this no problem:
// Within the app
Button myButton = (Button)rootView.findViewById(R.id.myAppButton);
myButton.setTypeface(someTypeface);
However, when working with a widget, views cannot be accessed directly but only via RemoteViews:
// Widget
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgetContent);
remoteViews.setTextViewText(R.id.myWidgetButton, "Some Text");
Is it somehow possible to set the typeface of the remote button as well?
A: There is no way to change the typeface of TextView in RemoteView.
To check properties that can be changed in RemoteView, in your case just go to Button and TextView classes and check all methods with annotation @android.view.RemotableViewMethod. As you can see, setTypeface don't have an annotation, so it can not be changed in RemoteView anyhow
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66473369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GIFs in Python and encoding I need to convert GIF to binary because I need to concatenate then the gif with a text string(which is in binary), because I am doing a Web Server in Python. The rest of the code already performs well and is able to load pictures, texts and htmls.
For gifs I have this:
elif format == "gif":
corpo = PIL.Image.open(path)
answer = corpo + ("\n").encode('UTF-8') #I need this line to end with a \n because it's the end of a HTTP answer
This gives me the error "TypeError: unsupported operand type(s) for +: 'GifImageFile' and 'bytes'", and, however, I haven't found any way to do what I am trying. Any help? Thank you.
A: Your GIF file on disk is already binary and already what a browser will expect if you send a Content-Type: image/gif so you just need to read its contents like this:
with open('image.gif', 'rb') as f:
corpo = f.read()
Your variable corpo will then contain a GIF-encoded image, with a header with the width and height, the palette and the LZW-compressed pixels.
Just by way of clarification, when you use:
im = Image.open('image.gif')
PIL will create a memory buffer according to the width and height in the GIF, then uncompress all the LZW-compressed pixels into that buffer. If you then convert that to bytes, you would be sending the browser the first pixel, then the second, then the third but without any header telling it how big the image is and also you'd be sending it uncompressed. That wouldn't work - as you discovered.
A: You'll need to use the .tobytes() method to get what you want (brief writeup here). Try this modification of your code snippet:
elif format == 'gif':
corpo = PIL.Image.open(path)
corpo_bytes = corpo.tobytes()
answer = corpo_bytes + ("\n").encode('UTF-8') #I need this line to end with a \n because it's the end of a HTTP answer
This might not be exactly what you're looking for, but it should be enough to get you started in the right direction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71453092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails Heroku change column data type I run this command for deploying database to heroku
heroku run rails db:migrate
But I got this error
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedObject: ERROR: type "dateti" does not exist
LINE 1: ALTER TABLE "users" ADD "activated_at" dateti
^
After that I changed wrong datatype "dateti" to "datetime"
class AddActivationToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :activation_digest, :string
add_column :users, :activated, :boolean, default: false
add_column :users, :activated_at, :datetime
end
end
But nothing changed. Still get this error. For development and test I use sqlite3 and for production postgresql. This error appear only when I try to deploy to heroku. On local database everything works.
database.yml file
# SQLite. Versions 3.8.0 and up are supported.
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem "sqlite3"
#
default: &default
adapter: sqlite3
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
<<: *default
database: db/development.sqlite3
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: db/test.sqlite3
production:
adapter: postgresql
encoding: unicode
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
database: sample_app_production
username: sample_app
password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %>
A: Before change activited_at (datetime) in AddActivationToUsers file. You must rollback AddActivationToUsers in db.
*
*rails db:rollback STEP=n (n migrations where n is the number of recent migrations you want to rollback)
*You change activited_at :datetime and save
*rails db:migration
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72721732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel9 Auth::user() retuns null I am learning Laravel Framework.
I am trying to redirect the user to Dashboard and get the user credential right after s/he is successfully registered. The problem is that I can register but when directed to Dashboard I get null object of a just registered user.
DashboardController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class DashboardController extends Controller
{
public function index()
{
dd(Auth::user());
// or dd(auth()->user());
return view('dashboard');
}
}
My routes in web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\Auth\RegisterController;
Route::get('/dashboard', [DashboardController::class,'index'])->name('dashboard');
Route::get('/register', [RegisterController::class,'index'])->name('register');
Route::post('/register', [RegisterController::class,'store']);
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class RegisterController extends Controller
{
public function index()
{
return view('auth.register');
}
public function store(Request $request)
{
$this->validate($request, [
'name'=> 'required|max:255',
'username' => 'required|max:255',
'email' => 'required|email|max:255',
'password' => 'required|confirmed',
]);
User::create([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
return redirect()->route('dashboard');
}
}
User.php Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'username',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I am using mysql db. Thanks in advance.
A: Try using any of the below Auth methods.
1st
$user = User::create([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
// here we're authenticating newly created user
Auth::login($user);
2nd
// newly created user email & password can be passed in an attempt function.
Auth::attempt(['email' => $email, 'password' => $password])
3rd
$user = User::create([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
// we can use loginUsingId like this
Auth::loginUsingId($user->id);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73230555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.