title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Order of legend entries in ggplot2 barplots with coord_flip()
|
<p>I'm struggling get the right ordering of variables in a graph I made with ggplot2 in R.</p>
<p>Suppose I have a dataframe such as:</p>
<pre><code>set.seed(1234)
my_df<- data.frame(matrix(0,8,4))
names(my_df) <- c("year", "variable", "value", "vartype")
my_df$year <- rep(2006:2007)
my_df$variable <- c(rep("VX",2),rep("VB",2),rep("VZ",2),rep("VD",2))
my_df$value <- runif(8, 5,10)
my_df$vartype<- c(rep("TA",4), rep("TB",4))
</code></pre>
<p>which yields the following table:</p>
<pre><code> year variable value vartype
1 2006 VX 5.568517 TA
2 2007 VX 8.111497 TA
3 2006 VB 8.046374 TA
4 2007 VB 8.116897 TA
5 2006 VZ 9.304577 TB
6 2007 VZ 8.201553 TB
7 2006 VD 5.047479 TB
8 2007 VD 6.162753 TB
</code></pre>
<p>There are four variables (VX, VB, VZ and VD), belonging to two groups of variable types, (TA and TB).</p>
<p>I would like to plot the values as horizontal bars on the y axis, <strong>ordered vertically first by variable groups and then by variable names</strong>, faceted by year, with values on the x axis and fill colour corresponding to variable group.
(i.e. in this simplified example, the order should be, top to bottom, VB, VX, VD, VZ)</p>
<p>1) My first attempt has been to try the following: </p>
<pre><code>ggplot(my_df,
aes(x=variable, y=value, fill=vartype, order=vartype)) +
# adding or removing the aesthetic "order=vartype" doesn't change anything
geom_bar() +
facet_grid(. ~ year) +
coord_flip()
</code></pre>
<p>However, the variables are listed in reverse alphabetical order, but not by <strong>vartype</strong> : the <code>order=vartype</code> aesthetic is ignored. </p>
<p><img src="https://i.stack.imgur.com/GGZNG.png" alt="enter image description here"></p>
<p>2) Following an answer to a similar question I posted yesterday, i tried the following, based on the post <a href="https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph">Order Bars in ggplot2 bar graph</a> :</p>
<pre><code>my_df$variable <- factor(
my_df$variable,
levels=rev(sort(unique(my_df$variable))),
ordered=TRUE
)
</code></pre>
<p>This approach does gets the variables in vertical alphabetical order in the plot, but ignores the fact that the variables should be ordered <strong>first by variable goups</strong> (with TA-variables on top and TB-variables below).</p>
<p><img src="https://i.stack.imgur.com/z7hYe.png" alt="enter image description here"></p>
<p>3) The following gives the same as 2 (above):</p>
<pre><code>my_df$vartype <- factor(
my_df$vartype,
levels=sort(unique(my_df$vartype)),
ordered=TRUE
)
</code></pre>
<p>... which has the same issues as the first approach (variables listed in reverse alphabetical order, groups ignored)</p>
<p>4) another approach, based on the original answer to <a href="https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph">Order Bars in ggplot2 bar graph</a> , also gives the same plat as 2, above</p>
<pre><code>my_df <- within(my_df,
vartype <- factor(vartype,
levels=names(sort(table(vartype),
decreasing=TRUE)))
)
</code></pre>
<p>I'm puzzled by the fact that, despite several approaches, the aesthetic <code>order=vartype</code> is ignored. Still, it seems to work in an unrelated problem: <a href="http://learnr.wordpress.com/2010/03/23/ggplot2-changing-the-default-order-of-legend-labels-and-stacking-of-data/" rel="noreferrer">http://learnr.wordpress.com/2010/03/23/ggplot2-changing-the-default-order-of-legend-labels-and-stacking-of-data/</a></p>
<p>I hope that the problem is clear and welcome any suggestions.</p>
<p>Matteo</p>
<p><em>I posted a similar question yesterday, but, unfortunately I made several mistakes when descrbing the problem and providing a reproducible example.
I've listened to several suggestions since, and <strong>thoroughly searched stakoverflow for similar question and applied, to the best of my knowledge, every suggested combination of solutions, to no avail.</strong>
I'm posting the question again hoping to be able to solve my issue and, hopefully, be helpful to others.</em></p>
| 0 | 1,615 |
Piping for input/output
|
<p>This question follows from my attempt to implement the instructions in:</p>
<p><a href="https://stackoverflow.com/questions/1734932/linux-pipes-as-input-and-output">Linux Pipes as Input and Output</a></p>
<p><a href="https://stackoverflow.com/questions/2784500/how-to-send-a-simple-string-between-two-programs-using-pipes">How to send a simple string between two programs using pipes?</a></p>
<p><a href="http://tldp.org/LDP/lpg/node11.html" rel="nofollow noreferrer">http://tldp.org/LDP/lpg/node11.html</a></p>
<p>My question is along the lines of the question in: <a href="https://stackoverflow.com/questions/1734932/linux-pipes-as-input-and-output">Linux Pipes as Input and Output</a>, but more specific.</p>
<p>Essentially, I am trying to replace:</p>
<pre><code>/directory/program < input.txt > output.txt
</code></pre>
<p>using pipes in C++ in order to avoid using the hard drive. Here's my code:</p>
<pre><code>//LET THE PLUMBING BEGIN
int fd_p2c[2], fd_pFc[2], bytes_read;
// "p2c" = pipe_to_child, "pFc" = pipe_from_child (see above link)
pid_t childpid;
char readbuffer[80];
string program_name;// <---- includes program name + full path
string gulp_command;// <---- includes my line-by-line stdin for program execution
string receive_output = "";
pipe(fd_p2c);//create pipe-to-child
pipe(fd_pFc);//create pipe-from-child
childpid = fork();//create fork
if (childpid < 0)
{
cout << "Fork failed" << endl;
exit(-1);
}
else if (childpid == 0)
{
dup2(0,fd_p2c[0]);//close stdout & make read end of p2c into stdout
close(fd_p2c[0]);//close read end of p2c
close(fd_p2c[1]);//close write end of p2c
dup2(1,fd_pFc[1]);//close stdin & make read end of pFc into stdin
close(fd_pFc[1]);//close write end of pFc
close(fd_pFc[0]);//close read end of pFc
//Execute the required program
execl(program_name.c_str(),program_name.c_str(),(char *) 0);
exit(0);
}
else
{
close(fd_p2c[0]);//close read end of p2c
close(fd_pFc[1]);//close write end of pFc
//"Loop" - send all data to child on write end of p2c
write(fd_p2c[1], gulp_command.c_str(), (strlen(gulp_command.c_str())));
close(fd_p2c[1]);//close write end of p2c
//Loop - receive all data to child on read end of pFc
while (1)
{
bytes_read = read(fd_pFc[0], readbuffer, sizeof(readbuffer));
if (bytes_read <= 0)//if nothing read from buffer...
break;//...break loop
receive_output += readbuffer;//append data to string
}
close(fd_pFc[0]);//close read end of pFc
}
</code></pre>
<p>I am absolutely sure that the above strings are initialized properly. However, two things happen that don't make sense to me:</p>
<p>(1) The program I am executing reports that the "input file is empty." Since I am not calling the program with "<" it should not be expecting an input file. Instead, it should be expecting keyboard input. Furthermore, it should be reading the text contained in "gulp_command."</p>
<p>(2) The program's report (provided via standard output) appears in the terminal. This is odd because the purpose of this piping is to transfer stdout to my string "receive_output." But since it is appearing on screen, that indicates to me that the information is not being passed correctly through the pipe to the variable. If I implement the following at the end of the if statement,</p>
<pre><code>cout << receive_output << endl;
</code></pre>
<p>I get nothing, as though the string is empty. I appreciate any help you can give me!</p>
<p>EDIT: Clarification</p>
<p>My program currently communicates with another program using text files. My program writes a text file (e.g. input.txt), which is read by the external program. That program then produces output.txt, which is read by my program. So it's something like this:</p>
<pre><code>my code -> input.txt -> program -> output.txt -> my code
</code></pre>
<p>Therefore, my code currently uses,</p>
<pre><code>system("program < input.txt > output.txt");
</code></pre>
<p>I want to replace this process using pipes. I want to pass my input as standard input to the program, and have my code read the standard output from that program into a string.</p>
| 0 | 1,530 |
How do I rewrite my MySQL update statement to eliminate "Truncated incorrect INTEGER value" warnings?
|
<p>I'm using MySQL 5.5.37. I want to eliminate the warnings from my update statement, which are shown below ...</p>
<pre><code>update resource r
set grade_id = convert(substring_index(substring_index(
r.description, 'Grade ', -1), ' ', 1), unsigned integer)
where r.description like '% Grade%'
and CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(
r.description, 'Grade ', -1), ' ' ,1),UNSIGNED) > 0;
Query OK, 0 rows affected, 7 warnings (0.02 sec)
Rows matched: 1333 Changed: 0 Warnings: 7
mysql> show warnings;
+---------+------+--------------------------------------------------+
| Level | Code | Message |
+---------+------+--------------------------------------------------+
| Warning | 1292 | Truncated incorrect INTEGER value: '' |
| Warning | 1292 | Truncated incorrect INTEGER value: '' |
| Warning | 1292 | Truncated incorrect INTEGER value: '' |
| Warning | 1292 | Truncated incorrect INTEGER value: 'MyCo' |
| Warning | 1292 | Truncated incorrect INTEGER value: 'MyCo' |
| Warning | 1292 | Truncated incorrect INTEGER value: 'MyCo' |
| Warning | 1292 | Truncated incorrect INTEGER value: 'MyCo' |
+---------+------+--------------------------------------------------+
</code></pre>
<p>What I do not understand is how I can rewrite my query differently given that none of the values being updated match what the warnings are complaining about. BElow is my query where I list the distinct values that are being updated ...</p>
<pre><code>mysql> select distinct substring_index(substring_index(
r.description, 'Grade ', -1), ' ', 1)
from resource r
where r.description like '% Grade%'
and CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(
r.description, 'Grade ',-1),' ',1),UNSIGNED) > 0;
+-----------------------------------------------------------------------+
| substring_index(substring_index(r.description, 'Grade ', -1), ' ', 1) |
+-----------------------------------------------------------------------+
| 7 |
| 8 |
| 11 |
| 9 |
| 12 |
| 10 |
| 6 |
+-----------------------------------------------------------------------+
</code></pre>
<p>How do I rewrite my update statement so that it updates the same values without tryihng to truncate incorrect integers?</p>
| 0 | 1,320 |
How to use default value in the builder pattern if that value is not passed and also make thread safe?
|
<p>I am trying to use Builder Pattern for my class.. </p>
<p>Below is my Builder class which I have built by following Joshua Bloch version as he showed in Effective Java, 2nd Edition. Our customer will mostly pass <code>userId</code>, <code>clientId</code> always but other fields are optional and they may or may not pass it. Here Preference is an ENUM class having four fields in it.</p>
<pre><code>public final class InputKeys {
private long userid;
private long clientid;
private long timeout = 500L;
private Preference pref;
private boolean debug;
private Map<String, String> parameterMap;
private InputKeys(Builder builder) {
this.userid = builder.userId;
this.clientid = builder.clientId;
this.pref = builder.preference;
this.parameterMap = builder.parameterMap;
this.timeout = builder.timeout;
this.debug = builder.debug;
}
public static class Builder {
protected final long userId;
protected final long clientId;
protected long timeout;
protected Preference preference;
protected boolean debug;
protected Map<String, String> parameterMap;
public Builder(long userId, long clientId) {
this.userId = userId;
this.clientId = clientId;
}
public Builder parameterMap(Map<String, String> parameterMap) {
this.parameterMap = parameterMap;
return this;
}
public Builder preference(Preference preference) {
this.preference = preference;
return this;
}
public Builder debug(boolean debug) {
this.debug = debug;
return this;
}
public Builder timeout(long timeout) {
this.timeout = timeout;
return this;
}
public InputKeys build() {
return new InputKeys(this);
}
}
}
</code></pre>
<p>Below is my ENUM class - </p>
<pre><code>public enum Preference {
PRIMARY,
SECONDARY
}
</code></pre>
<p>I am making a call like this to construct the <code>InputKeys</code> parameter - </p>
<pre><code>InputKeys keys = new InputKeys.Builder(12000L, 33L).build();
System.out.println(keys);
</code></pre>
<p>The only problem here I am seeing is, if the customers are not passing any timeout value, I need to have default timeout value set as 500 always but if they are passing any timeout value then it should override my default timeout value. And this is not working for me as when I see my <code>keys</code> in the debug mode, it always has timeout value as 0.</p>
<p>Is there anything I am missing? And also I am trying to make this class immutable and thread safe.. Is this a thread safe and immutable version of Builder or I have missed something?</p>
<p><strong>UPDATE:-</strong> </p>
<p>Specific scenarios when people will be using this is we have a factory which customers are going to use to make a call to our code. We have a simple interface which one of our class is implementing it and then we have a factory by which we will call a certain method of that implementation which accepts this <code>keys</code> parameter. </p>
<p>So they will be using the below code in there application to make a call and it might be possible they will be running there application in a multithreaded environment.</p>
<pre><code>InputKeys keys = new InputKeys.Builder(12000L, 33L).build();
IClient client = ClientFactory.getInstance();
client.getData(keys);
</code></pre>
<p>And then InputKeys Builder can be used multiple times to construct the keys, it's not one time. Whatever userId and clientId they will be getting they will construct the InputKeys again.</p>
| 0 | 1,288 |
View Model IEnumerable<> property is coming back null (not binding) from post method?
|
<p>I have a view model that contains a Product class type and an IEnumerable< Product > type. On the post the first level product object comes back binded from the viewmodel whereas the product enum is coming back null. </p>
<p>Why is the IEnumerable< Prouduct> property not getting binded to my view model per the post? Thx!</p>
<p>Models:</p>
<pre><code>public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductIndexViewModel
{
public Product NewProduct { get; set; }
public IEnumerable<Product> Products { get; set; }
}
public class BoringStoreContext
{
public BoringStoreContext()
{
Products = new List<Product>();
Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) });
Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) });
}
public List<Product> Products {get; set;}
}
</code></pre>
<p>View:</p>
<pre><code>@model ProductIndexViewModel
@using (@Html.BeginForm())
{
<div>
@Html.LabelFor(model => model.NewProduct.Name)
@Html.EditorFor(model => model.NewProduct.Name)
</div>
<div>
@Html.LabelFor(model => model.NewProduct.Price)
@Html.EditorFor(model => model.NewProduct.Price)
</div>
<div>
<input type="submit" value="Add Product" />
</div>
foreach (var item in Model.Products)
{
<div>
@Html.LabelFor(model => item.ID)
@Html.EditorFor(model => item.ID)
</div>
<div>
@Html.LabelFor(model => item.Name)
@Html.EditorFor(model => item.Name)
</div>
<div>
@Html.LabelFor(model => item.Price)
@Html.EditorFor(model => item.Price)
</div>
}
}
</code></pre>
<p>Controller:</p>
<pre><code>public class HomeController : Controller
{
BoringStoreContext db = new BoringStoreContext();
public ActionResult Index()
{
ProductIndexViewModel viewModel = new ProductIndexViewModel
{
NewProduct = new Product(),
Products = db.Products
};
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ProductIndexViewModel viewModel)
{
// ???? viewModel.Products is NULL here
// ???? viewModel.NewProduct comes back fine
return View();
}
</code></pre>
| 0 | 1,153 |
Room: Cannot access database on the main thread since it may potentially lock the UI for a long period of time
|
<p>In the main activity, I have LiveData which contains members and a click listener. If I click on a member, then his ID is passed with intent.putExtra. That ID is later passed on to the method open in this activity. With this activity, I want to see the details of a member. In my MemberInfo activity, I marked a line where my problem lies.
It shows me this error: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.</p>
<p>My DAO consists this code:</p>
<pre><code>@Query("SELECT * FROM member_table WHERE MemberID=:id")
Member getMemberInfo(long id);
</code></pre>
<p>This is my main activity:</p>
<pre><code>public class MemberMainActivity extends AppCompatActivity implements MemberListAdapter.MemberClickListener{
private MemberViewModel mMemberViewModel;
private List<Member> mMember;
void setMember(List<Member> members) {
mMember = members;
}
public static final int NEW_MEMBER_ACTIVITY_REQUEST_CODE = 1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MemberMainActivity.this, NewMemberActivity.class);
startActivityForResult(intent, NEW_MEMBER_ACTIVITY_REQUEST_CODE);
}
});
RecyclerView recyclerView = findViewById(R.id.recyclerviewcard_member);
final MemberListAdapter adapter = new MemberListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mMemberViewModel = ViewModelProviders.of(this).get(MemberViewModel.class);
mMemberViewModel.getAllMember().observe(this, new Observer<List<Member>>() {
@Override
public void onChanged(@Nullable final List<Member> members) {
mMember = members;
// Update the cached copy of the words in the adapter.
adapter.setMember(members);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_MEMBER_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
Member member = new Member(data.getStringExtra(NewMemberActivity.EXTRA_REPLY), data.getStringExtra(NewMemberActivity.EXTRA_REPLY2));
mMemberViewModel.insert(member);
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
public void onMemberClick(int position) {
Member member = mMember.get(position);
Intent intent = new Intent(getApplicationContext(),MemberInfo.class);
intent.putExtra("MemberID", member.getId());
MemberInfo.open(this, member.getId());
}
}
</code></pre>
<p>This is my activity: </p>
<pre><code>public class MemberInfo extends AppCompatActivity {
public static void open(Activity activity, long memberid) {
Intent intent = new Intent(activity, MemberInfo.class);
intent.putExtra("MemberID", memberid);
activity.startActivity(intent);
}
private List<Member> mMember;
private MemberViewModel mMemberViewModel;
void setMember(List<Member> members){
mMember = members;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memberinfo);
Log.i("okay", "memberinfo");
Intent intent = getIntent();
if (intent != null && intent.hasExtra("MemberID")) {
long memberid = intent.getLongExtra("MemberID", -1);
// TODO: get customer details based on customer id
TextView firstname = findViewById(R.id.layout_memberfirstname);
TextView surname = findViewById(R.id.layout_membersurname);
TextView balance = findViewById(R.id.layout_memberbalance);
-------------Member member = MemberRoomDatabase.getDatabase().memberDao().getMemberInfo(memberid);-------------
firstname.setText(member.getFirstname());
surname.setText(member.getSurname());
}
else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}
}
</code></pre>
<p>I thought that maybe it is because I'm missing a AsyncTask method. I tried this, but this also didn't work:</p>
<pre><code>private static class insertMemberInfoAsyncTask extends AsyncTask<Member, Void, Void> {
private MemberDao mAsyncTaskDao;
insertMemberInfoAsyncTask(MemberDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(Member... params) {
Member member = params[0];
mAsyncTaskDao.getMemberInfo(member.getId());
return null;
}
}
public Member getMemberInfo(long id) {
mAllMember = mMemberDao.getAllMember();
Member member = mMemberDao.getMemberInfo(id);
new insertMemberInfoAsyncTask(mMemberDao).execute(member);
return member;
}
</code></pre>
<p>I think I use the method wrong. Can anybody help me?</p>
| 0 | 1,958 |
Java 8 stream objects significant memory usage
|
<p>In looking at some profiling results, I noticed that using streams within a tight loop (used instead of another nested loop) incurred a significant memory overhead of objects of types <code>java.util.stream.ReferencePipeline</code> and <code>java.util.ArrayList$ArrayListSpliterator</code>. I converted the offending streams to foreach loops, and the memory consumption decreased significantly. </p>
<p>I know that streams make no promises about performing any better than ordinary loops, but I was under the impression that the difference would be negligible. In this case it seemed like it was a 40% increase.</p>
<p>Here is the test class I wrote to isolate the problem. I monitored memory consumption and object allocation with JFR:</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.function.Predicate;
public class StreamMemoryTest {
private static boolean blackHole = false;
public static List<Integer> getRandListOfSize(int size) {
ArrayList<Integer> randList = new ArrayList<>(size);
Random rnGen = new Random();
for (int i = 0; i < size; i++) {
randList.add(rnGen.nextInt(100));
}
return randList;
}
public static boolean getIndexOfNothingManualImpl(List<Integer> nums, Predicate<Integer> predicate) {
for (Integer num : nums) {
// Impossible condition
if (predicate.test(num)) {
return true;
}
}
return false;
}
public static boolean getIndexOfNothingStreamImpl(List<Integer> nums, Predicate<Integer> predicate) {
Optional<Integer> first = nums.stream().filter(predicate).findFirst();
return first.isPresent();
}
public static void consume(boolean value) {
blackHole = blackHole && value;
}
public static boolean result() {
return blackHole;
}
public static void main(String[] args) {
// 100 million trials
int numTrials = 100000000;
System.out.println("Beginning test");
for (int i = 0; i < numTrials; i++) {
List<Integer> randomNums = StreamMemoryTest.getRandListOfSize(100);
consume(StreamMemoryTest.getIndexOfNothingStreamImpl(randomNums, x -> x < 0));
// or ...
// consume(StreamMemoryTest.getIndexOfNothingManualImpl(randomNums, x -> x < 0));
if (randomNums == null) {
break;
}
}
System.out.print(StreamMemoryTest.result());
}
}
</code></pre>
<p>Stream implementation:</p>
<p><code>Memory Allocated for TLABs 64.62 GB</code></p>
<pre><code>Class Average Object Size(bytes) Total Object Size(bytes) TLABs Average TLAB Size(bytes) Total TLAB Size(bytes) Pressure(%)
java.lang.Object[] 415.974 6,226,712 14,969 2,999,696.432 44,902,455,888 64.711
java.util.stream.ReferencePipeline$2 64 131,264 2,051 2,902,510.795 5,953,049,640 8.579
java.util.stream.ReferencePipeline$Head 56 72,744 1,299 3,070,768.043 3,988,927,688 5.749
java.util.stream.ReferencePipeline$2$1 24 25,128 1,047 3,195,726.449 3,345,925,592 4.822
java.util.Random 32 30,976 968 3,041,212.372 2,943,893,576 4.243
java.util.ArrayList 24 24,576 1,024 2,720,615.594 2,785,910,368 4.015
java.util.stream.FindOps$FindSink$OfRef 24 18,864 786 3,369,412.295 2,648,358,064 3.817
java.util.ArrayList$ArrayListSpliterator 32 14,720 460 3,080,696.209 1,417,120,256 2.042
</code></pre>
<p>Manual implementation:</p>
<p><code>Memory Allocated for TLABs 46.06 GB</code></p>
<pre><code>Class Average Object Size(bytes) Total Object Size(bytes) TLABs Average TLAB Size(bytes) Total TLAB Size(bytes) Pressure(%)
java.lang.Object[] 415.961 4,190,392 10,074 4,042,267.769 40,721,805,504 82.33
java.util.Random 32 32,064 1,002 4,367,131.521 4,375,865,784 8.847
java.util.ArrayList 24 14,976 624 3,530,601.038 2,203,095,048 4.454
</code></pre>
<p>Has anyone else encountered issues with the stream objects themselves consuming memory? / Is this a known issue?</p>
| 0 | 1,962 |
Clicking a button with Selenium in Python
|
<p><strong>Goal</strong>: use Selenium and Python to search for company name on LinkedIn's search bar THEN click on the "Companies" button in the navigation to arrive to information about companies that are similar to the keyword (rather than individuals at that company). See below for an example. "CalSTRS" is the company I search for in the search bar. Then I want to click on the "Companies" navigation button.</p>
<p><a href="https://i.stack.imgur.com/YbdLH.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YbdLH.jpg" alt="LinkedIn list navigation"></a></p>
<p><strong>My Helper Functions</strong>: I have defined the following helper functions (including here for reproducibility). </p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from random import randint
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome()
def li_bot_login(usrnm, pwrd):
##-----Log into linkedin and get to your feed-----
browser.get('https://www.linkedin.com')
##-----Find the Search Bar-----
u = browser.find_element_by_name('session_key')
##-----Enter Username and Password, Enter-----
u.send_keys(usrnm)
p = browser.find_element_by_name('session_password')
p.send_keys(pwrd + Keys.ENTER)
def li_bot_search(search_term):
#------Search for term in linkedin search box and land you at the search results page------
search_box = browser.find_element_by_css_selector('artdeco-typeahead-input.ember-view > input')
search_box.send_keys(str(search_term) + Keys.ENTER)
def li_bot_close():
##-----Close the Webdriver-----
browser.close()
li_bot_login()
li_bot_search('calstrs')
time.sleep(5)
li_bot_close()
</code></pre>
<p>Here is the HTML of the "Companies" button element:</p>
<pre><code><button data-vertical="COMPANIES" data-ember-action="" data-ember-action-7255="7255">
Companies
</button>
</code></pre>
<p>And the XPath:</p>
<pre><code>//*[@id="ember1202"]/div[5]/div[3]/div[1]/ul/li[5]/button
</code></pre>
<p><strong>What I have tried</strong>: Admittedly, I am not very experienced with HTML and CSS so I am probably missing something obvious. Clearly, I am not selecting / interacting with the right element. So far, I have tried...</p>
<pre><code>companies_btn = browser.find_element_by_link_text('Companies')
companies_btn.click()
</code></pre>
<p>which returns this traceback:</p>
<pre><code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Companies"}
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64)
</code></pre>
<p>and</p>
<pre><code>companies_btn_xpath = '//*[@id="ember1202"]/div[5]/div[3]/div[1]/ul/li[5]/button'
browser.find_element_by_xpath(companies_btn_xpath).click()
</code></pre>
<p>with this traceback...</p>
<pre><code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ember1202"]/div[5]/div[3]/div[1]/ul/li[5]/button"}
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64)
</code></pre>
<p>and</p>
<pre><code>browser.find_element_by_css_selector('#ember1202 > div.application-outlet > div.authentication-outlet > div.neptune-grid.two-column > ul > li:nth-child(5) > button').click()
</code></pre>
<p>which returns this traceback...</p>
<pre><code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#ember1202 > div.application-outlet > div.authentication-outlet > div.neptune-grid.two-column > ul > li:nth-child(5) > button"}
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64)
</code></pre>
| 0 | 1,489 |
Android Studio - Issue in build.gradle uncaught translation error ExecutionException OutOfMemory
|
<p>I am having a strange problem with my Android app in Android Studio. Everything seemed to be working fine, until today after adding some <em>new files</em> and making some updates to <strong>build.gradle</strong>.</p>
<p>The error message I am seeing is the following:</p>
<pre><code>Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded
6 errors; aborting
Error:Execution failed for task ':myapplication:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_11\bin\java.exe'' finished with non-zero exit value 1
</code></pre>
<p>Do you know if there is any issue with my build.gradle below? The new lines are under "<strong>NEW DEPENDENCIES ADDED BELOW THIS LINE</strong>". I also set multiDexEnabled to true.</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.my.app"
minSdkVersion 14
targetSdkVersion 21
multiDexEnabled true
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
//useLibrary 'org.apache.http.legacy'
}
dependencies {
compile files('libs/aspectjrt-1.8.2.jar')
compile files('libs/isoparser-1.0-RC-27.jar')
compile files('libs/multiscreen-android-1.1.11.jar')
compile files('libs/picasso-2.5.2.jar')
compile files('libs/volley.jar')
compile 'com.facebook.android:facebook-android-sdk:4.5.0'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:support-v13:+'
/* NEW DEPENDENCIES BELOW THIS LINE */
compile 'com.android.support:design:23.0.1'
compile 'com.android.support:cardview-v7:23.1.0'
compile 'com.github.bumptech.glide:glide:3.6.0'
compile 'de.hdodenhof:circleimageview:1.3.0'
// Used to optimize rendering of list views
// compile 'com.android.support:recyclerview-v7:23.1.0'
compile 'uk.co.chrisjenx:calligraphy:2.1.0'
//compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.android.gms:play-services:7.8.0'
//compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'com.google.android.gms:play-services-plus:7.8.0'
compile 'com.google.android.gms:play-services-wallet:7.8.0'
}
</code></pre>
| 0 | 1,224 |
Why does C++ output negative numbers when using modulo?
|
<p><strong>Math</strong>:</p>
<p>If you have an equation like this:</p>
<pre><code>x = 3 mod 7
</code></pre>
<p>x could be ... -4, 3, 10, 17, ..., or more generally:</p>
<pre><code>x = 3 + k * 7
</code></pre>
<p>where k can be any integer. I don't know of a modulo operation is defined for math, but the factor ring certainly is.</p>
<p><strong>Python</strong>:</p>
<p>In Python, you will always get non-negative values when you use <code>%</code> with a positive <code>m</code>:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
m = 7
for i in xrange(-8, 10 + 1):
print(i % 7)
</code></pre>
<p>Results in:</p>
<pre><code>6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3
</code></pre>
<p><strong>C++:</strong></p>
<pre><code>#include <iostream>
using namespace std;
int main(){
int m = 7;
for(int i=-8; i <= 10; i++) {
cout << (i % m) << endl;
}
return 0;
}
</code></pre>
<p>Will output:</p>
<pre><code>-1 0 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 0 1 2 3
</code></pre>
<p><strong>ISO/IEC 14882:2003(E) - 5.6 Multiplicative operators:</strong></p>
<blockquote>
<p>The binary / operator yields the quotient, and the binary % operator
yields the remainder from the division of the first expression by the
second. If the second operand of / or % is zero the behavior is
undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are
nonnegative then the remainder is nonnegative; if not, <strong>the sign of the
remainder is implementation-defined 74)</strong>.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>74) According to work underway toward the revision of ISO C, the
preferred algorithm for integer division follows the rules defined in
the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is
always rounded toward zero.</p>
</blockquote>
<p>Source: <a href="http://cs.nyu.edu/courses/summer12/CSCI-GA.2110-001/downloads/C++%20Standard%202003.pdf" rel="noreferrer">ISO/IEC 14882:2003(E)</a> </p>
<p>(I couldn't find a free version of <code>ISO/IEC 1539:1991</code>. Does anybody know where to get it from?)</p>
<p>The operation seems to be defined like this:</p>
<p><img src="https://i.stack.imgur.com/8p2MN.png" alt="enter image description here"></p>
<p><strong>Question</strong>: </p>
<p>Does it make sense to define it like that? </p>
<p>What are arguments for this specification? Is there a place where the people who create such standards discuss about it? Where I can read something about the reasons why they decided to make it this way?</p>
<p>Most of the time when I use modulo, I want to access elements of a datastructure. In this case, I have to make sure that mod returns a non-negative value. So, for this case, it would be good of mod always returned a non-negative value.
(Another usage is the <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations" rel="noreferrer">Euclidean algorithm</a>. As you could make both numbers positive before using this algorithm, the sign of modulo would matter.)</p>
<p><strong>Additional material</strong>: </p>
<p>See <a href="http://en.wikipedia.org/wiki/Modulo_operation#Remainder_calculation_for_the_modulo_operation" rel="noreferrer">Wikipedia</a> for a long list of what modulo does in different languages.</p>
| 0 | 1,283 |
Can an Airflow task dynamically generate a DAG at runtime?
|
<p>I have an upload folder that gets irregular uploads. For each uploaded file, I want to spawn a DAG that is specific to that file.</p>
<p>My first thought was to do this with a FileSensor that monitors the upload folder and, conditional on presence of new files, triggers a task that creates the separate DAGs. Conceptually:</p>
<pre><code>Sensor_DAG (FileSensor -> CreateDAGTask)
|-> File1_DAG (Task1 -> Task2 -> ...)
|-> File2_DAG (Task1 -> Task2 -> ...)
</code></pre>
<p>In my initial implementation, <code>CreateDAGTask</code> was a <code>PythonOperator</code> that created DAG globals, by placing them in the global namespace (<a href="https://stackoverflow.com/a/44127627/2114580">see this SO answer</a>), like so:</p>
<pre class="lang-py prettyprint-override"><code>from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.contrib.sensors.file_sensor import FileSensor
from datetime import datetime, timedelta
from pathlib import Path
UPLOAD_LOCATION = "/opt/files/uploaded"
# Dynamic DAG generation task code, for the Sensor_DAG below
def generate_dags_for_files(location=UPLOAD_LOCATION, **kwargs):
dags = []
for filepath in Path(location).glob('*'):
dag_name = f"process_{filepath.name}"
dag = DAG(dag_name, schedule_interval="@once", default_args={
"depends_on_past": True,
"start_date": datetime(2020, 7, 15),
"retries": 1,
"retry_delay": timedelta(hours=12)
}, catchup=False)
dag_task = DummyOperator(dag=dag, task_id=f"start_{dag_name}")
dags.append(dag)
# Try to place the DAG into globals(), which doesn't work
globals()[dag_name] = dag
return dags
</code></pre>
<p>The main DAG then invokes this logic via a <code>PythonOperator</code>:</p>
<pre><code># File-sensing DAG
default_args = {
"depends_on_past" : False,
"start_date" : datetime(2020, 7, 16),
"retries" : 1,
"retry_delay" : timedelta(hours=5),
}
with DAG("Sensor_DAG", default_args=default_args,
schedule_interval= "50 * * * *", catchup=False, ) as sensor_dag:
start_task = DummyOperator(task_id="start")
stop_task = DummyOperator(task_id="stop")
sensor_task = FileSensor(task_id="my_file_sensor_task",
poke_interval=60,
filepath=UPLOAD_LOCATION)
process_creator_task = PythonOperator(
task_id="process_creator",
python_callable=generate_dags_for_files,
)
start_task >> sensor_task >> process_creator_task >> stop_task
</code></pre>
<p>But that doesn't work, because by the time <code>process_creator_task</code> runs, the globals have already been parsed by Airflow. New globals after parse time are irrelevant.</p>
<h2>Interim solution</h2>
<p>Per <a href="https://stackoverflow.com/questions/39133376/airflow-dynamic-dag-and-task-ids">Airflow dynamic DAG and task Ids</a>, <s>I can achieve what I'm trying to do by omitting the <code>FileSensor</code> task altogether and just letting Airflow generate the per-file task at each scheduler heartbeat, replacing the Sensor_DAG with just executing <code>generate_dags_for_files</code>:</s> Update: Nevermind -- while this does create a DAG in the dashboard, actual execution runs into the <a href="https://stackoverflow.com/questions/57472942/dag-seems-to-be-missing">"DAG seems to be missing"</a> issue:</p>
<pre class="lang-py prettyprint-override"><code>generate_dags_for_files()
</code></pre>
<p>This does mean that I can no longer regulate the frequency of folder polling with the <code>poke_interval</code> parameter of <code>FileSensor</code>; instead, Airflow will poll the folder every time it collects DAGs.</p>
<p>Is that the best pattern here?</p>
<h2>Other related StackOverflow threads</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/54992541/run-airflow-dag-for-each-file">Run Airflow DAG for each file</a> and <a href="https://stackoverflow.com/questions/60082546/airflow-proper-way-to-run-dag-for-each-file">Airflow: Proper way to run DAG for each file</a>: identical use case, but the accepted answer uses two static DAGs, presumably with different parameters.</li>
<li><a href="https://stackoverflow.com/questions/41517798/proper-way-to-create-dynamic-workflows-in-airflow">Proper way to create dynamic workflows in Airflow</a> - accepted answer dynamically creates tasks, not DAGs, via a complicated XCom setup.</li>
</ul>
| 0 | 1,824 |
Hibernate encodes wrong while persisting objects [UTF-8]
|
<p>I'm facing with UTF-8 encoding problem while persisting my model objects. In Turkish '<strong>ı</strong>' is a letter. Also there're some other Turkish characters that is included in UTF-8 encoding. While I persist my model objects, all '<strong>ı</strong>' characters are persisted as '<strong>?</strong>' to DB. I'm using <strong>MySQL 5.5 on Ubuntu Linux 64-bit OS</strong>. Also I've already set hibernate & c3p0 connection encoding property to UTF-8 too. When I debug, the data comes from client is true. </p>
<p>Here's my config and I'll be so happy if someone can help me. </p>
<p>Thanks in advance.</p>
<hr>
<p><strong>Spring & Hibernate Config</strong></p>
<pre><code> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="packagesToScan" value="com.tk.dms.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<!-- c3p0 properties -->
<prop key="hibernate.c3p0.min_size">2</prop>
<prop key="hibernate.c3p0.max_size">50</prop>
<prop key="hibernate.c3p0.maxPoolSize">50</prop>
<prop key="hibernate.c3p0.minPoolSize">2</prop>
<prop key="hibernate.c3p0.initialPoolSize">2</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
</props>
</property>
</bean>
</code></pre>
| 0 | 1,191 |
Warning while Running report: Found two components for namespace
|
<p>I have problem with report using <em>JasperReports</em>. I ran report on my program, it works, but there were error message just like this </p>
<pre><code>net.sf.jasperreports.engine.component.ComponentsEnvironment findComponentBundles
</code></pre>
<p><code>WARNING: Found two components for namespace http://jasperreports.sourceforge.net/jasperreports/components</code></p>
<p>When I searched any recommendation as same as mine, none is solution. Do you know how to fix this? </p>
<p>This' jrxml file</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="imp1_bln" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<parameter name="thn_proses" class="java.lang.String"/>
<parameter name="bln_proses" class="java.lang.Integer"/>
<queryString>
<![CDATA[SELECT DISTINCT
m_negara."id_negara" AS ID_Negara,
m_negara."nama_negara" AS Nama_Negara,
import_det."netto_hs" AS Curr_Net,
SUM(import_det.netto_hs)AS Cumm_Net,
import_det."cif_hs_us" AS Curr_CIF,
SUM(import_det.cif_hs_us)AS Cumm_CIF,
batch_hdr."bln_proses" AS batch_hdr_bln_proses,
batch_hdr."thn_proses" AS batch_hdr_thn_proses
FROM
m_hs10digit, m_negara, import_det, batch_hdr, import
WHERE
"dbo".import.negara_pemasok=dbo.m_negara.id_negara AND dbo.import_det.sk_import=dbo.import.sk_import
AND dbo.import.sk_batch=dbo.batch_hdr.sk_batch
AND dbo.batch_hdr.bln_proses between 01 and $P{bln_proses}
GROUP BY
m_negara."id_negara",
m_negara."nama_negara",
import_det."netto_hs",
import_det."cif_hs_us",
batch_hdr."bln_proses",
batch_hdr."thn_proses"]]>
</queryString>
<field name="ID_Negara" class="java.lang.String"/>
<field name="Nama_Negara" class="java.lang.String"/>
<field name="Curr_Net" class="java.lang.Double"/>
<field name="Cumm_Net" class="java.lang.Double"/>
<field name="Curr_CIF" class="java.lang.Double"/>
<field name="Cumm_CIF" class="java.lang.Double"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="93" splitType="Stretch">
<image>
<reportElement x="1" y="2" width="146" height="91"/>
<imageExpression class="java.lang.String"><![CDATA["coffee.jpg"]]></imageExpression>
</image>
<staticText>
<reportElement x="146" y="58" width="410" height="35"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font fontName="Times New Roman" size="12" isItalic="false" pdfFontName="Times-Roman"/>
</textElement>
<text><![CDATA[Tabel Impor Menurut Negara Asal (Import By Country of Origin)]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="79" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="41" height="19"/>
<textElement textAlignment="Left" verticalAlignment="Middle">
<font fontName="Times New Roman" size="12" pdfFontName="Times-Roman"/>
</textElement>
<text><![CDATA[Bulan :]]></text>
</staticText>
<staticText>
<reportElement x="64" y="0" width="39" height="19"/>
<textElement textAlignment="Left" verticalAlignment="Middle">
<font fontName="Times New Roman" size="12" pdfFontName="Times-Roman"/>
</textElement>
<text><![CDATA[Tahun:]]></text>
</staticText>
<staticText>
<reportElement x="0" y="40" width="56" height="39"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Kode Negara]]></text>
</staticText>
<staticText>
<reportElement x="146" y="59" width="90" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Bulan Ini]]></text>
</staticText>
<staticText>
<reportElement x="235" y="59" width="129" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Kumulatif]]></text>
</staticText>
<staticText>
<reportElement x="55" y="40" width="92" height="39"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Negara Asal]]></text>
</staticText>
<staticText>
<reportElement x="363" y="59" width="50" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Bulan Ini]]></text>
</staticText>
<staticText>
<reportElement x="412" y="59" width="144" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Kumulatif]]></text>
</staticText>
<staticText>
<reportElement x="146" y="40" width="218" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Berat Bersih (Netto)]]></text>
</staticText>
<staticText>
<reportElement x="363" y="40" width="193" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[CIF (US $)]]></text>
</staticText>
<textField>
<reportElement x="102" y="0" width="35" height="19"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.String"><![CDATA[$P{thn_proses}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="40" y="0" width="25" height="19"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.Integer"><![CDATA[$P{bln_proses}]]></textFieldExpression>
</textField>
</band>
</columnHeader>
<detail>
<band height="32" splitType="Stretch">
<textField>
<reportElement x="1" y="-1" width="55" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{ID_Negara}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="146" y="-1" width="90" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{Curr_Net}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="235" y="-1" width="129" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{Cumm_Net}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="55" y="-1" width="92" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{Nama_Negara}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="363" y="0" width="50" height="19"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{Curr_CIF}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="412" y="-1" width="144" height="20"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression class="java.lang.Double"><![CDATA[$F{Cumm_CIF}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
</code></pre>
| 0 | 5,233 |
How do you use AsParallel with the async and await keywords?
|
<p>I was looking at someone sample code for async and noticed a few issues with the way it was implemented. Whilst looking at the code I wondered if it would be more efficient to loop through a list using as parallel, rather than just looping through the list normally.</p>
<p>As far as I can tell there is very little difference in performance, both use up every processor, and both talk around the same amount of time to completed. </p>
<p>This is the first way of doing it</p>
<pre><code>var tasks= Client.GetClients().Select(async p => await p.Initialize());
</code></pre>
<p>And this is the second</p>
<pre><code>var tasks = Client.GetClients().AsParallel().Select(async p => await p.Initialize());
</code></pre>
<p>Am I correct in assuming there is no difference between the two?</p>
<p>The full program can be found below</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
RunCode1();
Console.WriteLine("Here");
Console.ReadLine();
RunCode2();
Console.WriteLine("Here");
Console.ReadLine();
}
private async static void RunCode1()
{
Stopwatch myStopWatch = new Stopwatch();
myStopWatch.Start();
var tasks= Client.GetClients().Select(async p => await p.Initialize());
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Time ellapsed(ms): " + myStopWatch.ElapsedMilliseconds);
myStopWatch.Stop();
}
private async static void RunCode2()
{
Stopwatch myStopWatch = new Stopwatch();
myStopWatch.Start();
var tasks = Client.GetClients().AsParallel().Select(async p => await p.Initialize());
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Time ellapsed(ms): " + myStopWatch.ElapsedMilliseconds);
myStopWatch.Stop();
}
}
class Client
{
public static IEnumerable<Client> GetClients()
{
for (int i = 0; i < 100; i++)
{
yield return new Client() { Id = Guid.NewGuid() };
}
}
public Guid Id { get; set; }
//This method has to be called before you use a client
//For the sample, I don't put it on the constructor
public async Task Initialize()
{
await Task.Factory.StartNew(() =>
{
Stopwatch timer = new Stopwatch();
timer.Start();
while(timer.ElapsedMilliseconds<1000)
{}
timer.Stop();
});
Console.WriteLine("Completed: " + Id);
}
}
}
</code></pre>
| 0 | 1,451 |
How do I display custom error pages in Asp.Net Mvc 3?
|
<p>I want all 401 errors to be be redirected to a custom error page. I have initially setup the following entry in my web.config. </p>
<pre><code><customErrors defaultRedirect="ErrorPage.aspx" mode="On">
<error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>
</code></pre>
<p>When using IIS Express I receive the stock IIS Express 401 error page.</p>
<p>In the event when I do not use IIS Express a blank page is returned. Using Google Chrome's Network tab to inspect the response, I see that while the page is blank a 401 status is returned in the headers</p>
<p>What I have tried thus far is using suggestions from <a href="https://stackoverflow.com/questions/2480006/what-is-the-difference-between-customerrors-and-httperrors">this SO answer</a> since I am using IIS Express but to no avail. I have tried using a combination <code><custom errors></code> and <code><httpErrors></code> with no luck - the standard error or blank page is still displayed. </p>
<p>The <code>httpErrors</code> section looks like this at the moment based on <a href="https://serverfault.com/questions/123729/iis-is-overriding-my-response-content-if-i-manually-set-the-response-statuscode/124074#124074">the link</a> from the <a href="https://stackoverflow.com/questions/2480006/what-is-the-difference-between-customerrors-and-httperrors">above SO question</a> ( I also found another very <a href="https://stackoverflow.com/questions/6512904/how-to-create-custom-404-error-pages-in-asp-net-mvc-3">promising answer</a> however no luck - blank response) </p>
<pre><code><system.webServer>
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
<remove statusCode="401" />
<error statusCode="401" path="/Views/Shared/AccessDenied.htm" />
</httpErrors>
<!--
<httpErrors errorMode="Custom"
existingResponse="PassThrough"
defaultResponseMode="ExecuteURL">
<remove statusCode="401" />
<error statusCode="401" path="~/Views/Shared/AccessDenied.htm"
responseMode="File" />
</httpErrors>
-->
</system.webServer>
</code></pre>
<p>I have even modified the <code>applicationhost.config</code> file and modified <code><httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath"></code> to <code><httpErrors lockAttributes="allowAbsolutePathsWhenDelegated"></code> based on information from <a href="http://www.iis.net/ConfigReference/system.webServer/httpErrors" rel="nofollow noreferrer">iis.net</a>. During the course of my endeavours I also managed to stumbled upon this error as described in <a href="https://stackoverflow.com/questions/6390886/500-19-error-with-iis7-5">another SO question</a>. </p>
<p>How do I display custom error pages in Asp.Net Mvc 3?</p>
<p><strong><em>Additional info</em></strong></p>
<p>The following controller actions have been decorated with the <code>Authorize</code> attribute for a specific user.</p>
<pre><code>[HttpGet]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit()
{
return GetSettings();
}
[HttpPost]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit(ConfigurationModel model, IList<Shift> shifts)
{
var temp = model;
model.ConfiguredShifts = shifts;
EsgConsole config = new EsgConsole();
config.UpdateConfiguration(model.ToDictionary());
return RedirectToAction("Index");
}
</code></pre>
| 0 | 1,214 |
DJANGO_SETTINGS_MODULE is undefined?
|
<pre><code>import os
from os.path import abspath, dirname
import sys
# Set up django
project_dir = abspath(dirname(dirname(__file__)))
sys.path.insert(0, project_dir)
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
</code></pre>
<p>I did that, and I still get </p>
<pre><code>Traceback (most recent call last):
File "main.py", line 4, in <module>
from django.middleware.csrf import get_token
File "/var/lib/system-webclient/system-webenv/lib/python2.6/site-packages/django/middleware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/var/lib/system-webclient/system-webenv/lib/python2.6/site-packages/django/utils/cache.py", line 24, in <module>
from django.core.cache import cache
File "/var/lib/system-webclient/system-webenv/lib/python2.6/site-packages/django/core/cache/__init__.py", line 68, in <module>
cache = get_cache(settings.CACHE_BACKEND)
File "/var/lib/system-webclient/system-webenv/lib/python2.6/site-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/var/lib/system-webclient/system-webenv/lib/python2.6/site-packages/django/conf/__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined
</code></pre>
<p>It was a small script calling some django functionality, but it is telling me ENVIRONMENT VARIABLE issue. </p>
<p>What can I do? I spent my whole afternoon reading many posts....</p>
<p>Thanks for helping! This was my 1st time hitting it.</p>
<hr>
<p>The traceback. It doesn't give raise our manual exception. It is giving the same exception as above.</p>
<p><em>webclient/main.py</em></p>
<pre><code>import os
from os.path import abspath, dirname
import sys
path = '/var/lib/graphyte-webclient/webclient'
if path not in sys.path:
sys.path.append(path)
sys.path.insert(0, path)
os.environ["DJANGO_SETTINGS_MODULE"] = "webclient.settings"
raise Exception("DJANGO_SETTINGS_MODULE = " + str(os.environ["DJANGO_SETTINGS_MODULE"]))
.... other things
</code></pre>
<p>In <em>manage.py shell</em></p>
<pre><code>>>> from webclient.settings import settings
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: cannot import name settings
>>> import webclient
>>> webclient
<module 'webclient' from '/var/lib/system-webclient/webclient/../webclient/__init__.pyc'>
>>> import webclient.settings
>>> webclient.settings
<module 'webclient.settings' from '/var/lib/system-webclient/webclient/../webclient/settings.pyc'>
</code></pre>
<p><strong>webclient/deploy/pinax.fcgi</strong></p>
<pre><code>import os
import sys
from os.path import abspath, dirname, join
from site import addsitedir
sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
from django.conf import settings
os.environ["DJANGO_SETTINGS_MODULE"] = "webclient.settings"
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
</code></pre>
<p><strong>webclient/deploy/pinax.wcgi</strong></p>
<pre><code>import os
import sys
from os.path import abspath, dirname, join
from site import addsitedir
sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
from django.conf import settings
os.environ["DJANGO_SETTINGS_MODULE"] = "webclient.settings"
#os.environ["SCRIPT_NAME"] = "/natrium"
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
</code></pre>
<p><a href="http://i.imgur.com/ROj8h.jpg" rel="nofollow">filesystem image</a></p>
| 0 | 1,435 |
jQuery populate form from json
|
<p>I'm clearly missing something about jquery... I'm trying to populate a form that is inside a jQueryUI dialog box.
I'm getting the JSON data just fine, but it escapes me how I reference the data and set the value of the form fields...</p>
<p>You will see THREE attempts below - the last one is the one almost everyone says to use - but the form remains BLANK...
What am I missing?????</p>
<pre><code>$( '#companies' ).on( 'click', '.uLink' , function( event ) {
// set ID
var xid = $( this ).data( 'identity' );
// get record
$.ajax({
type: 'POST',
url: 'm/company_edit.php',
dataType: 'json',
data: { id: xid },
success: function ( data ) {
// display dialog
$( '#company-form-container' ).dialog( 'open' );
/* ATTEMPT #1 - with a variant on 'name' - form remains blank
// populate form
$( '#companyid' ).val( value.id );
$( '#name' ).val( 'test' + value.name );
$( '#address1' ).val( value.address1 );
$( '#address2' ).val( value.address2 );
$( '#city' ).val( value.city );
$( '#state' ).val( value.state );
$( '#postalcode' ).val( value.postalcode );
$( '#phone' ).val( value.phone );
$( '#contact' ).val( value.contat );
$( '#email' ).val( value.email );
*/
/* ATTEMPT #2 - supposed to make some accommodation for field type...
Make assumption that fields are named same as JSON fields, and the you only
want to use the data value in that one spot...*/
/*
var frm = '#company-form';
$.each(data, function( key, value ){
var $ctrl = $( '[name='+key+']', frm );
switch( $ctrl.attr( "type" ) ) {
case "text" :
case "hidden":
case "textarea":
$ctrl.val(value);
break;
case "radio" : case "checkbox":
$ctrl.each(function(){ if($(this).attr('value') == value) { $(this).attr("checked",value); } });
break;
}
});
*/
// attempt 3 - still no go
$.each( data, function( key, value ) {
$( '#' + key ).val( value );
});
</code></pre>
<p>/*
// attempt suggested below - no changes...
var c = jQuery.parseJSON( data );</p>
<pre><code> // populate form
$( '#companyid' ).val( c.id );
$( '#name' ).val( c.name );
</code></pre>
<p>*/</p>
<pre><code> },
error: function () {
// there's an error
$( '#message' ).html( '<p>There was a problem on the server... </p>' );
$( '#message' ).removeClass( 'hidden' ).addClass( 'message' );
}
});
return false;
});
</code></pre>
<p>Sample of JSON data</p>
<pre><code>[{"id":"3", "name":"Sub Customer B", "address1":"232 road", "address2":"", "city":"Galatan ", "state":"TN", "phone":"", "email":""}]
</code></pre>
<p>and this is the HTML Form</p>
<pre><code><!-- the form -->
<div id="company-form-container" title="Create New Company">
<p class="validateTips">* fields are required.</p>
<form id="company-form" >
<fieldset>
<input type="hidden" name="customer_id" id="customer_id" value="" />
<label for="name">name<sup>*</sup> <span class="fieldhint"></span></label> <br/>
<input type="text" name="name" id="name"
size="50" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>
<label for="address1">address1 <span class="fieldhint"></span></label> <br/>
<input type="text" name="address1" id="address1"
size="20" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>
<label for="address2">address2 <span class="fieldhint"></span></label> <br/>
<input type="text" name="address2" id="address2"
size="10" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>
<label for="city">city <span class="fieldhint"></span></label> <br/>
<input type="text" name="city" id="city"
size="20" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>
<label for="state">state <span class="fieldhint"></span></label> <br/>
<input type="text" name="state" id="state"
size="5" maxlength="3" class="text ui-widget-content ui-corner-all" /><br/>
<label for="postalcode">postal code <span class="fieldhint"></span></label> <br/>
<input type="text" name="postalcode" id="postalcode"
size="20" maxlength="15" class="text ui-widget-content ui-corner-all" /><br/>
<label for="phone">phone <span class="fieldhint"></span></label> <br/>
<input type="text" name="phone" id="phone"
size="20" maxlength="20" class="text ui-widget-content ui-corner-all" /><br/>
<label for="contact">contact <span class="fieldhint"></span></label> <br/>
<input type="text" name="contact" id="contact"
size="20" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>
<label for="email">email <span class="fieldhint"></span></label> <br/>
<input type="text" name="email" id="email"
size="20" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>
</fieldset>
</form>
</code></pre>
<p></p>
| 0 | 2,954 |
How to query XML column in Postgresql?
|
<p>I've created a table in Postgres that contains an XML column:</p>
<pre><code> id | integer
date_created | timestamp with time zone
hash | character varying(10)
original | xml
report_name | text
</code></pre>
<p>I've inserted an XML string:</p>
<pre><code>id | date_created | hash | original | report_name
----+-------------------------------+------------+--------------------------------------------------------------------------+------------------------------------------
9 | 2017-09-26 17:37:16.823251+02 | aaaaaaaaaa | <RequestReportResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/">+| _GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_
| | | <RequestReportResult> +|
| | | <ReportRequestInfo> +|
| | | <ReportType>_GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_</ReportType> +|
| | | <ReportProcessingStatus>_SUBMITTED_</ReportProcessingStatus> +|
| | | <EndDate>2017-09-26T13:31:02+00:00</EndDate> +|
| | | <Scheduled>false</Scheduled> +|
| | | <ReportRequestId>50064017435</ReportRequestId> +|
| | | <SubmittedDate>2017-09-26T13:31:02+00:00</SubmittedDate> +|
| | | <StartDate>2017-09-26T13:31:02+00:00</StartDate> +|
| | | </ReportRequestInfo> +|
| | | </RequestReportResult> +|
| | | <ResponseMetadata> +|
| | | <RequestId>e092cdbe-2978-4064-a5f6-129b88322b02</RequestId> +|
| | | </ResponseMetadata> +|
| | | </RequestReportResponse> +|
| | | |
</code></pre>
<p>Using the same XML in an <a href="https://www.freeformatter.com/xpath-tester.html#ad-output" rel="noreferrer">online</a> XPath tester I am able to retrieve the value in <code>ReportRequestId</code> but when querying Postgresql I get no values back:</p>
<pre><code>select xpath('/RequestReportResponse/RequestReportResult/ReportRequestInfo/ReportRequestId', original) from amazon_output where hash='aaaaaaaaaa';
</code></pre>
<p>What am I missing with the XML data type?</p>
| 0 | 2,213 |
Magento remove zoom from product image
|
<p>Im not really familiar with Magento and i need to remove zoom effect from product image.
This is the code from /catalog/product/view/media.phtml inside template directory.</p>
<p>I tried to play around with if-else statement, but it seems im missing something because i am getting errors.</p>
<p>Is anybody more familiar with this to take a look?
Thanks a bunch!</p>
<pre><code> <div class="product-image">
<?php if ($scrollStatus): ?>
<div id="jp-container" class="jp-container" style="height:500px;">
<a href="javascript:void(0);"><?php
$_img = '<img src="'.$helpImg->getImg($_product, 'image', $imgSize, null).'" alt="'.$this->escapeHtml($this->getImageLabel()).'" title="'.$this->escapeHtml($this->getImageLabel()).'" />';
echo $_img;
?></a>
<?php foreach ($this->getGalleryImages() as $_image): ?>
<a href="javascript:void(0);" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"><img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile()); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /></a>
<?php endforeach; ?>
</div>
<script type="text/javascript">
jQuery(window).load(function(){
function jspaneStart(){
setTimeout(function(){
maxHeight = 0;
jQuery('#jp-container a').each(function(){
if(jQuery(this).height() > maxHeight){
maxHeight = jQuery(this).height();
}
});
maxHeight = maxHeight+(maxHeight/100)*<?php echo $scrollimagesHeight; ?>;
jQuery('#jp-container').css('height', maxHeight);
jQuery('#jp-container').jScrollPane();
}, 500);
}
jspaneStart();
jQuery(window).resize(function(){
jspaneStart();
});
});
</script>
<?php else: ?>
<a id='zoom' class="cloud-zoom" data-zoom="showTitle: false, adjustX: -5, adjustY:-5, tint: '#fff', tintOpacity:0.6, position:'inside'" href="<?php echo $this->helper('catalog/image')->init($_product, 'image'); ?>"><?php
$_img = '<img id="image" src="'.$helpImg->getImg($_product, 'image', $imgSize, null).'" alt="'.$this->escapeHtml($this->getImageLabel()).'" title="'.$this->escapeHtml($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?></a>
<?php /* Label New */ echo MAGE::helper('ThemeOptionsMinimalism')->getProductLabels($_product); ?>
<?php if (count($this->getGalleryImages()) > 0): ?>
<div class="more-views-container">
<div class="more-views<?php if ($productpage_moreviews == 'moreviews_slider' && count($this->getGalleryImages()) > 3){echo ' slider-on';} ?>">
<h2><?php echo $this->__('More Views') ?></h2>
<?php if ($productpage_moreviews == 'moreviews_slider' && count($this->getGalleryImages()) > 3): ?>
<div id="more-views-slider" class="es-carousel-wrapper">
<ul class="carousel-ul">
<?php foreach ($this->getGalleryImages() as $_image): ?>
<li>
<a class='cloud-zoom-gallery' data-zoom="useZoom: 'zoom', smallImage: '<?php echo $helpImg->getImg($_product, 'thumbnail', $imgSize, null, $_image->getFile()); ?>' " href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile()); ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"><img <?php echo $helpImg->getImgSources($_product, 'thumbnail', 200, null, $_image->getFile()); ?> alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class = 'next'><i class="fa fa-angle-right"></i></div>
<div class = 'prev unselectable'><i class="fa fa-angle-left"></i></div>
<?php else: ?>
<ul class="no-slider">
<?php foreach ($this->getGalleryImages() as $_image): ?>
<li>
<a class='cloud-zoom-gallery' data-zoom="useZoom: 'zoom', smallImage: '<?php echo $helpImg->getImg($_product, 'thumbnail', $imgSize, null, $_image->getFile()); ?>' " href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile()); ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"><img <?php echo $helpImg->getImgSources($_product, 'thumbnail', 200, null, $_image->getFile()); ?> alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if ($this->displayProductStockStatus()): ?>
<?php if ($_product->isAvailable()): ?>
<p class="availability in-stock"><i class="fa fa-check"></i><?php echo $this->__('In stock') ?></p>
<?php else: ?>
<p class="availability out-of-stock"><i class="fa fa-times"></i><?php echo $this->__('Out of stock') ?></p>
<?php endif; ?>
<?php endif; ?>
</div>
</code></pre>
| 0 | 2,965 |
how to make webpack typescript react webpack-dev-server configuration for auto building and reloading page
|
<p>My intention is to have such directory structure:</p>
<pre><code>- /my-project/
-- /src/ (here are all .tsx files located)
-- /dist/
- index.html
- /build/
-bundle.js
-- /node_modules/
-- package.json
-- tsconfig.json
-- webpack.config.js
</code></pre>
<p>So, I want to have my index.html which is made manually in the /dist subdirectory and inside of it I want to have /build subdir where the app.js made by webpack goes.</p>
<p>And I want when I'm saving some .tsx file located in my /src dir webpack automatically rebuild app.js and webpack-dev-server automatically reflect the changes.</p>
<p>My <code>package.json</code> looks like this:</p>
<pre><code>{
"name": "my-project",
"version": "1.0.0",
"description": "My first React App",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --content-base ./dist --hot --inline --colors --port 3000 --open",
"build": "webpack --config webpack.config.js --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "AndreyKo",
"license": "ISC",
"devDependencies": {
"@types/react": "^0.14.54",
"@types/react-dom": "^0.14.19",
"jquery": "^3.1.1",
"source-map-loader": "^0.1.5",
"ts-loader": "^1.3.0",
"typescript": "^2.1.4",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"react": "^15.4.1",
"react-dom": "^15.4.1"
}
}
</code></pre>
<p>My <code>webpack.config.js</code>:</p>
<pre><code>module.exports = {
entry: "./src/index.tsx",
output: {
filename: "app.js",
publicPath: "/dist/",
path: "./dist/build/"
},
dev_tool: "source-map",
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{test: /\.tsx?$/, loader: 'ts-loader'}
],
preloaders: [
{test: /\.js$/, loader: 'source-map-loader'}
]
}
}
</code></pre>
<p>My <code>index.html</code>:</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<div id="app-container"></div>
</body>
<script src="./build/app.js"></script>
</html>
</code></pre>
<p>And my <code>index.tsx</code> file looks like this:</p>
<pre><code>import * as jQuery from 'jquery';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
function appOutput() {
ReactDOM.render(<div>Hello, we are talking from React!</div>, document.getElementById("app-container"));
}
appOutput();
</code></pre>
<p>I've done commands to the terminal: </p>
<pre><code>npm run build
npm run start
</code></pre>
<p>So the app.js was created and webpack-dev-server started working and opened page in the browser. Everything goes fine by far. But when I change the text in my index.tsx and save this file nothing changes, I tried to refresh the browser page, the text remains the same and app.js is not rebuilt.
To make the text change I have to rebuild app.js with webpack by hand again from the terminal by issuing "npm run build". </p>
<p>How to improve my workflow to make the changes in my /src folder be reflected automatically in my dist/build/app.js file without having to manually rebuild it?</p>
| 0 | 1,360 |
dataTable sortBy function does not work(primefaces)
|
<p>I have a problem with the primefaces dataTable component. I dont know why it does not short the data in the table when i click on it. </p>
<pre><code><p:dataTable var="garbage" value="#{resultsController.allGarbage}" dynamic="true" paginator="true" paginatorPosition="bottom" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column sortBy="#{garbage[0].filename}">
<f:facet name="header">
<h:outputText value="Filename" />
</f:facet>
<h:outputText value="#{garbage[0]}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{garbage[1]}" />
</p:column>
<p:column sortBy="#{garbage[2].uploadDate}">
<f:facet name="header">
<h:outputText value="Upload date" />
</f:facet>
<h:outputText value="#{garbage[2]}" />
</p:column>
</p:dataTable>
</code></pre>
<p>This is the managed bean</p>
<pre><code>@ManagedBean
@RequestScoped
public class ResultsController {
@EJB
private ISearchEJB searchEJB;
private Garbage[] garbage;
public List<Garbage[]> getAllGarbage() {
return searchEJB.findAllGarbage();
}
public Garbage[] getGarbage() {
System.out.println("VALUES!!!!!!!!" + garbage[0].getFilename());
return garbage;
}
public void setGarbage(Garbage[] garbage) {
this.garbage = garbage;
}
</code></pre>
<p>}</p>
<p>This is the EJB that allows data access</p>
<pre><code>@Stateless(name = "ejbs/SearchEJB")
</code></pre>
<p>public class SearchEJB implements ISearchEJB {</p>
<pre><code>@PersistenceContext
private EntityManager em;
public List<Garbage[]> findAllGarbage() {
Query query = em.createNamedQuery("findAllGarbage");
return query.getResultList();
}
</code></pre>
<p>}</p>
<p>And this is the entity(Data representation)</p>
<pre><code>@NamedQuery(name = "findAllGarbage", query = "SELECT g.filename, g.description, g.uploadDate FROM Garbage g;")
@Entity
public class Garbage {
@Id
@GeneratedValue
@Column(nullable = false)
private Long id;
@Column(nullable = false)
private String filename;
@Column(nullable = false)
private String fileType;
@Column(nullable = false)
private String uploadDate;
@Column(nullable = false)
private String destroyDate;
@Lob
@Column(nullable = false)
private byte[] file;
@Column(nullable = false)
private String description;
...//Getters and Setters
</code></pre>
<p>As shown in the image there is no changes when the sort buttons are clicked:
<img src="https://i.stack.imgur.com/dDsir.png" alt="enter image description here"></p>
<p>This is what the console says:</p>
<blockquote>
<p>SEVERE: Error in sorting</p>
</blockquote>
<p><b>UPDATE</b></p>
<pre><code>public List<Garbage> findAllGarbage() {
Query query = em.createNamedQuery("findAllGarbage");
List<Garbage> gList = new ArrayList();
for (Object o: query.getResultList()) {
Garbage tmpG = new Garbage();
tmpG.setFilename(((Garbage) o).getFilename());
tmpG.setUploadDate(((Garbage) o).getUploadDate());
tmpG.setDescription(((Garbage) o).getDescription());
gList.add(tmpG);
}
return gList;
}
</code></pre>
<p>The modified managed bean</p>
<pre><code>@ManagedBean
@RequestScoped
public class ResultsController {
@EJB
private ISearchEJB searchEJB;
private Garbage garbage;
public List<Garbage> getAllGarbage() {
return searchEJB.findAllGarbage();
}
public Garbage getGarbage() {
return garbage;
}
public void setGarbage(Garbage garbage) {
this.garbage = garbage;
}
</code></pre>
<p>}</p>
<p>The modified JSF</p>
<pre><code><p:dataTable var="garbage" value="#{resultsController.allGarbage}" dynamic="true" paginator="true" paginatorPosition="bottom" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column sortBy="#{garbage.filename}" parser="string">
<f:facet name="header">
<h:outputText value="Filename" />
</f:facet>
<h:outputText value="#{garbage.filename}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Description" />
</f:facet>
<h:outputText value="#{garbage.description}" />
</p:column>
<p:column sortBy="#{garbage.uploadDate}" parser="string">
<f:facet name="header">
<h:outputText value="Upload date" />
</f:facet>
<h:outputText value="#{garbage.uploadDate}" />
</p:column>
</p:dataTable>
</code></pre>
| 0 | 2,456 |
How to test characters in a string [Assembly]
|
<p>I'm writing a program to search for vowels inside a string, but I'm having trouble testing the individual characters inside the string, I have the basic concept down and I've done this before using C++ and Python, but I don't know how to code it in Assembly.</p>
<p>I'm going to use a switch to add up and test the individual characters, and I know that I need to use a loop to cycle through all the characters, but I'm stuck on actually testing individual characters. (this isn't what I have coded per say but an illustrative example)</p>
<pre><code>max_length dd 40
user_input resd max_length
str_len dw $ - user_input
GetStr user_input ; "I am a boy"
mov ecx, str_len
</code></pre>
<p>And this is where I get stuck. How would you test the individual characters of <code>user_input</code> ? </p>
<p>In C++ you would have something like <code>if(user_input[0] = 'Y')</code>, but how do I translate that type of instruction to assembly (user_input[0])</p>
<p>I understand that it does not work this way in assembly but hopefully this will clear some things up.</p>
<pre><code>str_len DW $ - user_input
max_length EQU 40
jump_table:
DD case_0
DD case_1
DD case_2
DD case_3
DD case_4
DD case_5
.UDATA
user_input resd max_length
_main:
push ebp
mov ebp, esp
switch:
xor eax,eax
xor ebx,ebx
PutStr prompt
GetStr user_input
mov ecx, [str_len]
mov esi, user_input
read:
mov al, byte [esi+ebx]
or al, 20h
cmp al, 'a'
je [jump_table]
cmp al, 'e'
je [jump_table+4]
cmp al, 'i'
je [jump_table+8]
cmp al, 'o'
je [jump_table+12]
cmp al, 'u'
je [jump_table+16]
cmp ecx, 0
je [jump_table+20]
inc ebx
jmp read
</code></pre>
<p>this is where I am now, as I commented further down I'm getting an error linked to <code>str_len</code></p>
<p>This is all working, I just need to clear the buffer, Thanks!
str_len DD 40
max_length EQU 40</p>
<pre><code>jump_table:
DD case_0
DD case_1
DD case_2
DD case_3
DD case_4
DD case_5
.UDATA
user_input resb max_length
.CODE
.STARTUP
switch:
xor eax,eax
xor ebx,ebx
xor esi, esi
PutStr prompt
GetStr user_input
mov ecx, [str_len]
mov esi, user_input
read:
mov al, byte [esi+ebx]
or al, 20h
;PutCh al
cmp al, 'a'
je vowel_A
cmp al, 'e'
je vowel_E
cmp al, 'i'
je vowel_I
cmp al, 'o'
je vowel_O
cmp al, 'u'
je vowel_U
cmp ecx, 0
je str_end
inc ebx
dec ecx
jmp read
</code></pre>
| 0 | 1,520 |
Why is my SQL Server query failing?
|
<pre><code> connect();
$arr = mssql_fetch_assoc(mssql_query("SELECT Applications.ProductName,
Applications.ProductVersion, Applications.ProductSize,
Applications.Description, Applications.ProductKey, Applications.ProductKeyID,
Applications.AutomatedInstaller, Applications.AutomatedInstallerName,
Applications.ISO, Applications.ISOName, Applications.Internet,
Applications.InternetURL, Applications.DatePublished, Applications.LicenseID,
Applications.InstallationGuide, Vendors.VendorName
FROM Applications
INNER JOIN Vendors ON Applications.VendorID = Vendors.VendorID
WHERE ApplicationID = ".$ApplicationID));
$query1 = mssql_query("SELECT Issues.AppID, Issues.KnownIssues
FROM Issues
WHERE Issues.AppID=".$ApplicationID);
$issues = mssql_fetch_assoc($query1);
$query2 = mssql_query("SELECT ApplicationInfo.AppID,
ApplicationInfo.Support_Status, ApplicationInfo.UD_Training,
ApplicationInfo.AtomicTraining, ApplicationInfo.VendorURL
FROM ApplicationInfo
WHERE ApplicationInfo.AppID = ".$ApplicationID);
$row = mssql_fetch_assoc($query2);
function connect(){
$connect = mssql_connect(DBSERVER, DBO, DBPW) or
die("Unable to connect to server");
$selected = mssql_select_db(DBNAME, $connect) or
die("Unable to connect to database");
return $connect;
}
</code></pre>
<p>Above is the code. The first query/fetch_assoc works perfectly fine, however the next 2 queries fail and I cannot figure out why. Here is the error statement that shows up from php:</p>
<blockquote>
<p>Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'Issues'. (severity 16) in /srv/www/htdocs/agreement.php on line 47</p>
<p>Warning: mssql_query() [function.mssql-query]: General SQL Server error: Check messages from the SQL Server (severity 16) in /srv/www/htdocs/agreement.php on line 47
Warning: mssql_query() [function.mssql-query]: Query failed in /srv/www/htdocs/agreement.php on line 47</p>
<p>Warning: mssql_fetch_assoc(): supplied argument is not a valid MS SQL-result resource in /srv/www/htdocs/agreement.php on line 48</p>
<p>Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'software.software_dbo.ApplicationInfo'. (severity 16) in /srv/www/htdocs/agreement.php on line 51</p>
<p>Warning: mssql_query() [function.mssql-query]: General SQL Server error: Check messages from the SQL Server (severity 16) in /srv/www/htdocs/agreement.php on line 51</p>
<p>Warning: mssql_query() [function.mssql-query]: Query failed in /srv/www/htdocs/agreement.php on line 51</p>
<p>Warning: mssql_fetch_assoc(): supplied argument is not a valid MS SQL-result resource in /srv/www/htdocs/agreement.php on line 52</p>
</blockquote>
<p>The error clearly centers around the fact that the query is not executing. In my database I have a table called Issues and a table called ApplicationInfo so I am unsure why it is telling me that they are invalid objects.</p>
| 0 | 1,025 |
How to use docker volume to deploy war / jar in Tomcat
|
<p>Is it possible to deploy some java war or jar file in Tomcat? I looking for a lot of tutorials and the only solution I found is copy project war file into <code>/usr/local/tomcat/webapps/</code>.</p>
<p>I actually used that solution but I would like to improve my dockerisation. My primary goal is when I run my 2 images (application in tomcat and db image) with docker-compose I want to use my local war file of target folder in tomcat, and, when I build war again after the code changed, that change will be reflected without stopping containers, removing, and rebuilding. Can you help to do that? My attempts failed. I want it just for development purpose.</p>
<p>Here is my docker-compose.yml</p>
<pre><code>version: '3'
services:
tomcat-service:
build:
context: ../
dockerfile: docker/app/Dockerfile
volumes:
- D:\myproj\target\app.war:/usr/local/tomcat/webapps/ROOT.war
ports:
- "8080:8080"
depends_on:
- "db-service"
db-service:
build: ./database
ports:
- "5433:5432"
</code></pre>
<p>and Dockerfile for that tomcat</p>
<pre><code>FROM tomcat:8.0-jre8
RUN rm -rvf /usr/local/tomcat/webapps/ROOT
COPY ./docker/app/context.xml /usr/local/tomcat/conf/
# with following copy command it works, but when I rebuild war file, I need stop docker-compose and build and run it again .. I want use volume instead of copy war
#COPY ./pnp-web/target/pnp.war /usr/local/tomcat/webapps/ROOT.war
EXPOSE 8080
CMD ["catalina.sh", "run"]
</code></pre>
<p>With configuration above applicaton starts, but when I run <code>mvn clean package</code> application is not loaded anymore</p>
<p>EDIT</p>
<p>I checked log of tomcat container and I found this error:</p>
<pre><code>tomcat-cont | 10-Jul-2018 08:20:36.754 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /usr/local/tomcat/webapps/ROOT.war
tomcat-cont | 10-Jul-2018 08:20:36.858 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
tomcat-cont | org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
tomcat-cont | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
tomcat-cont | at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:755)
tomcat-cont | at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:731)
tomcat-cont | at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
tomcat-cont | at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:973)
tomcat-cont | at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1850)
tomcat-cont | at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
tomcat-cont | at java.util.concurrent.FutureTask.run(FutureTask.java:266)
tomcat-cont | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
tomcat-cont | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
tomcat-cont | at java.lang.Thread.run(Thread.java:748)
tomcat-cont | Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@51f50cb1]
tomcat-cont | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
tomcat-cont | at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:5016)
tomcat-cont | at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5149)
tomcat-cont | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
tomcat-cont | ... 10 more
tomcat-cont | Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@20e48a4a]
tomcat-cont | at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
tomcat-cont | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:135)
tomcat-cont | at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:722)
tomcat-cont | at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
tomcat-cont | ... 13 more
tomcat-cont | Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: error in opening zip file
tomcat-cont | at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:142)
tomcat-cont | at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
tomcat-cont | ... 16 more
tomcat-cont | Caused by: java.util.zip.ZipException: error in opening zip file
tomcat-cont | at java.util.zip.ZipFile.open(Native Method)
tomcat-cont | at java.util.zip.ZipFile.<init>(ZipFile.java:225)
tomcat-cont | at java.util.zip.ZipFile.<init>(ZipFile.java:155)
tomcat-cont | at java.util.jar.JarFile.<init>(JarFile.java:166)
tomcat-cont | at java.util.jar.JarFile.<init>(JarFile.java:130)
tomcat-cont | at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:170)
tomcat-cont | at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:155)
tomcat-cont | at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:139)
tomcat-cont | ... 17 more
tomcat-cont |
tomcat-cont | 10-Jul-2018 08:20:36.859 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /usr/local/tomcat/webapps/ROOT.war
tomcat-cont | java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].Stand
ardContext[]]
tomcat-cont | at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:759)
tomcat-cont | at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:731)
tomcat-cont | at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
tomcat-cont | at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:973)
tomcat-cont | at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1850)
tomcat-cont | at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
tomcat-cont | at java.util.concurrent.FutureTask.run(FutureTask.java:266)
tomcat-cont | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
tomcat-cont | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
tomcat-cont | at java.lang.Thread.run(Thread.java:748)
tomcat-cont |
tomcat-cont | 10-Jul-2018 08:20:36.860 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /usr/local/tomcat/webapps/ROOT.war has finish
ed in 105 ms
</code></pre>
<p>this error happened when I wanted to try restart container when new war is builded.</p>
| 0 | 2,936 |
CloudFormation: Create resources if they do not exist, but do not delete them
|
<p>I have the following CloudFormation template. (It is based off default the template created for running C# Web API in AWS Lambda, but that may not be relevant.)</p>
<p>It creates an AWS Lambda function. The template also creates an IAM Role and a DynamoDB table if the names of existing resources are not supplied as arguments.</p>
<p>That part works. If no names are supplied for the role and table, they are created.</p>
<p><strong>The problem exists when I run the template a second time to perform updates:</strong> at this point, my role and table exist, so I provide the names as arguments. However, when CloudFormation runs the second time, the resources it created the first time (the role and table) are deleted.</p>
<p><strong>Is there some way to set up the template such that it will create new resources if they don't exist, but not delete them if they are already present?</strong></p>
<p>I haven't done a lot with CloudFormation, but I did go through the documentation. The closest I found was <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html" rel="noreferrer">setting a stack policy</a>, but it doesn't seem to be part of the template. It looks like I would have to do this in the management console after the fact.</p>
<pre><code>{
"AWSTemplateFormatVersion" : "2010-09-09",
"Transform" : "AWS::Serverless-2016-10-31",
"Description" : "...",
"Parameters" : {
"ShouldCreateTable" : {
"Type" : "String",
"AllowedValues" : ["true", "false"],
"Description" : "If true then the underlying DynamoDB table will be created with the CloudFormation stack."
},
"TableName" : {
"Type" : "String",
"Description" : "Name of DynamoDB table to be used for underlying data store. If left blank a new table will be created.",
"MinLength" : "0"
},
"ShouldCreateRole" : {
"Type" : "String",
"AllowedValues" : ["true", "false"],
"Description" : "If true then the role for the Lambda function will be created with the CloudFormation stack."
},
"RoleARN" : {
"Type" : "String",
"Description" : "ARN of the IAM Role used to run the Lambda function. If left blank a new role will be created.",
"MinLength" : "0"
}
},
"Conditions" : {
"CreateDynamoTable" : {"Fn::Equals" : [{"Ref" : "ShouldCreateTable"}, "true"]},
"TableNameGenerated" : {"Fn::Equals" : [{"Ref" : "TableName"}, ""]},
"CreateRole":{"Fn::Equals" : [{"Ref" : "ShouldCreateRole"}, "true"]},
"RoleGenerated" : {"Fn::Equals" : [{"Ref" : "RoleARN"}, ""]}
},
"Resources" : {
"Get" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
...
"Role": {"Fn::If" : ["CreateRole", {"Fn::GetAtt":["LambdaRole", "Arn"]}, {"Ref":"RoleARN"}]},
"Environment" : {
"Variables" : {
"AppDynamoTable" : { "Fn::If" : ["CreateDynamoTable", {"Ref":"DynamoTable"}, { "Ref" : "TableName" } ] }
}
},
...
}
},
"LambdaRole":{
"Type":"AWS::IAM::Role",
"Condition":"CreateRole",
"Properties":{
"ManagedPolicyArns":["arn:aws:iam::aws:policy/AWSLambdaFullAccess"],
"AssumeRolePolicyDocument": {
"Version" : "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Principal": {
"Service": [ "lambda.amazonaws.com" ]
},
"Action": [ "sts:AssumeRole" ]
} ]
},
"Policies": [ {
"PolicyName": "root",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": [
"*"
]
}
]
}
}
]
}
},
"DynamoTable" : {
"Type" : "AWS::DynamoDB::Table",
"Condition" : "CreateDynamoTable",
"Properties" : {
"TableName" : { "Fn::If" : ["TableNameGenerated", {"Ref" : "AWS::NoValue" }, { "Ref" : "TableName" } ] },
"AttributeDefinitions": [
{ "AttributeName" : "id", "AttributeType" : "S" }
],
"KeySchema" : [
{ "AttributeName" : "id", "KeyType" : "HASH"}
],
"ProvisionedThroughput" : { "ReadCapacityUnits" : "5", "WriteCapacityUnits" : "5" }
}
}
},
"Outputs" : {
"UnderlyingDynamoTable" : {
"Value" : { "Fn::If" : ["CreateDynamoTable", {"Ref":"DynamoTable"}, { "Ref" : "TableName" } ] }
},
"LambdaRole" : {
"Value" : {"Fn::If" : ["CreateRole", {"Fn::GetAtt":["LambdaRole", "Arn"]}, {"Ref":"RoleARN"} ] }
}
}
}
</code></pre>
<p>I could just remove the creation step and create the resource manually before the API Gateway, but it seems like what I am trying to do should be possible.</p>
| 0 | 2,839 |
Ext js component query
|
<p>I am developing web site in extjs4 + yii framework. I am using a border layout as a viewport.
Inside it I am using a accordian layout and displays home page. <strong>In Home page there is a login window whcih i want to hide after ligin completion</strong>. how can i remove this window.
here is my code:--</p>
<pre><code>1)Viewport.js:-
Ext.define('AM.view.Viewport', {
extend: 'Ext.container.Viewport',
layout: 'border',
id:'vp',
border: 5,
style: {
borderColor: 'red',
borderStyle: 'solid'
},
requires: [
'AM.view.header.Header',
'AM.view.login.Login',
'AM.view.wordOfDay.WordOfDay',
'AM.view.weather.Weather',
'AM.view.poll.Poll',
'AM.view.qod.QOD',
'AM.view.history.History',
'AM.view.qod.LastQuestion'
],
items: [
{
region:'north',
xtype: 'headerHeader',
margins:5,
height:70,
//html:'<h1>Welcome</h1>',
},
{
/* title:'West',
region:'west',
margins:'0 5 0 5',
flex:.3,
collapsible:true,
split:true,
titleCollapse:true,
*/
// title:'Main menu',
region:'west',
margins:'0 5 5 5',
flex:.3,
//collapsible:true,
//titleCollapse:true,
layout:'accordion',
layoutConfig:
{
animate:false,
multi:true
},
items:[
{
title:'wordOfDay',
xtype:'wod'
},
{
title:'weather Information',
xtype:'weather'
},
{
title:'poll of the day',
xtype:'poll'
},
{
title:'questionOfDay',
xtype:'questionOfDay'
}
]//end if items
},
{
//title:'center',
region:'center',
html:'center region'
},
{
/* //title:'East',
xtype:'loginLogin',
region:'east',
margins:'0 5 0 5',
width:200,
//collapsible:true,
//collapsed:true,
*/
region:'east',
margins:'0 5 0 5',
flex:.3,
//collapsible:true,
//titleCollapse:true,
layout:'accordion',
layoutConfig:
{
animate:false,
multi:true
},
items:[
{
title:'Login Window',
xtype:'loginLogin'
},
{
title:'QuestionOfDay',
xtype:'questionOfDay'
},
{
title:'Last Question And its answer',
xtype:'lastQusetion'
},
{
title:'This Day In a History',
xtype:'history'
}
]//end if items
},
{
//title:'South',
region:'south',
margins:'0 5 5 5',
flex:.1,
html:'<h6 align="center">Footer</h6>',
split:false
},//mainMenu // used mainMenu when you are using mainMenu variable
]//end if items
});//End of view port
2)Login.js :-- this is the login view page
Ext.define('AM.view.login.Login',
{
extend:'Ext.form.Panel',
id:'lg',
alias:'widget.loginLogin',
bodyStyle:'padding:5px 5px 0',
title:'Login Window',
hidden:false,
height: 150,
//items:
//[
//{
//xtype:'form',
border:3,
items:[
{
xtype:'textfield',
fieldLabel:'Key In',
name:'uname',
//width:'10px',
anchor:'100%',
//flex:2,
//labelAlign:'top',
// cls:'field-margin',
allowBlank:false,
//minLength:6,
//draggable:true,
},
{
xtype:'textfield',
fieldLabel:'Key',
//width:'20px',
flex:6,
//labelAlign:'top',
name:'pass',
inputType:'password',
allowBlank:false,
minLength:6,
anchor:'100%',
},
{
xtype:'button',
formBind: true,
fieldLabel:'Keylogin',
action:'loginAction',
text:'login',
//width:'20px',
flex:6,
//labelAlign:'top',
anchor:'100%',
}
],
//}],//end of items
});//End
</code></pre>
<p>3) And here is some code in controller file </p>
<pre><code>authenticateUser:function(button)
{
console.log('enter');
var obj = Ext.ComponentQuery.query('#vp');
obj[0].remove('lg');
}
</code></pre>
<p>code is executing but is does not hides the login window.please give me suggestions..
Thanks in advance.</p>
| 0 | 3,151 |
Vue.JS 2.5.1 : Uncaught SyntaxError: Unexpected token export
|
<p>I was trying to make a radio button using VueJS and Bootstrap Vue, but this happens when I make it. I'm expecting this to be syntax error just like what it said, but I can't seem find any clue.</p>
<p>So I tried to copy pasted the code, here's the full code of test_radio.php</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/>
</head>
<body>
<template>
<div>
<b-form-group label="Radios using <code>options</code>">
<b-form-radio-group id="radios1" v-model="selected" :options="options" name="radioOpenions">
</b-form-radio-group>
</b-form-group>
<b-form-group label="Radios using sub-components">
<b-form-radio-group id="radios2" v-model="selected" name="radioSubComponent">
<b-form-radio value="first">Toggle this custom radio</b-form-radio>
<b-form-radio value="second">Or toggle this other custom radio</b-form-radio>
<b-form-radio value="third" disabled>This one is Disabled</b-form-radio>
<b-form-radio :value="{fourth: 4}">This is the 4th radio</b-form-radio>
</b-form-radio-group>
</b-form-group>
<div class="mt-3">
Selected: <strong>{{ selected }}</strong>
</div>
</div>
</template>
<!-- Vue.js @2.5.1 -->
<script type="text/javascript" src="js/vue.js"></script>
<!-- Add this after vue.js -->
<script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
<!-- The error is below -->
<script>
export default {
data () {
return {
selected: 'first',
options: [
{ text: 'Toggle this custom radio', value: 'first' },
{ text: 'Or toggle this other custom radio', value: 'second' },
{ text: 'This one is Disabled', value: 'third', disabled: true },
{ text: 'This is the 4th radio', value: {fourth: 4} }
]
}
}
}
</script>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/Che6u.png" rel="nofollow noreferrer">Uncaught SyntaxError: Unexpected token export</a></p>
<p>I'm pretty sure there's a mistake on the code on Export, but I already checked many times and I can't seem to find the error in the syntax.</p>
<p>I'm still new to Javascript, Vue.JS, and Bootstrap Vue, so any help would be useful, thanks! Anyway this code comes from Bootstrap Vue's <a href="https://bootstrap-vue.js.org/docs/components/form-radio" rel="nofollow noreferrer">documentation</a>.</p>
| 0 | 1,267 |
spring Java config for excel view resolver
|
<p>I have a spring java config based web app with (jsp) view resolver.
Now i want to show a excel sheet with some data when user clicks on excel icon in app.
All over internet i only found xml based spring config for excel view with which i am not familiar with.
I decoded to some extent and came pretty close to get my task done. Below is what i got.</p>
<p>I have similar controller and Homepage following the below link:</p>
<p><a href="http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch17s06.html">http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch17s06.html</a></p>
<p>Controlle Code:</p>
<pre><code>@Controller
public class ExcelController extends AbstractController {
@Override
@RequestMapping(value = "/Excel", method = RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
BufferedReader in = null;
try {
URL oracle = new URL("example.com");
URLConnection yc =null;
yc = oracle.openConnection();
in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
}
catch(Exception e){
System.err.println(e);
}
Map map = new HashMap();
map.put("input", in);
return new ModelAndView("xl", map);
}
</code></pre>
<p>}</p>
<p>View Code:</p>
<pre><code>public class ExcelReportView extends AbstractExcelView{
@Override
protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
try {
BufferedReader in = (BufferedReader) model.get("input");
sheet=workbook.createSheet("spring");
String inputLine;
int rowNum =0;
while ((inputLine = in.readLine()) != null) {
row = sheet.createRow(rowNum++);
String[] coloumns = inputLine.split("\t");
int cellNum =0;
for(String coloumn: coloumns){
cell = row.createCell(cellNum++);
cell.setCellValue(coloumn);
}
System.out.println(inputLine);
}
in.close();
System.out.println("Excel written successfully..");
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
<p>}
}</p>
<p>view.properties</p>
<pre><code> xl.class=package.ExcelReportView
</code></pre>
<p>WebAppConfig.java</p>
<pre><code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "package")
public class WebAppContextConfig extends WebMvcConfigurerAdapter {
// Resolve logical view names to .jsp resources in /WEB-INF/views directory
@Bean
public InternalResourceViewResolver configureInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/scripts/**").addResourceLocations(
"/scripts/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
}
</code></pre>
<p>}</p>
<p>Front end Code:</p>
<pre><code> function AjaxCallForExcel(){
$.ajax({
type: 'POST',
url: location.href + '/Excel',
data: ({name:name })
});
}
</code></pre>
<p>Below is what i see in logs:</p>
<pre><code> DispatcherServlet with name 'appServlet' processing POST request for [/App/Excel]
Looking up handler method for path /App/Excel
Returning handler method [protected org.springframework.web.servlet.ModelAndView package.ExcelController.handleRequestInternal(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception]
Returning cached instance of singleton bean 'excelController'
Invoking afterPropertiesSet() on bean with name 'xl'
Rendering view [org.springframework.web.servlet.view.JstlView: name 'xl'; URL [**/WEB-INF/jsp/xl.jsp**]] in DispatcherServlet with name 'appServlet'
Added model object 'org.springframework.validation.BindingResult.input' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'xl'
Added model object 'input' of type [java.io.BufferedReader] to request in view with name 'xl'
Forwarding to resource [/WEB-INF/jsp/xl.jsp] in InternalResourceView 'xl'
Successfully completed request
</code></pre>
<p>I dont know how to avoid it from forwarding it to xl.jsp. I am sure view resolver is making it into jsp view. Can someone point how can i fix it.</p>
<p><strong>EDIT</strong></p>
<p>I saw this xml equivalent config online. Not sure how to make it java config:</p>
<pre><code><bean id="excelViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
</code></pre>
<p>i tried converting it the below way:</p>
<pre><code>@Bean
public XmlViewResolver configureXmlViewResolver(){
XmlViewResolver resolver = new XmlViewResolver();
resolver.setOrder(1);
resolver.setLocation(**WHAT SHOULD BE HERE**);
}
</code></pre>
<p>I dont know what to put in location. I cant give string. i dont have views.xml as i am use java configs</p>
<p><strong>Edit</strong>(Here is my code after making changes as you said)</p>
<pre><code>public class ExcelReportView extends AbstractExcelView{
BufferedReader in;
ExcelReportView(BufferedReader in){
this.in = in;
}
@Override
protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=MyExcelSpreadsheet.xls");
try {
//BufferedReader in = (BufferedReader) model.get("input");
sheet=workbook.createSheet("spring");
String inputLine;
int rowNum =0;
while ((inputLine = in.readLine()) != null) {
row = sheet.createRow(rowNum++);
String[] coloumns = inputLine.split("\t");
int cellNum =0;
for(String coloumn: coloumns){
cell = row.createCell(cellNum++);
cell.setCellValue(coloumn);
}
System.out.println(inputLine);
}
in.close();
System.out.println("Excel written successfully..");
} catch (IOException e) {
e.printStackTrace();
}
OutputStream outStream = null;
try {
outStream = response.getOutputStream();
workbook.write(outStream);
outStream.flush();
} finally {
outStream.close();
}
}
}
</code></pre>
<p>Controller Code:</p>
<pre><code> @Controller
public class ExcelController {
@RequestMapping(value = "/Excel", method = RequestMethod.POST)
protected ModelAndView generateCSV(HttpServletRequest request,
HttpServletResponse response) throws Exception {
BufferedReader in = null;
try {
URL oracle = new URL("http://service.com");
URLConnection yc =null;
yc = oracle.openConnection();
in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
}
catch(Exception e){
System.err.println(e);
}
ModelAndView mav = new ModelAndView();
mav.setView(new ExcelReportView( in));
return mav;
}
}
</code></pre>
<p>Log output:</p>
<pre><code> DispatcherServlet with name 'appServlet' processing POST request for [/App/Excel]
Looking up handler method for path /App/Excel
Returning handler method [protected org.springframework.web.servlet.ModelAndView com.package.ExcelController.generateCSV(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception]
Returning cached instance of singleton bean 'excelController'
Rendering view [com.package.controllers.ExcelReportView: unnamed] in DispatcherServlet with name 'appServlet'
Created Excel Workbook from scratch
Title Id required
Excel written successfully..
Successfully completed request
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Response Header:</p>
<pre><code>HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Pragma: private
Cache-Control: private, must-revalidate
Content-Disposition: attachment; filename=MyExcelSpreadsheet.xls
Content-Type: application/octet-stream;charset=ISO-8859-1
Content-Language: en-US
Transfer-Encoding: chunked
Date: Tue, 12 Mar 2013 16:36:52 GMT
</code></pre>
| 0 | 4,082 |
Error : Object must implement IConvertible
|
<p>I am trying to insert Listbox Items and a Textbox value for each of the listbox items to the database when I get the below error.</p>
<p>IF i try to insert the list box items only I am successful but when i try to insert the textbox value I get this error. Can you please tell me what I am doing wrong.</p>
<pre>
Error Message: Object must implement IConvertible.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Object must implement IConvertible.
Source Error:
Line 60:
Line 61:
Line 62: cmd.ExecuteNonQuery();
Line 63:
Line 64:
</pre>
<hr>
<p>c# CODE</p>
<pre><code>using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
public partial class test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["RM_Jan2011ConnectionString"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO FileID(File_Code, Dept_Code) VALUES(@File_Code, @Dept_Code)";
sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.Parameters.Add("@File_Code", SqlDbType.VarChar);
cmd.Parameters["@File_Code"].Value = ListBox2.Items;
cmd.Parameters.Add("@Dept_Code", SqlDbType.VarChar);
cmd.Parameters["@Dept_Code"].Value = DropDownList1.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert ('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
int myint = Convert.ToInt32(TextBox1.Text) + 1;
for (int i = 1; i < myint; i++)
{
ListBox2.Items.Add(DropDownList1.SelectedItem.ToString() + i.ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
foreach (ListItem item in ListBox2.Items)
{
{
sc.Add(item.Text);
sc.Add(DropDownList1.Text);
}
}
InsertRecords(sc);
}
</code></pre>
<hr>
<p>I want to add all the values of the listbox to the database. </p>
<p>Secondlly even if I try to use .</p>
<p>SelectedItem</p>
<p>then I get the following error.</p>
<pre>
Insert Error: Incorrect syntax near 'CPD1'.
Incorrect syntax near 'CPD'.
Incorrect syntax near 'CPD2'.
Incorrect syntax near 'CPD'.
Incorrect syntax near 'CPD3'.
Incorrect syntax near 'CPD'.
</pre>
<p>Any idea where I am going wrong?</p>
| 0 | 1,506 |
What causes SignalR to receive net::ERR_CONNECTION_RESET on connect?
|
<p>I have a simple SingulaR example that I've added to a legacy ASP.Net MVC application.</p>
<p>Here are the various parts:</p>
<p><strong>OWIN Startup class</strong></p>
<pre><code>[assembly: OwinStartup(typeof (Startup))]
namespace MyApp.Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
</code></pre>
<p><strong>SignalR Hub</strong></p>
<pre><code>using System.Collections.Generic;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace MyApp.Web
{
[HubName("podService")]
public class PodServiceHub : Hub
{
public PodServiceHub()
{
;
}
public IEnumerable<string> GetMessages()
{
return new[] {"blah", "blah", "blah"};
}
}
}
</code></pre>
<p><strong>Server-side facade</strong></p>
<pre><code>using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace MyApp.Web
{
public class PodService
{
PodService(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
}
public PodService()
: this(GlobalHost.ConnectionManager.GetHubContext<PodServiceHub>().Clients)
{
}
IHubConnectionContext<dynamic> Clients { get; set; }
public void SendMessageToClient(string message)
{
Clients.All.doSomething(message);
}
}
}
</code></pre>
<p><strong>Portions of startup Javascript:</strong></p>
<pre><code> var podService = $.connection.podService;
...
$.extend(podService.client, {
doSomething: function(message) {
console.log("received message:" + message);
}
});
// test
$.connection.hub.start()
.done(function() {
podService.server.getMessages()
.done(function(messages) {
console.log("received message:" + message);
});
});
</code></pre>
<p>Within one of the controllers called by the first page:</p>
<pre><code>_podService.SendMessageToClient("Hello from the server!");
</code></pre>
<p>Upon executing the application, the following error is displayed in the console of Chrome's dev tools:</p>
<p>WebSocket connection to 'ws://localhost:62025/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=02LJFqBcRBWKXAOlaSwgMPWG0epV7AFl19gNjFCvA0dxD2QH8%2BC9V028Ehu8fYAFN%2FthPv65JZKfK2MgCEdihCJ0A2dMyENOcdPkhDzEwNB2WQ1X4QXe1fiZAyMbkZ1b&connectionData=%5B%7B%22name%22%3A%22podservice%22%7D%5D&tid=6' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET</p>
<p>After this error, however, the podService.server.getMessages() returns with the message from the server printing ["blah", "blah", "blah"] to the console and subsequently the doSomething client function is invoked printing "received message: Hello from the server!".</p>
<p>The calls from both the client and the server are transmitting data, so this error doesn't appear to be breaking the app. It definitely seems to be an issue though. The code above was based upon the sample code generated by the Microsoft.AspNet.SignalR.Sample NuGet package which doesn't display the same behavior. The only difference I'm aware of between my example and NuGet-based sample is that I've added this to a legacy MVC app vs. a pure OWIN-based app. Based upon a comment I read <a href="https://stackoverflow.com/questions/26273700/signalr-without-owin">on this SO question</a> this shouldn't be an issue.</p>
<p>So, what's wrong with this example usage and/or what could be causing the connection reset?</p>
| 0 | 1,505 |
Copy Data from one hbase table to another
|
<p>I have created one table hivetest which also create the table in hbase with name of 'hbasetest'. Now I want to copy 'hbasetest' data into another hbase table(say logdata) with the same schema. So, can anyone help me how do copy the data from 'hbasetest' to 'logdata' without using the hive.</p>
<pre><code>CREATE TABLE hivetest(cookie string, timespent string, pageviews string, visit string, logdate string)
STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
WITH SERDEPROPERTIES ("hbase.columns.mapping" = "m:timespent, m:pageviews, m:visit, m:logdate")
TBLPROPERTIES ("hbase.table.name" = "hbasetest");
</code></pre>
<p><strong>Updated question :</strong> </p>
<p>I have created the table logdata like this. But, I am getting the following error. </p>
<pre><code>create 'logdata', {NAME => ' m', BLOOMFILTER => 'NONE', REPLICATION_SCOPE => '0', VERSIONS => '3', COMPRESSION => 'NONE', MIN_VERSIONS =>'0', TTL => '2147483647', BLOCKSIZE=> '65536', IN_MEMORY => 'false', BLOCKCACHE => 'true'}
13/09/23 12:57:19 INFO mapred.JobClient: Task Id : attempt_201309231115_0025_m_000000_0, Status : FAILED
org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException: Failed 755 actions: org.apache.hadoop.hbase.regionserver.NoSuchColumnFamilyException: Column family m does not exist in region logdata,,1379920697845.30fce8bcc99bf9ed321720496a3ec498. in table 'logdata', {NAME => 'm', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'NONE', REPLICATION_SCOPE => '0', COMPRESSION => 'NONE', VERSIONS => '3', TTL => '2147483647', MIN_VERSIONS => '0', KEEP_DELETED_CELLS => 'false', BLOCKSIZE => '65536', ENCODE_ON_DISK => 'true', IN_MEMORY => 'false', BLOCKCACHE => 'true'}
at org.apache.hadoop.hbase.regionserver.HRegionServer.multi(HRegionServer.java:3773)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:320)
at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1426)
: 755 times, servers with issues: master:60020,
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.processBatchCallback(HConnectionManager.java:1674)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.processBatch(HConnectionManager.java:1450)
at org.apache.hadoop.hbase.client.HTable.flushCommits(HTable.java:916)
at org.apache.hadoop.hbase.client.HTable.close(HTable.java:953)
at org.apache.hadoop.hbase.mapreduce.TableOutputFormat$TableRecordWriter.close(TableOutputFormat.java:109)
at org.apache.hadoop.mapred.MapTask$NewDirectOutputCollector.close(MapTask.java:651)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:766)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:370)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
13/09/23 12:57:29 INFO mapred.JobClient: Task Id : attempt_201309231115_0025_m_000000_1, Status : FAILED
org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException: Failed 755 actions: org.apache.hadoop.hbase.regionserver.NoSuchColumnFamilyException: Column family m does not exist in region logdata,,1379920697845.30fce8bcc99bf9ed321720496a3ec498. in table 'logdata', {NAME => 'm', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'NONE', REPLICATION_SCOPE => '0', COMPRESSION => 'NONE', VERSIONS => '3', TTL => '2147483647', MIN_VERSIONS => '0', KEEP_DELETED_CELLS => 'false', BLOCKSIZE => '65536', ENCODE_ON_DISK => 'true', IN_MEMORY => 'false', BLOCKCACHE => 'true'}
at org.apache.hadoop.hbase.regionserver.HRegionServer.multi(HRegionServer.java:3773)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:320)
at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1426)
: 755 times, servers with issues: master:60020,
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.processBatchCallback(HConnectionManager.java:1674)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.processBatch(HConnectionManager.java:1450)
at org.apache.hadoop.hbase.client.HTable.flushCommits(HTable.java:916)
at org.apache.hadoop.hbase.client.HTable.close(HTable.java:953)
at org.apache.hadoop.hbase.mapreduce.TableOutputFormat$TableRecordWriter.close(TableOutputFormat.java:109)
at org.apache.hadoop.mapred.MapTask$NewDirectOutputCollector.close(MapTask.java:651)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:766)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:370)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
13/09/23 12:57:38 INFO mapred.JobClient: Task Id : attempt_201309231115_0025_m_000000_2, Status : FAILED
org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException: Failed 755 actions: org.apache.hadoop.hbase.regionserver.NoSuchColumnFamilyException: Column family m does not exist in region logdata,,1379920697845.30fce8bcc99bf9ed321720496a3ec498. in table 'logdata', {NAME => 'm', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'NONE', REPLICATION_SCOPE => '0', COMPRESSION => 'NONE', VERSIONS => '3', TTL => '2147483647', MIN_VERSIONS => '0', KEEP_DELETED_CELLS => 'false', BLOCKSIZE => '65536', ENCODE_ON_DISK => 'true', IN_MEMORY => 'false', BLOCKCACHE => 'true'}
at org.apache.hadoop.hbase.regionserver.HRegionServer.multi(HRegionServer.java:3773)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.hbase.ipc.WritableRpcEngine$Server.call(WritableRpcEngine.java:320)
at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1426)
: 755 times, servers with issues: master:60020,
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.processBatchCallback(HConnectionManager.java:1674)
at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.processBatch(HConnectionManager.java:1450)
at org.apache.hadoop.hbase.client.HTable.flushCommits(HTable.java:916)
at org.apache.hadoop.hbase.client.HTable.close(HTable.java:953)
at org.apache.hadoop.hbase.mapreduce.TableOutputFormat$TableRecordWriter.close(TableOutputFormat.java:109)
at org.apache.hadoop.mapred.MapTask$NewDirectOutputCollector.close(MapTask.java:651)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:766)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:370)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
13/09/23 12:57:53 INFO mapred.JobClient: Job complete: job_201309231115_0025
13/09/23 12:57:53 INFO mapred.JobClient: Counters: 7
13/09/23 12:57:53 INFO mapred.JobClient: Job Counters
13/09/23 12:57:53 INFO mapred.JobClient: SLOTS_MILLIS_MAPS=34605
13/09/23 12:57:53 INFO mapred.JobClient: Total time spent by all reduces waiting after reserving slots (ms)=0
13/09/23 12:57:53 INFO mapred.JobClient: Total time spent by all maps waiting after reserving slots (ms)=0
13/09/23 12:57:53 INFO mapred.JobClient: Rack-local map tasks=4
13/09/23 12:57:53 INFO mapred.JobClient: Launched map tasks=4
13/09/23 12:57:53 INFO mapred.JobClient: SLOTS_MILLIS_REDUCES=0
13/09/23 12:57:53 INFO mapred.JobClient: Failed map tasks=1
</code></pre>
| 0 | 3,481 |
Want to create a table using XSL/XML
|
<p>I’m trying to create a table using XSL/XML. I'm new to XSL and XML, so go easy on me please
I’m having a bit of trouble with a few things.
This is my XML file:</p>
<pre><code><List>
<Classification>
<Class>
<Label>Milk</Label>
<NumberZone>1</NumberZone>
<Zone>
<Label>Milk1</Label>
<Frontier>500</Frontier>
</Zone>
<Zone>
<Label>Milk2</Label>
<Frontier>600</Frontier>
</Zone>
<Zone>
<Label>Milk3</Label>
<Frontier>600</Frontier>
</Zone>
<Zone>
<Label>Milk4</Label>
<Frontier>700</Frontier>
</Zone>
<image>
<File>milk.jpg</File>
</image>
</Class>
<Class>
<Label>Water</Label>
<NumberZone>2</NumberZone>
<Zone>
<Label>Water1</Label>
<Frontier>800</Frontier>
</Zone>
<Zone>
<Label>Water2</Label>
<Frontier>900</Frontier>
</Zone>
<image>
<File>water.jpg</File>
</image>
</Class>
<Class>
<Label>Juice</Label>
<NumberZone>3</NumberZone>
<Zone>
<Label>Juice1</Label>
<Frontier>950</Frontier>
</Zone>
<Zone>
<Label>Juice2</Label>
<Frontier>990</Frontier>
</Zone>
<image>
<File>juice.jpg</File>
</image>
</Class>
</Classification>
</List>
</code></pre>
<p>It normally is longer, but I cut out some parts.</p>
<p>I want my table to look like this:</p>
<ul>
<li>First column: Milk, Water, Juice...</li>
<li>Second column: I want the images.</li>
<li>Third column: Milk1, Water1, Juice1. </li>
<li>Fourth column: Milk2, Water2, Juice2.</li>
<li>(And so on).</li>
</ul>
<p>So far I have this:</p>
<pre><code><table border="1">
<tr><th>Column 1</th><th>Image</th><th>Column 3</th></tr>
<xsl:for-each select="Classification/Class">
<tr>
<td><em><xsl:value-of select="Label" /></em></td>
<td>
<xsl:attribute name="src">
<xsl:value-of select="image/File"/>
</xsl:attribute>
</td>
<td><xsl:value-of select="Zone/Label"/></td>
<td colspan="1"><xsl:value-of select="Zone/Label"/></td>
<td colspan="1"><xsl:value-of select="Zone/Label"/></td>
</tr>
</xsl:for-each>
</table>
</code></pre>
<ul>
<li>This displays the first column perfectly with Milk, Water, and Juice.</li>
<li>The second column doesn't work, it's just blank. The image won't appear in the table, any idea on how to fix this?*</li>
<li>The third column also works perfectly showing Milk1, Water1, Juice1.</li>
<li>The fourth column doesn't work, obviously, because I'm using the same value-of as in the third column. I don't know how to get Milk2, Water2, and Juice2 to show in that column, since it uses the same element name (being Zone/Label)</li>
</ul>
<p><strong>So there's two thing I need to fix: I need to fix the second column to actually show the image in each boxes.
I also need to fix the fourth column to show Milk2, Water2, and Juice2.
My main problem for now is to get the fourth column to work, I really don't understand how to display Milk2, Water2, etc.</strong></p>
<p>I would also like to add either radio buttons, or check boxes later on in each cell, so I could use JavaScript in my web page. I feel like each box would need a different ID, so I'm not sure how to achieve that using XSL, since it just does a "loop" through the XML file, so I'm not sure how I would add a radio button, or a check box in each cell. * This isn't as important for now, I'll work on that after I'd rather have help with what I mentioned before, but this would be helpful too.</p>
<p>EDIT:</p>
<p>I have two problems.
I managed to add check boxes by doing something like this:</p>
<pre><code><td colspan="1"><input type="checkbox" name="Zone1" id="Zone1" /><xsl:value-of select="Zone[1]/Label"/></td>
<td colspan="1"><input type="checkbox" name="Zone2" id="Zone1" /><xsl:value-of select="Zone[2]/Label"/></td>
<td colspan="1"><input type="checkbox" name="Zone3" id="Zone1"/> <xsl:value-of select="Zone[3]/Label"/></td>
<td colspan="1"><input type="checkbox" name="Zone4" id="Zone1" /><xsl:value-of select="Zone[4]/Label"/></td>
</code></pre>
<p>The problem is, I think every elements in each column will have the same ID, am I right? How do I change it so they all have a different ID?</p>
<p>Also, it can't be seen from the XML file in my question, but later on there would only be, for example, Milk4. meaning I would want the cells for Water4 and Juice4 to dissapear completely, but it's still there, empty with a check box.</p>
| 0 | 2,687 |
Python. SQL Alchemy NotImplementedError: Operator 'getitem' is not supported on this expression
|
<p>I create record in DB through sql alchemy. The next step is trying to capture the id of the created object into another table that has fk on the created object (assign_resource_to_user) . This is my code:</p>
<pre><code>from dev_tools.models.user import User
from dev_tools.models.resource Resource
resource = Resource(
code=self.message_body['code'],
description=self.message_body['description'],
crew_id=None,
catalog_resource_type_id=self.message_body['catalog_resource_type_id'],
catalog_resource_status_id=self.message_body['catalog_resource_status_id'],
created_at=datetime.utcnow(),
created_by=None,
is_available=self.message_body['is_available'],
)
self.db_session.add(resource)
self.db_session.flush()
assign_resource_to_user = self.db_session.query(
User
).filter(
User.id == self.user_info.id
).update(
User.resource_id == resource.id
)
self.db_session.add(assign_resource_to_user)
</code></pre>
<p>I have error:</p>
<pre><code>Traceback (most recent call last):
File "/home/Документы/project/ResourseManagment/rm-private-application-server/apps/controller/helpers/data_processing/action/custom/resource_from_a_user.py", line 227, in <module>
resources.create_record_in_db()
File "/home/Документы/project/ResourseManagment/rm-private-application-server/apps/controller/helpers/data_processing/action/custom/resource_from_a_user.py", line 211, in create_record_in_db
User.resource_id == resource.id
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/query.py", line 3486, in update
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1334, in exec_
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1405, in _do_pre_synchronize
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1540, in _additional_evaluators
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1473, in _resolved_values_keys_as_propnames
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/orm/persistence.py", line 1457, in _resolved_values
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/sql/operators.py", line 411, in __getitem__
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/sql/elements.py", line 694, in operate
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/sql/operators.py", line 411, in __getitem__
File "<string>", line 1, in <lambda>
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/sql/type_api.py", line 63, in operate
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/sql/default_comparator.py", line 192, in _getitem_impl
File "/home/Документы/project/venv/lib/python3.7/site-packages/SQLAlchemy-1.2.14-py3.7-linux-x86_64.egg/sqlalchemy/sql/default_comparator.py", line 197, in _unsupported_impl
NotImplementedError: Operator 'getitem' is not supported on this expression
</code></pre>
<p>Error in this string:</p>
<pre><code>).update(
User.resource_id == resource.id
)
</code></pre>
<p>Maybe someone know how fix it or have same problem and can help me solve it. Thanks.</p>
| 0 | 1,600 |
ASP.Net MVC Show/Hide Content
|
<p>Ok I have the following View</p>
<pre><code>@model IEnumerable<WebApplication3.Models.user>
@{
ViewBag.Title = "Password Management";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section title {<h1>@ViewBag.Title</h1>}
<div id="page-block" class="page-block-three row">
<div style="margin-top: 30px;" class="col-lg-offset-2 col-lg-8">
@using (Html.BeginForm())
{
<div class="input-group">
@Html.TextBox("SearchString", null, new { @class = "form-control ccl-form", @style = "z-index: 10", @placeholder = "Enter Username"})
<div class="input-group-btn">
<button class="btn ccl-btn ccl-btn-red ccl-btn-search" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
}
</div>
<div class="col-lg-offset-3 col-lg-6">
@foreach (var item in Model)
{
<div class="details-block">
@Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
</div>
</code></pre>
<p>What I want to be able to do is hide the following div</p>
<pre><code><div class="col-lg-offset-3 col-lg-6">
@foreach (var item in Model)
{
<div class="details-block">
@Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
</code></pre>
<p>Then show that Div when the submit button is clicked</p>
<p>My Controller looks like the following</p>
<pre><code>public class PasswordController : Controller
{
private CCLPasswordManagementDBEntities db = new CCLPasswordManagementDBEntities();
public ActionResult Search(string searchString)
{
var users = from x in db.users select x;
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(x => x.UserName.ToUpper().Contains(searchString.ToUpper()));
}
return View(users);
}
}
</code></pre>
<p>At the moment the div is constantly shown and updates when the submit button is pressed but I want to hide that div until someone presses the submit button then it can show.</p>
<p>Thanks in advance for the help.</p>
| 0 | 1,258 |
Watch date input value and use it with v-model
|
<p>I tried for 4 days to get a stupid date from the input, that the user selected. Looks probably simple but believe me that I ask here because I run out of solutions.</p>
<p>I have a page/component AddNewEvent and inside this input where the user adds the date and time. I have to get it in my v-model so I can send it back to database.</p>
<p>I use bootstrap 4 input <code>type="datetime-local"</code> to get the date and time. I tried to use some vue plugins for date but all are based on bootstrap 3 and in the project is bootstrap 4.</p>
<p>Inside template:</p>
<pre><code><div class="form-group">
<label class="eda-form-label" for="event-name">Event Name <span>(Max characters number is 60)</span></label>
<input type="text" class="eda-form-input" v-model="newEvent.eventName">
</div>
<div class="form-group">
<label class="eda-form-label" for="exampleTextarea">Event Description <span>(Max characters number is 2000)</span></label>
<textarea class="eda-form-input" rows="3" v-model="newEvent.description"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col-6 ">
<label class="eda-form-label" for="start-time">START TIME</label>
<input class="form-control" type="datetime-local" v-model="dateNow">
</div>{{createdDate(value)}}
<div class="col-6">
<label class="eda-form-label" for="end-time">END TIME</label>
<input class="form-control" type="datetime-local" v-model="dateEnd">
</div>
</div>
</div>
</code></pre>
<p>In the script:</p>
<pre><code>data() {
return {
dateNow: '',
value: '',
oldValue: ''
}
},
watch: {
dateNow(val, oldVal) {
this.value = val;
this.oldValue = oldVal;
}
},
methods: {
createEvent(){
axios.post("/event", this.newEvent,
{'headers':{'X-AUTH-TOKEN': localStorage.token}},
{'headers':{'Content-Type': 'application/json'}})
.then((response) => {
alertify.success("Success! You added a new the user");
this.$router.push('/events');
})
.catch((response) => {
alertify.error();
})
},
}
</code></pre>
<p>If I use in the input, how is right now, <code>v-model="dateNow"</code> works. I can see when I select date, time am/pm shows me the seleted date. But I have to use it like this </p>
<p><code>v-model="newEvent.dateNow"</code> </p>
<p><code>v-model="newEvent.dateEnd"</code> </p>
<p>so I can add it to newEvent and send the whole obj back to database. </p>
<p>createdDate is a function that transforms the date in a real date. It's only for testing, because I have to send the date in ms back to database.</p>
<p>Someone please show me what I do wrong, because I'm not so very advance in vuejs.</p>
| 0 | 1,185 |
WHY am I getting this NameError : name 'url_for' is not defined?
|
<p>I am trying to build a URL following the instructions of the flask tutorial </p>
<p><a href="http://flask.pocoo.org/docs/0.11/quickstart/" rel="noreferrer">http://flask.pocoo.org/docs/0.11/quickstart/</a></p>
<p>However I am keeping getting this NameError </p>
<blockquote>
<p>name 'url_for' is not defined</p>
</blockquote>
<p>THIS is the code : </p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/')
def Index() : pass
@app.route ('/ login')
def loGin() : pass
@app.route('/user/<username>')
def profile( username) : pass
with app.test_request_context() :
print url_for('Index')
print url_for('loGin')
print url_for('loGin', next='/')
print url_for('profile', username = 'Jon DD')
</code></pre>
<p>THIS is the total error message : </p>
<pre><code>eloiim:minimalapp iivri.andre$ export FLASK_APP=Greet.py
eloiim:minimalapp iivri.andre$ flask run
Traceback (most recent call last):
File "/usr/local/bin/flask", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 478, in main
cli.main(args=args, prog_name=name)
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 345, in main
return AppGroup.main(self, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 388, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 124, in __init__
self._load_unlocked()
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 148, in _load_unlocked
self._app = rv = self.loader()
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 209, in load_app
rv = locate_app(self.app_import_path)
File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 89, in locate_app
__import__(module)
File "/Users/iivri.andre/Documents/minimalapp/Greet.py", line 16, in <module>
print url_for('Index')
NameError: name 'url_for' is not defined
</code></pre>
<p>I am not sure what the issue is.</p>
| 0 | 1,143 |
How to use ajax in laravel 5.3
|
<p>I am new to Laravel and am using Laravel 5.3. I want to make a text field where it will automatically suggest some data and when I select a data it will add it to an array. I want to send that array to a controller for further use. For this the </p>
<blockquote>
<p>view file is as follows:</p>
</blockquote>
<pre><code><head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var members = {!! json_encode($member) !!};
console.log(members);
var arr = [];
$("#tags").autocomplete({
source: members,
select: function (event, ui) {
arr.push(ui);
console.log(arr);
}
});
$("#submit").click(function(event){
$.ajax({
type: "POST",
url: '/storeresearch',
data: {selectedMembers: arr},
success: function( msg ) {
console.log(msg);
}
});
});
});
</script>
</head>
<body>
<form id="hu" action="/storeresearch" method="POST">
{!! csrf_field() !!}
<label>Research Author</label>
<input type="text" id="tags" name="researchsupervisor_1" value="">
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Add">
</form>
</body>
</code></pre>
<blockquote>
<p>My Controller file is as follows:</p>
</blockquote>
<pre><code>public function store(Request $request){
if($request->ajax())
{
$mem = $request->all();
return response()->json($mem,200) ;
}
else{
return "not found";
}
</code></pre>
<blockquote>
<p>And web.php is as followings:</p>
</blockquote>
<pre><code>Route::post('/storeresearch','ResearchController@store');
</code></pre>
<p>But it seems that there is no ajax call happening. In the controller it always enters the else section. What is the problem can anyone help? </p>
| 0 | 1,121 |
System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.
|
<p>I'm trying to get the email address from a user that is submitting an ASP.NET form on the local intranet. When testing this on my local machine it works fine. But when I publish and begin testing it in production it doesn't like line 74.</p>
<pre><code>Server Error in '/' Application.
--------------------------------------------------------------------------------
An operations error occurred.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.
Source Error:
Line 71: adSearcher.SearchScope = SearchScope.Subtree;
Line 72: adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
Line 73: SearchResult userObject = adSearcher.FindOne();
Line 74: if (userObject != null)
Line 75: {
Source File: c:\Web\Support-t\Content\Default.aspx.cs Line: 73
Stack Trace:
[DirectoryServicesCOMException (0x80072020): An operations error occurred.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +628309
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_AdsObject() +42
System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) +98
System.DirectoryServices.DirectorySearcher.FindOne() +44
_Default.Page_Load(Object sender, EventArgs e) in c:\Web\Support-t\Content\Default.aspx.cs:73
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
</code></pre>
<p>This block of code is in my page load just for testing purposes so in can get an immediate result....but it never get to the loading of the page in production but works fine when debugging in VS on local machine...</p>
<pre><code>IIdentity id = WindowsIdentity.GetCurrent();
WindowsIdentity winId = id as WindowsIdentity;
if (id == null)
{
txtDetailedProblem.Text = "Identity is not a windows identity";
return;
}
string userInQuestion = winId.Name.Split('\\')[1];
string myDomain = winId.Name.Split('\\')[0]; // this is the domain that the user is in
// the account that this program runs in should be authenticated in there
DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
DirectorySearcher adSearcher = new DirectorySearcher(entry);
adSearcher.SearchScope = SearchScope.Subtree;
adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
SearchResult userObject = adSearcher.FindOne();
if (userObject != null)
{
string[] props = new string[] {"mail"};
foreach (string prop in props)
{
txtTEST.Text = prop.ToString() + " " + userObject.Properties[prop][0].ToString();
}
}
</code></pre>
| 0 | 1,111 |
How do I debug macros?
|
<p>So I've got the following macro code I'm trying to debug. I've taken it from the <a href="http://doc.rust-lang.org/book/macros.html" rel="noreferrer" title="The Rust Programming Language Book">Rust Book</a> under the section "The deep end". I renamed the variables within the macro to more closely follow <a href="http://esolangs.org/wiki/Bitwise_Cyclic_Tag" rel="noreferrer" title="Bitwise Cyclic Tag">this</a> post.</p>
<p>My goal is to have the program print out each line of the BCT program. I'm well aware that this is very compiler heavy.</p>
<p>The only error rustc is giving me is:</p>
<pre><code>user@debian:~/rust/macros$ rustc --pretty expanded src/main.rs -Z unstable-options > src/main.precomp.rs
src/main.rs:151:34: 151:35 error: no rules expected the token `0`
src/main.rs:151 bct!(0, 1, 1, 1, 0, 0, 0; 1, 0);
</code></pre>
<p>What steps can I take to figure out <strong><em>where</em></strong> in the macro the problem is coming from?</p>
<p>Here's my code:</p>
<pre><code>fn main() {
{
// "Bitwise Cyclic Tag" automation through macros
macro_rules! bct {
// cmd 0: 0 ... => ...
(0, $($program:tt),* ; $_head:tt)
=> (bct_p!($($program),*, 0 ; ));
(0, $($program:tt),* ; $_head:tt, $($tail:tt),*)
=> (bct_p!($($program),*, 0 ; $($tail),*));
// cmd 1x: 1 ... => 1 ... x
(1, $x:tt, $($program:tt),* ; 1)
=> (bct_p!($($program),*, 1, $x ; 1, $x));
(1, $x:tt, $($program:tt),* ; 1, $($tail:tt),*)
=> (bct_p!($($program),*, 1, $x ; 1, $($tail),*, $x));
// cmd 1x: 0 ... => 0 ...
(1, $x:tt, $($program:tt),* ; $($tail:tt),*)
=> (bct_p!($($program),*, 1, $x ; $($tail),*));
// halt on empty data string
( $($program:tt),* ; )
=> (());
}
macro_rules! print_bct {
($x:tt ; )
=> (print!("{}", stringify!($x)));
( ; $d:tt)
=> (print!("{}", stringify!($d)));
($x:tt, $($program:tt),* ; )
=> {
print!("{}", stringify!($x));
print_bct!($program ;);
};
($x:tt, $($program:tt),* ; $($data:tt),*)
=> {
print!("{}", stringify!($x));
print_bct!($program ; $data);
};
( ; $d:tt, $($data:tt),*)
=> {
print!("{}", stringify!($d));
print_bct!( ; $data);
};
}
macro_rules! bct_p {
($($program:tt),* ; )
=> {
print_bct!($($program:tt),* ; );
println!("");
bct!($($program),* ; );
};
($($program:tt),* ; $(data:tt),*)
=> {
print_bct!($($program),* ; $($data),*);
println!("");
bct!($($program),* ; $($data),*);
};
}
// the compiler is going to hate me...
bct!(0, 1, 1, 1, 0, 0, 0; 1, 0);
}
</code></pre>
| 0 | 1,602 |
ImportError: No module named 'flask_jwt_extended' in PYTHON FLASK
|
<p>in localhost:5000 the script is running without any errors. but when it comes to symlink an error has been thrown to appache log.</p>
<pre><code>[Sun Jun 10 17:07:16.170057 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] mod_wsgi (pid=30438): Exception occurred processing$
[Sun Jun 10 17:07:16.170435 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] Traceback (most recent call last):
[Sun Jun 10 17:07:16.170461 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] File "/var/www/html/salesappserver/app.wsgi", lin$
[Sun Jun 10 17:07:16.170465 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] from api import app as application
[Sun Jun 10 17:07:16.170471 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] File "/var/www/html/salesappserver/api.py", line $
[Sun Jun 10 17:07:16.170474 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] from flask_jwt_extended import JWTManager
[Sun Jun 10 17:07:16.170491 2018] [wsgi:error] [pid 30438] [client 120.29.113.65:32852] ImportError: No module named 'flask_jwt_extended'
[Sun Jun 10 17:07:17.501917 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] mod_wsgi (pid=30439): Target WSGI script '/var/www/$
[Sun Jun 10 17:07:17.501994 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] mod_wsgi (pid=30439): Exception occurred processing$
[Sun Jun 10 17:07:17.502345 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] Traceback (most recent call last):
[Sun Jun 10 17:07:17.502372 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] File "/var/www/html/salesappserver/app.wsgi", lin$
[Sun Jun 10 17:07:17.502376 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] from api import app as application
[Sun Jun 10 17:07:17.502382 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] File "/var/www/html/salesappserver/api.py", line $
[Sun Jun 10 17:07:17.502393 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] from flask_jwt_extended import JWTManager
[Sun Jun 10 17:07:17.502411 2018] [wsgi:error] [pid 30439] [client 120.29.113.65:32858] ImportError: No module named 'flask_jwt_extended'
</code></pre>
<p>this is the main problem ImportError: No module named 'flask_jwt_extended' which i already satisfied the requirement in FLASK</p>
<pre><code>(salesappserver) ubuntu@ip-172-31-3-35:~$ pip install flask-jwt-extended
Requirement already satisfied: flask-jwt-extended in ./salesappserver/lib/python3.6/site-packages (3.10.0)
Requirement already satisfied: Flask in ./salesappserver/lib/python3.6/site-packages (from flask-jwt-extended) (1.0.2)
Requirement already satisfied: PyJWT in ./salesappserver/lib/python3.6/site-packages (from flask-jwt-extended) (1.6.4)
Requirement already satisfied: Werkzeug>=0.14 in ./salesappserver/lib/python3.6/site-packages (from flask-jwt-extended) (0.14.1)
Requirement already satisfied: Jinja2>=2.10 in ./salesappserver/lib/python3.6/site-packages (from Flask->flask-jwt-extended) (2.10)
Requirement already satisfied: itsdangerous>=0.24 in ./salesappserver/lib/python3.6/site-packages (from Flask->flask-jwt-extended) (0.24)
Requirement already satisfied: click>=5.1 in ./salesappserver/lib/python3.6/site-packages (from Flask->flask-jwt-extended) (6.7)
Requirement already satisfied: MarkupSafe>=0.23 in ./salesappserver/lib/python3.6/site-packages (from Jinja2>=2.10->Flask->flask-jwt-extended) (1.0)
(salesappserver) ubuntu@ip-172-31-3-35:~$
</code></pre>
<p>Please help me. thanks in advance</p>
| 0 | 1,420 |
No mapping found for HTTP request with URI [/myappname/] in DispatcherServlet with name 'appServlet'
|
<p>I have got error <code>No mapping found for HTTP request with URI [/myappname/] in DispatcherServlet with name 'appServlet'</code> when I was starting my project on JBoss. This is issue has occurred after resolving another issue described here: <a href="https://stackoverflow.com/q/12299322/845220">"No Session found for current thread" after changing access method to the session</a></p>
<p>Before everything was working fine. I am using Apache Tiles 2. I am reading few similar questions but I can't find working solution.</p>
<p>This is my <code>DispatcherServlet Context</code> file without Hibernate configuration:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<tx:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="finances.webapp" />
<!-- Handles HTTP GET requests for resources by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/tiles-definitions.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
</beans:bean>
</code></pre>
<p>My <code>web.xml</code> whole file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>And this is my <code>IndexController</code>:</p>
<pre><code>@Controller
public class IndexController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model, Principal principal) {
return "index";
}
}
</code></pre>
<p>What is wrong with my configuration at this moment?</p>
| 0 | 1,873 |
Making Sidebar with material-ui
|
<p>i'm learning material-ui by making the right navigation menu like this one: <a href="http://demo.geekslabs.com/materialize/v3.1/" rel="noreferrer">http://demo.geekslabs.com/materialize/v3.1/</a> or least like this: <a href="http://www.material-ui.com/#/components/app-bar" rel="noreferrer">http://www.material-ui.com/#/components/app-bar</a></p>
<p>I'm using Drawer to make my sidebar, the problem is when the sidebar is toggled, it hides the content on the right. I want when my sidebar is toggled, it took place and push the content to the right and both sidebar and content got their own scrollbar. Here is my current code:</p>
<p>Sidebar.js:</p>
<pre><code>import React from 'react';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
import AppBar from 'material-ui/AppBar';
export default class Sidebar extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle = () => this.setState({open: !this.state.open});
handleClose = () => this.setState({open: false});
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
<div>
<RaisedButton
label="Open Drawer"
onTouchTap={this.handleToggle}
/>
<Drawer
containerStyle={{height: 'calc(100% - 64px)', top: 64}}
docked={true}
width={200}
open={this.state.open}
onRequestChange={(open) => this.setState({open})
}
>
<AppBar title="AppBar" />
<MenuItem onTouchTap={this.handleClose}>Menu Item</MenuItem>
<MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem>
</Drawer>
</div>
</MuiThemeProvider>
);
}
}
</code></pre>
<p>My Layout.js:</p>
<pre><code>import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Layout.css';
import Header from '../Header';
import Feedback from '../Feedback';
import Footer from '../Footer';
import Sidebar from '../Sidebar';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AppBar from 'material-ui/AppBar';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
function Layout({ children }) {
return (
<div>
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
<AppBar title="My web" />
</MuiThemeProvider>
<Sidebar/>
{React.Children.only(children)}
<Feedback />
<Footer />
</div>
);
}
Layout.propTypes = {
children: PropTypes.element.isRequired,
};
export default withStyles(s)(Layout);
</code></pre>
| 0 | 1,544 |
How to define a user define data type in XML schema?
|
<p>I have defined two complex element types - Developer and App.</p>
<p>Developer childs - ID ,Name, Email</p>
<p>App childs - ID, Name, <strong>Developer</strong></p>
<p>Here the <strong>Developer</strong> in App complex element refers to Developer/ID.</p>
<p>How to define this relationship in xml schema. I am using XML spy2013 editor.</p>
<p>I have tried specifying name in the declaration of simple type Developer->ID. And using this name in App->Developer datatype. But it gives error..</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2013 (x64) (http://www.altova.com) by Piyush (USC) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="appinfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Developer">
<xs:complexType>
<xs:all>
**<xs:element name="ID">**
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="5"/>
<xs:pattern value="[a-zA-Z][a-zA-Z][0-9][0-9][a-zA-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-zA-Z])+"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Email">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[^@]+@[^\.]+\..+"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Company" type="xs:string"/>
<xs:element name="Website" type="xs:string"/>
<xs:element name="Phone">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="13"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
<xs:element name="App">
<xs:complexType>
<xs:all>
<xs:element name="ID">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="5"/>
<xs:pattern value="[0-9][0-9][0-9][0-9][A-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-zA-Z])+"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Developer" ***type="xs:anySimpleType"/>***
<xs:element name="Price">
<xs:simpleType>
<xs:restriction base="xs:float">
<xs:minInclusive value="0.00"/>
<xs:maxInclusive value="6.99"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="TabletCompatible" type="xs:boolean" minOccurs="0"/>
<xs:element name="Category">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Travel"/>
<xs:enumeration value="Productivity"/>
<xs:enumeration value="Game"/>
<xs:enumeration value="Music"/>
<xs:enumeration value="Education"/>
<xs:enumeration value="Lifestyle"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Platform">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Android"/>
<xs:enumeration value="iOS"/>
<xs:enumeration value="Blackberry"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
<xs:element name="AppStat">
<xs:complexType>
<xs:all>
<xs:element name="AppID" type="xs:anySimpleType"/>
<xs:element name="Statistics">
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="Platform" type="xs:anySimpleType"/>
<xs:element name="Downloads" type="xs:positiveInteger"/>
<xs:element name="Rating">
<xs:simpleType>
<xs:restriction base="xs:float">
<xs:minInclusive value="0.0"/>
<xs:maxInclusive value="5.0"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="LastChecked" type="xs:date"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</code></pre>
<p></p>
| 0 | 5,146 |
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet google app engine
|
<p>I'm trying to set up an application for Google app engine, and I cannot make it work. I'm have everything set up with maven but spring its not working.</p>
<p>I've been trough a lot of configuration setting and I cannot get it done!!</p>
<p>Here you have the stack trace:</p>
<pre><code>05-oct-2010 0:56:54 com.google.appengine.tools.info.RemoteVersionFactory getVersion
INFO: Unable to access https://appengine.google.com/api/updatecheck?runtime=java&release=1.3.7&timestamp=1282754401&api_versions=['1.0']
java.net.UnknownHostException: appengine.google.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at java.net.URL.openStream(URL.java:1010)
at com.google.appengine.tools.info.RemoteVersionFactory.getVersion(RemoteVersionFactory.java:76)
at com.google.appengine.tools.info.UpdateCheck.checkForUpdates(UpdateCheck.java:99)
at com.google.appengine.tools.info.UpdateCheck.doNagScreen(UpdateCheck.java:174)
at com.google.appengine.tools.info.UpdateCheck.maybePrintNagScreen(UpdateCheck.java:142)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:150)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:113)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:89)
05-oct-2010 0:56:55 com.google.apphosting.utils.jetty.JettyLogger info
INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
05-oct-2010 0:56:55 com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed E:\development\Tune My Party\src\main\webapp\WEB-INF/appengine-web.xml
05-oct-2010 0:56:55 com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
INFO: Successfully processed E:\development\Tune My Party\src\main\webapp\WEB-INF/web.xml
05-oct-2010 3:56:55 com.google.apphosting.utils.jetty.JettyLogger info
INFO: jetty-6.1.x
05-oct-2010 3:56:57 com.google.apphosting.utils.jetty.JettyLogger warn
ADVERTENCIA: EXCEPTION
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:151)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at org.mortbay.util.Loader.loadClass(Loader.java:91)
at org.mortbay.util.Loader.loadClass(Loader.java:71)
at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:185)
at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:147)
at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:219)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:164)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:113)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:89)
05-oct-2010 3:56:57 com.google.appengine.tools.development.ApiProxyLocalImpl log
GRAVE: [1286251017245000] javax.servlet.ServletContext log: unavailable
javax.servlet.UnavailableException: org.springframework.web.servlet.DispatcherServlet
at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:79)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:185)
at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:147)
at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:219)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:164)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:113)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:89)
05-oct-2010 3:56:57 com.google.apphosting.utils.jetty.JettyLogger warn
ADVERTENCIA: failed dispatcher: java.lang.NullPointerException
05-oct-2010 3:56:57 com.google.apphosting.utils.jetty.JettyLogger warn
ADVERTENCIA: Failed startup of context com.google.apphosting.utils.jetty.DevAppEngineWebAppContext@24988707{/,E:\development\Tune My Party\src\main\webapp}
java.lang.NullPointerException
at java.lang.Class.isAssignableFrom(Native Method)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:256)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:185)
at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:147)
at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:219)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:164)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:113)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:89)
05-oct-2010 3:56:57 com.google.apphosting.utils.jetty.JettyLogger info
INFO: Started SelectChannelConnector@127.0.0.1:8888
05-oct-2010 3:56:57 com.google.appengine.tools.development.DevAppServerImpl start
INFO: The server is running at http://localhost:8888/
</code></pre>
<p>If someone could give me an idea it will be great!!</p>
<p>Thanks!!</p>
| 0 | 3,697 |
how to pass value data between classes/activity in Android?
|
<p>For example i have activity1, activity2, activity3 and lastly valueAllActivity?
how do I pass the data from activity1, activity2, activity3 to --> valueAllActivity?</p>
<p>to pass INT value in each activity to valueAllActivity.</p>
<p>I am very new in developing Android program, so if anyone could guide, it would be an honor :)
Thank you</p>
<p>//Activity1</p>
<pre><code>package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
public class Breakfast extends Activity {
public static int TotalKalori;
ArrayAdapter<String> FoodType1Adapter;
ArrayAdapter<String> DrinkType1Adapter;
String FoodTypeArray[] = { "","white bread"}
int[] valueFoodTypeArray = { 0,20};
String[] DrinkTypeArray = { "","tea"};
int[] valueDrinkTypeArray = { 0,201};
Spinner FoodTypeSpinner;
Spinner DrinkTypeSpinner;
TextView SarapanTotalKalori;
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.breakfast);
FoodTypeSpinner = (Spinner) findViewById(R.id.spinner1);
DrinkTypeSpinner = (Spinner) findViewById(R.id.spinner2);
SarapanTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
// load the default values for the spinners
loadFoodValue1Range();
loadDrinkValue1Range();
}
// nk handle button --> refer calculate button
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
// nk bace dkat spinner
int food1 = getSelectedFood();
int drink1 = getSelectedDrink();
// kira kalori sarapan
// view kalori sarapan
int totalKalori1 = calculateSarapan(food1, drink1);
SarapanTotalKalori.setText(totalKalori1 + "");
//setttlBreakfast(totalKalori1);
Intent b= new Intent(Breakfast.this, Lunch.class);
b.putExtra("totalBreakfast",totalKalori1);
Breakfast.this.startActivity(b);
}
}
public int getSelectedFood() {
String selectedFoodValue = (String) FoodTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodTypeArray.length; i++) {
if (selectedFoodValue.equals(FoodTypeArray[i])) {
index = i;
break;
}
}
return valueFoodTypeArray[index];
}
public int getSelectedDrink() {
String selectedDrinkValue = (String) DrinkTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkTypeArray.length; i++) {
if (selectedDrinkValue.equals(DrinkTypeArray[i])) {
index = i;
break;
}
}
return valueDrinkTypeArray[index];
}
public int calculateSarapan(int food1, int drink1) {
return (int) (food1 + drink1);
}
public void loadFoodValue1Range() {
FoodTypeSpinner.setAdapter(FoodType1Adapter);
// set makanan b4 pilih
FoodTypeSpinner.setSelection(FoodType1Adapter.getPosition("400"));
}
public void loadDrinkValue1Range() {
DrinkTypeSpinner.setAdapter(DrinkType1Adapter);
DrinkTypeSpinner.setSelection(DrinkType1Adapter.getPosition("77"));
}
public void initializeSpinnerAdapters() {
FoodType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodTypeArray);
DrinkType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkTypeArray);
}
}
</code></pre>
<p>//Acitivity 2</p>
<pre><code>package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Lunch extends Activity {
public static int TotalKalori;
private int totalKalori1;
/* private int ttlLunch;
public void setttlLunch(int ttlLunch){
this.ttlLunch=ttlLunch;
}
public int getttlLunch(){
return ttlLunch;
} */
ArrayAdapter<String> FoodType2Adapter;
ArrayAdapter<String> DrinkType2Adapter;
ArrayAdapter<String> LaukType2Adapter;
String FoodType2Array[] = { "","Burger"};
int[] valueFoodType2Array = { 0, 150 };
String DrinkType2Array[] = { "","Pepsi" };
int[] valueDrinkType2Array = { 0,100 };
String LaukType2Array[] = { "","Wings" };
int[] valueLaukType2Array = { 0,200 };
Spinner FoodType2Spinner;
Spinner DrinkType2Spinner;
Spinner LaukType2Spinner;
TextView LunchTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.lunch);
FoodType2Spinner = (Spinner) findViewById(R.id.spinner1);
LaukType2Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType2Spinner = (Spinner) findViewById(R.id.spinner3);
LunchTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue2Range();
loadDrinkValue2Range();
loadLaukValue2Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food2 = getSelectedFood2();
int drink2 = getSelectedDrink2();
int lauk2 = getSelectedLauk2();
int totalKalori2 = calculateLunch(food2, drink2, lauk2);
LunchTotalKalori.setText(totalKalori2 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(Lunch.this, Dinner.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
Lunch.this.startActivity(n);
}
}
public int getSelectedFood2() {
String selectedFoodValue2 = (String) FoodType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType2Array.length; i++) {
if (selectedFoodValue2.equals(FoodType2Array[i])) {
index = i;
break;
}
}
return valueFoodType2Array[index];
}
public int getSelectedDrink2() {
String selectedDrinkValue2 = (String) DrinkType2Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType2Array.length; i++) {
if (selectedDrinkValue2.equals(DrinkType2Array[i])) {
index = i;
break;
}
}
return valueDrinkType2Array[index];
}
public int getSelectedLauk2() {
String selectedLaukValue2 = (String) LaukType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < LaukType2Array.length; i++) {
if (selectedLaukValue2.equals(LaukType2Array[i])) {
index = i;
break;
}
}
return valueLaukType2Array[index];
}
public int calculateLunch(double food2, double drink2, double lauk2) {
return (int) (food2 + drink2 + lauk2);
}
public void loadFoodValue2Range(){
FoodType2Spinner.setAdapter(FoodType2Adapter);
FoodType2Spinner.setSelection(FoodType2Adapter.getPosition("200"));
}
public void loadDrinkValue2Range(){
DrinkType2Spinner.setAdapter(DrinkType2Adapter);
DrinkType2Spinner.setSelection(DrinkType2Adapter.getPosition("77"));
}
public void loadLaukValue2Range(){
LaukType2Spinner.setAdapter(LaukType2Adapter);
LaukType2Spinner.setSelection(LaukType2Adapter.getPosition("2"));
}
public void initializeSpinnerAdapters(){
FoodType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodType2Array);
DrinkType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkType2Array);
LaukType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, LaukType2Array);
}
}
</code></pre>
<p>//Activity 3</p>
<pre><code>package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Dinner extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
/*private int ttlDinner;
public void setttlDinner(int ttlDinner){
this.ttlDinner=ttlDinner;
}
public int getttlDinner(){
return ttlDinner;
} */
ArrayAdapter<String> FoodType3Adapter;
ArrayAdapter<String> ProteinType3Adapter;
ArrayAdapter<String> DrinkType3Adapter;
String FoodType3Array[] = { "","chicken chop" };
int[] valueFoodType3Array = { 0, 204};
String ProteinType3Array[] = { "","chicken breast", };
int[] valueProteinType3Array = { 0, 40 };
String DrinkType3Array[] = { "","mineral water" };
int[] valueDrinkType3Array = { 0, 0};
Spinner FoodType3Spinner;
Spinner ProteinType3Spinner;
Spinner DrinkType3Spinner;
TextView DinnerTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.dinner);
FoodType3Spinner = (Spinner) findViewById(R.id.spinner1);
ProteinType3Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType3Spinner = (Spinner) findViewById(R.id.spinner3);
DinnerTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue3Range();
loadProteinValue3Range();
loadDrinkValue3Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food3 = getSelectedFood3();
int protein3 = getSelectedProtein3();
int drink3 = getSelectedDrink3();
int totalKalori3 = calculateDinner(food3, protein3, drink3);
DinnerTotalKalori.setText(totalKalori3 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlDinner(totalKalori3);
Intent d= new Intent(Dinner.this, CalculateAll.class);
d.putExtra("totalBreakfast", totalKalori1);
d.putExtra("totalLunch", totalKalori2);
d.putExtra("totalDinner", totalKalori3);
startActivity(d);
}
}
public int getSelectedFood3() {
String selectedFoodValue3 = (String) FoodType3Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType3Array.length; i++) {
if (selectedFoodValue3.equals(FoodType3Array[i])) {
index = i;
break;
}
}
return valueFoodType3Array[index];
}
public int getSelectedProtein3() {
String selectedProteinValue3 = (String) ProteinType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < ProteinType3Array.length; i++) {
if (selectedProteinValue3.equals(ProteinType3Array[i])) {
index = i;
break;
}
}
return valueProteinType3Array[index];
}
public int getSelectedDrink3() {
String selectedDrinkValue3 = (String) DrinkType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType3Array.length; i++) {
if (selectedDrinkValue3.equals(DrinkType3Array[i])) {
index = i;
break;
}
}
return valueDrinkType3Array[index];
}
public int calculateDinner(int food3, int protein3, int drink3) {
return (int) (food3 + protein3 + drink3);
}
public void loadFoodValue3Range() {
FoodType3Spinner.setAdapter(FoodType3Adapter);
FoodType3Spinner.setSelection(FoodType3Adapter.getPosition("10"));
}
public void loadProteinValue3Range() {
ProteinType3Spinner.setAdapter(ProteinType3Adapter);
ProteinType3Spinner.setSelection(ProteinType3Adapter.getPosition("99"));
}
public void loadDrinkValue3Range(){
DrinkType3Spinner.setAdapter(DrinkType3Adapter);
DrinkType3Spinner.setSelection(DrinkType3Adapter.getPosition("10"));
}
public void initializeSpinnerAdapters(){
FoodType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, FoodType3Array);
ProteinType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ProteinType3Array);
DrinkType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DrinkType3Array);
}
}
</code></pre>
<p>// CalulateAllActivity - where I want to add up all the value (int) </p>
<pre><code>package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class CalculateAll extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
private int totalKalori3;
ArrayAdapter<String> SexTypeAdapter;
String SexTypeArray[] = { "Lelaki", "Perempuan" };
Spinner SexTypeSpinner;
TextView TotalKaloriSehari;
TextView totalsarapan;
public CalculateAll() {
}
@Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.calculate_all);
SexTypeSpinner = (Spinner) findViewById(R.id.spinnerSex);
TotalKaloriSehari = (TextView) findViewById(R.id.JumlahKalori);
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.buttonKiraAll) {
// public final int TotalKalori;
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
int TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2, totalKalori3);
TotalKaloriSehari.setText(TotalKalori+ "");
// int ttlCAl =getttlBreakfast()+getttlLunch()+getttlDinner();
//String finalString = Integer.toString(calcAll());
//TextView tv1 = (TextView) findViewById(R.id.JumlahKalori);
//tv1.setText(finalString);
}
}
public int calculateTotalKalori(int totalKalori1, int totalKalori2,
int totalKalori3) {
return (int) (totalKalori1 + totalKalori2 + totalKalori3);
}
}
</code></pre>
<p>thank you anyone who try to help me. much appreciated :) as you know, I on my early stage developing the program, so thank you very much everyone :)</p>
| 0 | 5,943 |
Dynamically create a treeview
|
<p>I am trying to create a treeview dynamically using c# and asp.net.</p>
<p>I have created a lazy load treeview using the populate ondemand attribute. </p>
<pre><code>> <asp:TreeView ID="treeView1" runat="server"
> OnTreeNodePopulate="treeview1_TreeNodePopulate"></asp:TreeView>
</code></pre>
<p>Behind code I have loaded my data but initially I populate the parent nodes. What I want to achieve is when i click on parent node I then do a postback and then populate its child and then again populate its child's and so now. I have thousands of data so i dont want all data to be populated due to performance. So thats the reason why I only want to populate the node childs based on selected node. See example below:</p>
<pre><code>>Peter
- - >user1
- - >user2
- - >user3
- - >userPassword
- - >userId
>john
>david
>Jack
- - >user1
- - >user2
- - >userpassword
- - >userId
- - >Permissions
>Laura
- - > admin
- - > permissions
-- > user1
-- > user2
- - >userpassword
- - >userId
- - >Permissions
>...
>...
>...
</code></pre>
<p>As you can see there can be multiple parent nodes and multiple layers. These will be populated dynically based on what i pass in to DB. Everytime i click on node it will expand the node and populate its child using postback and then when you click on its child again it will do a postback and populate its child again etc. So i wanted help on how to create a dynamic treeview.</p>
<p>c# :</p>
<pre><code>private void LoadTreeview()
{
//Load data
// Get data from DB.
//loop through the list and build its parent nodes.
foreach (var dxm in list)
{
TreeNode tnParent = CheckNodeExist(dxm.Node); //I check to see if exists.
if (tnParent== null)
{
TreeNode tn = new TreeNode();
tn.Text = dxm.Node;
tn.Value = dxm.Id.ToString();
tn.SelectAction = TreeNodeSelectAction.None;
tn.Collapse();
treeView1.Nodes.Add(tn);
tn.PopulateOnDemand = true; //lazy load
tnParent= tn;
}
}
</code></pre>
<p>This method above is called on page load.</p>
<p>On TreeNodePopulateEvent: (when a node is clicked on)</p>
<pre><code>protected void treeview1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
ICollection<ITEMS> list = new Collection<ITEMS>();
list = GetData(e.Node.Text); //pass in the node you have selected this will go and check in DB if the node does have any child nodes. If so will return with child nodes.
foreach (var dxm in list)
{
TreeNode tnChild = CheckNodeExist(dxm.Node);
if (tnChild == null)
{
TreeNode tn = new TreeNode();
tn.Text = dxm.Node;
tn.Value = dxm.Id.ToString();
tn.SelectAction = TreeNodeSelectAction.None;
tn.Collapse();
tn.PopulateOnDemand = true;
tnChild = tn;
tnChild.ChildNodes.Add(tnChild);
}
}
}
</code></pre>
| 0 | 1,613 |
Invalid XML document, The document does not have a root element
|
<pre><code> private void btnmap_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode, xmlroot, docNode, Doc;
XmlAttribute xmlatt;
docNode = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmldoc.AppendChild(docNode);
if (rchtextfile.Text == "")
{
MessageBox.Show("Please Select a Text file", "File Name Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
con = new System.Data.SqlClient.SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = @"Server=MDS-SW02; User ID=sa; Pwd=Admin2011; Initial Catalog=xml;";
con.Open();
MessageBox.Show("Database Connected");
String sql = "select Styles from Xml_Tags,pdfelement where Xml_Tags.Mapping_Id=pdfelement.Mapping_Id AND Xml_Tags.Pdf_Tag=pdfelement.Element_Name AND pdfelement.Style=Xml_Tags.Styles";
com = new SqlCommand(sql);
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da.Fill(ds, "xml");
maxrows = ds.Tables["xml"].Rows.Count;
StreamReader objReader = new StreamReader(file, Encoding.Default, true);
do
{
for (int i = 0; i < maxrows; i++)
{
dRow = ds.Tables["xml"].Rows[i];
line = objReader.ReadLine();
if (line == null)
{
//xmldoc.Save(ya);
}
else
{
string st1 = ">";
string st2 = "</";
int end = line.IndexOf(st2);
if (end != -1 && end > 1)
{
st = line.IndexOf(st1);
en = line.IndexOf(st2);
int v = en - st;
sub = line.Substring(st + 1, v - 1);
rchtext.Text = rchtext.Text + sub + "\r\n";
}
String sqll = "select Dtd_Tag from Xml_Tags,pdfelement where Xml_Tags.Mapping_Id=pdfelement.Mapping_Id AND Xml_Tags.Pdf_Tag=pdfelement.Element_Name AND pdfelement.Style=Xml_Tags.Styles";
SqlCommand comm = new SqlCommand(sqll);
SqlDataAdapter daa = new System.Data.SqlClient.SqlDataAdapter(sqll, con);
DataSet ds1 = new DataSet();
daa.Fill(ds1, "xml");
dRow1=ds1.Tables["xml"].Rows[i];
String sqlll = "select Dtd_Attribute_Name from Mapped_Tags_Attributes,Xml_Tags where Mapped_Tags_Attributes.Pdf_Tag=Xml_Tags.Pdf_Tag AND Mapped_Tags_Attributes.Mapping_Id=Xml_Tags.Mapping_Id";
SqlCommand cmd = new SqlCommand(sqlll);
SqlDataAdapter dt = new System.Data.SqlClient.SqlDataAdapter(sqlll, con);
DataSet ds2 = new DataSet();
dt.Fill(ds2, "xml");
dRow2 = ds2.Tables["xml"].Rows[i];
name = XmlConvert.EncodeName(dRow1.ItemArray.GetValue(0).ToString());
xmlnode = xmldoc.CreateElement(name);
Doc = xmldoc.CreateDocumentType(name, null, "E:\\Rachana_mds\\proj\\pdfextraction\\docbook.dtd", null);
xmlroot = xmldoc.CreateElement(name);
xmlatt = xmldoc.CreateAttribute(dRow2.ItemArray.GetValue(0).ToString());
xmlroot.AppendChild(xmlnode);
xmlnode.InnerText = sub;
}
}
}
while (dRow[0].ToString()!=line && !objReader.EndOfStream);
MessageBox.Show("Done");
string filename = @"E:" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Minute + ".xml";
xmldoc.Save(filename);
MessageBox.Show("Successfully saved");
}
con.Close();
}
</code></pre>
<p>I am getting error for this line. <code>...xmldoc.Save(filename);</code></p>
| 0 | 3,592 |
Spring Integration - how to send POST parameters with http outbound-gateway
|
<p>I'm trying to put together a really simple HTTP POST example using Spring Integration and a http outbound-gateway.<br>
I need to be able to send a HTTP POST message with some POST parameters, as I would with <code>curl</code>:</p>
<pre><code>$ curl -d 'fName=Fred&sName=Bloggs' http://localhost
</code></pre>
<p>I can get it working (without the POST parameters) if I send a simple <code>String</code> as the argument to the interface method, but I need to send a pojo, where each property of the pojo becomes a POST parameter.</p>
<p>I have the following SI config:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<int:gateway id="requestGateway"
service-interface="RequestGateway"
default-request-channel="requestChannel"/>
<int:channel id="requestChannel"/>
<int-http:outbound-gateway request-channel="requestChannel"
url="http://localhost"
http-method="POST"
expected-response-type="java.lang.String"/>
</beans>
</code></pre>
<p>My <code>RequestGateway</code> interface looks like this:</p>
<pre><code>public interface RequestGateway {
String echo(Pojo request);
}
</code></pre>
<p>My <code>Pojo</code> class looks like this:</p>
<pre><code>public class Pojo {
private String fName;
private String sName;
public Pojo(String fName, String sName) {
this.fName = fName;
this.sName = sName;
}
.... getters and setters
}
</code></pre>
<p>And my class to kick it all off looks like this:</p>
<pre><code>public class HttpClientDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/si-email-context.xml");
RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);
Pojo pojo = new Pojo("Fred", "Bloggs");
String reply = requestGateway.echo(pojo);
System.out.println("Replied with: " + reply);
}
}
</code></pre>
<p>When I run the above, I get:</p>
<pre><code>org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [Pojo] and content type [application/x-java-serialized-object]
</code></pre>
<p>I've googled a lot for this, but cannot find any examples of sending HTTP POST parameters with an outbound-gateway (I can find lots about setting HTTP Headers, but that's not what I'm trying to do here)<br>
The only thing I did find was <a href="https://stackoverflow.com/questions/20083604/spring-integration-how-to-pass-post-request-parameters-to-http-outbound">spring-integration: how to pass post request parameters to http-outbound</a> but it's a slightly different use case as the OP was trying to send a JSON representation of his pojo which I am not, and the answer talks about setting headers, not POST parameters.</p>
<p>Any help with this would be very much appreciated;<br>
Thanks<br>
Nathan</p>
| 0 | 1,320 |
Getting Spark, Python, and MongoDB to work together
|
<p>I'm having difficulty getting these components to knit together properly. I have Spark installed and working successfully, I can run jobs locally, standalone, and also via YARN. I have followed the steps advised (to the best of my knowledge) <a href="https://github.com/mongodb/mongo-hadoop/wiki/Spark-Usage" rel="nofollow noreferrer">here</a> and <a href="https://github.com/mongodb/mongo-hadoop/blob/master/spark/src/main/python/README.rst" rel="nofollow noreferrer">here</a></p>
<p>I'm working on Ubuntu and the various component versions I have are</p>
<ul>
<li><strong>Spark</strong> spark-1.5.1-bin-hadoop2.6</li>
<li><strong>Hadoop</strong> hadoop-2.6.1</li>
<li><strong>Mongo</strong> 2.6.10</li>
<li><strong>Mongo-Hadoop connector</strong> cloned from <a href="https://github.com/mongodb/mongo-hadoop.git" rel="nofollow noreferrer">https://github.com/mongodb/mongo-hadoop.git</a></li>
<li><strong>Python</strong> 2.7.10</li>
</ul>
<p>I had some difficulty following the various steps such as which jars to add to which path, so what I have added are</p>
<ul>
<li>in <code>/usr/local/share/hadoop-2.6.1/share/hadoop/mapreduce</code> <strong>I have added</strong> <code>mongo-hadoop-core-1.5.0-SNAPSHOT.jar</code></li>
<li>the following <strong>environment variables</strong>
<ul>
<li><code>export HADOOP_HOME="/usr/local/share/hadoop-2.6.1"</code></li>
<li><code>export PATH=$PATH:$HADOOP_HOME/bin</code></li>
<li><code>export SPARK_HOME="/usr/local/share/spark-1.5.1-bin-hadoop2.6"</code></li>
<li><code>export PYTHONPATH="/usr/local/share/mongo-hadoop/spark/src/main/python"</code></li>
<li><code>export PATH=$PATH:$SPARK_HOME/bin</code></li>
</ul>
</li>
</ul>
<p>My Python program is basic</p>
<pre class="lang-python prettyprint-override"><code>from pyspark import SparkContext, SparkConf
import pymongo_spark
pymongo_spark.activate()
def main():
conf = SparkConf().setAppName("pyspark test")
sc = SparkContext(conf=conf)
rdd = sc.mongoRDD(
'mongodb://username:password@localhost:27017/mydb.mycollection')
if __name__ == '__main__':
main()
</code></pre>
<p>I am running it using the command</p>
<pre><code>$SPARK_HOME/bin/spark-submit --driver-class-path /usr/local/share/mongo-hadoop/spark/build/libs/ --master local[4] ~/sparkPythonExample/SparkPythonExample.py
</code></pre>
<p>and I am getting the following output as a result</p>
<pre><code>Traceback (most recent call last):
File "/home/me/sparkPythonExample/SparkPythonExample.py", line 24, in <module>
main()
File "/home/me/sparkPythonExample/SparkPythonExample.py", line 17, in main
rdd = sc.mongoRDD('mongodb://username:password@localhost:27017/mydb.mycollection')
File "/usr/local/share/mongo-hadoop/spark/src/main/python/pymongo_spark.py", line 161, in mongoRDD
return self.mongoPairRDD(connection_string, config).values()
File "/usr/local/share/mongo-hadoop/spark/src/main/python/pymongo_spark.py", line 143, in mongoPairRDD
_ensure_pickles(self)
File "/usr/local/share/mongo-hadoop/spark/src/main/python/pymongo_spark.py", line 80, in _ensure_pickles
orig_tb)
py4j.protocol.Py4JError
</code></pre>
<p>According to <a href="https://github.com/bartdag/py4j/blob/master/py4j-web/advanced_topics.rst#id19" rel="nofollow noreferrer">here</a></p>
<blockquote>
<p>This exception is raised when an exception occurs in the Java client
code. For example, if you try to pop an element from an empty stack.
The instance of the Java exception thrown is stored in the
java_exception member.</p>
</blockquote>
<p>Looking at the source code for <code>pymongo_spark.py</code> and the line throwing the error, it says</p>
<blockquote>
<p>"Error while communicating with the JVM. Is the MongoDB Spark jar on
Spark's CLASSPATH? : "</p>
</blockquote>
<p>So in response, I have tried to be sure the right jars are being passed, but I might be doing this all wrong, see below</p>
<pre><code>$SPARK_HOME/bin/spark-submit --jars /usr/local/share/spark-1.5.1-bin-hadoop2.6/lib/mongo-hadoop-spark-1.5.0-SNAPSHOT.jar,/usr/local/share/spark-1.5.1-bin-hadoop2.6/lib/mongo-java-driver-3.0.4.jar --driver-class-path /usr/local/share/spark-1.5.1-bin-hadoop2.6/lib/mongo-java-driver-3.0.4.jar,/usr/local/share/spark-1.5.1-bin-hadoop2.6/lib/mongo-hadoop-spark-1.5.0-SNAPSHOT.jar --master local[4] ~/sparkPythonExample/SparkPythonExample.py
</code></pre>
<p>I have imported <code>pymongo</code> to the same python program to verify that I can at least access MongoDB using that, and I can.</p>
<p>I know there are quite a few moving parts here so if I can provide any more useful information please let me know.</p>
| 0 | 1,847 |
Resetting a select box in Angular JS with a only one option
|
<p>I don't know if what I'm experiencing is a bug, but I can't seem to reset a select box in Angular JS 1.0.2 (also tested with 1.1.5) where there is only one option. This is for a iPad app wrapped in Phonegap. I've tested in the browser (Safari, Chrome) though and the issue is still there.</p>
<p>I'm working on an app that has many products that are in different categories and sub-categories. When you select a category the route changes and normally resets the select box. And it looks like so:</p>
<p><img src="https://i.stack.imgur.com/0Orqi.png" alt="enter image description here"></p>
<p>However, if you were to choose an option and then decide to choose another sub-category when there is only one option in the select box for a sub-category (when the user clicks one of the images where it says "Other Products") the select box doesn't properly reset. The userthen can't advance from this point to the next select box. It looks like this:</p>
<p><img src="https://i.stack.imgur.com/uQ7ig.png" alt="enter image description here"></p>
<p>I've almost gotten it to work by coming up with this function from the various resources out there, but seems Angular is being quirky. It looks like this with where I've got so far:</p>
<p><img src="https://i.stack.imgur.com/KywIf.png" alt="enter image description here"></p>
<p>The problem is that I want the blank space to be before the option, not after. Then the user has to click the second blank option and then click the option again in order to activate the second select box. </p>
<p>Here is the JS:</p>
<pre><code> $scope.reset = function() {
$scope.variants.selectedIndex = 0;
};
</code></pre>
<p>Here is the JSON. Notice that these set of variants have the same size:</p>
<pre><code>1: {
name: 'Super Awesome Product',
description: 'Cool description',
category: 'viewers',
variants: {
1: {
color: 'Gold',
size: '55-62mm',
productCode: 'FCSTVG',
price: 0,
image: [path + 'FCSTVG-T.png', path + 'FCSTVG.png']
},
2: {
color: 'Silver',
size: '55-62mm',
productCode: 'FCSTVS',
price: 0,
image: [path + 'FCSTVS-t.png', path + 'FCSTVS.png']
}
}
}
};
</code></pre>
<p>And the HTML for the select box:</p>
<pre><code><select ng-model="selectedVariant" ng-show="variants != null">
<option ng-repeat="size in variants" value="{{size}}">
{{size[0].size}}
</option>
</select>
</code></pre>
<p>And the HTML for the where my <code>reset()</code> is clicked. Like I had said, these are the "Other Products" of images below: </p>
<pre><code><div class="other-products">
<h2>Other products</h2>
<div class="slide-container">
<ul ng-show="products != null" style="width: {{products.length * 112}}px">
<li ng-repeat="p in products" ng-show="findDefaultImage(p) != null">
<a href="#" eat-click ng-click="selectProduct(p.id);reset()">
<img ng-src="{{findDefaultImage(p)}}" alt="" />
</a>
</li>
</ul>
</div>
</div>
</code></pre>
<p>I've tried everything, like adding different values to this line <code>$scope.variants.selectedIndex = 0;</code> like -1 or 1. </p>
<p>Any help would be appreciated!</p>
<p>UPDATE: I solved the issue by hardcoding it. Didn't know why I didn't do it before, but I'm still endorsing @Shawn Balestracci answer as it answers the question. </p>
<p>Angular has a tendency to empty out the "index 0" of a select box pushing all of the options back 1 in the select box, but in actuality the option that a user selects is actually the next option in the drop down list. I don't know if this is a bug or a feature. </p>
<p>Here's how I hardcoded the HTML: </p>
<pre><code><select ng-model="selectedVariant" required="required" ng-show="variants != null">
<option style="display:none" value="">PICK ONE:</option>
<option ng-repeat="size in variants" value="{{size}}">
{{size[0].size}}
</option>
</select>
</code></pre>
<p>This stops Angular from pushing back the options in the drop down.</p>
| 0 | 1,577 |
403 forbidden. You don't have permission to access / on this server. localhost. wamp 2.5
|
<p>I am facing problem to access localhost even 127.0.0.1 is not working; from my own computer. But, i have no problem for /phpmyadmin. I am using wamp 2.5 Apache/2.4.9 (Win64) PHP/5.5.12 Server at 127.0.0.1 Port 80 for win 8.1. </p>
<p><strong>httpd.conf</strong></p>
<pre><code>#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'.
#
# NOTE: Where filenames are specified, you must use forward slashes
# instead of backslashes (e.g., "c:/apache" instead of "c:\apache").
# If a drive letter is omitted, the drive on which httpd.exe is located
# will be used by default. It is recommended that you always supply
# an explicit drive letter in absolute paths to avoid confusion.
ServerSignature On
ServerTokens Full
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used. If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "c:/wamp/bin/apache/apache2.4.9"
Define APACHE24 Apache2.4
#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:logs
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 0.0.0.0:80
Listen [::0]:80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule buffer_module modules/mod_buffer.so
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
#LoadModule charset_lite_module modules/mod_charset_lite.so
#LoadModule data_module modules/mod_data.so
#LoadModule dav_module modules/mod_dav.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule dav_lock_module modules/mod_dav_lock.so
#LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
#LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
#LoadModule expires_module modules/mod_expires.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule filter_module modules/mod_filter.so
#LoadModule headers_module modules/mod_headers.so
#LoadModule heartbeat_module modules/mod_heartbeat.so
#LoadModule heartmonitor_module modules/mod_heartmonitor.so
#LoadModule ident_module modules/mod_ident.so
#LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
#LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
#LoadModule ldap_module modules/mod_ldap.so
#LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule log_forensic_module modules/mod_log_forensic.so
#LoadModule lua_module modules/mod_lua.so
LoadModule mime_module modules/mod_mime.so
#LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_html_module modules/mod_proxy_html.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
#LoadModule reflector_module modules/mod_reflector.so
#LoadModule remoteip_module modules/mod_remoteip.so
#LoadModule request_module modules/mod_request.so
#LoadModule reqtimeout_module modules/mod_reqtimeout.so
#LoadModule rewrite_module modules/mod_rewrite.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule session_module modules/mod_session.so
#LoadModule session_cookie_module modules/mod_session_cookie.so
#LoadModule session_crypto_module modules/mod_session_crypto.so
#LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
#LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule status_module modules/mod_status.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule unique_id_module modules/mod_unique_id.so
#LoadModule userdir_module modules/mod_userdir.so
#LoadModule usertrack_module modules/mod_usertrack.so
#LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule xml2enc_module modules/mod_xml2enc.so
LoadModule php5_module "c:/wamp/bin/php/php5.5.12/php5apache2_4.dll"
#PHPIniDir c:/wamp/bin/php/php5.5.12
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User daemon
Group daemon
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin admin@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost:80
HostnameLookups Off
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "c:/wamp/www/"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
AllowOverride none
Require all denied
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
<Directory "c:/wamp/www/">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride all
#
# Controls who can get stuff from this server.
#
# onlineoffline tag - don't remove
Require local
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.php index.php3 index.html index.htm
</IfModule>
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
Require all denied
</Files>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
#ErrorLog "logs/error.log"
ErrorLog "c:/wamp/logs/apache_error.log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "c:/wamp/logs/access.log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access.log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "c:/wamp/bin/apache/apache2.4.9/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock cgisock
</IfModule>
#
# "c:/wamp/bin/apache/apache2.4.9/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "c:/wamp/bin/apache/apache2.4.9/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
AddEncoding x-compress .Z
AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php .php3
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile off
# AcceptFilter: On Windows, none uses accept() rather than AcceptEx() and
# will not recycle sockets between connections. This is useful for network
# adapters with broken driver support, as well as some virtual network
# providers such as vpn drivers, or spam, virus or spyware filters.
AcceptFilter http none
AcceptFilter https none
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
#Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
Include conf/extra/proxy-html.conf
</IfModule>
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
#
# uncomment out the below to deal with user agents that deliberately
# violate open standards by misusing DNT (DNT *must* be a specific
# end-user choice)
#
#<IfModule setenvif_module>
#BrowserMatch "MSIE 10.0;" bad_DNT
#</IfModule>
#<IfModule headers_module>
#RequestHeader unset DNT env=bad_DNT
#</IfModule>
#IncludeOptional "c:/wamp/vhosts/*"
Include "c:/wamp/alias/*"
</code></pre>
<p><strong>phpmyadmin.conf</strong></p>
<pre><code>Alias /phpmyadmin "c:/wamp/apps/phpmyadmin4.1.14/"
# to give access to phpmyadmin from outside
# replace the lines
#
# Require local
#
# by
#
# Require all granted
#
<Directory "c:/wamp/apps/phpmyadmin4.1.14/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
<IfDefine APACHE24>
Require local
</IfDefine>
<IfDefine !APACHE24>
Order Deny,Allow
Deny from all
Allow from localhost ::1 127.0.0.1
</IfDefine>
php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360
</Directory>
</code></pre>
| 0 | 6,961 |
TypeError: "ctx.cart is undefined"
|
<p>I'm working on pizza ordering app, and currently I'm trying to implement Cart.</p>
<p>I have a cart for every user, and each cart contains following details: cart.ts</p>
<pre><code>import { CartItem } from './cartitem';
export class Cart {
id: string;
user: string;
cartitems: CartItem[];
grand_total: number;
}
</code></pre>
<p>User can add items from the menu, which will become my cart items: cartitem.ts</p>
<pre><code>import { Topping } from './topping';
export class CartItem {
id: string;
name: string;
baseprice: number;
toppings: Topping[];
extraprice: number;
quantity= 1;
total: number;
}
</code></pre>
<p>So on adding an item to the cart, I'm making a PUT request on the API endpoint on the user cart, to put the cart item, and in response, I'm returning the cart contents from there.</p>
<p>Here's how my cart.component.ts looks:</p>
<pre><code>import { Component, OnInit, ViewChild, Inject, Injector } from '@angular/core';
import { CartItem } from '../shared/cartitem';
import { ActivatedRoute } from '@angular/router';
import { CartService } from '../services/cart.service';
import { map, catchError } from 'rxjs/operators';
import { Cart } from '../shared/cart';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.scss']
})
export class CartComponent implements OnInit {
cart: Cart;
// cartitems: CartItem[];
constructor(
private route: ActivatedRoute,
private cartService: CartService,
@Inject('BaseURL')public BaseURL) { }
ngOnInit(): void {
this.updateCart();
}
updateCart() {
this.cartService.mysubject.subscribe((value) => {
console.log(value);
this.cartService.getItems().subscribe(response => {
console.log("Response in cart comp:", response);
let cartContent = new Cart();
cartContent.cartitems = response['cartitems'];
cartContent.id = response['id'];
cartContent.grand_total = response['grand_total'];
cartContent.user = response['user'];
this.cart = cartContent;
console.log("Cart is:", this.cart);
});
});
}
}
</code></pre>
<p>Now issue here is that I'm not able to bind the data on cart.component.html side with 'cart', it generates this error- ERROR TypeError: "ctx.cart is undefined".</p>
<p>I'm clueless on how to fix this. </p>
<p><strong>Edit</strong>:
Here is the cart.component.html:</p>
<pre><code><h2>Cart</h2>
<div>{{cart.user}}</div>
<mat-list dense>
<mat-list-item *ngFor="let cartitem of cart.cartitems">
<h2 matLine>Item: {{cartitem.name}}</h2>
<p matLine>Base Price: ${{cartitem.baseprice}}</p>
<p matLine [hidden]="cartitem.toppings == []">Extra Toppings:
<mat-list matLine>
<mat-list-item matLine *ngFor="let topping of cartitem.toppings">
<h4 matLine>{{topping.name}} : + ${{topping.rate}}</h4>
</mat-list-item>
</mat-list>
</p>
<button mat-mini-fab color="primary"><i class="fa fa-minus-circle"></i></button><div></div><button mat-mini-fab color="primary"><i class="fa fa-plus-circle"></i></button>
</mat-list-item>
</mat-list>
<div [hidden]="!cart.cartitems"><h2>Subtotal: ${{cart.grand_total}}</h2></div>
<div [hidden]="cart.cartitems">
<p> Your Cart is Empty!</p>
</div>
</code></pre>
<p>and error log:</p>
<pre><code>ERROR TypeError: "ctx.cart is undefined"
CartComponent_Template cart.component.html:2
Angular 26
executeTemplate
refreshView
refreshComponent
refreshChildComponents
refreshView
refreshComponent
refreshChildComponents
refreshView
refreshDynamicEmbeddedViews
refreshView
refreshComponent
refreshChildComponents
refreshView
renderComponentOrTemplate
tickRootContext
detectChangesInRootView
detectChanges
tick
next
invoke
onInvoke
invoke
run
run
next
schedulerFn
RxJS 5
Angular 8
core.js:6185:19
</code></pre>
| 0 | 1,866 |
Can't build and run an android test project created using "ant create test-project" when tested project has jars in libs directory
|
<p>I have a module that builds an app called MyApp. I have another that builds some testcases for that app, called MyAppTests. They both build their own APKs, and they both work fine from within my IDE. I'd like to build them using ant so that I can take advantage of continuous integration.</p>
<p>Building the app module works fine. I'm having difficulty getting the Test module to compile and run.</p>
<p>Using Christopher's tip from a <a href="https://stackoverflow.com/questions/2466437/how-to-build-an-android-test-app-with-a-dependency-on-another-app-using-ant">previous question</a>, I used <code>android create test-project -p MyAppTests -m ../MyApp -n MyAppTests</code> to create the necessary build files to build and run my test project. This seems to work great (once I remove an unnecessary test case that it constructed for me and revert my AndroidManifest.xml to the one I was using before it got replaced by <code>android create</code>), but I have two problems.</p>
<p>The first problem: The project doesn't compile because it's missing libraries.</p>
<pre><code>$ ant run-tests
Buildfile: build.xml
[setup] Project Target: Google APIs
[setup] Vendor: Google Inc.
[setup] Platform Version: 1.6
[setup] API level: 4
[setup] WARNING: No minSdkVersion value set. Application will install on all Android versions.
-install-tested-project:
[setup] Project Target: Google APIs
[setup] Vendor: Google Inc.
[setup] Platform Version: 1.6
[setup] API level: 4
[setup] WARNING: No minSdkVersion value set. Application will install on all Android versions.
-compile-tested-if-test:
-dirs:
[echo] Creating output directories if needed...
-resource-src:
[echo] Generating R.java / Manifest.java from the resources...
-aidl:
[echo] Compiling aidl files into Java classes...
compile:
[javac] Compiling 1 source file to /Users/mike/Projects/myapp/android/MyApp/bin/classes
-dex:
[echo] Converting compiled files and external libraries into /Users/mike/Projects/myapp/android/MyApp/bin/classes.dex...
[echo]
-package-resources:
[echo] Packaging resources
[aaptexec] Creating full resource package...
-package-debug-sign:
[apkbuilder] Creating MyApp-debug-unaligned.apk and signing it with a debug key...
[apkbuilder] Using keystore: /Users/mike/.android/debug.keystore
debug:
[echo] Running zip align on final apk...
[echo] Debug Package: /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk
install:
[echo] Installing /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk onto default emulator or device...
[exec] 1567 KB/s (288354 bytes in 0.179s)
[exec] pkg: /data/local/tmp/MyApp-debug.apk
[exec] Success
-compile-tested-if-test:
-dirs:
[echo] Creating output directories if needed...
[mkdir] Created dir: /Users/mike/Projects/myapp/android/MyAppTests/gen
[mkdir] Created dir: /Users/mike/Projects/myapp/android/MyAppTests/bin
[mkdir] Created dir: /Users/mike/Projects/myapp/android/MyAppTests/bin/classes
-resource-src:
[echo] Generating R.java / Manifest.java from the resources...
-aidl:
[echo] Compiling aidl files into Java classes...
compile:
[javac] Compiling 5 source files to /Users/mike/Projects/myapp/android/MyAppTests/bin/classes
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:4: package roboguice.test does not exist
[javac] import roboguice.test.RoboUnitTestCase;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:8: package com.google.gson does not exist
[javac] import com.google.gson.JsonElement;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:9: package com.google.gson does not exist
[javac] import com.google.gson.JsonParser;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:11: cannot find symbol
[javac] symbol: class RoboUnitTestCase
[javac] public class GsonTest extends RoboUnitTestCase<MyApplication> {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:6: package roboguice.test does not exist
[javac] import roboguice.test.RoboUnitTestCase;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:7: package roboguice.util does not exist
[javac] import roboguice.util.RoboLooperThread;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:11: package com.google.gson does not exist
[javac] import com.google.gson.JsonObject;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:15: cannot find symbol
[javac] symbol: class RoboUnitTestCase
[javac] public class HttpTest extends RoboUnitTestCase<MyApplication> {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:4: package roboguice.test does not exist
[javac] import roboguice.test.RoboUnitTestCase;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:12: cannot find symbol
[javac] symbol: class RoboUnitTestCase
[javac] public class LinksTest extends RoboUnitTestCase<MyApplication> {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:4: package roboguice.test does not exist
[javac] import roboguice.test.RoboUnitTestCase;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:5: package roboguice.util does not exist
[javac] import roboguice.util.RoboAsyncTask;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:6: package roboguice.util does not exist
[javac] import roboguice.util.RoboLooperThread;
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:12: cannot find symbol
[javac] symbol: class RoboUnitTestCase
[javac] public class SafeAsyncTest extends RoboUnitTestCase<MyApplication> {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectResource': class file for roboguice.inject.InjectResource not found
[javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectResource'
[javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView': class file for roboguice.inject.InjectView not found
[javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView'
[javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView'
[javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView'
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:15: cannot find symbol
[javac] symbol : class JsonParser
[javac] location: class com.myapp.test.GsonTest
[javac] final JsonParser parser = new JsonParser();
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:15: cannot find symbol
[javac] symbol : class JsonParser
[javac] location: class com.myapp.test.GsonTest
[javac] final JsonParser parser = new JsonParser();
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:18: cannot find symbol
[javac] symbol : class JsonElement
[javac] location: class com.myapp.test.GsonTest
[javac] final JsonElement e = parser.parse(s);
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:20: cannot find symbol
[javac] symbol : class JsonElement
[javac] location: class com.myapp.test.GsonTest
[javac] final JsonElement e2 = parser.parse(s2);
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:19: cannot find symbol
[javac] symbol : method getInstrumentation()
[javac] location: class com.myapp.test.HttpTest
[javac] assertEquals("MyApp", getInstrumentation().getTargetContext().getResources().getString(com.myapp.R.string.app_name));
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:62: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.HttpTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:82: cannot find symbol
[javac] symbol : method assertTrue(java.lang.String,boolean)
[javac] location: class com.myapp.test.HttpTest
[javac] assertTrue(result[0], result[0].contains("Search"));
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:87: cannot find symbol
[javac] symbol : class JsonObject
[javac] location: class com.myapp.test.HttpTest
[javac] final JsonObject[] result = {null};
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:90: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.HttpTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:117: cannot find symbol
[javac] symbol : class JsonObject
[javac] location: class com.myapp.test.HttpTest
[javac] final JsonObject[] result = {null};
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:120: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.HttpTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:27: cannot find symbol
[javac] symbol : method assertTrue(boolean)
[javac] location: class com.myapp.test.LinksTest
[javac] assertTrue(m.matches());
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:28: cannot find symbol
[javac] symbol : method assertEquals(java.lang.String,java.lang.String)
[javac] location: class com.myapp.test.LinksTest
[javac] assertEquals( map.get(url), m.group(1) );
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:19: cannot find symbol
[javac] symbol : method getInstrumentation()
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] assertEquals("MyApp", getInstrumentation().getTargetContext().getString(com.myapp.R.string.app_name));
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:27: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:65: cannot find symbol
[javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State)
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] assertEquals(State.TEST_SUCCESS,state[0]);
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:74: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:105: cannot find symbol
[javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State)
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] assertEquals(State.TEST_SUCCESS,state[0]);
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:113: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:144: cannot find symbol
[javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State)
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] assertEquals(State.TEST_SUCCESS,state[0]);
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:154: cannot find symbol
[javac] symbol : class RoboLooperThread
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] new RoboLooperThread() {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:187: cannot find symbol
[javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State)
[javac] location: class com.myapp.test.SafeAsyncTest
[javac] assertEquals(State.TEST_SUCCESS,state[0]);
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/StoriesTest.java:11: cannot access roboguice.activity.GuiceListActivity
[javac] class file for roboguice.activity.GuiceListActivity not found
[javac] public class StoriesTest extends ActivityUnitTestCase<Stories> {
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/StoriesTest.java:21: cannot access roboguice.application.GuiceApplication
[javac] class file for roboguice.application.GuiceApplication not found
[javac] setApplication( new MyApplication( getInstrumentation().getTargetContext() ) );
[javac] ^
[javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/StoriesTest.java:22: incompatible types
[javac] found : com.myapp.activity.Stories
[javac] required: android.app.Activity
[javac] final Activity activity = startActivity(intent, null, null);
[javac] ^
[javac] 39 errors
[javac] 6 warnings
BUILD FAILED
/opt/local/android-sdk-mac/platforms/android-1.6/templates/android_rules.xml:248: Compile failed; see the compiler error output for details.
Total time: 24 seconds
</code></pre>
<p>That's not a hard problem to solve. I'm not sure it's the right thing to do, but I copied the missing libraries (roboguice and gson) from the MyApp/libs directory to the MyAppTests/libs directory and everything seems to compile fine.</p>
<p>But that leads to the second problem, which I'm currently stuck on. The tests compile fine but they won't run:</p>
<pre><code>$ cp ../MyApp/libs/gson-r538.jar libs/
$ cp ../MyApp/libs/roboguice-1.1-SNAPSHOT.jar libs/
0 10:23 /Users/mike/Projects/myapp/android/MyAppTests $ ant run-testsBuildfile: build.xml
[setup] Project Target: Google APIs
[setup] Vendor: Google Inc.
[setup] Platform Version: 1.6
[setup] API level: 4
[setup] WARNING: No minSdkVersion value set. Application will install on all Android versions.
-install-tested-project:
[setup] Project Target: Google APIs
[setup] Vendor: Google Inc.
[setup] Platform Version: 1.6
[setup] API level: 4
[setup] WARNING: No minSdkVersion value set. Application will install on all Android versions.
-compile-tested-if-test:
-dirs:
[echo] Creating output directories if needed...
-resource-src:
[echo] Generating R.java / Manifest.java from the resources...
-aidl:
[echo] Compiling aidl files into Java classes...
compile:
[javac] Compiling 1 source file to /Users/mike/Projects/myapp/android/MyApp/bin/classes
-dex:
[echo] Converting compiled files and external libraries into /Users/mike/Projects/myapp/android/MyApp/bin/classes.dex...
[echo]
-package-resources:
[echo] Packaging resources
[aaptexec] Creating full resource package...
-package-debug-sign:
[apkbuilder] Creating MyApp-debug-unaligned.apk and signing it with a debug key...
[apkbuilder] Using keystore: /Users/mike/.android/debug.keystore
debug:
[echo] Running zip align on final apk...
[echo] Debug Package: /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk
install:
[echo] Installing /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk onto default emulator or device...
[exec] 1396 KB/s (288354 bytes in 0.201s)
[exec] pkg: /data/local/tmp/MyApp-debug.apk
[exec] Success
-compile-tested-if-test:
-dirs:
[echo] Creating output directories if needed...
-resource-src:
[echo] Generating R.java / Manifest.java from the resources...
-aidl:
[echo] Compiling aidl files into Java classes...
compile:
[javac] Compiling 5 source files to /Users/mike/Projects/myapp/android/MyAppTests/bin/classes
[javac] Note: /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java uses unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
-dex:
[echo] Converting compiled files and external libraries into /Users/mike/Projects/myapp/android/MyAppTests/bin/classes.dex...
[echo]
-package-resources:
[echo] Packaging resources
[aaptexec] Creating full resource package...
-package-debug-sign:
[apkbuilder] Creating MyAppTests-debug-unaligned.apk and signing it with a debug key...
[apkbuilder] Using keystore: /Users/mike/.android/debug.keystore
debug:
[echo] Running zip align on final apk...
[echo] Debug Package: /Users/mike/Projects/myapp/android/MyAppTests/bin/MyAppTests-debug.apk
install:
[echo] Installing /Users/mike/Projects/myapp/android/MyAppTests/bin/MyAppTests-debug.apk onto default emulator or device...
[exec] 1227 KB/s (94595 bytes in 0.075s)
[exec] pkg: /data/local/tmp/MyAppTests-debug.apk
[exec] Success
run-tests:
[echo] Running tests ...
[exec]
[exec] android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests:INSTRUMENTATION_RESULT: shortMsg=Class ref in pre-verified class resolved to unexpected implementation
[exec] INSTRUMENTATION_RESULT: longMsg=java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
[exec] INSTRUMENTATION_CODE: 0
BUILD SUCCESSFUL
Total time: 38 seconds
</code></pre>
<p>Any idea what's causing the "Class ref in pre-verified class resolved to unexpected implementation" error?</p>
| 0 | 8,504 |
Android AudioRecord won't initialize
|
<p>I'm trying to implement an app that listens to microphone input (specifically, breathing), and presents data based on it. I'm using the Android class AudioRecord, and when trying to instantiate AudioRecord I get three errors.</p>
<pre><code>AudioRecord: AudioFlinger could not create record track, status: -1
AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
</code></pre>
<p>I found this excellent thread: <a href="https://stackoverflow.com/questions/4843739/audiorecord-object-not-initializing">AudioRecord object not initializing</a></p>
<p>I have borrowed the code from the accepted answer that tries all sample rates, audio formats and channel configurations to try to solve the problem, but it didn't help, I get the above errors for all settings. I have also added a call to AudioRecord.release() on several places according to one of the answers in the thread but it made no difference.</p>
<p>This is my code:</p>
<pre><code>import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
public class SoundMeter {
private AudioRecord ar = null;
private int minSize;
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 32000, 44100 };
public boolean start() {
ar = findAudioRecord();
if(ar != null){
ar.startRecording();
return true;
}
else{
Log.e("SoundMeter", "ERROR, could not create audio recorder");
return false;
}
}
public void stop() {
if (ar != null) {
ar.stop();
ar.release();
}
}
public double getAmplitude() {
short[] buffer = new short[minSize];
ar.read(buffer, 0, minSize);
int max = 0;
for (short s : buffer)
{
if (Math.abs(s) > max)
{
max = Math.abs(s);
}
}
return max;
}
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT, AudioFormat.ENCODING_PCM_FLOAT }) {
for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.d("SoundMeter", "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: " + channelConfig);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
// check if we can instantiate and have a success
Log.d("SoundMeter", "Found a supported bufferSize, attempting to instantiate");
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED){
minSize = bufferSize;
return recorder;
}
else
recorder.release();
}
} catch (Exception e) {
Log.e("SoundMeter", rate + " Exception, keep trying.", e);
}
}
}
}
return null;
}
</code></pre>
<p>}</p>
<p>I have also added the </p>
<pre><code><uses-permission android:name="android.permission.RECORD_AUDIO"/>
</code></pre>
<p>tag to my manifest file, as a child to the manifest tag and a sibling to the application tag according to one of the other answers in the thread mentioned above. I have rebuilt the project after adding this tag.</p>
<p>These are the solutions I find when googling the problem, but they unfortunately don't seem to do it for me.
I am debugging on my Nexus 5 phone (not an emulator). These errors appear upon calling the contructor of AudioRecord. I have rebooted my phone several times to try to release the microphone, to no avail. The project is based on Android 4.4, and my phone is currently running Android 6.0.1.</p>
<p>Would highly appreciate some tips on what else I can try, what I could have missed. Thank you!</p>
| 0 | 1,642 |
How can I run code on a background thread on Android?
|
<p>I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible? </p>
<p>I have tried calling the <code>Thread</code> class in my <code>Activity</code> but my <code>Activity</code> remains in the background for sometime and then it stops. The <code>Thread</code> class also stops working.</p>
<pre><code>class testThread implements Runnable {
@Override
public void run() {
File file = new File( Environment.getExternalStorageDirectory(), "/BPCLTracker/gpsdata.txt" );
int i = 0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile( file, "rw" );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String line =null;
while ( true ) {
HttpEntity entity = null;
try {
if ( isInternetOn() ) {
while ( ( line = in.readLine() ) != null ) {
HttpClient client = new DefaultHttpClient();
String url = "some url";
HttpPost request = new HttpPost( url );
StringEntity se = new StringEntity( line );
se.setContentEncoding( "UTF-8" );
se.setContentEncoding( new BasicHeader( HTTP.CONTENT_TYPE, "application/json" ) );
entity = se;
request.setEntity( entity );
HttpResponse response = client.execute( request );
entity = response.getEntity();
i++;
}
if ( ( line = in.readLine() ) == null && entity != null ) {
file.delete();
testThread t = new testThread();
Thread t1 = new Thread( t );
t1.start();
}
} else {
Thread.sleep( 60000 );
} // end of else
} catch (NullPointerException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}// end of while
}// end of run
}
</code></pre>
| 0 | 1,475 |
Swagger API which is having query string
|
<p>I want to deploy an API which is having query string.This is the API</p>
<pre><code>v1/products?q=circuit breaker&locale=en-GB&pageSize=8&pageNo=1&project=GLOBAL
</code></pre>
<p>Here is how i am implementing</p>
<pre><code>"/v1/products?q={searchText}&locale={ctrCode}&pageSize={pageSize}&pageNo={pageNo}&project={project}&country={country}":{
"get":{
"tags":[
"Search Text"
],
"summary":"Get Products by searching text, countrycode, page number, pagesize, project and country(optional)",
"description":"Get Products by searching text, countrycode, page number, pagesize, project and country(optional)",
"operationId":"getProductName",
"produces":[
"application/json",
"application/xml"
],
"parameters":[
{
"name":"searchText",
"in":"path",
"description":"The Product that needs to be fetched",
"required":true,
"type":"string"
},
{
"name":"ctrCode",
"in":"path",
"description":"The Product locale needs to be fetched. Example=en-GB, fr-FR, etc.",
"required":true,
"type":"string"
},
{
"name":"pageSize",
"in":"path",
"description":"The Product PageSize that needs to be fetched. Example=10, 20 etc.",
"required":true,
"type":"number"
},
{
"name":"pageNo",
"in":"path",
"description":"The Product pageNo that needs to be fetched. Example=1,2 etc.",
"required":true,
"type":"number"
},
{
"name":"project",
"in":"path",
"description":"The Project that needs to be fetched. Example=Mypact, DSL etc.",
"required":true,
"type":"string"
},
{
"name":"country",
"in":"header",
"description":"The Country that needs to be fetched. Example=France, India etc.",
"required":false,
"type":"string"
}
],
"responses":{
"200":{
"description":"successful operation",
"schema":{
"$ref":"#/definitions/Products"
}
},
"400":{
"description":"Invalid Product_id supplied"
},
"404":{
"description":"Product not found"
}
}
}
}
</code></pre>
<p>The country is optional parameter in this. I want the URL should display country only when if user enter some value, else it should not be displayed in the URL.</p>
| 0 | 1,762 |
How to configure jax-rs web service web.xml properly
|
<p>I am trying to implement a jax-rs web service using jersey framework. I have written the web service but I don't fully understand what the web.xml tags mean so I don't know if I have configured it correct but when I try to access the service I get an error. Here is the web service:</p>
<pre><code>package org.LMS.Controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path ("/test")
public class Test {
private String name = "Worked";
@GET
@Produces (MediaType.APPLICATION_XHTML_XML)
public String getTest ()
{
return name;
}
}
</code></pre>
<p>my web.xml is:</p>
<pre><code> <!-- Test web service mapping -->
<servlet>
<display-name>Test</display-name>
<servlet-name>Test</servlet-name>
<servlet-class>org.LMS.Controller</servlet-class>
<init-param>
<param-name>org.LMS.Controller.Test</param-name>
<param-value>eduscope</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<!--end Test web service mapping -->
</code></pre>
<p>and this is the error I'm getting when I try to access my application:
HTTP Status 500 -
type Exception report
message</p>
<p>description The server encountered an internal error () that prevented it from fulfilling this request.</p>
<p>exception</p>
<pre><code>javax.servlet.ServletException: Wrapper cannot find servlet class org.LMS.Controller or a class it depends on
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:679)
root cause
java.lang.ClassNotFoundException: org.LMS.Controller
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:679)
</code></pre>
<p>Can you guys tell me what I'm doing wrong and explain what each tag in the web.xml file means has it relates to web services</p>
| 0 | 1,166 |
Exception of type 'System.OutOfMemoryException' was thrown
|
<p>I have suddenly been getting the memory exception errors for two programs running on different machines and even though it seems there is enough memory, it still shows up. I am creating multiple threads in the program so not sure if this appropriate for this forum but could it be something else related to visual studio or is it definitely memory issue.The one program runs on my desktop using visual studio 2008 with 2 gb ram. The other is running on a windows 2003 server with 4 GB ram using visual basic 2008 express.
Now the module takes a large xml file that is read into a string and then split and stored in a string array. Now the number of chunks can be upto 10000. Now I know this is big, but I have been running this for over a month now and never had the issue. The only other possible related issue I noticed was that I was running out of space on my harddrive but that was quickly solved with a cleanup. Oh yes the processor for my machine is a duo core set at 2.13 GHZ.
It is a console program that makes multiple webrequests but the memory problem arises in one specific module only as I explained above.</p>
<pre><code>Public Shared Function textLoad(ByVal _html As String) As Boolean
Try
//_html is the filestream that was read in
Dim defaultHeading = "xmlns:gnip=""http://www.gnip.com/schemas/2010"" xmlns=""http://www.w3.org/2005/Atom"""
Dim header_of_xml As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbNewLine & "<entry " & defaultHeading & ">"
Dim footer_of_xml As String = "</entry>"
Dim entry As String = String.Empty
Dim xrs As XmlReaderSettings = New XmlReaderSettings()
Dim dupeArray As New ArrayList
Dim stringSplitter() As String = {"</entry>"}
//split the file content based on the closing entry tag
sampleResults = Nothing
sampleResults = _html.Split(stringSplitter, StringSplitOptions.RemoveEmptyEntries)
entryResults.Clear()
If getEntryId(sampleResults) Then
// the following loops seem clumsy but I wanted to dedupe the lists to //ensure that I am not adding duplicate entries and I do this by going to the getEntryID //method and extracting the ids and then comparing them below
For i As Integer = 0 To sampleResults.Count - 1
For j As Integer = 0 To idList.Count - 1
If sampleResults(i).Contains(idList.Item(j)) AndAlso Not dupeArray.Contains(idList.Item(j)) Then
dupeArray.Add(idList.Item(j))
entry = sampleResults(i)
</code></pre>
<p>I did look at taskmanager for identifying resources used by this program and this is what is going on:</p>
<p>Parser.exe CPU = 34
MEM usage = 349,500 K</p>
<p>nothing else intensive is running</p>
<p>Edit <em>_</em>-</p>
<p>Figured out exactly where the problem originates:</p>
<pre><code>**sampleResults = _html.Split(stringSplitter, StringSplitOptions.RemoveEmptyEntries)**
</code></pre>
<p>Can anyone notice anything wrong with this??</p>
| 0 | 1,035 |
Processing huge data with spring batch partitioning
|
<p>I am implementing spring batch job for processing millions of records in a DB table using partition approach as follows -</p>
<ol>
<li><p>Fetch a unique partitioning codes from table in a partitioner and set the same in execution context.</p></li>
<li><p>Create a chunk step with reader,processor and writer to process records based on particular partition code.</p></li>
</ol>
<p>Is this approach is proper or is there any better approach for situation like this? As some partition codes can have more number of records than others,so those with more records might take more time to process than the ones with less records.</p>
<p>Is it possible to create partition/thread to process like thread1 process 1-1000,thread2 process 1001-2000 etc ?</p>
<p>How do I control number of threads getting created as partition codes can be around 100, I would like to create only 20 thread and process in 5 iteration?</p>
<p>What happens if one partition fails, will all processing stop and reverted back?</p>
<p>Following are configurations -</p>
<pre><code> <bean id="MyPartitioner" class="com.MyPartitioner" />
<bean id="itemProcessor" class="com.MyProcessor" scope="step" />
<bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step" >
<property name="dataSource" ref="dataSource"/>
<property name="sql" value="select * from mytable WHERE code = '#{stepExecutionContext[code]}' "/>
<property name="rowMapper">
<bean class="com.MyRowMapper" scope="step"/>
</property>
</bean>
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
<property name="corePoolSize" value="20"/>
<property name="maxPoolSize" value="20"/>
<property name="allowCoreThreadTimeOut" value="true"/>
</bean>
<batch:step id="Step1" xmlns="http://www.springframework.org/schema/batch">
<batch:tasklet transaction-manager="transactionManager">
<batch:chunk reader="itemReader" processor="itemProcessor" writer="itemWriter" commit-interval="200"/>
</batch:tasklet>
</batch:step>
<batch:job id="myjob">
<batch:step id="mystep">
<batch:partition step="Step1" partitioner="MyPartitioner">
<batch:handler grid-size="20" task-executor="taskExecutor"/>
</batch:partition>
</batch:step>
</batch:job>
</code></pre>
<p>Partitioner -</p>
<pre><code>public class MyPartitioner implements Partitioner{
@Override
public Map<String, ExecutionContext> partition(int gridSize)
{
Map<String, ExecutionContext> partitionMap = new HashMap<String, ExecutionContext>();
List<String> codes = getCodes();
for (String code : codes)
{
ExecutionContext context = new ExecutionContext();
context.put("code", code);
partitionMap.put(code, context);
}
return partitionMap;}}
</code></pre>
<p>Thanks</p>
| 0 | 1,035 |
Maven: Failed to deploy artifacts, Acces denied
|
<p>I have a Sonatype Nexus server and I want to deploy a snapshot.</p>
<p>This is a snippet of my settings.xml file:</p>
<pre><code><servers>
<server>
<id>test-snapshots</id>
<username>myname1</username>
<password>mypasswd1</password>
</server>
<server>
<id>test-releases</id>
<username>myname2</username>
<password>mypasswd2</password>
</server>
</servers>
</code></pre>
<p>And this a snippet of my pom.xml file:</p>
<pre><code><distributionManagement>
<repository>
<id>test-releases</id>
<name>Releases</name>
<url>https://nxs.company.com/content/repositories/test-releases</url>
</repository>
<snapshotRepository>
<id>test-snapshots</id>
<name>Snapshots</name>
<url>https://nxs.company.com/content/repositories/test-snapshots</url>
</snapshotRepository>
</distributionManagement>
</code></pre>
<p>Doing a <code>mvn deploy</code> (Maven 3.0.3) I get this error:</p>
<pre><code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.5:deploy
(default-deploy) on project MyProject: Failed to deploy artifacts:
Could not transfer artifact com.company.project:MyProject:jar:1.0.0-20121003.154427-1
from/to test-snapshots (https://nxs.company.com/content/repositories/test-snapshots):
Access denied to: https://nxs.company.com/content/repositories/test-snapshots/
com.company.project/MyProject/1.0.0-SNAPSHOT/MyProject-1.0.0-20121003.154427-1.jar
-> [Help 1]
</code></pre>
<p>And in my Nexus logfile, I see that no credentials are received, so it will try it later with anonymous and this will of course fail. So why are no credentials passed to Nexus?</p>
<pre><code>2012-10-03 17:24:14 DEBUG [1027496148-8353] - org.apache.shiro.session.mgt.DefaultSessionManager - Unable to resolve session ID from SessionKey [org.apache.shiro.web.session.mgt.WebSessionKey@791a17dc]. Returning null to indicate a session could not be found.
2012-10-03 17:24:14 DEBUG [1027496148-8353] - org.sonatype.nexus.security.filter.authc.NexusContentAuthenticationFilter - No authorization found (header or request parameter)
2012-10-03 17:24:14 DEBUG [1027496148-8353] - org.sonatype.nexus.security.filter.authc.NexusContentAuthenticationFilter - No authorization found (header or request parameter)
2012-10-03 17:24:14 DEBUG [1027496148-8353] - org.sonatype.nexus.security.filter.authc.NexusContentAuthenticationFilter - Attempting to authenticate Subject as Anonymous request...
2012-10-04 17:24:14 DEBUG [1027496148-8353] - org.sonatype.security.ldap.realms.DefaultLdapContextFactory - Initializing LDAP context using URL [ldap://10.100.100.1:3268/DC=company,DC=com] and username [ldap@company.com] with pooling [enabled]
</code></pre>
| 0 | 1,147 |
java.lang.RuntimeException: setAudioSource failed
|
<p>I am new to android development. I am just trying to record an audio with android studio(2.1.1) testing with 6.0.1 Marshmallow device.</p>
<pre><code>public class MainActivity extends AppCompatActivity {
Button start, stop;
public MediaRecorder recorder = null;
public String fileextn = ".mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start_button);
stop = (Button) findViewById(R.id.stop_button);
start.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_button:
startRecord();
case R.id.stop_button:
stoprecord();
}
}
}
);
}
public void startRecord() {
recorder = new MediaRecorder();
recorder.reset();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setOutputFile(getFilePath());
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stoprecord() {
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
private String getFilePath() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, "MediaRecorderSample");
if (!file.exists())
file.mkdirs();
return (file.getAbsolutePath() + "/" + fileextn);
}
}
</code></pre>
<p>By the way, I have included the uses-permission in manifext.xml file. </p>
<p><strong>This is what i get in the Android Monitor:</strong> </p>
<pre><code> 05-18 11:08:36.576 10414-10414/com.example.gk.audiocapture E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.gk.audiocapture, PID: 10414
java.lang.RuntimeException: stop failed.
at android.media.MediaRecorder.stop(Native Method)
at com.example.gk.audiocapture.MainActivity.stoprecord(MainActivity.java:65)
at com.example.gk.audiocapture.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
</code></pre>
<p>I tried for some answers, didn't find any.</p>
<p>MY AndroidManifest.xml: </p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gk.audiocapture">
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</code></pre>
<p></p>
| 0 | 3,075 |
How to decode json into structs
|
<p>I'm trying to decode some json in Go but some fields don't get decoded.
See the code running in browser <a href="http://play.golang.org/p/ZunE4_lKKv" rel="nofollow noreferrer">here</a>: </p>
<p>What am I doing wrong?</p>
<p>I need only the MX records so I didn't define the other fields. As I understand from the godoc you don't need to define the fields you don't use/need.</p>
<pre><code>// You can edit this code!
// Click here and start typing.
package main
import "fmt"
import "encoding/json"
func main() {
body := `
{"response": {
"status": "SUCCESS",
"data": {
"mxRecords": [
{
"value": "us2.mx3.mailhostbox.com.",
"ttl": 1,
"priority": 100,
"hostName": "@"
},
{
"value": "us2.mx1.mailhostbox.com.",
"ttl": 1,
"priority": 100,
"hostName": "@"
},
{
"value": "us2.mx2.mailhostbox.com.",
"ttl": 1,
"priority": 100,
"hostName": "@"
}
],
"cnameRecords": [
{
"aliasHost": "pop.a.co.uk.",
"canonicalHost": "us2.pop.mailhostbox.com."
},
{
"aliasHost": "webmail.a.co.uk.",
"canonicalHost": "us2.webmail.mailhostbox.com."
},
{
"aliasHost": "smtp.a.co.uk.",
"canonicalHost": "us2.smtp.mailhostbox.com."
},
{
"aliasHost": "imap.a.co.uk.",
"canonicalHost": "us2.imap.mailhostbox.com."
}
],
"dkimTxtRecord": {
"domainname": "20a19._domainkey.a.co.uk",
"value": "\"v=DKIM1; g=*; k=rsa; p=DkfbhO8Oyy0E1WyUWwIDAQAB\"",
"ttl": 1
},
"spfTxtRecord": {
"domainname": "a.co.uk",
"value": "\"v=spf1 redirect=_spf.mailhostbox.com\"",
"ttl": 1
},
"loginUrl": "us2.cp.mailhostbox.com"
}
}}`
type MxRecords struct {
value string
ttl int
priority int
hostName string
}
type Data struct {
mxRecords []MxRecords
}
type Response struct {
Status string `json:"status"`
Data Data `json:"data"`
}
type apiR struct {
Response Response
}
var r apiR
err := json.Unmarshal([]byte(body), &r)
if err != nil {
fmt.Printf("err was %v", err)
}
fmt.Printf("decoded is %v", r)
}
</code></pre>
| 0 | 1,188 |
Babel unexpected token import when running mocha tests
|
<p>The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.</p>
<p>I have two projects (lets call them A and B) which both use ES6 module syntax. In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error: </p>
<blockquote>
<p>SyntaxError: Unexpected token import</p>
</blockquote>
<p>Which is preceded by this alleged erroneous line of code from Project B:</p>
<blockquote>
<p>(function (exports, require, module, __filename, __dirname) { import
createBrowserHistory from 'history/lib/createBrowserHistory';</p>
</blockquote>
<p>The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.</p>
<p>Full Stack Trace:</p>
<pre><code> SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Module._extensions..js (module.js:405:10)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (actionCreators.js:4:17)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
at Array.forEach (native)
at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
</code></pre>
<p>Here is my test command from package.json:</p>
<pre><code>"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"
</code></pre>
<p>This StackOverflow post is similar but doesn't offer a solution for my use of the command line:
<a href="https://stackoverflow.com/questions/31822593/import-a-module-from-node-modules-with-babel-but-failed">import a module from node_modules with babel but failed</a></p>
| 0 | 1,499 |
org.hibernate.HibernateException: /hibernate.cfg.xml not found
|
<p>I'm trying to use hibernate with spring 3 mvc but at the moment I get this exception thrown. I think I need to define my <code>hibernate.cfg.xml</code> somewhere, but not sure where?</p>
<p>I basically followed this example here <a href="http://www.nabeelalimemon.com/blog/2010/05/spring-3-integrated-with-hibernate-part-a/">http://www.nabeelalimemon.com/blog/2010/05/spring-3-integrated-with-hibernate-part-a/</a> And in particularly saw this line of code there that suppose to "magically" find my hibernate.cfg file using this:</p>
<pre><code>return new Configuration().configure().buildSessionFactory();
</code></pre>
<p>I'm guessing that is not correct? i currently have my hibernate.cfg file inside <code>src/com/jr/hibernate/</code></p>
<p>below is my cfg file:</p>
<pre><code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/racingleague</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<property name="hibernate.format_sql">true</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--property name="hbm2ddl.auto">update</property-->
<mapping resource="com/jr/model/hibernateMappings/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
</code></pre>
<p>my hibernate utils class:</p>
<pre><code>package com.jr.utils;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
</code></pre>
<p>which gets called bu this abstract class:</p>
<pre><code>package com.jr.db;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import com.jr.utils.HibernateUtils;
public abstract class DbWrapper<T> {
private static SessionFactory sessionFactory = null;
private static Session session;
public DbWrapper() {
setSessionFactory();
}
private void setSessionFactory() {
sessionFactory = HibernateUtils.buildSessionFactory();
session = sessionFactory.getCurrentSession();
}
public boolean addNewItem(T dbItem) {
try {
session.getTransaction().begin();
session.save(dbItem);
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("error exception when adding new item to table"
+ e);
} finally {
session.close();
sessionFactory.close();
}
return false;
}
public abstract boolean removeItem(String uid);
public abstract boolean modifyItem(String uid, T item);
}
</code></pre>
<p>And here is the controller that originally does some hibernate stuff:</p>
<pre><code>private Logger logger = Logger.getLogger(UserController.class);
private UserDb userDb;
@RequestMapping(value = "/user/registerSuccess", method = RequestMethod.POST)
public String submitRegisterForm(@Valid User user, BindingResult result) {
// validate the data recieved from user
logger.info("validate the data recieved from user");
if (result.hasErrors()) {
logger.info("form has "+result.getErrorCount()+" errors");
return "account/createForm";
} else{
// if everthings ok, add user details to database
logger.info("if everthings ok, add user details to database");
userDb = new UserDb();
userDb.addNewItem(user);
// display success and auto log the user to the system.
return "account/main";
}
}
</code></pre>
<p>Cheers in advance. I also have all my table hibvernate xml mappings in the same location as my hibernate.cfg.xml file</p>
| 0 | 2,082 |
Java: download CSV file with REST service
|
<p>I am trying to download csv file from REST endpoint. Here is what I am trying.</p>
<pre><code>@ApiOperation(value = "export",
notes = "Export Cache details for a given criteria")
@ApiImplicitParams({
})
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Internal Server Error") })
@RequestMapping(method = RequestMethod.GET, value = "/export")
public ResponseEntity export( HttpServletRequest request )
{
CacheDataManager cacheResultHandler = new CacheDataManager();
InputStreamResource inputStreamResource = null;
HttpHeaders httpHeaders = new HttpHeaders();
long contentLengthOfStream;
try
{
inputStreamResource = cacheResultHandler.exportCacheResults( request );
httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "test.csv" );
contentLengthOfStream = inputStreamResource.contentLength();
httpHeaders.setContentLength( contentLengthOfStream );
}
catch ( IOException e )
{
e.printStackTrace();
}
return new ResponseEntity( inputStreamResource, httpHeaders, HttpStatus.OK );
}
</code></pre>
<p>My export function.</p>
<pre><code>@Override
public InputStreamResource export( HttpServletRequest request )
{
StringBuilder sb = new StringBuilder();
StringBuilder fileName = new StringBuilder( VALIDATION_REPORT );
sb.append( "Column A" );
sb.append( "," );
sb.append( "Column B" );
sb.append( "\n" );
try
{
sb.append( "TEST A");
sb.append( ',' );
sb.append( "TEST B" );
sb.append( '\n' );
fileName.append( "_" ).append( sdf.format( new Date() ) ).append( ".csv" );
return CsvFileWriter.csvFileWrite( fileName.toString(), sb );
}
catch ( Exception e )
{
e.printStackTrace();
}
return null;
}
</code></pre>
<p><strong>CsvFileWriter.java</strong></p>
<pre><code>package it.app.ext.dashboard.util;
import org.springframework.core.io.InputStreamResource;
import java.io.*;
public class CsvFileWriter
{
public static InputStreamResource csvFileWrite( String fileName, StringBuilder content ) throws FileNotFoundException
{
File file = null;
PrintWriter pw = null;
try
{
file = new File( fileName );
pw = new PrintWriter( file );
pw.write( content.toString() );
}
catch ( FileNotFoundException e )
{
e.printStackTrace();
}
finally
{
pw.flush();
pw.close();
}
InputStream inputStream = new FileInputStream( file );
return new InputStreamResource( inputStream );
}
</code></pre>
<p>}</p>
<p>File is generating with content inside the <strong>tomcat/bin</strong> folder but exception occurred.</p>
<pre><code>java.lang.IllegalStateException: InputStream has already been read - do not use InputStreamResource if a stream needs to be read multiple times.
</code></pre>
<p>I want to download a .csv file once call this endpoint.</p>
<p>Any suggestions are appreciated.</p>
<p>Thanks You</p>
| 0 | 1,196 |
Angular 2/4 how to add multiple headers to http post
|
<p>I've problem with adding additonal headers to html post.
with curl works very well like with postman.
I can't add Authorization header to post request.</p>
<p>my problem is similar to <a href="https://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request">https://stackoverflow.com/questions/39408413/angular2-http-post-how-to-send-authorization-header</a> </p>
<p>my code:</p>
<pre><code> getToken(){
let headers = new Headers;
headers.append('Authorization', 'Basic ' + btoa(Spotify.clientId + ':' + Spotify.clientSecret));
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
let params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
console.log(
this.http.post(Spotify.tokenUrl, params.toString(), options).subscribe()
)
}
</code></pre>
<p>Now, when I try to get this none of those two headers aren't added</p>
<pre><code>OPTIONS /api/token HTTP/1.1
Host: accounts.spotify.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://172.21.7.171:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/59.0.3071.86 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */ *
Referer: http://172.21.7.171:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: pl,en;q=0.8,en-US;q=0.6
</code></pre>
<p>But when I comment Authorization header, Content-Type is added and a get invalid_client with error 400</p>
<pre><code>POST /api/token HTTP/1.1
Host: accounts.spotify.com
Connection: keep-alive
Content-Length: 29
Accept: application/json, text/plain, */ *
Origin: http://172.21.7.171:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/59.0.3071.86 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://172.21.7.171:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: pl,en;q=0.8,en-US;q=0.6
</code></pre>
<p>But when I comment Content-Type header and append Authorization I have the same issue like first time - no added header :/</p>
<p>I'have angular 4.2 - installed and upgraded from ng cli</p>
<p>How to add additonal headers to POST? in Postman this work perfect</p>
<p><a href="https://i.stack.imgur.com/0FlhS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0FlhS.png" alt="enter image description here"></a></p>
<p>===== Edited ====
Thanks for reply, but both solutions don't work </p>
<pre><code>getToken(){
let options = new RequestOptions();
options.headers = new Headers();
options.headers.append('Authorization', Spotify.token);
options.headers.append('Content-Type', 'application/x-www-form-urlencoded')
let params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
console.log(
this.http.post(Spotify.tokenUrl, params.toString(), options).subscribe()
)
}
</code></pre>
<p>now if I comment 'Authorization' Content-Type is added to Request with AUthorization i none header isn't added and body isn't sent too</p>
<p>========= edited =========</p>
<p>According to this topic <a href="https://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request">Angular2 - set headers for every request</a> I've created default-request-options.service.ts </p>
<pre><code>import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, Headers } from '@angular/http';
@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {
private superHeaders: Headers;
get headers() {
// Set the default 'Content-Type' header
this.superHeaders.set('Content-Type', 'application/json');
const token = localStorage.getItem('authToken');
if(token) {
this.superHeaders.set('Authorization', `Bearer ${token}`);
} else {
this.superHeaders.delete('Authorization');
}
return this.superHeaders;
}
set headers(headers: Headers) {
this.superHeaders = headers;
}
constructor() {
super();
}
}
export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };
</code></pre>
<p>in app.module.ts</p>
<pre><code>import { requestOptionsProvider, DefaultRequestOptions } from './default-request-options.service'
...
providers: [
requestOptionsProvider
],
</code></pre>
<p>now in my service</p>
<pre><code>import { DefaultRequestOptions } from '../default-request-options.service';
getToken(){
let params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
let options = new DefaultRequestOptions();
//options.headers = new Headers();
// options.headers.append('Authorization', Spotify.basicCode);
//options.headers.append('Content-Type', 'application/x-www-form-urlencoded');
// options.body = params.toString();
// options.method = 'post';
console.log(
this.http.post(Spotify.tokenUrl, params.toString(), options).subscribe()
)
}
</code></pre>
<p>And I have errors still :/ Headers aren't added :/</p>
<p>I've made some investigations, tests. When I try send only 'Content-type=application/x-www-form-urlencoded' I get reply with error 'bad client' because I don't send Authorization. Problem occours when I try to add another header with Authorization.</p>
<p>I've made similar with GET method and I can add only 'Authorization' header, none other. If I added for example "X-Authorization" header that GET method is changed to OPTIONS method like in POST :/</p>
<p>In console I get error:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="https://accounts.spotify.com/api/token" rel="nofollow noreferrer">https://accounts.spotify.com/api/token</a>.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://localhost:4200" rel="nofollow noreferrer">http://localhost:4200</a>' is therefore not allowed
access.</p>
</blockquote>
<p>Is there any way to provide more in one header in http post request? </p>
<p>I added only Content-Type header with body. I got reply with 400 code because my request was without Authorization header. In firefox I edited this reqest by adding Authorization to headers and I got what I wanted code 200 with token :)
So the problem is with Angular not with browser.</p>
<p>==== EDITED ====
Spotify says that i shouldn't use clientid and client+secret. i should use this:</p>
<pre><code> let options = new RequestOptions()
options.headers = new Headers();
options.params = new URLSearchParams();
options.params.append('client_id', Spotify.clientId);
options.params.append('redirect_uri', 'http://localhost:4200/callback');
options.params.append('scope', 'user-read-private user-read-email');
options.params.append('response_type', 'token');
options.params.append('state', '789935');
this.http.get('https://accounts.spotify.com/authorize', options )
.subscribe(
res=> {
console.log('res',res)
}
)
</code></pre>
<p>now i get 200 but callback isnt displayed. in console i have:</p>
<pre><code>XMLHttpRequest cannot load https://accounts.spotify.com/authorize?client_id=2100FakeClientId45688548d5a2b9…scope=user-read-private%20user-read-email&response_type=token&state=789935. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
</code></pre>
<p>and this comes from "callback:1"</p>
<p>I've made route for callback and callbackComponent</p>
<pre><code>import { Component } from '@angular/core';
// import { AuthService } from './auth.service';
@Component({
template: `<h2>callback</h2>`
})
export class CallbackComponent {
}
</code></pre>
<p>but in console I've error still :/</p>
<pre><code>localhost/:1 XMLHttpRequest cannot load https://accounts.spotify.com/authorize?client_id=21006d1ceeFakeClient548d5a2b9…scope=user-read-private%20user-read-email&response_type=token&state=789935. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
</code></pre>
<p>but this time this comes from 'localhost/:1</p>
<p>In postman I het full html to redirect. How can I make this redirection in Angular 2</p>
| 0 | 2,914 |
How to draw an arrow on every polyline segment on Google Maps V3
|
<p>I was looking for a solution to this problem on stackoverflow but since I couldn't find the accurate solution I ended up solving it myself and post it here, hope it help.</p>
<p>Google Maps provides you the Polyline feature, which based on a list of coordinates can draw a series of lines joining all of them.</p>
<p>You can draw a polyline with a single arrow with the following code:</p>
<pre><code> var allCoordinates = [
new google.maps.LatLng(26.291, 148.027),
new google.maps.LatLng(26.291, 150.027),
new google.maps.LatLng(22.291, 153.027),
new google.maps.LatLng(18.291, 153.027)
];
var polyline = new google.maps.Polyline({
path: allCoordinates,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
geodesic: true,
icons: [{
icon: {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW},
offset: '100%'
}]
});
</code></pre>
<p>The problem here is that the arrow will be only drawn in the last segment as shown in the next picture, but sometimes the route could be not so straightforward and we need to add an arrow on every segment.</p>
<p>The attribute 'repeat' inside the icon definition could be another option but allows only to define a measure in pixels and that definelty won't match with every change of direction on the polyline.</p>
<p><img src="https://i.stack.imgur.com/c5a3x.png" alt="PICTURE1"></p>
<p>So, one way I found to achive this was to make several polylines, one per segment allowing in that case the arrow to be drawn on each one. This is the code:</p>
<pre><code> var allCoordinates = [
new google.maps.LatLng(26.291, 148.027),
new google.maps.LatLng(26.291, 150.027),
new google.maps.LatLng(22.291, 153.027),
new google.maps.LatLng(18.291, 153.027)
];
for (var i = 0, n = allCoordinates.length; i < n; i++) {
var coordinates = new Array();
for (var j = i; j < i+2 && j < n; j++) {
coordinates[j-i] = allCoordinates[j];
}
var polyline = new google.maps.Polyline({
path: coordinates,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
geodesic: true,
icons: [{
icon: {path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW},
offset: '100%'
}]
});
polyline.setMap(map);
polylines.push(polyline);
}
</code></pre>
<p>And this is the Picture:</p>
<p><img src="https://i.stack.imgur.com/zfzWF.png" alt="PICTURE2"></p>
<p>I hope this works for anyone who is looking for something like this!</p>
| 0 | 1,186 |
Doctrine2 - "class" is not a valid entity or mapped super class
|
<p>I get exception <code>Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class "Users" is not a valid entity or mapped super class</code> every time when I run the next code:</p>
<p><strong>test.php</strong></p>
<pre><code><?php
require_once "vendor/autoload.php";
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
$paths = array(dirname(__FILE__)."/entities");
$isDevMode = false;
// the connection configuration
$dbParams = array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'pass',
'dbname' => 'snabcentr',
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$em = EntityManager::create($dbParams, $config);
$user = $em->find("Users", 5);
</code></pre>
<p><strong>entities/Users.php</strong></p>
<pre><code><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Users
*
* @ORM\Table(name="users")
* @ORM\Entity
*/
class Users
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=255, nullable=true)
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255, nullable=true)
*/
private $password;
/**
* @var string
*
* @ORM\Column(name="type", type="string", nullable=true)
*/
private $type;
/**
* @var string
*
* @ORM\Column(name="client_inn", type="string", length=255, nullable=true)
*/
private $clientInn;
/**
* @var string
*
* @ORM\Column(name="client_ogrn", type="string", length=255, nullable=true)
*/
private $clientOgrn;
/**
* @var string
*
* @ORM\Column(name="client_rs", type="string", length=255, nullable=true)
*/
private $clientRs;
/**
* @var string
*
* @ORM\Column(name="client_ks", type="string", length=255, nullable=true)
*/
private $clientKs;
/**
* @var string
*
* @ORM\Column(name="client_bik", type="string", length=255, nullable=true)
*/
private $clientBik;
/**
* @var string
*
* @ORM\Column(name="client_uaddress", type="string", length=255, nullable=true)
*/
private $clientUaddress;
/**
* @var string
*
* @ORM\Column(name="client_faddress", type="string", length=255, nullable=true)
*/
private $clientFaddress;
/**
* @var string
*
* @ORM\Column(name="client_daddress", type="string", length=255, nullable=true)
*/
private $clientDaddress;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="notes", type="text", nullable=true)
*/
private $notes;
/**
* @var \DateTime
*
* @ORM\Column(name="added_date", type="datetime", nullable=true)
*/
private $addedDate;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set email
*
* @param string $email
* @return Users
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* @param string $password
* @return SnabUsers
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set type
*
* @param string $type
* @return SnabUsers
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set clientInn
*
* @param string $clientInn
* @return SnabUsers
*/
public function setClientInn($clientInn)
{
$this->clientInn = $clientInn;
return $this;
}
/**
* Get clientInn
*
* @return string
*/
public function getClientInn()
{
return $this->clientInn;
}
/**
* Set clientOgrn
*
* @param string $clientOgrn
* @return SnabUsers
*/
public function setClientOgrn($clientOgrn)
{
$this->clientOgrn = $clientOgrn;
return $this;
}
/**
* Get clientOgrn
*
* @return string
*/
public function getClientOgrn()
{
return $this->clientOgrn;
}
/**
* Set clientRs
*
* @param string $clientRs
* @return SnabUsers
*/
public function setClientRs($clientRs)
{
$this->clientRs = $clientRs;
return $this;
}
/**
* Get clientRs
*
* @return string
*/
public function getClientRs()
{
return $this->clientRs;
}
/**
* Set clientKs
*
* @param string $clientKs
* @return SnabUsers
*/
public function setClientKs($clientKs)
{
$this->clientKs = $clientKs;
return $this;
}
/**
* Get clientKs
*
* @return string
*/
public function getClientKs()
{
return $this->clientKs;
}
/**
* Set clientBik
*
* @param string $clientBik
* @return SnabUsers
*/
public function setClientBik($clientBik)
{
$this->clientBik = $clientBik;
return $this;
}
/**
* Get clientBik
*
* @return string
*/
public function getClientBik()
{
return $this->clientBik;
}
/**
* Set clientUaddress
*
* @param string $clientUaddress
* @return SnabUsers
*/
public function setClientUaddress($clientUaddress)
{
$this->clientUaddress = $clientUaddress;
return $this;
}
/**
* Get clientUaddress
*
* @return string
*/
public function getClientUaddress()
{
return $this->clientUaddress;
}
/**
* Set clientFaddress
*
* @param string $clientFaddress
* @return SnabUsers
*/
public function setClientFaddress($clientFaddress)
{
$this->clientFaddress = $clientFaddress;
return $this;
}
/**
* Get clientFaddress
*
* @return string
*/
public function getClientFaddress()
{
return $this->clientFaddress;
}
/**
* Set clientDaddress
*
* @param string $clientDaddress
* @return SnabUsers
*/
public function setClientDaddress($clientDaddress)
{
$this->clientDaddress = $clientDaddress;
return $this;
}
/**
* Get clientDaddress
*
* @return string
*/
public function getClientDaddress()
{
return $this->clientDaddress;
}
/**
* Set name
*
* @param string $name
* @return SnabUsers
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set notes
*
* @param string $notes
* @return SnabUsers
*/
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
/**
* Get notes
*
* @return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Set addedDate
*
* @param \DateTime $addedDate
* @return SnabUsers
*/
public function setAddedDate($addedDate)
{
$this->addedDate = $addedDate;
return $this;
}
/**
* Get addedDate
*
* @return \DateTime
*/
public function getAddedDate()
{
return $this->addedDate;
}
}
</code></pre>
<p>Do you have any ideas why? eAccelerator is not set up. Doctrine v 2.2, PHP v 5.3.22, zend engine 2.3.0</p>
| 0 | 4,056 |
How do I debug GlassFish 3 using Eclipse Helios?
|
<p>I am using the GlassFish 3 server adapter with Eclipse Helios 3.6. I can start the server using the <em>Servers</em> view in Eclipse, and things run just fine - but I am not able to debug my code.</p>
<p>After using the GF Admin Console to enable debugging (<em>Configuration → JVM Settings → Debug</em>, then restart the server), clicking <em>Debug</em> (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>D</kbd>) gives me an error window:</p>
<p><img src="https://i.stack.imgur.com/YdK1k.png" alt="error window"></p>
<p>I'm guessing this is because Eclipse can't connect to the JVM's debug port (9009 by default).</p>
<p>What is the proper way to set up GlassFish 3 debugging in Helios?</p>
<hr>
<h2>Edit</h2>
<p>Re: @The Elite Gentleman, there aren't any errors that show up in the console. Here's an example:</p>
<pre><code>Nov 29, 2010 11:47:42 AM com.sun.enterprise.admin.launcher.GFLauncherLogger info
INFO: JVM invocation command line:
C:\Program Files\Java\jdk1.6.0_22\bin\java.exe
-cp
C:/glassfishv3/glassfish/modules/glassfish.jar
-XX:+UnlockDiagnosticVMOptions
-XX:MaxPermSize=192m
-XX:NewRatio=2
-XX:+LogVMOutput
-XX:LogFile=C:\glassfishv3\glassfish\domains\myDomain/logs/jvm.log
-Xmx512m
-client
-javaagent:C:/glassfishv3/glassfish/lib/monitor/btrace-agent.jar=unsafe=true,noServer=true
-Dosgi.shell.telnet.maxconn=1
-Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
-Dfelix.fileinstall.dir=C:\glassfishv3\glassfish/modules/autostart/
-Djavax.net.ssl.keyStore=C:\glassfishv3\glassfish\domains\myDomain/config/keystore.jks
-Dosgi.shell.telnet.port=6666
-Djava.security.policy=C:\glassfishv3\glassfish\domains\myDomain/config/server.policy
-Dfelix.fileinstall.poll=5000
-Dcom.sun.aas.instanceRoot=C:\glassfishv3\glassfish\domains\myDomain
-Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
-Dosgi.shell.telnet.ip=127.0.0.1
-Djava.endorsed.dirs=C:\glassfishv3\glassfish/modules/endorsed;C:\glassfishv3\glassfish/lib/endorsed
-Dcom.sun.aas.installRoot=C:\glassfishv3\glassfish
-Djava.ext.dirs=C:\Program Files\Java\jdk1.6.0_22/lib/ext;C:\Program Files\Java\jdk1.6.0_22/jre/lib/ext;C:\glassfishv3\glassfish\domains\myDomain/lib/ext
-Dfelix.fileinstall.bundles.new.start=true
-Djavax.net.ssl.trustStore=C:\glassfishv3\glassfish\domains\myDomain/config/cacerts.jks
-Dcom.sun.enterprise.security.httpsOutboundKeyAlias=s1as
-Djava.security.auth.login.config=C:\glassfishv3\glassfish\domains\myDomain/config/login.conf
-DANTLR_USE_DIRECT_CLASS_LOADING=true
-Dfelix.fileinstall.debug=1
-Dorg.glassfish.web.rfc2109_cookie_names_enforced=false
-Djava.library.path=C:/glassfishv3/glassfish/lib;C:/Program Files/Java/jdk1.6.0_22/bin;C:/glassfishv3/glassfish;C:/Windows/Sun/Java/bin;C:/Windows/System32;C:/Windows;C:/Program Files/Java/jdk1.6.0_22/jre/bin/server;C:/Program Files/Java/jdk1.6.0_22/jre/bin;C:/Program Files/Java/jdk1.6.0_22/jre/lib/amd64;C:/Python26/Scripts;C:/Python26;C:/Windows/System32/wbem;C:/Program Files (x86)/ATI Technologies/ATI.ACE/Core-Static;C:/Program Files (x86)/Common Files/Roxio Shared/DLLShared;C:/Program Files (x86)/Common Files/Roxio Shared/10.0/DLLShared;C:/Program Files (x86)/Microsoft SQL Server/100/Tools/Binn;C:/Program Files/Microsoft SQL Server/100/Tools/Binn;C:/Program Files/Microsoft SQL Server/100/DTS/Binn;C:/Windows/System32/WindowsPowerShell/v1.0;C:/Program Files (x86)/Microsoft SQL Server/100/Tools/Binn/VSShell/Common7/IDE;C:/Program Files (x86)/Microsoft SQL Server/100/DTS/Binn;C:/Program Files (x86)/PuTTY;C:/Program Files (x86)/jboss-4.2.2.GA/bin;C:/Program Files/MySQL/MySQL Server 5.0/bin;C:/Program Files/IBM/SQLLIB/BIN;C:/Program Files/IBM/SQLLIB/FUNCTION;C:/Program Files/IBM/SQLLIB/samples/repl;C:/Program Files/TortoiseSVN/bin;C:/jboss-5.1.0.GA/bin;C:/Program Files (x86)/QuickTime/QTSystem;C:/Program Files (x86)/Git/cmd;C:/Program Files/SlikSvn/bin;C:/glassfishv3/glassfish/%APPDATA%/Python/Scripts;C:/Program Files (x86)/Apache/apache-ant-1.7.0/bin;C:/Program Files (x86)/CVSNT/C:/jboss-5.1.0.GA/bin;C:/Program Files (x86)/Java/jdk1.6.0_14;C:/Program Files (x86)/Apache/apache-maven-2.1.0/bin;C:/glassfishv3/glassfish/bin
com.sun.enterprise.glassfish.bootstrap.ASMain
-domainname
myDomain
-asadmin-args
start-domain,,,--domaindir,,,C:\glassfishv3\glassfish\domains,,,--debug,,,--verbose=true,,,myDomain
-instancename
server
-verbose
true
-debug
true
-asadmin-classpath
C:/glassfishv3/glassfish/modules/admin-cli.jar
-asadmin-classname
com.sun.enterprise.admin.cli.AsadminMain
-upgrade
false
-domaindir
C:/glassfishv3/glassfish/domains/myDomain
-read-stdin
true
Nov 29, 2010 11:47:43 AM com.sun.enterprise.admin.launcher.GFLauncherLogger info
INFO: Successfully launched in 4 msec.
INFO: Running GlassFish Version: GlassFish Server Open Source Edition 3.0.1 (build 22)
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Starting Grizzly Framework 1.9.18-o - Mon Nov 29 11:47:46 EST 2010
INFO: Starting Grizzly Framework 1.9.18-o - Mon Nov 29 11:47:46 EST 2010
INFO: Grizzly Framework 1.9.18-o started in: 40ms listening on port 7676
INFO: Grizzly Framework 1.9.18-o started in: 50ms listening on port 3700
INFO: Grizzly Framework 1.9.18-o started in: 90ms listening on port 80
INFO: Grizzly Framework 1.9.18-o started in: 60ms listening on port 4848
INFO: Grizzly Framework 1.9.18-o started in: 67ms listening on port 8181
INFO: The Admin Console is already installed, but not yet loaded.
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
INFO: SEC1002: Security Manager is OFF.
INFO: Security startup service called
INFO: SEC1143: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.
INFO: Realm admin-realm of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
INFO: Realm file of classtype com.sun.enterprise.security.auth.realm.file.FileRealm successfully created.
INFO: Realm certificate of classtype com.sun.enterprise.security.auth.realm.certificate.CertificateRealm successfully created.
INFO: Realm jdbc of classtype com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm successfully created.
INFO: Security service(s) started successfully....
INFO: Created HTTP listener http-listener-1 on port 80
INFO: Created HTTP listener http-listener-2 on port 8181
INFO: Created HTTP listener admin-listener on port 4848
INFO: Created virtual server server
INFO: Created virtual server server
INFO: Created virtual server __asadmin
INFO: Created virtual server __asadmin
INFO: Created virtual server __asadmin
INFO: Virtual server server loaded system default web module
|#]
INFO: Virtual server server loaded system default web module
INFO: Initializing Mojarra 2.0.2 (FCS b10) for context '/richfaces-showcase'
INFO: Selected fallback cache factory
INFO: Creating LRUMap cache instance using parameters: {org.richfaces.enableControlSkinningClasses=false, javax.faces.PROJECT_STAGE=Development, com.sun.faces.validateXml=true, com.sun.faces.forceLoadConfiguration=true, javax.faces.STATE_SAVING_METHOD=server, org.richfaces.enableControlSkinning=true, javax.faces.FACELETS_LIBRARIES=/WEB-INF/app-tags.taglib.xml, org.richfaces.skin=#{skinBean.skin}}
INFO: Creating LRUMap cache instance of 512 items capacity
INFO: RichFaces Core Implementation by JBoss, a division of Red Hat, Inc., version v.4.0.0-SNAPSHOT SVN r.20127
INFO: Monitoring jndi:/server/richfaces-showcase/WEB-INF/faces-config.xml for modifications
INFO: Loading application richfaces-showcase at /richfaces-showcase
INFO: Loading application richfaces-showcase at /richfaces-showcase
INFO: Loading richfaces-showcase Application done is 7895 ms
INFO: Hibernate Validator bean-validator-3.0-JBoss-4.0.2
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Portable JNDI names for EJB UserBean : [java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/UserBean, java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/UserBean!com.lapis.retailerportal.demo.ejb.UserBean]
INFO: Portable JNDI names for EJB DbTestBean : [java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/DbTestBean!com.lapis.retailerportal.demo.ejb.DbTestBean, java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/DbTestBean]
INFO: Portable JNDI names for EJB NewsBean : [java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/NewsBean!com.lapis.retailerportal.demo.ejb.NewsBean, java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/NewsBean]
INFO: Portable JNDI names for EJB GameConfigBean : [java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/GameConfigBean!com.lapis.retailerportal.demo.ejb.GameConfigBean, java:global/RetailerPortalDemo/RetailerPortalDemo_Bean/GameConfigBean]
INFO: Initializing Mojarra 2.0.2 (FCS b10) for context '/RetailerPortalDemo'
INFO: com.lapis.retailerportal.demo.entity.Retailer actually got transformed
INFO: Selected fallback cache factory
INFO: Creating LRUMap cache instance using parameters: {javax.faces.PROJECT_STAGE=Development, com.sun.faces.validateXml=true, com.sun.faces.forceLoadConfiguration=true, org.richfaces.skin=tweaked}
INFO: Creating LRUMap cache instance of 512 items capacity
INFO: RichFaces Core Implementation by JBoss, a division of Red Hat, Inc., version v.4.0.0.20101110-M4 SVN r.20021
INFO: com.lapis.retailerportal.demo.entity.GameConfig actually got transformed
INFO: com.lapis.retailerportal.demo.entity.NewsItem actually got transformed
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.0.1.v20100213-r6600
INFO: file:/C:/glassfishv3/glassfish/domains/myDomain/eclipseApps/RetailerPortalDemo/RetailerPortalDemo_Bean_jar/_RPD_Persistence_CTX login successful
INFO: Loading application RetailerPortalDemo#RetailerPortalDemo_Web.war at RetailerPortalDemo
INFO: Loading application RetailerPortalDemo#RetailerPortalDemo_Web.war at RetailerPortalDemo
INFO: Loading RetailerPortalDemo Application done is 5656 ms
INFO: GlassFish Server Open Source Edition 3.0.1 (22) startup time : Felix(2386ms) startup services(14265ms) total(16651ms)
INFO: Binding RMI port to *:8686
INFO: JMXStartupService: Started JMXConnector, JMXService URL = service:jmx:rmi://192.168.5.10:8686/jndi/rmi://192.168.5.10:8686/jmxrmi
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\glassfishv3\glassfish\modules\autostart, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\Users\mjball\AppData\Local\Temp\fileinstall-2104459395405070416, felix.fileinstall.filter = null}
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\glassfishv3\glassfish\domains\myDomain\autodeploy\bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\Users\mjball\AppData\Local\Temp\fileinstall-286375592969619901, felix.fileinstall.filter = null}
INFO: Started bundle: file:/C:/glassfishv3/glassfish/modules/autostart/osgi-web-container.jar
INFO: Updating configuration from org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: Installed C:\glassfishv3\glassfish\modules\autostart\org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\glassfishv3\glassfish\domains\myDomain\autodeploy\bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\Users\mjball\AppData\Local\Temp\fileinstall--3209587030652226629, felix.fileinstall.filter = null}
</code></pre>
<h2>Edit 2</h2>
<p>I was able to successfully debug in Eclipse by starting GlassFish externally, e.g.</p>
<pre><code>> asadmin start-domain myDomain
</code></pre>
<p>and then creating a custom Debug Configuration:</p>
<p><img src="https://imgur.com/jJlg7.png" alt="bloody hell >:("></p>
<p><em>So why can't the GlassFish server adapter do this?</em></p>
<h2>Edit 3 - Problem solved</h2>
<p>Originally, I had added GlassFish support through the <a href="http://download.java.net/glassfish/eclipse/helios" rel="noreferrer">GlassFish Tools plugin</a>. I uninstalled the plugin, and added GlassFish support using <em>Servers → New → Server → Download additional server adapters</em>. Now I can debug. <strong>Woohoo!</strong></p>
| 0 | 4,450 |
Automatically solve Android build Error:Frame pixels must be either solid or transparent (not intermediate alphas). - Found at pixel #4 along top edge
|
<p>Android Studio (using SDK 19, 21 or 22) shows an error that Eclipse ADT (using SDK 19) does not:</p>
<blockquote>
<p>Error:9-patch image D:\Workspaces....\res\drawable-hdpi\btn_bg_common_press.9.png malformed.
Error:Frame pixels must be either solid or transparent (not intermediate alphas). - Found at pixel #4 along top edge.</p>
</blockquote>
<p>Or <a href="https://stackoverflow.com/questions/28940476/android-gradle-build-errorticks-in-transparent-frame-must-be-black-or-red">another error</a>:</p>
<blockquote>
<p>Error:Ticks in transparent frame must be black or red.</p>
</blockquote>
<p>both within <code>aapt</code></p>
<blockquote>
<p>Error:Error: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'E:\Android\sdk-Android-Studio\build-tools\19.1.0\aapt.exe'' finished with non-zero exit value 42</p>
</blockquote>
<p><img src="https://i.stack.imgur.com/euMip.png" alt="btn_bg_common_press.9.png"></p>
<p>Example of file is above, but there are 20+ such files that worked well.</p>
<p><strong>How do I make Android Studio or Gradle skip this error and not fail without having to modify those files one-by-one?</strong></p>
<p>If it is not possible with Gradle, what command-line tool could I use to replace all transparent pixel with non-transparent?</p>
<p>The build.gradle file for the application module (where resources are) is below.</p>
<p>I have tried both with <a href="http://developer.android.com/tools/revisions/platforms.html" rel="nofollow noreferrer">SDK 19 and SDK 21</a> and <a href="http://developer.android.com/tools/revisions/build-tools.html" rel="nofollow noreferrer">build tools 19.1, 21.1.2, 22</a>.</p>
<p>A similar issue on AOSP, <a href="https://code.google.com/p/android/issues/detail?id=159464" rel="nofollow noreferrer">Issue 159464: Android studio: mergeDebugResources FAILED when importing Eclipse project</a>.</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.+'
}
}
allprojects {
repositories {
jcenter()
}
}
//---
task wrapper(type: Wrapper) {
gradleVersion = '2.2.1'
}
apply plugin: 'com.android.application'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile project(':afinal')
compile 'com.android.support:appcompat-v7:19.0.+'
//compile 'com.android.support:appcompat-v7:21.0.+'
}
//---
android {
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
compileSdkVersion 19
buildToolsVersion "19.1.0"
//compileSdkVersion 21
//buildToolsVersion "21.1.2"
//compileSdkVersion Integer.parseInt(project.COMPILE_SDK_VERSION)
//buildToolsVersion project.BUILD_TOOLS_VERSION
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
zipAlignEnabled true
//signingConfig signingConfigs.release
}
debug {
zipAlignEnabled true
}
}
lintOptions {
//checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false // false also required by https://wiki.jenkins-ci.org/display/JENKINS/Android+Lint+Plugin
}
}//android
</code></pre>
<p>Android Gradle plugins sources are at <a href="https://android.googlesource.com/platform/tools/build/+/master" rel="nofollow noreferrer">https://android.googlesource.com/platform/tools/build/+/master</a>.</p>
| 0 | 1,463 |
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:annotation-driven'
|
<p>i guess this is a xml parsing problem, but I just cannot see where it is. I read some articles about this topic and nothing helped:</p>
<p>i have this spring mvc config:</p>
<pre><code><?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"
>
<mvc:annotation-driven />
<context:component-scan base-package="controllers" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>
</code></pre>
<p>and here is what tomcat says:</p>
<pre><code>org.xml.sax.SAXParseException; lineNumber: 23; columnNumber: 30; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:annotation-driven'.
com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:458)
com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3237)
com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1917)
com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(XMLSchemaValidator.java:766)
com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:356)
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2786)
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:428)
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>any idea what might be wrong in my code?</p>
<p>thanks</p>
| 0 | 2,808 |
Mongoose Populate returning null or undefined
|
<p>I'm sorry if this is a n00b question, I've been searching Google & Stack for hours now and I've got to ask!</p>
<p>I have two schemas, User and Story, shown below. I am trying to reference the User for a Story using the Ref option to Populate in a Query - I've using mySQL before and so wanted to try to replicate a JOIN statement.
Whenever I try to use populate I just get the objectID returned, or null (shown below).</p>
<p><strong>Edited 12 Nov to fix hardcoded IDs & add console data</strong></p>
<p><strong>story-schema.js</strong></p>
<pre><code>var mongoose = require('mongoose'),
Schema = mongoose.Schema,
User = require('./user-schema');
var StorySchema = new Schema({
title: { type: String, required: true },
author_id: { type: Schema.Types.ObjectId, ref: 'User' },
summary: { type: String, required: true },
rating: { type: String, required: true }
});
module.exports = mongoose.model('Story', StorySchema, 'stories');
</code></pre>
<p><strong>user-schema.js</strong></p>
<pre><code>var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
is_admin: {type: Boolean, required: true, default: false }
});
</code></pre>
<p><strong>save - id hardcoded for example</strong></p>
<pre><code>app.post('/api/new_story', function(req, res){
var story;
story = new Story({
title: req.body.title,
author_id: mongoose.Types.ObjectId(req.params._id),
/* ex of req.params._id: 527fc8ff241cdb8c09000003*/
summary: req.body.summary,
rating: req.body.rating
});
story.save(function(err) {
if (!err) {
return console.log("created");
} else {
return console.log(err);
}
});
return res.send(story);
});
</code></pre>
<p><strong>example user when logged in terminal</strong></p>
<pre><code>{
"__v" : 0,
"_id" : ObjectId("527fc8ff241cdb8c09000003"),
"is_admin" : false,
"username" : "ted"
}
</code></pre>
<p><strong>example story when logged in terminal</strong></p>
<pre><code>{
"title" : "Test Story",
"author_id" : "527fc8ff241cdb8c09000003",
"summary" : "Test summary",
"rating" : "12",
"_id" : ObjectId("52827692496c16070b000002"),
"__v" : 0
}
</code></pre>
<p><strong>queries</strong></p>
<pre><code>//other mongoose/app includes above
User = require('./config/schema/user-model'),
Story = require('./config/schema/story-model');
// data.author_id = 527fc8ff241cdb8c09000003
// data.author_id.username = undefined
app.get('/api/query/:id', function (req, res){
return Story.findOne({_id:req.params.id})
.populate( { path: 'User' } )
.exec(function (err, data) {
console.log(data.author_id);
console.log(data.author_id.username);
if (err) {
return res.json({error:err})
}
})
});
// data.author_id = null
app.get('/api/query2/:id', function (req, res){
return Story.findOne({_id:req.params.id}) //_id hardcoded for example
.populate( 'author_id' )
.exec(function (err, data) {
console.log(data.author_id);
if (err) {
return res.json({error:err})
}
})
});
</code></pre>
<p>In the first query I get the author_id I already saved back, which kind of makes sense as that's what I saved - but I access the username.</p>
<p>In the second query I can't even access the author_id I've already saved.</p>
<p><strong>Edit:</strong> I can run a normal GET query fine without the 'populate'</p>
<p><strong>What I'd like to happen</strong></p>
<p>Is to be able to access the author information from the story - this is more like a proof of concept.
Eventually I'd like to reference the Story _id in the the User model as there can be many Stories to a User, but only one User per Story but thought I'd start here first.</p>
| 0 | 1,448 |
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
|
<p>When I run my Ktor application with <code>gradle run</code> then I've got the following exception: </p>
<pre><code>19:21:11.795 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - Java version: 11
19:21:11.811 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: unavailable
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
at io.netty.util.internal.ReflectionUtil.trySetAccessible(ReflectionUtil.java:31)
at io.netty.util.internal.PlatformDependent0$4.run(PlatformDependent0.java:225)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:219)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
19:21:11.815 [main] DEBUG io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.IllegalAccessException: class io.netty.util.internal.PlatformDependent0$6 cannot access class jdk.internal.misc.Unsafe (in module java.base) because module java.base does not export jdk.internal.misc to unnamed module @557caf28
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
at java.base/java.lang.reflect.Method.invoke(Method.java:558)
at io.netty.util.internal.PlatformDependent0$6.run(PlatformDependent0.java:335)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:326)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
</code></pre>
<p>the content of <strong>build.gradle.kts</strong> file </p>
<pre><code>plugins {
application
kotlin("jvm") version "1.3.61"
}
group = "io.flatmap"
version = "1.0-SNAPSHOT"
val ktor_version = "1.3.0"
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
compile("io.ktor:ktor-server-netty:$ktor_version")
compile("io.ktor:ktor-server-core:$ktor_version")
compile("ch.qos.logback:logback-classic:1.2.3")
testCompile(group = "junit", name = "junit", version = "4.12")
}
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "11"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "11"
}
}
application {
mainClassName = "io.ktor.server.netty.EngineMain"
}
</code></pre>
<p>I am using Zulu OpenJDK 11: </p>
<pre><code> java --version
openjdk 11.0.6 2020-01-14 LTS
OpenJDK Runtime Environment Zulu11.37+17-CA (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.37+17-CA (build 11.0.6+10-LTS, mixed mode)
</code></pre>
<p>What am I doing wrong? </p>
| 0 | 1,889 |
package 'stringi' does not work after updating to R3.2.1
|
<p>I saw a <a href="https://stackoverflow.com/questions/30983013/error-in-loadnamespacei-clib-loc-libpaths-versioncheck-vii-the">version of this question</a> posted, but still did not see the answer. I am trying to use ggplot2 but get the following errors (everything worked this morning using R3.0.2 'frisbee sailing' with RStudio version 0.98.1102. </p>
<p>I updated both R and Rstudio and now get the following:</p>
<pre><code>library(ggplot)
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
there is no package called ‘stringi’
Error: package or namespace load failed for ‘ggplot2’
</code></pre>
<p>So naturally I tried: </p>
<pre><code>> install.packages('stringi')
**There is a binary version available but the source version is later:
binary source needs_compilation
stringi 0.4-1 0.5-2 FALSE**
installing the source package ‘stringi’
trying URL 'http://cran.rstudio.com/src/contrib/stringi_0.5-2.tar.gz'
Content type 'application/x-gzip' length 3641292 bytes (3.5 MB)
==================================================
downloaded 3.5 MB
* installing *source* package ‘stringi’ ...
** package ‘stringi’ successfully unpacked and MD5 sums checked
checking for local ICUDT_DIR... icu55/data
checking for R_HOME... /Library/Frameworks/R.framework/Resources
checking for R... /Library/Frameworks/R.framework/Resources/bin/R
checking for R >= 3.1.0... yes
checking for cat... /bin/cat
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make:
command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 151: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 152: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/private/var/folders/bq/3jbmwwh553s395pjg1m9h7fr0000gn/T/Rtmpugc1jZ/R.INSTALLc4677f69ffba/stringi':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
ERROR: configuration failed for package ‘stringi’
* removing ‘/Library/Frameworks/R.framework/Versions/3.2/Resources/library/stringi’
Warning in install.packages :
installation of package ‘stringi’ had non-zero exit status
The downloaded source packages are in
‘/private/var/folders/bq/3jbmwwh553s395pjg1m9h7fr0000gn/T/RtmpXvl7fe/downloaded_packages’
</code></pre>
<p>Any suggestions on how to get 'stringi' to install? I'm not real familiar with the error output. Should I just try to go back to older versions of R and Rstudio? Ultimately I'm worried that this will be the tip of the iceberg in terms of packages now not working with the updated R</p>
<p>oh and:</p>
<pre><code> > sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
Running under: OS X 10.7.5 (Lion)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] plyr_1.8.3 tools_3.2.1 gtable_0.1.2 Rcpp_0.11.6 grid_3.2.1 digest_0.6.8 proto_0.3-10
</code></pre>
| 0 | 2,047 |
iOS Swift uploading PDF file with Alamofire (Multipart)
|
<p>I'm currently developing an application using iOS 10 and Swift 3 and Alamofire 4</p>
<p>The purpose of this application is to upload a PDF file generated previously.</p>
<p>The PDF generation is working perfectly and the file is created.</p>
<p>However the upload doesn’t work…
I received a success response but the file is not uploaded.</p>
<p><strong>My server response</strong></p>
<pre><code>Multi part Content-Type => multipart/form-data; boundary=alamofire.boundary.56958be35bdb49cb
Multi part Content-Length => 293107
Multi part Content-Boundary => alamofire.boundary.56958be35bdb49cb
responses
SUCCESS: {
uploadedFiles = (
{
details = " Key=Content-Disposition - values=[form-data; name=\"pdfDocuments\"] length=8";
storedFileName = "/var/www/pdf/17/009/22/TMP104150531290406.tmp";
type = PDF;
uploadedDate = 1483999296701;
uploadedFileName = UnknownFile;
}
);
}
end responses
</code></pre>
<p>I’m using multi-part to upload my file as Data as you can see <a href="https://github.com/Alamofire/Alamofire#uploading-data-to-a-server" rel="noreferrer">here</a> </p>
<p>File url is fine. </p>
<p>I have searched on SO but didn’t find any solution working… </p>
<p>Here you can see my <strong>Controller</strong></p>
<pre><code>Alamofire.upload(
multipartFormData: {
multipartFormData in
if let urlString = urlBase2 {
let pdfData = try! Data(contentsOf: urlString.asURL())
var data : Data = pdfData
multipartFormData.append(data as Data, withName:"test.pdf", mimeType:"application/pdf")
for (key, value) in body {
multipartFormData.append(((value as? String)?.data(using: .utf8))!, withName: key)
}
print("Multi part Content -Type")
print(multipartFormData.contentType)
print("Multi part FIN ")
print("Multi part Content-Length")
print(multipartFormData.contentLength)
print("Multi part Content-Boundary")
print(multipartFormData.boundary)
}
},
to: url,
method: .post,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(" responses ")
print(response)
print("end responses")
onCompletion(true, "Something bad happen...", 200)
}
case .failure(let encodingError):
print(encodingError)
onCompletion(false, "Something bad happen...", 200)
}
})
</code></pre>
<p>Thanks in advance for the help.</p>
<p>Regards</p>
| 0 | 1,477 |
Launching Spring application Address already in use
|
<p>I have this error launching my spring application:</p>
<pre><code>java -jar target/gs-serving-web-content-0.1.0.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v0.5.0.M6)
2013-12-23 00:23:09.466 INFO 19252 --- [ main] hello.Application : Starting Application on mbp-de-antoine.home with PID 19252 (/Users/antoine/Documents/workspace-sts-3.4.0.RELEASE/springapp/target/gs-serving-web-content-0.1.0.jar started by antoine)
2013-12-23 00:23:09.511 INFO 19252 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@24024c39: startup date [Mon Dec 23 00:23:09 CET 2013]; root of context hierarchy
2013-12-23 00:23:10.910 INFO 19252 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2013-12-23 00:23:10.910 INFO 19252 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.42
2013-12-23 00:23:11.045 INFO 19252 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2013-12-23 00:23:11.046 INFO 19252 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1537 ms
2013-12-23 00:23:11.274 INFO 19252 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2013-12-23 00:23:11.274 INFO 19252 --- [ost-startStop-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2013-12-23 00:23:11.409 INFO 19252 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-12-23 00:23:11.634 INFO 19252 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String hello.GreetingController.greeting(java.lang.String,org.springframework.ui.Model)
2013-12-23 00:23:11.717 INFO 19252 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-12-23 00:23:11.717 INFO 19252 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-12-23 00:23:12.406 INFO 19252 --- [ost-startStop-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 1132 ms
2013-12-23 00:23:12.417 ERROR 19252 --- [ main] o.a.coyote.http11.Http11NioProtocol : Failed to start end point associated with ProtocolHandler ["http-nio-8080"]
java.net.BindException: Address already in use
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:444)
at sun.nio.ch.Net.bind(Net.java:436)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:473)
at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:617)
at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:444)
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1010)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:459)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:335)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:58)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:53)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:259)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:140)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:135)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:552)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:293)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:749)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:738)
at hello.Application.main(Application.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:744)
2013-12-23 00:23:12.419 ERROR 19252 --- [ main] o.apache.catalina.core.StandardService : Failed to start connector [Connector[org.apache.coyote.http11.Http11NioProtocol-8080]]
org.apache.catalina.LifecycleException: Failed to start component [Connector[org.apache.coyote.http11.Http11NioProtocol-8080]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:459)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:335)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:58)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:53)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:259)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:140)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:135)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:552)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:293)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:749)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:738)
at hello.Application.main(Application.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.catalina.LifecycleException: service.getName(): "Tomcat"; Protocol handler start failed
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1017)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 24 common frames omitted
Caused by: java.net.BindException: Address already in use
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:444)
at sun.nio.ch.Net.bind(Net.java:436)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:473)
at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:617)
at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:444)
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1010)
... 25 common frames omitted
2013-12-23 00:23:12.420 INFO 19252 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2013-12-23 00:23:12.430 INFO 19252 --- [ main] nitializer$AutoConfigurationReportLogger :
=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches:
-----------------
MessageSourceAutoConfiguration
- @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found no beans (OnBeanCondition)
PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
- @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)
ThymeleafAutoConfiguration
- @ConditionalOnClass classes found: org.thymeleaf.spring3.SpringTemplateEngine (OnClassCondition)
- @ConditionalOnClass classes found: org.thymeleaf.spring3.SpringTemplateEngine (OnClassCondition)
ThymeleafAutoConfiguration.DefaultTemplateResolverConfiguration
- @ConditionalOnMissingBean (names: defaultTemplateResolver; SearchStrategy: all) found no beans (OnBeanCondition)
ThymeleafAutoConfiguration.ThymeleafDefaultConfiguration
- @ConditionalOnMissingBean (types: org.thymeleaf.spring3.SpringTemplateEngine; SearchStrategy: all) found no beans (OnBeanCondition)
ThymeleafAutoConfiguration.ThymeleafViewResolverConfiguration
- @ConditionalOnClass classes found: javax.servlet.Servlet (OnClassCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet (OnClassCondition)
ThymeleafAutoConfiguration.ThymeleafViewResolverConfiguration#thymeleafViewResolver
- @ConditionalOnMissingBean (names: thymeleafViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)
DispatcherServletAutoConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
- @ConditionalOnBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: all) found the following [tomcatEmbeddedServletContainerFactory] (OnBeanCondition)
DispatcherServletAutoConfiguration#dispatcherServlet
- no DispatcherServlet found (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
EmbeddedServletContainerAutoConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
- @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: current) found no beans (OnBeanCondition)
ServerPropertiesAutoConfiguration#serverProperties
- @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.properties.ServerProperties; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
- @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration#hiddenHttpMethodFilter
- @ConditionalOnMissingBean (types: org.springframework.web.filter.HiddenHttpMethodFilter; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#defaultViewResolver
- @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.InternalResourceViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)
Negative matches:
-----------------
RabbitAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)
AopAutoConfiguration
- required @ConditionalOnClass classes not found: org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
BatchAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher (OnClassCondition)
JpaRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)
MongoRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)
DataSourceAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
DataSourceTransactionManagerAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
JmsTemplateAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate,javax.jms.ConnectionFactory (OnClassCondition)
DeviceResolverAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)
HibernateJpaAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
ReactorAutoConfiguration
- required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)
ThymeleafAutoConfiguration.ThymeleafSecurityDialectConfiguration
- required @ConditionalOnClass classes not found: org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect (OnClassCondition)
ThymeleafAutoConfiguration.ThymeleafWebLayoutConfiguration
- required @ConditionalOnClass classes not found: nz.net.ultraq.thymeleaf.LayoutDialect (OnClassCondition)
EmbeddedServletContainerAutoConfiguration.EmbeddedJetty
- required @ConditionalOnClass classes not found: org.eclipse.jetty.server.Server,org.eclipse.jetty.util.Loader (OnClassCondition)
MultipartAutoConfiguration
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
- @ConditionalOnBean (types: javax.servlet.MultipartConfigElement; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#beanNameViewResolver
- @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#viewResolver
- @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)
WebSocketAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.web.socket.WebSocketHandler (OnClassCondition)
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embdedded Tomcat
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:138)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:552)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:293)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:749)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:738)
at hello.Application.main(Application.java:12)
... 6 more
Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embdedded Tomcat
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:85)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:53)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:259)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:140)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:135)
... 13 more
Caused by: java.lang.IllegalStateException: Tomcat connector in failed state
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:81)
... 18 more
</code></pre>
<p>I think this is because my port is used. My port 8080 is used so I try the port 8181
I have no application on the port 8181</p>
<p>in the tomcat server.xml I set the port to 8181 but the problem persist</p>
<p>I find this post:</p>
<p><a href="https://stackoverflow.com/questions/646649/alternate-port-for-tomcat-not-8080-when-starting-with-maven">Alternate port for Tomcat (not 8080) when starting with Maven?</a></p>
<p>But I have the same problem after launching mvn -Dmaven.tomcat.port=8181 tomcat:run-war</p>
<p>I don't realy understand how to maven is linked to the tomcat server
This is my pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-serving-web-content</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>0.5.0.M6</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
</dependency>
</dependencies>
<properties>
<start-class>hello.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>http://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestone</id>
<url>http://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
</code></pre>
<p>Thanks for your help</p>
| 0 | 8,365 |
python Pip install using wheel file not working
|
<p>Due to network constraints and certificates error I am not able to install python libraries using pip normally. </p>
<p>So I tried downloading <code>.whl</code> and install the library manually. However it also failed with the same error. </p>
<pre><code>C:\python3.7>python -m pip install requests-2.21.0-py2.py3-none-any.whl
Processing c:\python3.7\requests-2.21.0-py2.py3-none-any.whl
Collecting idna<2.9,>=2.5 (from requests==2.21.0)
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x039C3D90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/idna/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04567350>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/idna/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04567D10>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/idna/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04567FD0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/idna/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04545F70>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/idna/
Could not find a version that satisfies the requirement idna<2.9,>=2.5 (from requests==2.21.0) (from versions: )
No matching distribution found for idna<2.9,>=2.5 (from requests==2.21.0)
</code></pre>
<p>Tried <code>--use-wheel</code> option as suggested but doesn't work. Looks like pip is old, however I can't even upgrade pip because that also needs a proper working net. It's a catch22 situation. </p>
<pre><code>C:\python3.7>python -m pip install --use-wheel requests-2.21.0-py2.py3-none-any.whl
Usage:
C:\python3.7\python.exe -m pip install [options] <requirement specifier> [package-index-options] ...
C:\python3.7\python.exe -m pip install [options] -r <requirements file> [package-index-options] ...
C:\python3.7\python.exe -m pip install [options] [-e] <vcs project url> ...
C:\python3.7\python.exe -m pip install [options] [-e] <local project path> ...
C:\python3.7\python.exe -m pip install [options] <archive url/path> ...
no such option: --use-wheel
</code></pre>
<p>How can I manually install libraries?</p>
| 0 | 1,037 |
Multi-Tenancy with Spring + Hibernate: "SessionFactory configured for multi-tenancy, but no tenant identifier specified"
|
<p>In a Spring 3 application, I'm trying to implement multi-tenancy via Hibernate 4's native <a href="http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch16.html#d5e4661">MultiTenantConnectionProvider</a> and <a href="http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch16.html#d5e4686">CurrentTenantIdentifierResolver</a>. I see that <a href="https://hibernate.onjira.com/browse/HHH-7306">there was a problem with this in Hibernate 4.1.3</a>, but I'm running 4.1.9 and still getting a similar exception:</p>
<pre><code> Caused by:
org.hibernate.HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified
at org.hibernate.internal.AbstractSessionImpl.<init>(AbstractSessionImpl.java:84)
at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:239)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1597)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:963)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:328)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:334)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.afflatus.edu.thoth.repository.UserRepository$$EnhancerByCGLIB$$c844ce96.getAllUsers(<generated>)
at com.afflatus.edu.thoth.service.UserService.getAllUsers(UserService.java:29)
at com.afflatus.edu.thoth.HomeController.hello(HomeController.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:671)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:448)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:138)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:564)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:213)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1070)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:375)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:175)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1004)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:258)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:439)
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:246)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:265)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:240)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:589)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:520)
at java.lang.Thread.run(Thread.java:722) enter code here
</code></pre>
<p>Below is the relevant code. In the <code>MultiTenantConnectionProvider</code> I've simply wrote some dumb code for now that just returns a new connection every time, and the <code>CurrentTenantIdentifierResolver</code> always returns the same ID at this point. Obviously this logic was to be implemented after I managed to get the connections to instantiate.</p>
<h1>config.xml</h1>
<pre><code><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.afflatus.edu.thoth.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl">${hibernate.dbm2ddl}</prop>
<prop key="hibernate.multiTenancy">DATABASE</prop>
<prop key="hibernate.multi_tenant_connection_provider">com.afflatus.edu.thoth.connection.MultiTenantConnectionProviderImpl</prop>
<prop key="hibernate.tenant_identifier_resolver">com.afflatus.edu.thoth.context.MultiTenantIdentifierResolverImpl</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="autodetectDataSource" value="false" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</code></pre>
<h1>MultiTenantConnectionProvider.java</h1>
<pre><code>package com.afflatus.edu.thoth.connection;
import java.util.Properties;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.service.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.hibernate.cfg.*;
public class MultiTenantConnectionProviderImpl extends AbstractMultiTenantConnectionProvider {
private final Map<String, ConnectionProvider> connectionProviders
= new HashMap<String, ConnectionProvider>();
@Override
protected ConnectionProvider getAnyConnectionProvider() {
System.out.println("barfoo");
Properties properties = getConnectionProperties();
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
ds.setUsername("root");
ds.setPassword("");
InjectedDataSourceConnectionProvider defaultProvider = new InjectedDataSourceConnectionProvider();
defaultProvider.setDataSource(ds);
defaultProvider.configure(properties);
return (ConnectionProvider) defaultProvider;
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
System.out.println("foobar");
Properties properties = getConnectionProperties();
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/test2");
ds.setUsername("root");
ds.setPassword("");
InjectedDataSourceConnectionProvider defaultProvider = new InjectedDataSourceConnectionProvider();
defaultProvider.setDataSource(ds);
defaultProvider.configure(properties);
return (ConnectionProvider) defaultProvider;
}
private Properties getConnectionProperties() {
Properties properties = new Properties();
properties.put(AvailableSettings.DIALECT, "org.hibernate.dialect.MySQLDialect");
properties.put(AvailableSettings.DRIVER, "com.mysql.jdbc.Driver");
properties.put(AvailableSettings.URL, "jdbc:mysql://127.0.0.1:3306/test");
properties.put(AvailableSettings.USER, "root");
properties.put(AvailableSettings.PASS, "");
return properties;
}
}
</code></pre>
<h1>CurrentTenantIdentifierResolver.java</h1>
<pre><code>package com.afflatus.edu.thoth.context;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver {
public String resolveCurrentTenantIdentifier() {
return "1";
}
public boolean validateExistingCurrentSessions() {
return true;
}
}
</code></pre>
<p>Can anybody see anything specifically wrong? This throws an exception as soon as a transaction is opened. It <em>seems</em> like the <code>SessionFactory</code> isn't opening the Session correctly, or the <code>Session</code> is simply ignoring the value returned by the <code>CurrentTenantIdentifierResolver</code>, which I believe was the issue in Hibernate 4.1.3; this was supposed to have been resolved.</p>
| 0 | 3,824 |
Hibernate could not fetch the SequenceInformation from the database
|
<p>I have recently updated hibernate in my application to 5.4.4.Final. And now, I have faced with the following exception during deployment.</p>
<pre><code>ERROR [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl|[STANDBY] ExecuteThread: '5' for queue: 'weblogic.kernel.Default (self-tuning)']
Could not fetch the SequenceInformation from the database
java.sql.SQLException: Numeric Overflow
at oracle.jdbc.driver.NumberCommonAccessor.throwOverflow(NumberCommonAccessor.java:4136)
at oracle.jdbc.driver.NumberCommonAccessor.getLong(NumberCommonAccessor.java:634)
at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:206)
at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:259)
at oracle.jdbc.driver.GeneratedResultSet.getLong(GeneratedResultSet.java:558)
at weblogic.jdbc.wrapper.ResultSet_oracle_jdbc_driver_ForwardOnlyResultSet.getLong(Unknown Source)
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.resultSetMaxValue(SequenceInformationExtractorLegacyImpl.java:139)
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:61)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:268)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:900)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:931)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:141)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at com.sternkn.app.services.web.AppContextLoaderListener.<clinit>(AppContextLoaderListener.java:30)
</code></pre>
<p>I use the following persistence.xml.</p>
<pre class="lang-xml prettyprint-override"><code><persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="appPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect" />
<property name="hibernate.id.new_generator_mappings" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value = "true"/>
<property name="hibernate.cache.use_query_cache" value="false" />
<property name="hibernate.cache.region.factory_class" value="ehcache"/>
<property name="hibernate.cache.ehcache.missing_cache_strategy" value="create" />
<property name="hibernate.cache.region_prefix" value="app_cache" />
<property name="net.sf.ehcache.configurationResourceName" value="/META-INF/app-ehcache.xml" />
<property name="hibernate.bytecode.provider" value="bytebuddy" />
</properties>
</persistence-unit>
</persistence>
</code></pre>
<p>After further investigation, I found out that the root cause is the following: hibernate uses the <strong>SequenceInformation</strong> interface for the sequences metadata manipulations</p>
<pre class="lang-java prettyprint-override"><code>public interface SequenceInformation {
Long getMinValue();
Long getMaxValue();
Long getIncrementValue();
...
}
</code></pre>
<p>However, my app uses the sequences like the following:</p>
<pre><code>SQL> CREATE SEQUENCE SEQ_TEST START WITH 1 INCREMENT BY 1 NOCYCLE;
SQL> select MIN_VALUE, MAX_VALUE, INCREMENT_BY
from USER_SEQUENCES
where SEQUENCE_NAME = 'SEQ_TEST';
MIN_VALUE MAX_VALUE INCREMENT_BY
--------- ---------------------------- ------------
1 9999999999999999999999999999 1
</code></pre>
<p>The <strong>Long.MAX_VALUE</strong> is equal to 9223372036854775807, therefore I got the numeric overflow exception.</p>
<p>So, my questions:</p>
<ul>
<li>Is it a bug in hibernate?</li>
<li>What will be the best way to solve it?</li>
</ul>
<p>Now I see the following ways:</p>
<ol>
<li>Fix the sequences declarations.
It can be quite problematic in my case. And, by the way, it looks strange that hibernate tries to read metadata about all sequences, not only about used in my application.</li>
<li>Create custom dialect that will extend Oracle12cDialect and override getQuerySequencesString() and/or getSequenceInformationExtractor().</li>
</ol>
<pre class="lang-java prettyprint-override"><code>public class Oracle8iDialect extends Dialect {
...
public String getQuerySequencesString() {
return "select * from all_sequences";
}
public SequenceInformationExtractor getSequenceInformationExtractor() {
return SequenceInformationExtractorOracleDatabaseImpl.INSTANCE;
}
}
</code></pre>
<p>I can switch <strong>SequenceInformationExtractor</strong> to <strong>SequenceInformationExtractorNoOpImpl.INSTANCE</strong> and hibernate will not read sequences metadata. What impact will this decision have? Hibernate tries to validate <strong>allocationSize</strong> of @SequenceGenerator() by INCREMENT_BY. Are there other reasons?</p>
<p>Any suggestions will be appreciated.</p>
<p><strong>UPDATE</strong>: This is <a href="https://hibernate.atlassian.net/browse/HHH-13694" rel="noreferrer">HHH-13694</a></p>
| 0 | 3,201 |
C++/Win32: How to wait for a pending delete to complete
|
<p><strong>Solved:</strong></p>
<ul>
<li>Workable solution: <a href="https://stackoverflow.com/questions/3764072/c-win32-how-to-wait-for-a-pending-delete-to-complete/3764298#3764298">sbi's answer</a></li>
<li>Explanation for what really happens: <a href="https://stackoverflow.com/questions/3764072/c-win32-how-to-wait-for-a-pending-delete-to-complete/3764322#3764322">Hans's answer</a></li>
<li>Explanation for why OpenFile doesn't pass through "DELETE PENDING": <a href="https://stackoverflow.com/questions/3764072/c-win32-how-to-wait-for-a-pending-delete-to-complete/3776438#3776438">Benjamin's answer</a></li>
</ul>
<p><strong>The Problem:</strong></p>
<p>Our software is in large part an interpreter engine for a proprietary scripting language. That scripting language has the ability to create a file, process it, and then delete the file. These are all separate operations, and no file handles are kept open in between these operations.</p>
<p>(I.e. during the file creation, a handle is created, used for writing, then closed. During the file processing portion, a separate file handle opens the file, reads from it, and is closed at EOF. And <em>finally</em>, delete uses ::DeleteFile which only has use of a filename, not a file handle at all).</p>
<p>Recently we've come to realize that a particular macro (script) fails sometimes to be able to create the file at some random subsequent time (i.e. it succeeds during the first hundred iterations of "create, process, delete", but when it comes back to creating it a hundred and first time, Windows replies "Access Denied").</p>
<p>Looking deeper into the issue, I have written a very simple program that loops over something like this:</p>
<pre><code>while (true) {
HANDLE hFile = CreateFileA(pszFilename, FILE_ALL_ACCESS, FILE_SHARE_READ,
NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return OpenFailed;
const DWORD dwWrite = strlen(pszFilename);
DWORD dwWritten;
if (!WriteFile(hFile, pszFilename, dwWrite, &dwWritten, NULL) || dwWritten != dwWrite)
return WriteFailed;
if (!CloseHandle(hFile))
return CloseFailed;
if (!DeleteFileA(pszFilename))
return DeleteFailed;
}
</code></pre>
<p>As you can see, this is direct to the Win32 API and is pretty darn simple. I create a file, write to it, close the handle, delete it, rinse, repeat...</p>
<p>But somewhere along the line, I'll get an Access Denied (5) error during the CreateFile() call. Looking at sysinternal's ProcessMonitor, I can see that the underlying issue is that there is a pending delete on the file while I'm trying to create it again.</p>
<p><strong>Questions:</strong></p>
<ul>
<li>Is there a way to wait for the delete to complete?</li>
<li>Is there a way to detect that a file is pending deletion?</li>
</ul>
<p>We have tried the first option, by simply WaitForSingleObject() on the HFILE. But the HFILE is always closed before the WaitForSingleObject executes, and so WaitForSingleObject always returns WAIT_FAILED. Clearly, trying to wait for the closed handle doesn't work.</p>
<p>I could wait on a change notification for the folder that the file exists in. However, that seems like an extremely overhead-intensive kludge to what is a problem only occasionally (to wit: in my tests on my Windows 7 x64 E6600 PC it typically fails on iteration 12000+ -- on other machines, it can happen as soon as iteration 7 or 15 or 56 or never).</p>
<p>I have been unable to discern any CreateFile() arguments that would explicitly allow for this ether. No matter what arguments CreateFile has, it really is not okay with opening a file for <em>any</em> access when the file is pending deletion.</p>
<p>And since I can see this behavior on both an Windows XP box and on an x64 Windows 7 box, I am quite certain that this is core NTFS behavior "as intended" by Microsoft. So I need a solution that allows the OS to complete the delete before I attempt to proceed, preferably without tying up CPU cycles needlessly, and without the extreme overhead of watching the folder that this file is in (if possible).</p>
<p><a href="https://stackoverflow.com/questions/3764072/c-win32-how-to-wait-for-a-pending-delete-to-complete/3764298#3764298">1</a> Yes, this loop returns on a failure to write or a failure to close which leaks, but since this is a simple console test application, the application itself exits, and Windows guarantees that all handles are closed by the OS when a process completes. So no leaks exist here.</p>
<pre><code>bool DeleteFileNowA(const char * pszFilename)
{
// Determine the path in which to store the temp filename
char szPath[MAX_PATH];
strcpy(szPath, pszFilename);
PathRemoveFileSpecA(szPath);
// Generate a guaranteed to be unique temporary filename to house the pending delete
char szTempName[MAX_PATH];
if (!GetTempFileNameA(szPath, ".xX", 0, szTempName))
return false;
// Move the real file to the dummy filename
if (!MoveFileExA(pszFilename, szTempName, MOVEFILE_REPLACE_EXISTING))
return false;
// Queue the deletion (the OS will delete it when all handles (ours or other processes) close)
if (!DeleteFileA(szTempName))
return false;
return true;
}
</code></pre>
| 0 | 1,673 |
horizontal only webkit scrollbar style css
|
<p>this is custom scrollbar in css</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> /* Gmail style scrollbar */
::-webkit-scrollbar {
width: 12px
}
::-webkit-scrollbar-thumb {
border-width: 1px 1px 1px 2px
}
::-webkit-scrollbar-track {
border-width: 0
}
::-webkit-scrollbar {
height: 16px;
overflow: visible;
width: 16px;
}
::-webkit-scrollbar-button {
height: 0;
width: 0;
}
::-webkit-scrollbar-track {
background-clip: padding-box;
border: solid transparent;
border-width: 0 0 0 4px;
}
::-webkit-scrollbar-track:horizontal {
border-width: 4px 0 0
}
::-webkit-scrollbar-track:hover {
background-color: rgba(220, 172, 0, .05);
box-shadow: inset 1px 0 0 rgba(220, 172, 0, .1);
}
::-webkit-scrollbar-track:horizontal:hover {
box-shadow: inset 0 1px 0 rgba(220, 172, 0, .1)
}
::-webkit-scrollbar-track:active {
background-color: rgba(220, 172, 0, .05);
box-shadow: inset 1px 0 0 rgba(220, 172, 0, .14), inset -1px 0 0 rgba(220, 172, 0, .07);
}
::-webkit-scrollbar-track:horizontal:active {
box-shadow: inset 0 1px 0 rgba(220, 172, 0, .14), inset 0 -1px 0 rgba(220, 172, 0, .07)
}
::-webkit-scrollbar-thumb {
background-color: rgba(220, 172, 0, .2);
background-clip: padding-box;
border: solid transparent;
border-width: 1px 1px 1px 6px;
min-height: 28px;
padding: 100px 0 0;
box-shadow: inset 1px 1px 0 rgba(220, 172, 0, .1), inset 0 -1px 0 rgba(220, 172, 0, .07);
}
::-webkit-scrollbar-thumb:horizontal {
border-width: 6px 1px 1px;
padding: 0 0 0 100px;
box-shadow: inset 1px 1px 0 rgba(220, 172, 0, .1), inset -1px 0 0 rgba(220, 172, 0, .07);
}
::-webkit-scrollbar-thumb:hover {
background-color: rgba(220, 172, 0, .4);
box-shadow: inset 1px 1px 1px rgba(220, 172, 0, .25);
}
::-webkit-scrollbar-thumb:active {
background-color: rgba(220, 172, 0, 0.5);
box-shadow: inset 1px 1px 3px rgba(220, 172, 0, 0.35);
}
::-webkit-scrollbar-track {
border-width: 0 1px 0 6px
}
::-webkit-scrollbar-track:horizontal {
border-width: 6px 0 1px
}
::-webkit-scrollbar-track:hover {
background-color: rgba(220, 172, 0, .035);
box-shadow: inset 1px 1px 0 rgba(220, 172, 0, .14), inset -1px -1px 0 rgba(220, 172, 0, .07);
}
::-webkit-scrollbar-thumb {
border-width: 0 1px 0 6px
}
::-webkit-scrollbar-thumb:horizontal {
border-width: 6px 0 1px
}
::-webkit-scrollbar-corner {
background: transparent
}
body::-webkit-scrollbar-track-piece {
background-clip: padding-box;
background-color: #f5f5f5;
border: solid #fff;
border-width: 0 0 0 3px;
box-shadow: inset 1px 0 0 rgba(220, 172, 0, .14), inset -1px 0 0 rgba(220, 172, 0, .07);
}
body::-webkit-scrollbar-track-piece:horizontal {
border-width: 3px 0 0;
box-shadow: inset 0 1px 0 rgba(220, 172, 0, .14), inset 0 -1px 0 rgba(220, 172, 0, .07);
}
body::-webkit-scrollbar-thumb {
border-width: 1px 1px 1px 5px
}
body::-webkit-scrollbar-thumb:horizontal {
border-width: 5px 1px 1px
}
body::-webkit-scrollbar-corner {
background-clip: padding-box;
background-color: #f5f5f5;
border: solid #fff;
border-width: 3px 0 0 3px;
box-shadow: inset 1px 1px 0 rgba(220, 172, 0, .14);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p></code></pre>
</div>
</div>
</p>
<p>I use the above code to beautify my scroll bar, but I do not want to style my vertical bar. </p>
<p>I tried to remove the tags which don't contain 'horizontal' but it doesn't work.</p>
| 0 | 2,110 |
FFT real/imaginary/abs parts interpretation
|
<p>I'm currently learning about discret Fourier transform and I'm playing with numpy to understand it better.</p>
<p>I tried to plot a "sin x sin x sin" signal and obtained a clean FFT with 4 non-zero points. I naively told myself : "well, if I plot a "sin + sin + sin + sin" signal with these amplitudes and frequencies, I should obtain the same "sin x sin x sin" signal, right?</p>
<p>Well... not exactly</p>
<p>(First is "x" signal, second is "+" signal)</p>
<p><img src="https://i.stack.imgur.com/AlE2o.png" alt="enter image description here"></p>
<p>Both share the same amplitudes/frequencies, but are not the same signals, even if I can see they have some similarities.</p>
<p>Ok, since I only plotted absolute values of FFT, I guess I lost some informations.</p>
<p>Then I plotted real part, imaginary part and absolute values for both signals :</p>
<p><img src="https://i.stack.imgur.com/Rqa7T.png" alt="enter image description here"></p>
<p>Now, I'm confused. What do I do with all this? I read about DFT from a mathematical point of view. I understand that complex values come from the unit circle. I even had to learn about Hilbert space to understand how it works (and it was painful!...and I only scratched the surface). I only wish to understand if these real/imaginary plots have any <em>concrete</em> meaning outside mathematical world:</p>
<ul>
<li>abs(fft) : frequencies + amplitudes</li>
<li>real(fft) : ?</li>
<li>imaginary(fft) : ?</li>
</ul>
<p>code :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
N = 512 # Sample count
fs = 128 # Sampling rate
st = 1.0 / fs # Sample time
t = np.arange(N) * st # Time vector
signal1 = \
1 *np.cos(2*np.pi * t) *\
2 *np.cos(2*np.pi * 4*t) *\
0.5 *np.cos(2*np.pi * 0.5*t)
signal2 = \
0.25*np.sin(2*np.pi * 2.5*t) +\
0.25*np.sin(2*np.pi * 3.5*t) +\
0.25*np.sin(2*np.pi * 4.5*t) +\
0.25*np.sin(2*np.pi * 5.5*t)
_, axes = plt.subplots(4, 2)
# Plot signal
axes[0][0].set_title("Signal 1 (multiply)")
axes[0][0].grid()
axes[0][0].plot(t, signal1, 'b-')
axes[0][1].set_title("Signal 2 (add)")
axes[0][1].grid()
axes[0][1].plot(t, signal2, 'r-')
# FFT + bins + normalization
bins = np.fft.fftfreq(N, st)
fft = [i / (N/2) for i in np.fft.fft(signal1)]
fft2 = [i / (N/2) for i in np.fft.fft(signal2)]
# Plot real
axes[1][0].set_title("FFT 1 (real)")
axes[1][0].grid()
axes[1][0].plot(bins[:N/2], np.real(fft[:N/2]), 'b-')
axes[1][1].set_title("FFT 2 (real)")
axes[1][1].grid()
axes[1][1].plot(bins[:N/2], np.real(fft2[:N/2]), 'r-')
# Plot imaginary
axes[2][0].set_title("FFT 1 (imaginary)")
axes[2][0].grid()
axes[2][0].plot(bins[:N/2], np.imag(fft[:N/2]), 'b-')
axes[2][1].set_title("FFT 2 (imaginary)")
axes[2][1].grid()
axes[2][1].plot(bins[:N/2], np.imag(fft2[:N/2]), 'r-')
# Plot abs
axes[3][0].set_title("FFT 1 (abs)")
axes[3][0].grid()
axes[3][0].plot(bins[:N/2], np.abs(fft[:N/2]), 'b-')
axes[3][1].set_title("FFT 2 (abs)")
axes[3][1].grid()
axes[3][1].plot(bins[:N/2], np.abs(fft2[:N/2]), 'r-')
plt.show()
</code></pre>
| 0 | 1,319 |
How to use dup2/close correctly to connect these three processes?
|
<p>I'm trying to properly connect three processes in order to allow inter-process communication between them. I have one process, scanner, which takes the parent's STDIN and then processes the words within the stream. If a word length is odd, it sends it to one process, if it is even, it sends it to another. These processes should take in these words via STDIN (I assume) and then output some info back to the scanner process via STDOUT. The STDOUT of even/odd should be redirected to scanner, which will then read (using read) and then output/process the words. It's an academic exercise, not a practical one. Here's what a picture of it would look like:</p>
<p><img src="https://i.stack.imgur.com/wXtMq.png" alt="Pipe setup"></p>
<p>Here's what my code currently looks like. The problem is I'm not exactly sure what to dup and what to close. Once I figure that out I should be good to go! Any advice would be appreciated.</p>
<p>File descriptors:</p>
<pre><code>int scannertoeven[2]; int scannertoodd[2];
int eventoscanner[2]; int oddtoscanner[2];
//Pipe stuff here (ommitted)
</code></pre>
<p>Code:</p>
<pre><code> //Create the child processes
if ((scanner_pid = fork()) == 0) {
//We need the scanner pid so even and odd can send signals to it
char pidofparent[sizeof(getpid())];
sprintf(pidofparent, "%i", getpid());
//Even stuff
if ((even_pid = fork()) == 0) {
close(scannertoodd[0]); close(scannertoodd[1]);
close(oddtoscanner[0]); close(oddtoscanner[1]);
//Not sure which ones to close
close(scannertoeven[0]); close(scannertoeven[1]);
close(eventoscanner[0]); close(eventoscanner[1]);
//Correct?
close(STDIN_FILENO);
dup2(scannertoeven[0], STDIN_FILENO);
close(STDOUT_FILENO);
dup2(eventoscanner[1], STDOUT_FILENO);
if(execl("./evenodd", "even", pidofparent, NULL ) == -1) {
printf("execl Error!");
exit(1);
}
//Odd Stuff
} else if ((odd_pid = fork()) == 0){
close(scannertoeven[0]); close(scannertoeven[1]);
close(eventoscanner[0]); close(eventoscanner[1]);
//Not sure which ones to close
close(scannertoodd[0]); close(scannertoodd[1]);
close(oddtoscanner[0]); close(oddtoscanner[1]);
//Correct?
close(STDIN_FILENO);
dup2(scannertoodd[0], STDIN_FILENO);
close(STDOUT_FILENO);
dup2(oddtoscanner[1], STDOUT_FILENO);
if(execl("./evenodd", "odd", pidofparent, NULL ) == -1) {
printf("execl Error!");
exit(1);
}
//Actual Scanner
} else {
// Not sure which ones to close- this is very wrong
close(scannertoeven[0]); close(scannertoeven[1]);
close(eventoscanner[0]); close(eventoscanner[1]);
close(scannertoodd[0]); close(scannertoodd[1]);
close(oddtoscanner[0]); close(oddtoscanner[1]);
//Not sure what to dup either
dup2(scannertoodd[1], STDOUT_FILENO);
dup2(scannertoeven[1], STDOUT_FILENO);
if(execl("./scanner", "scanner", stoeven, stoodd, eventos, oddtos, NULL ) == -1) {
printf("execl Error!");
exit(1);
}
//Wait twice here, or three times in main?
waitpid(odd_pid, &status2, 0);
waitpid(even_pid, &status3, 0);
}
//Main
} else {
//Close Pipes
close(scannertoodd[0]); close(scannertoeven[0]); close(eventoscanner[0]); close(oddtoscanner[0]);
close(scannertoodd[1]); close(scannertoeven[1]); close(eventoscanner[1]); close(oddtoscanner[1]);
//Wait for children to finish
waitpid(scanner_pid, &status1, 0);
printf("Done\n");
}
</code></pre>
| 0 | 1,733 |
Are there alternatives to using Google's in-app-billing , as a way to avoid publishing private info?
|
<h2>Background</h2>
<p>Starting from September 30th this year (end of this month), Google won't allow developers that sell apps and developers that use in-app-billing to show their apps without also showing their address . Here's what they write:</p>
<blockquote>
<p>Add a physical contact address Beginning September 30, 2014, you need
to add a physical address to your Settings page. After you've added an
address, it will be available on your app's detail page to all users
on Google Play. If your physical address changes, make sure to update
your information on your Settings page.</p>
<p>If you have paid apps or apps with in-app purchases, it's mandatory to
provide a physical address where you can be contacted, as you are the
seller of that content, to comply with consumer protection laws. If
you don't provide a physical address on your account, it may result in
your apps being removed from the Play Store.</p>
</blockquote>
<p>There are plenty of articles about this new requirement:</p>
<ul>
<li><a href="http://www.androidauthority.com/google-forcing-developers-to-publish-home-addresses-527772/" rel="noreferrer">http://www.androidauthority.com/google-forcing-developers-to-publish-home-addresses-527772/</a></li>
<li><a href="http://www.androidpolice.com/2014/09/18/google-will-now-require-all-app-publishers-with-paid-apps-or-in-app-purchases-to-have-an-address-on-file-in-google-play/" rel="noreferrer">http://www.androidpolice.com/2014/09/18/google-will-now-require-all-app-publishers-with-paid-apps-or-in-app-purchases-to-have-an-address-on-file-in-google-play/</a></li>
<li><a href="http://phandroid.com/2014/09/18/google-play-now-requires-devs-to-make-their-home-address-public/" rel="noreferrer">http://phandroid.com/2014/09/18/google-play-now-requires-devs-to-make-their-home-address-public/</a></li>
<li><a href="http://www.androidheadlines.com/2014/09/google-play-policy-will-soon-require-physical-address-file-paid-apps-apps-iap.html" rel="noreferrer">http://www.androidheadlines.com/2014/09/google-play-policy-will-soon-require-physical-address-file-paid-apps-apps-iap.html</a></li>
<li><a href="http://androidandme.com/2014/09/news/googles-insane-new-requirement-forces-app-developers-to-list-a-physical-address/" rel="noreferrer">http://androidandme.com/2014/09/news/googles-insane-new-requirement-forces-app-developers-to-list-a-physical-address/</a>
-<a href="http://www.greenbot.com/article/2685242/android-developers-must-now-list-physical-address-in-play-store.html" rel="noreferrer">http://www.greenbot.com/article/2685242/android-developers-must-now-list-physical-address-in-play-store.html</a></li>
<li><a href="http://www.pcworld.com/article/2685242/android-developers-must-now-list-physical-address-in-play-store.html" rel="noreferrer">http://www.pcworld.com/article/2685242/android-developers-must-now-list-physical-address-in-play-store.html</a></li>
</ul>
<p>There are even petitions against it , here:</p>
<ul>
<li><a href="https://www.change.org/p/google-remove-the-need-for-developers-to-reveal-their-physical-addresses-publicly-on-google-play" rel="noreferrer">https://www.change.org/p/google-remove-the-need-for-developers-to-reveal-their-physical-addresses-publicly-on-google-play</a></li>
<li><a href="https://www.change.org/p/google-inc-reverse-your-decision-to-require-android-developers-who-sell-apps-on-google-play-to-publicly-disclose-their-physical-address?lang=en-US" rel="noreferrer">https://www.change.org/p/google-inc-reverse-your-decision-to-require-android-developers-who-sell-apps-on-google-play-to-publicly-disclose-their-physical-address?lang=en-US</a></li>
</ul>
<p>And I've requested to have a solution for it <a href="https://code.google.com/p/android-developer-preview/issues/detail?id=1340" rel="noreferrer"><strong>here</strong></a>.</p>
<h2>The problem</h2>
<p>As I don't really have a company, I don't like the fact I will actually need to publish my home address. </p>
<p>For me, it's a privacy issue, as I don't always work on the app at home (plus it's more of a hobby).</p>
<p><a href="https://play.google.com/store/apps/details?id=com.lb.app_manager" rel="noreferrer"><strong>My app</strong></a> is free to use, and it has in-app-billing only used to remove ads. That's it.</p>
<p>It doesn't add any feature when using in-app-billing, and the user is free to pay whatever he wishes, as a donation.</p>
<p>I do not want to publish my address, and according to what I've read, you can't even use a P.O. box (which costs money anyway), as they specifically ask for "Physical address" and not "postal address".</p>
<h2>The question</h2>
<p>Since I will probably not be able to use Google's in-app-billing AND avoid putting my home address, is it possible (and legal, and according to Google's rules) to use other services of other companies?</p>
<p>If so, which companies offer similar services?</p>
<p>If not, is there any alternative or a solution to this problem?</p>
<p>Is there maybe a workaround or a loophole that will allow me to publish such apps without the reason to also publish my home address?</p>
| 0 | 1,735 |
java.lang.NoClassDefFoundError: com/thoughtworks/xstream/io/naming/NameCode error in setting up restful webservice in spring 4.3.1
|
<p>I want to create rest controller in spring but I get this error : </p>
<blockquote>
<p>org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0'
defined in ServletContext resource
[/WEB-INF/mvc-dispatcher-servlet.xml]: Initialization of bean failed;
nested exception is java.lang.NoClassDefFoundError:
com/thoughtworks/xstream/io/naming/NameCoder</p>
</blockquote>
<p>These jar files were added to my project correctly :
jackson-annotations:2.1.1/
jackson-core:2.1.1/
jackson-databind:2.1.2</p>
<pre><code><dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
</code></pre>
| 0 | 1,857 |
How to resize image with CSS without altering image quality
|
<p>I have a Bootstrap carousel with the below code; how can I size this image to completely fill the carousel with losing image quality and also ensure the image height does not exceed the width or height of the carousel? <a href="https://i.stack.imgur.com/iHFvM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iHFvM.png" alt="image"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active" style="width:400px;">
<img class="d-block w-100" src="{{articles.image.url}}" alt="First slide" style=" width:100%;height:auto;">
<div class="carousel-caption d-none d-md-block">
<h5>Latest</h5>
<p>{{articles.title}}</p>
</div>
</div>
<div class="carousel-item">
<img class="d-block w-100" src=".../800x400?auto=yes&bg=666&fg=444&text=Second slide" alt="Second slide">{% lorem 1 p %}
</div>
<div class="carousel-item">
<img class="d-block w-100" src=".../800x400?auto=yes&bg=555&fg=333&text=Third slide" alt="Third slide">{% lorem 1 p %}
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div></code></pre>
</div>
</div>
</p>
| 0 | 1,061 |
VBA EXCEL: How to call a subroutine in another subroutine?
|
<pre><code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Here I want my code
Sub Licenses()
Dim transientLicense As Integer
Dim steadyLicense As Integer
Dim staticLicense As Integer
Dim arr1 As Variant, arr2 As Variant, elem As Variant
arr1 = Array("radial vibration", "acceleration", "acceleration2", "velocity", "velocity2") '<--| set your first values list
arr2 = Array("axial vibration", "temperature", "pressure") '<--| set your 2nd values list
With Worksheets("Rack Properties") '<-| reference your relevant worksheet
With .Range("D1", Cells(Rows.Count, "AH").End(xlUp)) '<--| reference its columns D to AH range from row 1 down to column AH last not empty row
For Each elem In arr1 '<--| loop through 1st array list
transientLicense = transientLicense + WorksheetFunction.CountIfs(.Columns(1), "active", .Columns(20), "yes", .Columns(31), elem) '<-- update 'transientLicense' for every record matching: "active" in referenced range column 1(i.e. "D"), "yes" in referenced range column 20 (i.e. "W") and current list element in referenced range column 31 (i.e. "AH")
steadyLicense = steadyLicense + WorksheetFunction.CountIfs(.Columns(1), "active", .Columns(20), "no", .Columns(31), elem) '<-- update 'steadyLicense' for every record matching: "active" in referenced range column 1(i.e. "D"), "no" in referenced range column 20 (i.e. "W") and current list element in referenced range column 31 (i.e. "AH")
Next elem
For Each elem In arr2 '<--| loop through 2nd array list
staticLicense = staticLicense + WorksheetFunction.CountIfs(.Columns(1), "active", .Columns(31), elem) '<-- update 'staticLicense' for every record matching: "active" in referenced range column 1(i.e. "D") and current list element in referenced range column 31 (i.e. "AH")
Next elem
End With
End With
With Worksheets.Add
.Name = "Results"
.Columns("B:D").ColumnWidth = 20
.Range("B2:D2").Value = Array("Transient Licenses", "Steady Licenses", "Static Licenses")
.Range("B3:D3").Value = Array(transientLicense, steadyLicense, staticLicense)
End With
End Sub
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>I want to open all the excel sheets in a given folder and count the total no of licenses in each sheet and display the output in another workbook.
I have just started learning VBA and I am not able to use it in a macro.
A little help is really appreciated.
thank you so much in advance :)</p>
| 0 | 1,430 |
How to install optional rpms on RedHat 7?
|
<p>I am trying to install RedHat optional rpms on RHEL 7 as follow.</p>
<pre><code>sudo yum install rhel-7-server-extras-rpms rhel-7-server-optional-rpms
Loaded plugins: langpacks, product-id, rhnplugin, search-disabled-repos, subscription-
: manager
This system is receiving updates from RHN Classic or Red Hat Satellite.
epel/x86_64/metalink | 13 kB 00:00:00
epel | 4.7 kB 00:00:00
nginx | 2.9 kB 00:00:00
nodesource | 2.5 kB 00:00:00
(1/5): epel/x86_64/group_gz | 266 kB 00:00:00
(2/5): epel/x86_64/updateinfo | 860 kB 00:00:00
(3/5): nginx/x86_64/primary_db | 31 kB 00:00:00
(4/5): nodesource/x86_64/primary_db | 29 kB 00:00:00
(5/5): epel/x86_64/primary_db | 6.1 MB 00:00:02
rhel-x86_64-server-7 | 1.5 kB 00:00:00
rhel-x86_64-server-7/group | 636 kB 00:00:00
rhel-x86_64-server-7/updateinfo | 2.1 MB 00:00:00
rhel-x86_64-server-7/primary | 25 MB 00:00:02
rhel-x86_64-server-7 17802/17802
No package rhel-7-server-extras-rpms available.
No package rhel-7-server-optional-rpms available.
Error: Nothing to do
</code></pre>
<p>I am not able to understand this .</p>
<p>Why are the optional rpms not available to me ?</p>
<p>How do i setup a local repository of optional and extra rpms ?</p>
| 0 | 1,186 |
How to change Ruby Version for rails application
|
<p>Having some serious issues with Ruby at the moment and I have a feeling it's around versioning. </p>
<p>I have a Gemfile that looks like this</p>
<pre><code>source "https://rubygems.org"
ruby "2.5.2"
gem "rails", "4.2.1"
gem "unicorn", "4.8.3"
gem "mysql2"
gem "sass-rails", "~> 4.0.3"
gem "uglifier", ">= 1.3.0"
gem "coffee-rails", "~> 4.0.0"
gem "turbolinks"
gem "ancestry"
gem "kaminari"
gem "saxerator"
gem "factory_girl_rails"
gem "delayed_job_active_record"
gem "tree_delta", "~> 2.0.0"
gem "daemons"
gem "which-user", git: "https://ad131a5ab23a69365434b0e7e36d6275b6a1e9fb:x-oauth-basic@github.com/whichdigital/which-user.git", ref: '18eb7'
gem "eva_rails", git: "https://ad131a5ab23a69365434b0e7e36d6275b6a1e9fb:x-oauth-basic@github.com/whichdigital/eva_rails.git", tag: "v1.0.6"
gem "dam_client", git: "https://ad131a5ab23a69365434b0e7e36d6275b6a1e9fb:x-oauth-basic@github.com/whichdigital/digital_asset_manager_client.git", tag: "1.0.0"
gem "fragment_client", git: "https://ad131a5ab23a69365434b0e7e36d6275b6a1e9fb:x-oauth-basic@github.com/whichdigital/fragment_client.git", ref: '3c197'
gem 'frontend_containers', git: "https://ad131a5ab23a69365434b0e7e36d6275b6a1e9fb:x-oauth-basic@github.com/whichdigital/frontend_containers.git"
gem "cucumber-rails", require: false
gem "parallel_tests"
gem "elasticsearch"
gem 'patron'
gem 'typhoeus'
gem 'net-http-persistent'
gem "dalli"
gem "jbuilder"
gem "newrelic_rpm"
gem 'airbrake'
gem 'rest-client'
gem 'redis-rails'
gem 'dotenv-rails', :require => 'dotenv/rails-now'
gem 'mail'
gem 'rack-rewrite', '~> 1.5.0'
gem 'net-sftp'
gem 'httparty'
group :production do
gem 'rails_12factor'
end
group :test do
gem "timecop"
gem "webmock"
gem "site_prism"
gem "simplecov", require: false
end
group :development, :test do
gem "rspec-rails"
gem "rspec-its"
gem "shoulda-matchers", require: false
gem "database_cleaner"
gem "spring"
gem "spring-commands-rspec"
gem "spring-commands-cucumber"
gem "pry-rails"
gem "pry-byebug"
gem "rubocop", require: false
gem "selenium-webdriver"
gem "poltergeist"
gem "capybara-firebug"
gem "capybara-screenshot"
gem "yarjuf"
gem "launchy"
gem "web-console", "~> 2.0"
gem "bullet"
gem "rspec-collection_matchers"
gem "eyes_selenium"
gem 'ftpd'
end
</code></pre>
<p>I have <code>Bundler version 1.11.2</code> installed.</p>
<p>Gem version <code>2.4.6</code> </p>
<p>Rails <code>4.2.5.1</code></p>
<p>When I execute <code>ruby -v</code> I get this returned <code>ruby 2.0.0p645 (2015-04-13 revision 50299) [universal.x86_64-darwin15]</code></p>
<p>The read me file that came with this project said to run <code>"bin/setup"</code> which then prompted me to install <code>bundler</code>. Installed as you see above. </p>
<p>As that command is running I get the following error <code>Your Ruby version is 2.0.0, but your Gemfile specified 2.5.2</code></p>
<p>I cannot for some reason update to this version. </p>
<p>If anyone needs anymore information please let me know.</p>
| 0 | 1,321 |
Java homework hangman
|
<p>So for a class we are having to make a hangman game that can take a user input for a word and then have another person solve for it. It has to be able to recognize multiple repeating letters in the word or I would be done. Below is my code, it works great until I remove the break statement in my checkformatch method so that it goes past the initial finding of a letter. With the break in there it never finds the second third etc repeated letters, without it, it returns that each letter that is not the letter searched is a miss and reduces my life count. What I'm needing is some hints on how to search my array for the letter that is inputted as a guess and return their index positions in the array without it thinking each character in the array that is not the one guessed is a wrong input. Thank you in advance.</p>
<pre><code>package hangman;
import java.util.Scanner;
class Game {
int livesRemaining;
String letterGuessed;
String wordInput;
char[] hiddenWord;
char[] aOfWord ;
Scanner input = new Scanner(System.in);
boolean isFound;
int a;
public Game()
{
this.setLives(8);
//this.output();
System.out.println("Player 1 please enter the word to be searched: ");
wordInput = input.nextLine();
aOfWord = wordInput.toCharArray();
hiddenWord = new char[aOfWord.length];
for(int j = 0; j < hiddenWord.length; j++)
hiddenWord[j] = '*';
this.output();
while(livesRemaining > 0)
{
System.out.println("Please choose a letter: ");
letterGuessed = input.nextLine();
this.checkForMatch(letterGuessed);
if(isFound == true)
{
hiddenWord[a] = letterGuessed.charAt(0);
}
else
{
System.out.println("Is not found!");
this.reduceLives();
}
this.output();
}
}
public void setLives(int a)
{
this.livesRemaining = a;
}
public void reduceLives()
{
livesRemaining = livesRemaining -1;
System.out.println("Lives remaining: " + this.getLives());
}
public int getLives()
{
return livesRemaining;
}
public void output()
{
System.out.println("Lives remaining: " + this.getLives());
System.out.println("Word found so far ");
for(int i = 0; i < hiddenWord.length; i++)
{
System.out.print(hiddenWord[i] + "\n");
}
}
public void checkForMatch(String l)
{
for(int i = 0; i < aOfWord.length; i++)
{
//System.out.println("Comparing " + l.charAt(0) + " To " + aOfWord[i]);
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
a = i;
break;
}
else
{
isFound = false;
}
}
}
}
</code></pre>
| 0 | 1,080 |
Private fields from abstract class cannot be accessed in the subclass
|
<p>I have class which represents every object in my simple game (player, enemy, beam etc - they all have many commons like speed, position, dmg). So i made class named Thing. Here is how it looks like:</p>
<pre><code>public abstract class Thing {
private Image image;
private float x;
private float y;
private float speed;
private final int WIDTH;
private final int HEIGHT;
public Thing(String filename, float x, float y, float speed) {
try {
Image image = ImageIO.read(new File(filename));
} catch (Exception e) {}
this.x = x;
this.y = y;
this.speed = speed;
WIDTH = image.getWidth(null);
HEIGHT = image.getHeight(null);
}
//Zwraca ksztalt do sprawdzania czy contains...
public Rectangle2D getShade() {
return new Rectangle2D.Float(x, y, WIDTH, HEIGHT);
}
public Image getImage() {
return image;
}
public Point2D getPoint() {
return new Point2D.Float(x, y);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
</code></pre>
<p>I have extended the class Player:</p>
<pre><code>public class Player extends Thing {
public Player(String filename, float x, float y, float speed) {
super(filename, x, y, speed);
}
public void moveToPoint(Point2D targetPoint) {
int targetX = (int)targetPoint.getX();
int targetY = (int)targetPoint.getY();
if ( ((int)x+20 < targetX+3) && ((int)x+20 > targetX-3) ) {
return;
}
float distanceX = targetX - x;
float distanceY = targetY - y;
//Dodanie 20px wymiarow statku
distanceX -= 20;
distanceY -= 20;
//Ustalenie wartosci shiftow
float shiftX = speed;
float shiftY = speed;
if (abs(distanceX) > abs(distanceY)) {
shiftY = abs(distanceY) / abs(distanceX) * speed;
}
if (abs(distanceY) > abs(distanceX)) {
shiftX = abs(distanceX) / abs(distanceY) * speed;
}
//Zmiana kierunku shifta w zaleznosci od polozenia
if (distanceX < 0) {
shiftX = -shiftX;
}
if (distanceY < 0) {
shiftY = -shiftY;
}
//Jezeli statek mialby wyjsc poza granice to przerywamy
if ( (((int)x+shiftX < 0) || ((int)x+shiftX > 260)) || ((y+shiftY < 0) || (y+shiftY > 360)) ) {
return;
}
//Zmiana pozycji gracza
x += shiftX;
y += shiftY;
}
}
</code></pre>
<p>And here is the problem because my IDE underlines x, y and speed fields red and tells they cannot be accessed from Player class. I tried to change them into private and default but there appears an error after that. What am I doing wrong? When i create new object from class which extends Thing I want to copy all fields and init them as it is said in constructor. So how to repair it?</p>
| 0 | 1,306 |
Fatal crash: Focus search returned a view that wasn't able to take focus
|
<p>My application keeps crashing when I type something in a EditText, but this does not happen always only in some cases. I am running my app on a Samsung Galaxy Tab 2 10.1 WiFI & 3G (GT-P5100) with Android 4.0.4 (ICS). I use the stock Keyboard.</p>
<p>This is my logcat:</p>
<pre><code>11-28 21:43:01.007: E/AndroidRuntime(15540): java.lang.IllegalStateException: focus search returned a view that wasn't able to take focus!
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.widget.TextView.onKeyUp(TextView.java:5833)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.KeyEvent.dispatch(KeyEvent.java:2659)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.View.dispatchKeyEvent(View.java:5547)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1246)
11-28 21:43:01.007: E/AndroidRuntime(15540): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:2027)
11-28 21:43:01.007: E/AndroidRuntime(15540): at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1388)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.app.Activity.dispatchKeyEvent(Activity.java:2324)
11-28 21:43:01.007: E/AndroidRuntime(15540): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1954)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3360)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2618)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.os.Looper.loop(Looper.java:137)
11-28 21:43:01.007: E/AndroidRuntime(15540): at android.app.ActivityThread.main(ActivityThread.java:4514)
11-28 21:43:01.007: E/AndroidRuntime(15540): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 21:43:01.007: E/AndroidRuntime(15540): at java.lang.reflect.Method.invoke(Method.java:511)
11-28 21:43:01.007: E/AndroidRuntime(15540): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
11-28 21:43:01.007: E/AndroidRuntime(15540): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
11-28 21:43:01.007: E/AndroidRuntime(15540): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>This is my one of my EditTexts:</p>
<pre><code> <EditText
android:id="@+id/input_ftu_position_other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="64dp"
android:ems="20"
android:inputType="text" />
</code></pre>
| 0 | 1,307 |
jquery datatable border issue
|
<p>How to show the border for empty cells ? There some columns are blank and no values , so those columns are not displaying the border and its blank.Please see the below screen shot and advise.</p>
<p>One more is there are two lines of border , How to make it one of border ?</p>
<p><strong>HTML</strong></p>
<pre><code><table border="1" id="products1" style="width:750px" >
<thead>
<tr>
<th>End Date</th>
<th>Modify Date</th>
<th>Comments</th>
<th>By Who</th>
</tr>
</thead>
<tbody></tbody>
</table>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>oTable = $("#products1").dataTable({
"aaData": newarray,
"bProcessing": true,
"bDeferRender": true,
"bFilter": true,
"bRetrieve": true,
"bPaginate": true,
"bJQueryUI": true,
"iDisplayLength": 5,
"sPaginationType": "two_button",
"sDom": 'T<"clear">frtip',
"aoColumns": [{"sWidth": "135px","sClass": "center","bSortable": true},{
"sWidth": "145px","sClass": "center","bSortable": true},{
"sWidth": "145px","sClass": "center","bSortable": true},{
"sWidth": "20px","sClass": "center","bSortable": false}
],
"aoColumnDefs": [{ "fnRender": function (o, val) {
return o.aData[0];
},
"sClass": "end date","aTargets": [0]
}, {
"fnRender": function (o, val) {
return o.aData[1];
},
"sClass": "modified date","aTargets": [1]
}, {
"fnRender": function (o, val) {
return o.aData[2];
},
"sClass": "comments","aTargets": [2]
},{
"fnRender": function (o, val) {
return o.aData[3];
},
"sClass": "By who","aTargets": [3]
}
]
});
</code></pre>
| 0 | 1,049 |
iOS 11 Layout guidance about safe Area for iPhone x
|
<p>My application already in app store, yesterday i have updated my Xcode version to 9 and works fine except <strong>iPhone x</strong>. UI got collapsed.</p>
<p>1.Here I have Created Two <strong>UIView</strong>(both are fixed height) named as Header and Tab bar and I have hidden my <strong>NavigationBar</strong> entire app.</p>
<p>2.Added extension to <strong>UIViewController</strong> for making <strong>Header</strong> and <strong>Tab bar</strong></p>
<pre><code>func addHeaderTab(currentViewController:UIViewController,content:String, isMenu:Bool){
let noView = TopHeaderView()
noView.tag = 12345
noView.isMenu = isMenu
noView.translatesAutoresizingMaskIntoConstraints = false
currentViewController.view .addSubview(noView)
if isMenu{
noView.menuBtn .setImage(UIImage(named: "Small"), for: .normal)
noView.logoImg.isHidden = false
}else{
noView.menuBtn .setImage(UIImage(named: "arrow_small"), for: .normal)
noView.logoImg.isHidden = true
}
noView.titleLbl.text = content
noView.delegate = (currentViewController as! menuOpen)
NSLayoutConstraint(item: noView, attribute: .leading, relatedBy: .equal, toItem: currentViewController.view, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: noView, attribute: .trailing, relatedBy: .equal, toItem: currentViewController.view, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: noView, attribute: .top, relatedBy: .equal, toItem: currentViewController.view, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: noView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 64).isActive = true
}
</code></pre>
<p>and calling this every <strong>Viewcontroller</strong> like below :</p>
<pre><code>self.addHeaderTab(currentViewController: self, content:"நிகழ்ச்சி நிரல்" , isMenu: true)
</code></pre>
<p>Like that Tab bar also i have done but all the device working expect <strong>iPhone x</strong>.</p>
<p>See My screen shot : </p>
<p><a href="https://i.stack.imgur.com/1us5e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1us5e.png" alt="Image"></a></p>
<p>i have studied about <a href="https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/" rel="noreferrer">https://developer.apple.com/ios/human-interface-guidelines/overview/iphone-x/</a></p>
<p>but am not clear with their document.</p>
<p>Help would be appreciated, Thanks in advance.</p>
| 0 | 1,025 |
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI Spring 3
|
<p>Im new to spring mvc, earlier I accessed homepage via root package name "localhost/spring", and I cant find out what i'd changed that i got this error.
Web.xml:</p>
<pre><code> <servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</code></pre>
<p>Homepage Controller</p>
<pre><code>@Controller
public class HomeController {
private UserServiceImpl userService;
@Inject
public HomeController(UserServiceImpl userService)
{
this.userService = userService;
}
@RequestMapping(value="/")
public String home(Model model) {
System.out.println("Sdfsd");
model.addAttribute("users", userService.getUsers());
return "home";
}
}
</code></pre>
<p>servlet-context.xml:</p>
<pre><code> <annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="by.mvc.dao" />
<beans:bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<beans:property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<beans:property name="url" value="jdbc:hsqldb:hsql://localhost/user_db" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
<beans:property name="initialSize" value="5" />
<beans:property name="maxActive" value="10" />
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="by.mvc.dao" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory"/>
</beans:bean>
<beans:bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver"/>
<beans:bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/views/views.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</code></pre>
<p>Any ideas? thanks</p>
| 0 | 1,338 |
https URL is working fine with curl but not with Java
|
<p>I am trying to post data to a server with java to this url:</p>
<pre><code>https:www.stackoverflow.com
</code></pre>
<p>It's not updating the data.</p>
<p>But when I tried the same with curl it's updating the data with this url:</p>
<pre><code>E:\curl ssl>curl -k -X POST -u"user:pass" "www.stackoverflow.com"
</code></pre>
<p><strong>Edit:</strong></p>
<pre><code>public void authenticatePostUrl() {
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName
+ " vs. " + session.getPeerHost());
return true;
}
};
// Now you are telling the JRE to trust any https server.
// If you know the URL that you are connecting to then this should
// not be a problem
try {
trustAllHttpsCertificates();
} catch (Exception e) {
System.out.println("Trustall" + e.getStackTrace());
}
HttpsURLConnection.setDefaultHostnameVerifier(hv);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
URL url = new URL("www.stackoverflow.com");
String credentials = "user" + ":" + "password";
String encoding = Base64Converter.encode(credentials.getBytes("UTF-8"));
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
uc.setRequestMethod("POST");
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
uc.setRequestProperty("Accept", "application/x-www-form-urlencoded; charset=utf-8");
uc.getInputStream();
System.out.println(uc.getContentType());
InputStream content = (InputStream) uc.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = in.readLine()) != null) {
pw.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
pw.println("Invalid URL");
} catch (IOException e) {
e.printStackTrace();
pw.println("Error reading URL");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sw.toString());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CurlAuthentication au = new CurlAuthentication();
au.authenticatePostUrl();
au.authenticateUrl();
}
// Just add these two functions in your program
public static class TempTrustedManager implements
javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
private static void trustAllHttpsCertificates() throws Exception {
// Create a trust manager that does not validate certificate chains:
javax.net.ssl.TrustManager[] trustAllCerts =
new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TempTrustedManager();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc =
javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
</code></pre>
<p>Why is it not working in Java?</p>
<p>(For security reasons I changed the URLs above.)</p>
| 0 | 2,047 |
Missing Dll in dependency walker
|
<p>I am having a dll and which I am opening into the dependency walker with platform visual studio 2003 and OS is 2000. and my that dll find all dependency.</p>
<p>But when I am going to open that dll in to tha another system which is having OS- windows7 and visual studio 2010, I found missing dlls errors.</p>
<pre>
GDIPLUS.DLL,
GPSVC.DLL,
IESHIMS.DLL.
</pre>
<p>above listed 3 dll were missing. when I have downloded those dlls and put them into the same location where my dll is residing, I am finding below listed missing dlls list. </p>
<pre>
API-MS-WIN-CORE-COM-L1-1-1.DLL,
API-MS-WIN-CORE-DEBUG-L1-1-1.DLL,
API-MS-WIN-CORE-DELAYLOAD-L1-1-1.DLL,
API-MS-WIN-CORE-ERRORHANDLING-L1-1-1.DLL,
API-MS-WIN-CORE-FILE-L1-2-1.DLL,
API-MS-WIN-CORE-FILE-L2-1-1.DLL,
API-MS-WIN-CORE-HEAP-L1-2-0.DLL,
API-MS-WIN-CORE-HEAP-OBSOLETE-L1-1-0.DLL,
API-MS-WIN-CORE-JOB-L2-1-0.DLL,
API-MS-WIN-CORE-KERNEL32-LEGACY-L1-1-1.DLL,
API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.DLL,
API-MS-WIN-CORE-LOCALIZATION-L1-2-1.DLL,
API-MS-WIN-CORE-LOCALIZATION-OBSOLETE-L1-2-0.DLL,
API-MS-WIN-CORE-MEMORY-L1-1-2.DLL,
API-MS-WIN-CORE-PRIVATEPROFILE-L1-1-1.DLL,
API-MS-WIN-CORE-PROCESSENVIRONMENT-L1-2-0.DLL,
API-MS-WIN-CORE-PROCESSTHREADS-L1-1-2.DLL,
API-MS-WIN-CORE-REGISTRY-L1-1-0.DLL,
API-MS-WIN-CORE-REGISTRY-PRIVATE-L1-1-0.DLL,
API-MS-WIN-CORE-STRING-OBSOLETE-L1-1-0.DLL,
API-MS-WIN-CORE-SYNCH-L1-2-0.DLL,
API-MS-WIN-CORE-SYSINFO-L1-2-1.DLL,
API-MS-WIN-CORE-THREADPOOL-L1-2-0.DLL,
API-MS-WIN-CORE-THREADPOOL-LEGACY-L1-1-0.DLL,
API-MS-WIN-CORE-THREADPOOL-PRIVATE-L1-1-0.DLL,
API-MS-WIN-CORE-TIMEZONE-L1-1-0.DLL,
API-MS-WIN-DOWNLEVEL-ADVAPI32-L1-1-0.DLL,
API-MS-WIN-DOWNLEVEL-OLE32-L1-1-0.DLL,
API-MS-WIN-DOWNLEVEL-SHLWAPI-L1-1-0.DLL,
API-MS-WIN-EVENTING-PROVIDER-L1-1-0.DLL,
API-MS-WIN-SECURITY-ACTIVEDIRECTORYCLIENT-L1-1-0.DLL,
API-MS-WIN-SECURITY-BASE-L1-2-0.DLL,
API-MS-WIN-SECURITY-GROUPPOLICY-L1-1-0.DLL,
API-MS-WIN-SECURITY-LSALOOKUP-L1-1-1.DLL,
API-MS-WIN-SECURITY-LSALOOKUP-L2-1-1.DLL,
API-MS-WIN-SECURITY-PROVIDER-L1-1-0.DLL,
API-MS-WIN-SERVICE-CORE-L1-1-1.DLL,
API-MS-WIN-SERVICE-WINSVC-L1-2-0.DLL,
SYSNTFY.DLL.
</pre>
<p>It is may be because of configuration issue, please help me out to resolve this issue.</p>
| 0 | 1,192 |
How to solve "Failed to parse XML in AndroidManifest.xml"?
|
<p>In Android Studio I have a sync error:</p>
<pre><code>ERROR: Failed to parse XML in C:\...\app\src\main\AndroidManifest.xml
ParseError at [row,col]:[70,1]
Message: expected start or end tag
Affected Modules: app
</code></pre>
<p>I added <code>android:hardwareAccelerated ="true"</code> to <code>AndroidManifest.xml</code> but this did not fix my problem. How should I resolve this?</p>
<p>AndroidManifest.xml</p>
<pre><code><!--android:hardwareAccelerated ="true"-->
<application
android:name=".App"
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:roundIcon="@drawable/icon_round"
android:supportsRtl="true"
android:theme="@style/Theme.MaterialComponents.Light.NoActionBar"
android:hardwareAccelerated="true">
<activity
android:name=".SelectColor"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".AddAimActivity"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".MainActivity"
android:screenOrientation="sensorPortrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PopActivity"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".AddActionAtivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait" />
<activity
android:name=".SelectIconActivity"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".EditActionActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".EditRoutineActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".EditAimActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".AddReminder"
android:screenOrientation="sensorPortrait"/>
<receiver
android:name=".AlarmReceiver"
android:screenOrientation="sensorPortrait"/>
<activity
android:name=".AddRoutine"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait"/>
<service android:name="net.eagledev.planner.BackgroundService" android:exported="false" />
<service android:name=".NotificationService"/>
</application>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
</code></pre>
<p></p>
<p>App module</p>
<pre><code>compileSdkVersion 28
defaultConfig {
applicationId "net.eagledev.planner"
minSdkVersion 23
targetSdkVersion 28
versionCode 5
versionName "0.6"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
}}
</code></pre>
<p>Dependencies </p>
<pre><code>implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
implementation 'com.android.support:design:28.0.0'
implementation 'com.getbase:floatingactionbutton:1.10.1'
implementation 'com.github.clans:fab:1.6.2'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.android.support:recyclerview-v7:28'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-selection:28.0.0'
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
implementation 'com.android.support:gridlayout-v7:28.0.0'
</code></pre>
| 0 | 1,830 |
Butter Knife return null pointer
|
<p>I want to using Butter Knife in my project.I did everything according to the Butter Knife tutorial.
But when I set anything to the views (setText, setClickListener ...) I got null object reference exception.</p>
<p>This is my code:</p>
<pre><code>public class LoginActivity extends AppCompatActivity implements LoginView, View.OnClickListener {
@BindView(R.id.acEtUsername) AppCompatEditText userName;
@BindView(R.id.acEtPassword) AppCompatEditText password;
@BindView(R.id.prgCheckLogin) ProgressBar prgCheckLogin;
@BindView(R.id.btnLogin) Button btnLogin;
LoginPresenter loginPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
ButterKnife.setDebug(true);
loginPresenter = new LoginPresenterImpl(this);
btnLogin.setOnClickListener(this); // or userName.setText("userName");
}
/** Other Methods **/
</code></pre>
<p>activity_login.xml</p>
<pre class="lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.v7.widget.AppCompatEditText
android:id="@+id/acEtUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginRight="32dp"
android:layout_marginLeft="32dp"
android:hint="@string/user_name"/>
<android.support.v7.widget.AppCompatEditText
android:id="@+id/acEtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="32dp"
android:layout_marginLeft="32dp"
android:hint="@string/password"/>
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:text="@string/login"/>
<ProgressBar
android:id="@+id/prgCheckLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center|bottom"/>
</LinearLayout>
</code></pre>
<p>And error log</p>
<pre><code> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.AppCompatEditText.setText(java.lang.CharSequence)' on a null object reference
</code></pre>
<p>What's wrong in my code ?</p>
<p>Thanks</p>
| 0 | 1,209 |
Non-monotonous DTS in output stream when concat videos using ffmpeg
|
<p>I have three videos which I want to concat together the problem it works fine for some videos but when I test a specific video it gives me an error and cause the resulting video to show in a strange way and everything is moving very fast in the video like I was forward up the video<br>
this the code I used to add the video together from a file this the out.txt</p>
<pre><code>file 'D:/Build/start.mp4'
file 'D:/Build/a.mp4'
file 'D:/Build/Song & Lyrics/2f.mp4'
</code></pre>
<p>the command i used with ffmpeg</p>
<pre><code>ffmpeg -f concat -safe 0 -i out.txt -c copy -y go.mp4
</code></pre>
<p>i faced this error </p>
<pre><code> [mov,mp4,m4a,3gp,3g2,mj2 @ 05c0dbc0] Auto-inserting h264_mp4toannexb bitstream filter
Input #0, concat, from 'out.txt':
Duration: N/A, start: 0.000000, bitrate: 280 kb/s
Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 1280x720 [SAR 1:1 DAR 16:9], 155 kb/s, 29.97 fps, 29.97 tbr, 90k tbn, 59.94 tbc
Metadata:
creation_time : 2018-02-08T13:25:49.000000Z
handler_name : ISO Media file produced by Google Inc. Created on: 02/08/2018.
Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 125 kb/s
Metadata:
creation_time : 2018-02-08T13:25:49.000000Z
handler_name : ISO Media file produced by Google Inc. Created on: 02/08/2018.
Output #0, mp4, to 'go.mp4':
Metadata:
encoder : Lavf58.7.100
Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 1280x720 [SAR 1:1 DAR 16:9], q=2-31, 155 kb/s, 29.97 fps, 29.97 tbr, 90k tbn, 90k tbc
Metadata:
creation_time : 2018-02-08T13:25:49.000000Z
handler_name : ISO Media file produced by Google Inc. Created on: 02/08/2018.
Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 125 kb/s
Metadata:
creation_time : 2018-02-08T13:25:49.000000Z
handler_name : ISO Media file produced by Google Inc. Created on: 02/08/2018.
Stream mapping:
Stream #0:0 -> #0:0 (copy)
Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
[mov,mp4,m4a,3gp,3g2,mj2 @ 05c38840] Auto-inserting h264_mp4toannexb bitstream filter
[mp4 @ 061b8f00] Non-monotonous DTS in output stream 0:0; previous: 624624, current: 88735; changing to 624625. This may result in incorrect timestamps in the output file.
[mp4 @ 061b8f00] Non-monotonous DTS in output stream 0:0; previous: 624625, current: 89247; changing to 624626. This may result in incorrect timestamps in the output file.
[mp4 @ 061b8f00] Non-monotonous DTS in output stream 0:0; previous: 624626, current: 89759; changing to 624627. This may result in incorrect timestamps in the output file.
.....
[mov,mp4,m4a,3gp,3g2,mj2 @ 05c38840] Auto-inserting h264_mp4toannexb bitstream filtereed=69.7x
frame= 8991 fps=2903 q=-1.0 Lsize= 8378kB time=00:05:58.22 bitrate= 191.6kbits/s speed= 116x
video:2469kB audio:5625kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 3.500685%
</code></pre>
<p>so what the problem make this error. the problem appear when i use this new start.mp4 to be merge with my videos i tried on other ones and it worked fine.<br>
<strong>Update</strong><br>
i tested to convert the videos to MTS formate then concate them as an answer to similar problem but the problem is when i convert the mp4 videos to this formate the size of the file be too large from 6 MB to 42 MB!! so if there is a better answer. or a way to make the file still same size or less
the linke of the answer is <a href="https://superuser.com/a/1273576">here</a> but it worked fine
Thanks in advance </p>
| 0 | 1,436 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.