qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
4,413,878 | In my iPhone application, I need to get the data in an xml file. I'm using TBXML to do that.
Here's the the xml (simplified) that I need to get the data from:
```
<ResultSet version="1.0">
<Result>
<woeid>12792023</woeid>
</Result>
</ResultSet>
```
I need to put the data in `woeid` into an NSString.
I'm still very new to XML, and I'm problably very confused. Here's how I was trying to access it.
```
//locationString is a NSString containing a URL of a XML file
TBXML * XML = [[TBXML tbxmlWithURL:[NSURL URLWithString:locationString]] retain];
TBXMLElement * rootXML = XML.rootXMLElement;
NSString *WOEID = [TBXML textForElement:[TBXML childElementNamed:@"Result" parentElement:rootXML]];
```
It doesn't work correctly, so I'm assuming I'm doing it all wrong. Any suggestions?
Thanks in advance!
**--------------------------------------------------------------------------------------------------------------------**
The full XML file is here:
```
-<ResultSet version="1.0">
<Error>0</Error>
<ErrorMessage>No error</ErrorMessage>
<Locale>us_US</Locale>
<Quality>99</Quality>
<Found>1</Found>
−<Result>
<quality>72</quality>
<latitude>xxxxxxxx</latitude>
<longitude>xxxxxxxxx</longitude>
<offsetlat>xxxxxxxx</offsetlat>
<offsetlon>xxxxxxxxx</offsetlon>
<radius>500</radius>
<name>xxxxxxxx,xxxxxxx</name>
<line1>xxxxx xxx</line1>
<line2>xxxx, xx xxxxx</line2>
<line3/>
<line4>United States</line4>
<house/>
<street>xxxx xxx</street>
<xstreet/>
<unittype/>
<unit/>
<postal>11111</postal>
<neighborhood/>
<city>xxxxxxx</city>
<county>xxxxxxx</county>
<state>xxxxxx</state>
<country>United States</country>
<countrycode>US</countrycode>
<statecode>TX</statecode>
<countycode/>
<hash/>
<woeid>11111111</woeid>
<woetype>11</woetype>
<uzip>xxxxx</uzip>
</Result>
</ResultSet>
``` | 2010/12/10 | [
"https://Stackoverflow.com/questions/4413878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456851/"
] | When you *Attach* an entity, it goes to *Unchanged* state (it has not been changed since it attached to the context). All you need to is to explicitly change the Entity State to *Modified*:
```
_context.Users.Attach(user);
_context.Entry(user).State = System.Data.Entity.EntityState.Modified;
_context.SaveChanges();
``` | I believe u do not need to attach the entity before u call modified. simply setting to modified will do the job.
```
if (_context.Entry(user).State == EntityState.Detached)
{
_context.Entry(user).State = EntityState.Modified;
}
``` |
30,749,778 | i have two lists based on other objects.
```
List<Emyployee> emyployeeList;
List<Display> displayEmployeeList;
```
both of them have the id's of the employees, but the second list only have a few of them.
I want to filter the employeeList that i have all id's that arent in the displayEmployeeList.
how can i do that? | 2015/06/10 | [
"https://Stackoverflow.com/questions/30749778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4968222/"
] | Do not do this in JavaScript. Anyone can look at your source code and see the password. Do the password check in PHP instead. Then use `$_SESSION` variables to save the state while they are on your site. You may also want to use `$_COOKIE` variables for long term access, but just `$_SESSION` by itself is generally preferred in most cases for password access.
An alternate way to do it is with your web server. For example, if you are using Apache you can create a `.htaccess` file at the root of your website to ask for a name and password. That way you don't even need to code anything.
To do the second option, create a file called .htaccess in the root of your web directory. In the file put this in:
```
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /opt/passwords/.htpasswd
Require valid-user
```
(where /opt/passwords is a directory location outside of your web directory. It can be anywhere you want, you just want to make sure it is not anywhere within your web directory (otherwise it will be available for public viewing)).
In that directory, create a file called .htpasswd. This file will simply take a username and encrypted password. This page will allow you to create your name with password encryption: <http://www.htaccesstools.com/htpasswd-generator/> . Just paste that into your .htpasswd file.
With that said, any password you use can be intercepted if you are only using http and not https, but setting up https is a bit difficult if you haven't done it before. | This is not safe. User can have disabled JS.
One of correct ways is to use [http auth](http://httpd.apache.org/docs/2.2/howto/auth.html). |
6,522,865 | ```
return *reinterpret_cast<UInt32*>((reinterpret_cast<char*>(this) + 2));
```
Struct is pragma packed 1 and contains a bunch of uint, char, short fields...
Since it's UInt32, should it first be reinterpret\_cast to unsigned char\* instead or does it even matter?
Also, speed is critical here and I believe reinterpret\_cast is the fastest of the casts as opposed to static\_cast.
EDIT: The struct is actually composed of two single-byte fields followed by a union of about 16 other structs 15 of which have the UInt32 as its first field. I do a quick check that it's not the one without and then do the reinterpret\_cast to the 2 byte offset. | 2011/06/29 | [
"https://Stackoverflow.com/questions/6522865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/582204/"
] | Can't you just access the member directly? This is undefined behavior and won't work at all on systems that enforce word alignment (which is probably not a problem given you're doing it but needs to be mentioned).
`reinterpret_cast` wouldn't be any faster than `static_cast` because they just tell the compiler how to use memory at compile time. However `dynamic_cast` would be slower.
There's no legal way to just treat your `struct + offset` as a non-`char` type. | Since you say that the struct contains ints and shorts, I'm going to go out on a limb and answer on the assumption that this union is POD. If so then you benefit from 9.5/1:
>
> one special guarantee is made in
> order to simplify the use of unions:
> If a POD-union contains several
> POD-structs that share a common
> initial sequence (9.2), and if an
> object of this POD-union type contains
> one of the POD-structs, it is
> permitted to inspect the common
> initial sequence of any of POD-struct
> members
>
>
>
So, assuming your structure looks like this:
```
struct Foo1 { UInt32 a; other stuff; };
struct Foo2 { UInt32 b; other stuff; };
...
struct Foo15 { UInt32 o; other stuff; };
struct Bar { UInt16 p; other stuff; };
// some kind of packing pragma
struct Baz {
char is_it_Foo;
char something_else;
union {
Foo1 f1;
Foo2 f2;
...
Foo15 f15;
Bar b;
} u;
};
```
Then you can do this:
```
Baz *baz = whatever;
if (baz->is_it_Foo) {
UInt32 n = baz->u.f1.a;
}
```
If the members of the union aren't POD, then your `reinterpret_cast` is broken anyway, since there is no longer any guarantee that the first data member of the struct is located at offset 0 from the start of the struct. |
31,749,755 | A simple question with i had problems several times and i dind´t find a solution so far. For sure it is a peanut for you.
I am trying to bind the Text property of a comboBox to a column in the dataTable. If the column name has no spaces it is working:
For example:
```
Text="{Binding Path= MyColumn, ... }"
```
If the name has a space in between it doesn´t work:
For example:
```
Text="{Binding Path= My Column, ... }"
```
There must be something indicating the compiler that the name consists of both words with the space ("My Column"). But i didn´t find it yet.
Thanks | 2015/07/31 | [
"https://Stackoverflow.com/questions/31749755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4321369/"
] | The following delimiters did not work: `"" [] {}`
What you need is single quotes `''`
```
Text="{Binding Path= 'My Column', ... }"
``` | ```
Text="{Binding Path= 'My Column', ... }"
```
didn't work for me so I tried the code below that worked fine.
```
<TextBox>
<TextBox.Text>
<Binding Path="My Column"/>
</TextBox.Text>
</TextBox>
``` |
4,697,540 | If a float is repeatedly multiplied by a number that is less than one, is it plausible that the the float could become zero?
Here is an example:
```
float number = 1.0f;
for ( int i = 0; i < ONE_BILLION; ++i )
{
number *= 0.01f;
}
```
But please don't limit your answer to the example.
Thanks! | 2011/01/15 | [
"https://Stackoverflow.com/questions/4697540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes, when the result of the multiplication would be smaller than the representable number closest to zero, it will become zero. With IEEE floating point, this will happen for any multiplier less than or equal to `0.5f` (but greater than zero); however, if the multiplier is even slightly larger than `0.5f` (for instance, `0.5f + FLT_EPSILON`) the result will converge to the smallest representable positive number and stay there forever. Compare the behavior of this program with and without `-DGREATER`:
```
#include <stdio.h>
#include <float.h>
#ifdef GREATER
#define MULTIPLIER (0.5f + FLT_EPSILON)
#else
#define MULTIPLIER 0.5f
#endif
int
main(void)
{
float x = 1.0f;
unsigned int count = 0;
while (x > 0.0f && count < 200)
{
x *= MULTIPLIER;
printf("%g %a\n", x, x);
count++;
}
return 0;
}
``` | Depends on the implementation. With typical IEEE 754 implementation you'll first get down into denormals (losing precision) and then snap to 0. But some other implementation may give you a floating point underflow error, bang crash.
Cheers & hth., |
54,474,066 | I am using filter search for recyclerview.My app crashes automatically after some time,it looks like that text watcher is calling automatically.
I am getting this error
```
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual
> method 'void
> com.qasoftearth.abcipl.Adapter.ProductAdapter.filterList(java.util.ArrayList)'
> on a null object reference
> at com.qasoftearth.abcipl.NavDrawerActivity.filter(NavDrawerActivity.java:288)
> at com.qasoftearth.abcipl.NavDrawerActivity.access$100(NavDrawerActivity.java:60)
> at com.qasoftearth.abcipl.NavDrawerActivity$2.afterTextChanged(NavDrawerActivity.java:168)
**
```
>
>
> >
> > E/AndroidRuntime: FATAL EXCEPTION: main
> > Process: com.qasoftearth.abcipl, PID: 22202
> > java.lang.RuntimeException: Unable to start activity ComponentInfo{com.qasoftearth.abcipl/com.qasoftearth.abcipl.NavDrawerActivity}:
> > java.lang.NullPointerException: Attempt to invoke virtual method 'void
> > com.qasoftearth.abcipl.Adapter.ProductAdapter.filterList(java.util.ArrayList)'
> > on a null object reference
> > at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2584)
> > at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2666)
> > at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4336)
> > at android.app.ActivityThread.-wrap15(ActivityThread.java)
> > at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499)
> > at android.os.Handler.dispatchMessage(Handler.java:111)
> > at android.os.Looper.loop(Looper.java:207)
> > at android.app.ActivityThread.main(ActivityThread.java:5769)
> > at java.lang.reflect.Method.invoke(Native Method)
> > at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
> > at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
> > Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
> > com.qasoftearth.abcipl.Adapter.ProductAdapter.filterList(java.util.ArrayList)'
> > on a null object reference
> > at com.qasoftearth.abcipl.NavDrawerActivity.filter(NavDrawerActivity.java:288)
> > at com.qasoftearth.abcipl.NavDrawerActivity.access$100(NavDrawerActivity.java:60)
> > at com.qasoftearth.abcipl.NavDrawerActivity$2.afterTextChanged(NavDrawerActivity.java:168)
> > at android.widget.TextView.sendAfterTextChanged(TextView.java:8356)
> > at android.widget.TextView.setText(TextView.java:4419)
> > at android.widget.TextView.setText(TextView.java:4252)
> > at android.widget.EditText.setText(EditText.java:90)
> > at android.widget.TextView.setText(TextView.java:4227)
> > at android.widget.TextView.onRestoreInstanceState(TextView.java:4120)
> > at android.view.View.dispatchRestoreInstanceState(View.java:14957)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3264)
> > at android.view.View.restoreHierarchyState(View.java:14935)
> > at com.android.internal.policy.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2123)
> > at android.app.Activity.onRestoreInstanceState(Activity.java:1024)
> > at android.app.Activity.performRestoreInstanceState(Activity.java:979)
> > at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1171)
> > at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2551)
> > at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2666)
> > at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4336)
> > at android.app.ActivityThread.-wrap15(ActivityThread.java)
> > at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499)
> > at android.os.Handler.dispatchMessage(Handler.java:111)
> > at android.os.Looper.loop(Looper.java:207)
> > at android.app.ActivityThread.main(ActivityThread.java:5769)
> > at java.lang.reflect.Method.invoke(Native Method)
> > at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
> > at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
> >
> >
> >
>
>
>
\*\*
**NavDrawerActivity.java**
```
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
EditText search_edittext;
TextView viewCart,orderNow,addToCart,txtItemName,txtItemModelNum,txtItemDescriptions;
RecyclerView recyclerViewCategory,recyclerViewProduct;
ArrayList<CategoryDataModel> categoryArrayList;
ArrayList<ProductModelClass> productModelClassList;
ProductAdapter productAdapter;
CategoryAdapter categoryAdapter;
IntentFilter intentFilter;
MyReceiver receiver;
ShimmerFrameLayout shimmerContainer;
SharedPrefLogin sharedPrefLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sharedPrefLogout=new SharedPrefLogin(getApplicationContext());
categoryArrayList=new ArrayList<>();
productModelClassList=new ArrayList<>();
recyclerViewCategory = findViewById(R.id.recycler_view_horizontal);
recyclerViewProduct = findViewById(R.id.recycler_view_product_list);
search_edittext=findViewById(R.id.search_edittext);
viewCart=findViewById(R.id.txtv_viewCart);
orderNow=findViewById(R.id.txtv_OrderNow);
addToCart=findViewById(R.id.txtvAddToCart);
txtItemName=findViewById(R.id.txtItemName);
txtItemModelNum=findViewById(R.id.txtItemModelNum);
txtItemDescriptions=findViewById(R.id.txtItemDescriptions);
shimmerContainer = findViewById(R.id.shimmer_view_container);
shimmerContainer.startShimmerAnimation();
intentFilter = new IntentFilter();
intentFilter.addAction(Constants.CONNECTIVITY_ACTION);
if(InternetUtils.checkForInternet(getApplicationContext()))
{
fetchJSON();
}
else
{
if (!InternetUtils.checkForInternet(getApplicationContext())) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("No Internet Connection");
alertDialogBuilder
.setMessage("Please check your internet connection. ")
.setCancelable(false).setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
receiver = new MyReceiver();
registerReceiver(receiver, intentFilter);
}
//adding a TextChangedListener
//to call a method whenever there is some change on the EditText
search_edittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
//after the change calling the method and passing the search input
filter(editable.toString());
}
});
search_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
search_edittext.clearFocus();
InputMethodManager in = (InputMethodManager)getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(search_edittext.getWindowToken(), 0);
return true;
}
return false;
}
});
viewCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent viewCart=new Intent(NavDrawerActivity.this,CartListActivity.class);
startActivity(viewCart);
}
});
//*************************************Recyclerview Category**********************************************************
recyclerViewCategory.setHasFixedSize(true);
categoryArrayList.add(new CategoryDataModel("All Categories",R.drawable.delhi));
categoryArrayList.add(new CategoryDataModel("Fashion",R.drawable.delhi));
categoryArrayList.add(new CategoryDataModel("Mobile and \nElectronics",R.drawable.delhi));
categoryArrayList.add(new CategoryDataModel("Home and \n Living",R.drawable.delhi));
categoryArrayList.add(new CategoryDataModel("Daily Needs",R.drawable.delhi));
categoryArrayList.add(new CategoryDataModel("Books",R.drawable.delhi));
recyclerViewCategory.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
categoryAdapter = new CategoryAdapter(this, categoryArrayList);
recyclerViewCategory.setAdapter(categoryAdapter);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onResume() {
super.onResume();
shimmerContainer.startShimmerAnimation();
}
@Override
public void onPause() {
shimmerContainer.stopShimmerAnimation();
super.onPause();
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Constants.CONNECTIVITY_ACTION)){
if(InternetUtils.checkForInternet(context))
{
fetchJSON();
unregisterReceiver(receiver);
}
}
}
}
private void filter(String text) {
//new array list that will hold the filtered data
ArrayList<ProductModelClass> filteredNames = new ArrayList<>();
//looping through existing elements
for (ProductModelClass s : productModelClassList) {
//if the existing elements contains the search input
if (s.getName().toLowerCase().contains(text.toLowerCase())) {
//adding the element to filtered list
filteredNames.add(s);
}
}
Log.d("wwwee",text);
//calling a method of the adapter class and passing the filtered list
productAdapter.filterList(filteredNames);
}
private void fetchJSON() {
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.jsonURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("tennis", response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
ProductModelClass playersModel = new ProductModelClass();
JSONObject dataobj = dataArray.getJSONObject(i);
playersModel.setId(dataobj.getInt("id"));
playersModel.setName(dataobj.getString("name"));
playersModel.setCountry(dataobj.getString("country"));
playersModel.setCity(dataobj.getString("city"));
playersModel.setImgURL(dataobj.getString("imgURL"));
productModelClassList.add(playersModel);
}
}
recyclerViewProduct.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
productAdapter= new ProductAdapter(getApplicationContext(),productModelClassList);
recyclerViewProduct.setAdapter(productAdapter);
shimmerContainer.stopShimmerAnimation();
shimmerContainer.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
// Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_drawer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/* if (id == R.id.action_settings) {
return true;
}*/
if (id == R.id.action_cart) {
startActivity(new Intent(NavDrawerActivity.this, CartListActivity.class));
return true;
}
if (id == R.id.action_settings) {
startActivity(new Intent(NavDrawerActivity.this, SettingsActivity.class));
return true;
}
if (id == R.id.action_logout) {
sharedPrefLogout.logout();
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager=getSupportFragmentManager();
if (id == R.id.nav_about) {
// fragmentManager.beginTransaction().replace(R.id.content_frame,new Menu1Fragment()).commit();
Intent intent=new Intent(NavDrawerActivity.this, AboutUsActivity.class);
startActivity(intent);
}
if (id == R.id.nav_user) {
setTitle("Home");
// fragmentManager.beginTransaction().replace(R.id.content_frame,new Menu1Fragment()).commit();
Intent intent=new Intent(NavDrawerActivity.this, UserProfileActivity.class);
startActivity(intent);
} else if (id == R.id.nav_uploadImages) {
//fragmentManager.beginTransaction().replace(R.id.content_frame,new Menu1Fragment()).commit();
Intent intent=new Intent(NavDrawerActivity.this, UploadImagesActivity.class);
startActivity(intent);
// fragmentManager.beginTransaction().replace(R.id.content_frame,new Menu2Fragment()).commit();
} else if (id == R.id.nav_order_history) {
Intent intent=new Intent(NavDrawerActivity.this, OrderHistoryTabActivity.class);
startActivity(intent);
} else if (id == R.id.nav_settings) {
Intent intent=new Intent(NavDrawerActivity.this,SettingsActivity.class);
startActivity(intent);
} else if (id == R.id.nav_share) {
shareIt();
}
else if (id == R.id.nav_helpdesk) {
Intent intent=new Intent(NavDrawerActivity.this, HelpdeskActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
```
**ProductAdapter.java**
```
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Context ctx;
private List<ProductModelClass> productModelClassList;
public ProductAdapter(Context ctx, List<ProductModelClass> productModelClassList) {
this.ctx = ctx;
this.productModelClassList = productModelClassList;
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater=LayoutInflater.from(ctx);
View view=inflater.inflate(R.layout.layout_product_item_list,null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ProductViewHolder holder, final int position) {
Picasso.get().load(productModelClassList.get(position).getImgURL()).into(holder.imageView_product);
holder.txtview_itemname.setText(productModelClassList.get(position).getName());
holder.txtview_model.setText(productModelClassList.get(position).getCountry());
holder.txtview_desc.setText(productModelClassList.get(position).getCity());
holder.editTextQuantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
holder.editTextQuantity.setHint("");
else
holder.editTextQuantity.setHint("quantity");
}
});
holder.addToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProductModelClass item = new ProductModelClass();
int pid= productModelClassList.get(position).getId();
String image=productModelClassList.get(position).getImgURL();
String name = holder.txtview_itemname.getText().toString();
String country = holder.txtview_model.getText().toString();
String city = holder.txtview_desc.getText().toString();
ProductListDBHelper dbHelper = new ProductListDBHelper(ctx.getApplicationContext());
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertData(pid,image,name,country,city,database);
Toast.makeText(ctx.getApplicationContext(), "Product Added to the Cart", Toast.LENGTH_SHORT).show();
dbHelper.close();
}
});
}
@Override
public int getItemCount() {
return productModelClassList.size();
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
EditText editTextQuantity;
ImageView imageView_product;
TextView txtview_itemname,txtview_model,txtview_desc,addToCart;
Spinner spinner;
public ProductViewHolder(@NonNull View itemView) {
super(itemView);
imageView_product=itemView.findViewById(R.id.imageview_product);
txtview_itemname=itemView.findViewById(R.id.txtItemName);
txtview_model=itemView.findViewById(R.id.txtItemModelNum);
txtview_desc=itemView.findViewById(R.id.txtItemDescriptions);
editTextQuantity=itemView.findViewById(R.id.edttxt_quantity);
addToCart=itemView.findViewById(R.id.txtvAddToCart);
// spinner=(Spinner)itemView.findViewById(R.id.spinnerQuantity);
}
}
public void filterList(ArrayList<ProductModelClass> filterdNames) {
this.productModelClassList = filterdNames;
Log.d("dlkd", String.valueOf(productModelClassList));
notifyDataSetChanged();
}
}
``` | 2019/02/01 | [
"https://Stackoverflow.com/questions/54474066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10999478/"
] | After testing all the way I got a perfect solution for "fopen faild" & "execution time expired".
It happens when you'll use your invoice code in extending the master file like
```
@extends('admin.master')
@section('body')
/* your invoice code*/
@sectionend
```
To avoid all issue just paste source code of your invoice in download invoice blade, like
```
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>BigStore: Shopping Invoice</title>
</head>
<body>
<style>
/*css*/
</style>
<br>
/**html code**/
</body>
</html>
``` | At first run this :
```
php artisan vendor:publish
```
Then create fonts directory in storage
/storage/fonts
Make sure fonts directory has writable permission. |
50,890 | Any ideas what the average user's download speed is? I'm working on a site that streams video and am trying to figure out what an average download speed as to determine quality.
I know i might be comparing apples with oranges but I'm just looking for something to get a basis for where to start. | 2008/09/08 | [
"https://Stackoverflow.com/questions/50890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | It would depend on the geography that you are targeting. For example, in India, you can safely assume it would be a number below 256kbps. | There are a lot of factors involved (server bandwidth, local ISP, network in between, etc) which make it difficult to give a hard answer. With my current ISP, I typically get 200-300 kB/sec. Although when the planets align I've gotten as much as 2 MB/sec (the "quoted" peak downlink speed). That was with parallel streams, however. The peak bandwidth I've achieved on a single stream is 1.2 MB/sec |
3,989,816 | >
> **Possible Duplicate:**
>
> [Easiest way to split a string on newlines in .net?](https://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net)
>
>
>
I'm trying to read out and interpret a string line per line. I took a look at the StringReader class, but I need to find out when I'm on the last line. Here's some pseudocode of what I'm trying to accomplish:
```
while (!stringReaderObject.atEndOfStream()) {
interpret(stringReaderObject.readLine());
}
```
Does somebody know how to do this?
Thanks!
Yvan | 2010/10/21 | [
"https://Stackoverflow.com/questions/3989816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/254850/"
] | The StreamReader class has an EndOfStream property. Have you looked into using that? | Dismissile is correct:
<http://msdn.microsoft.com/en-us/library/system.io.streamreader.endofstream.aspx>
```
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
``` |
10,229 | Which are the parallel lines?

I prove that $a$ and $b$ are parallel but can't prove that $c$ and $d$ are parallel.
The angles, which are $135^o$ and $45^o$ are alternate angles.They aren't equal , so $c$ *isn't* parallel to $d$ but the answer is that $c$ is parallel to $d$. Am I right that they aren't?
**Edit**:
They are a little inclined like these:
 | 2010/11/14 | [
"https://math.stackexchange.com/questions/10229",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1795/"
] | This is a problem with extra information. Part of solving problems is knowing what to ignore! You are thinking about 4 lines, but to show two lines are parallel, you only really need 3.
So, you don't need to use **all** of the information given to solve this problem. In fact, you can *ignore line d* and just focus on how line c interacts with the lines you want to prove are parallel.
Next look at the theorem about parallel lines and their [transverse](http://www.mathnstuff.com/math/spoken/here/2class/260/trans.htm) again.
Then, you should have your proof. | Use corresponding angles to see if the lines are parallel. Note if the alternate interior angles are congruent. This will prove if any of these two pairs might fall under the category of Euclidean parallel lines. |
30,657,373 | I'm trying to embed these pages into my website.
<http://globalnews.ca/regina/feed/>
<http://weather.gc.ca/rss/city/sk-32_e.xml>
I'm not sure exactly how these pages are supposed to work. Are these pages only used for scraping data? I'm not sure how to get the information from these XML/RSS feeds? | 2015/06/05 | [
"https://Stackoverflow.com/questions/30657373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2192106/"
] | After some more search I discovered that I need to parse them XML in some fashion. I am using PHP so my first step is to use
```
simplexml_load_file('http://weather.gc.ca/rss/city/sk-32_e.xml');
```
and then read it from an array. | RSS (Rich Site Summary) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it.
Taggbox: the Free Online Feed Widget - Taggbox is a RSS feed widget. Simply copy & paste the snippet of code to embed into your web page. It's free and ready to use
CaRP Evolution | PHP RSS Parser / RSS to HTML Converter | Free Download — CaRP is an "RSS parser" or "RSS to HTML converter" -- a PHP web script that automatically keeps your website fresher by converting RSS data feeds to HTML, and integrating them seamlessly into your webpages.
Free RSS to HTML PHP Script — Free RSS to HTML PHP Script In addition to making your RSS feed available to your visitors for use with their RSS Feed Reader, as a webmaster you may also want to make the same feed available on your website for viewing with a regular web browser.
Feed Informer: Mix, convert, and republish feeds — Publishing a digest in your blog or on a website, or even Myspace page is extremely easy with our service. Plus, you can use our templates to fit it into your page's style.
Feedo Style - Feedo Style RSS Feed & Embedding — Try out Feedo Style by creating a digest. Use the controls and options below to customize the digest. You can also change the source of the feed by using the Feed Scraper: enter the address of a website, blog or podcast in the text field and hit the...
Feedroll - RSS tools, rss viewer, combine feeds — simple to use RSS viewer, and set up your very own RSS feed within minutes. Simple to use, effective and bringing relevant up to date information to your customers.
Bitty Browser -- Picture-in-Picture for the Web — Bitty Browser helps you keep track of your favorite Web stuff by enabling navigable windows directly within your favorite sites — it's like Picture-in-Picture for the Web. Bitty is a free embeddable browser that allows you to have a navigable window
How to Embed Almost Anything in your Website — Learn how to embed almost anything in your HTML web pages from Flash videos to Spreadsheets to high resolution photographs to static images from Google Maps and more.
How to Embed RSS Feeds into HTML Web Pages – The Easy Way — Google Gadget Creator for adding feeds to web pages – it’s easy as well as customizable. \*If you are looking for a non-Javascript solution, get one of these Flash based RSS widgets from Yourminis or WidgetBox.
Embed RSS/Atom Feed Content in Your Website - Basically, an RSSbox is an RSS reader widget - a rectangular area on your website or blog displaying text and images from RSS feeds. When creating a new RSSbox you decide on which type of layout and which RSS feeds to use. |
553,669 | In Russian we have the word *сор**о**ка* (magpie) for a person that (among other negative traits) likes and is attracted to shiny things (e.g. gold), usually cheap ones like fake jewelry, or just kind of hoards cheap things in general.
**What is the closest equivalent to this in English (preferably American English), if there is one of course?** | 2020/12/04 | [
"https://english.stackexchange.com/questions/553669",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/377101/"
] | Perhaps surprisingly, the answer is in your own question: "сорока" = *magpie*
>
> magpie (countable noun): If you describe someone as a magpie, you mean that they like collecting and keeping things, often things that have little value.
>
>
> {informal} "A born magpie, Mandy collects any object that catches her eye."
>
>
> [Collins dictionary](https://www.collinsdictionary.com/dictionary/english/magpie)
>
>
>
For example:
>
> "Magpies do not steal trinkets and are positively scared of shiny objects, according to new research.
>
>
> The study appears to refute the myth of the “thieving magpie”, which pervades European folklore.
>
>
> It is widely believed that magpies have a compulsive urge to steal sparkly things for their nests."
>
>
> [BBC](https://www.bbc.co.uk/news/science-environment-28797519)
>
>
> | @Anton's answer of *magpie* is probably the way to go here. But I feel compelled to throw in
>
> *positive phototaxis* which is the compulsion of an organism to move towards bight objects. ([Wikipedia](https://en.wikipedia.org/wiki/Phototaxis)) Like a moth to a flame.
>
>
>
Next time I'm feeling clever with my wife, I'll be sure to use this one. |
34,628,683 | I want to select image into gallery and that image i want to upload in dropbox.How can i do this?
i tried dropbox SDK but i do not know how to upload selected image
```
- (void)uploadFile:(NSString*)filename toPath:(NSString*)path fromPath:(NSString *)sourcePath
```
this method is defined in `DBRestClient.h`,a library file from the `DropBox SDK` for iOS. But as from the above declaration of the method, the "fromPath" of the image which is present in the UIImageView needs to be ascertained to upload it to my account on dropbox. Can you please help me in how to determine the path, or for that matter, any work around which can be applicable. | 2016/01/06 | [
"https://Stackoverflow.com/questions/34628683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055722/"
] | You should check whether there are rows first. dr.Read() returns whether the DataReader has rows, use it.
Your DataReader returns no results...
```
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
// read data for first record here
}
```
If you have more than one result, use a 'while' loop.
```
while (dr.Read()) {
// read data for each record here
}
``` | You should use dr.HasRows to check whether there is data or not. |
5,348,577 | This is a homework question.
I need to calculate 45^60 mod 61. I want to know of any fast method to get the result either programmatically or manually whichever is faster. | 2011/03/18 | [
"https://Stackoverflow.com/questions/5348577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665582/"
] | The result would be 1 because of Fermat's little theorem

if `p` is prime.
61 is a prime number so `a``p-1` when divided by `p` would give 1 as the remainder.
However if `p` is non-prime the usual trick is repeated-squaring. | Wolfram Alpha
--------------
Always have [Wolfram Alpha](http://www.wolframalpha.com/input/?i=45%5E60+mod+61) at hand :D
 |
15,285,032 | Is there a way to automatically apply [autopep8](https://github.com/hhatto/autopep8) to a file being edited in vim? I have the following [vimrc](https://github.com/mictadlo/vimrc4GO/blob/master/.vimrc).
Thank you in advance. | 2013/03/08 | [
"https://Stackoverflow.com/questions/15285032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/977828/"
] | autopep8 is included into [python-mode](https://github.com/klen/python-mode "python-mode").
Call :PymodeLintAuto or map it:
```
" Automatically fix PEP8 errors in the current buffer:
noremap <F8> :PymodeLintAuto<CR>
``` | The plugin didn't exist yet when the question has been submitted, but now there is vim-autopep8.
<https://github.com/tell-k/vim-autopep8> |
26,945,819 | I want my mysql query to be executed when the user clicks on delete button on the pop up box.I have button named 'Delete' and when the user clicks on the button a confirm box pops up and if the user clicks ok then the data should be deleted.I am not asking the query i want to know where should i write the code and how.I have written the code for button in controller and i have called a function in view.Please help as i have just started on cake and don't know i suppose anything about it. | 2014/11/15 | [
"https://Stackoverflow.com/questions/26945819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4255462/"
] | OpenCL is a standard defined by Kronos. They [distribute header files](https://github.com/KhronosGroup/OpenCL-Headers) that you have to give to your compiler. They do not distribute binaries to link against. For that, you must get an ICD (Installable Client Driver), on Windows this is in the form of a DLL file. You will get it from installing one or more of...
* [Nvidia drivers](http://www.nvidia.com/Download/index.aspx) (if you have an Nvidia GPU)
* [AMD drivers](http://support.amd.com/en-us/kb-articles/Pages/OpenCL2-Driver.aspx) (if you have an AMD GPU or an AMD CPU)
* [Intel Drivers](https://software.intel.com/en-us/articles/opencl-drivers) (if you have an Intel CPU, also some Intel CPU's have built in GPU's).
Do not worry about compiling against one vendor and it not working on another, OpenCL has been carefully designed to work around this. Compile against any version you have, it will work with any other version that is the same or newer, regardless of who made it.
**Be Aware**, the AMD OpenCL driver will operate as an OpenCL driver for Intel CPU's. If, for example, you have an AMD GPU and an Intel CPU, and have installed the Intel OpenCL driver **and** the AMD OpenCL driver, the AMD driver will report that it can provide both a GPU device and a CPU device (your CPU), and the Intel driver will report having a CPU device (also your CPU) and most likely also a GPU device (the GPU that is on the Intel CPU die, for example on an i7-3770, this will be a HD4000). If you blindly ask OpenCL for "All CPU's available" you will get the AMD drivers and the Intel drivers offering you the *same CPU*. Your code will not run very well in this case.
On Windows it is expected that you will [download the header files](https://github.com/KhronosGroup/OpenCL-Headers) yourself, and then either create a library from the DLL (MSVC), or link directly against the DLL (Mingw & Clang default behavior).
On Linux, you package manager will likely have a library to link against, consult your distributions documentation regarding this. On Ubuntu and Debian this command will work...
```
sudo apt-get install ocl-icd-opencl-dev
```
On Mac, there is nothing to install, and trying to install something will likely damage your system. Just install Xcode, and use the framework "OpenCL".
There are other platforms, for example Android. Some FPGA vendors offer OpenCL libraries. Consult your vendors documentation. | Khronos defines OpenCL standard. Each vendor/ open source will implement that standards.
Khronos defines set of conformance tests which need to pass if a vendor claims that his opencl implementation is as per standard. |
45,071,557 | How do redirect
* stderr to logfile
* stdout to object
Things I've looked at:
`>>` and `2>>` only redirect to file .
`-RedirectStandardOutput` and `-RedirectStandardError` only redirect to file again.
`| Out-File` cannot redirect stderr.
`| Tee-Object` same issue. | 2017/07/13 | [
"https://Stackoverflow.com/questions/45071557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2778405/"
] | A comprehensive explanation in [about\_Redirection](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_redirection) MSDN article.
[A Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) (*`stdout` to pipe*):
```none
PS D:\PShell> -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Output
-15
3
7.5
PS D:\PShell> Get-Content "$env:temp\err.txt"
Attempted to divide by zero.
At line:1 char:28
+ -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Outpu ...
+ ~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
PS D:\PShell>
```
Another example (*`stdout` to object*):
```none
PS D:\PShell> $x = -1,5,0,2| ForEach-Object { 15/$_} 2>"$env:temp\err.txt"
PS D:\PShell> $x
-15
3
7.5
``` | ```
cls
function GetAnsVal {
param([Parameter(Mandatory=$true, ValueFromPipeline=$true)][System.Object[]][AllowEmptyString()]$Output,
[Parameter(Mandatory=$false, ValueFromPipeline=$true)][System.String]$firstEncNew="UTF-8",
[Parameter(Mandatory=$false, ValueFromPipeline=$true)][System.String]$secondEncNew="CP866"
)
function ConvertTo-Encoding ([string]$From, [string]$To){#"UTF-8" "CP866" "ASCII" "windows-1251"
Begin{
$encFrom = [System.Text.Encoding]::GetEncoding($from)
$encTo = [System.Text.Encoding]::GetEncoding($to)
}
Process{
$Text=($_).ToString()
$bytes = $encTo.GetBytes($Text)
$bytes = [System.Text.Encoding]::Convert($encFrom, $encTo, $bytes)
$encTo.GetString($bytes)
}
}
$all = New-Object System.Collections.Generic.List[System.Object];
$exception = New-Object System.Collections.Generic.List[System.Object];
$stderr = New-Object System.Collections.Generic.List[System.Object];
$stdout = New-Object System.Collections.Generic.List[System.Object]
$i = 0;$Output | % {
if ($_ -ne $null){
if ($_.GetType().FullName -ne 'System.Management.Automation.ErrorRecord'){
if ($_.Exception.message -ne $null){$Temp=$_.Exception.message | ConvertTo-Encoding $firstEncNew $secondEncNew;$all.Add($Temp);$exception.Add($Temp)}
elseif ($_ -ne $null){$Temp=$_ | ConvertTo-Encoding $firstEncNew $secondEncNew;$all.Add($Temp);$stdout.Add($Temp)}
} else {
#if (MyNonTerminatingError.Exception is AccessDeniedException)
$Temp=$_.Exception.message | ConvertTo-Encoding $firstEncNew $secondEncNew;
$all.Add($Temp);$stderr.Add($Temp)
}
}
$i++
}
[hashtable]$return = @{}
$return.Meta0=$all;$return.Meta1=$exception;$return.Meta2=$stderr;$return.Meta3=$stdout;
return $return
}
Add-Type -AssemblyName System.Windows.Forms;
& C:\Windows\System32\curl.exe 'api.ipify.org/?format=plain' 2>&1 | set-variable Output;
$r = & GetAnsVal $Output
$Meta2=""
foreach ($el in $r.Meta2){
$Meta2+=$el
}
$Meta2=($Meta2 -split "[`r`n]") -join "`n"
$Meta2=($Meta2 -split "[`n]{2,}") -join "`n"
[Console]::Write("stderr:`n");
[Console]::Write($Meta2);
[Console]::Write("`n");
$Meta3=""
foreach ($el in $r.Meta3){
$Meta3+=$el
}
$Meta3=($Meta3 -split "[`r`n]") -join "`n"
$Meta3=($Meta3 -split "[`n]{2,}") -join "`n"
[Console]::Write("stdout:`n");
[Console]::Write($Meta3);
[Console]::Write("`n");
``` |
23,917,646 | I am currently building a layout where I have several 'triggers' inside a `<nav><ul><li><a>` element - each display a `<div>` which effectively sits 'behind' (z-index).
I need the divs (#showme and #showmetoo) to stay visible even if the user moves the mouse from the respective trigger (.thetrigger, .thenextrigger) - as the divs will contain content/links.
Additionally, when the user moves from one trigger to the next the displayed div should change.
```
<header>
<nav>
<ul>
<li><a class="thetrigger">Show Me That Thing</a></li>
<li><a class="thenexttrigger">Show Me That Thing</a></li>
</ul>
</nav>
<div id="showme">Yay, this thing</div>
<div id="showmetoo">and this thing</div>
</header>
```
CSS
```
header {
width: 100%;
height: 300px;
position: relative;
background: red;
z-index: 1;
}
nav {
position: absolute;
top: 10px;
left: 30px;
z-index: 3;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
}
nav ul li {
float: left;
padding: 30px;
}
.thetrigger, .thenexttrigger {
color: white;
}
#showme {
display: none;
background: blue;
color: white;
position: absolute;
top: 0;
left: 0;
height: 300px;
width: 100%;
z-index: 2;
}
#showmetoo {
display: none;
background: green;
color: white;
position: absolute;
top: 0;
left: 0;
height: 300px;
width: 100%;
z-index: 2;
}
```
jQuery
```
$(document).ready(function() {
$('.thetrigger').hover(function() {
$('#showme').fadeIn();
}, function() {
$('#showme').fadeOut();
});
$('.thenexttrigger').hover(function() {
$('#showmetoo').fadeIn();
}, function() {
$('#showmetoo').fadeOut();
});
});
```
<http://jsfiddle.net/richardblyth/24bcs/> | 2014/05/28 | [
"https://Stackoverflow.com/questions/23917646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050226/"
] | [**Demo**](http://jsfiddle.net/24bcs/4/)
It sounds like you want the div to remain until the next trigger is hovered over.
You can use a lot less jQuery if you use a class for the triggers, and find their respective divs using data. With this you can add as many triggers + corresponding divs as you like without having to write more jQuery.
HTML
```
<header>
<nav>
<ul>
<li><a class="trigger" data-show="pane1">Show Me That Thing</a></li>
<li><a class="trigger" data-show="pane2">Show Me That Thing</a></li>
</ul>
</nav>
<div class="pane" data-show="pane1" id="showme">Yay, this thing</div>
<div class="pane" data-show="pane2" id="showmetoo">and this thing</div>
</header>
```
jQuery
```
$(function(){
$('.trigger').on('mouseover', function(){
// show the desired pane and hide its siblings
$('.pane[data-show="' + $(this).data('show') + '"]').fadeIn().siblings('.pane').fadeOut();
});
});
``` | I think what you actually want, if I understand you question, is to hide the other #showme element when you hover into the trigger element associated with the #showmetoo element.
Like this:
```
$(document).ready(function() {
$('.thetrigger').hover(function() {
$('#showme').fadeIn();
$('#showmetoo').fadeOut();
});
$('.thenexttrigger').hover(function() {
$('#showmetoo').fadeIn();
$('#showme').fadeOut();
});
```
});
<http://jsfiddle.net/4N26S/> |
17,987,884 | I am new to android application development. I was doing this tutorial app.
When I run it in the emulator ,it says "Unfortunately AndroidJSONParsingActivity has stopped working.
" There are no errors in the code. The API level is 17 and the emulator is Nexus S.
Please help me out.
I got the tutorial CODE from [JSON tutorial](http://www.androidhive.info/2012/01/android-json-parsing-tutorial/)
AndroidJsonParsing.java
```
package com.example.androidjsonparsingactivity;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsing extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
```
JSONParser.java
```
package com.example.androidjsonparsingactivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
```
SingleMenuItemActivity.java
```
package com.example.androidjsonparsingactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
```
AndroidManifest.xml
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsingactivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidjsonparsingactivity.AndroidJSONParsing"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
```
Logcat
```
08-01 07:32:35.531: D/dalvikvm(1121): GC_FOR_ALLOC freed 42K, 7% free 2609K/2792K, paused 37ms, total 41ms
08-01 07:32:35.541: I/dalvikvm-heap(1121): Grow heap (frag case) to 3.288MB for 635812-byte allocation
08-01 07:32:35.591: D/dalvikvm(1121): GC_FOR_ALLOC freed 2K, 6% free 3227K/3416K, paused 47ms, total 47ms
08-01 07:32:35.672: D/dalvikvm(1121): GC_CONCURRENT freed <1K, 6% free 3237K/3416K, paused 9ms+16ms, total 82ms
08-01 07:32:35.740: D/AndroidRuntime(1121): Shutting down VM
08-01 07:32:35.740: W/dalvikvm(1121): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 07:32:35.761: E/AndroidRuntime(1121): FATAL EXCEPTION: main
08-01 07:32:35.761: E/AndroidRuntime(1121): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidjsonparsingactivity/com.example.androidjsonparsingactivity.AndroidJSONParsing}: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Looper.loop(Looper.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 07:32:35.761: E/AndroidRuntime(1121): at dalvik.system.NativeStart.main(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): Caused by: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.AndroidJSONParsing.onCreate(AndroidJSONParsing.java:54)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Activity.performCreate(Activity.java:5104)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-01 07:32:35.761: E/AndroidRuntime(1121): ... 11 more
``` | 2013/08/01 | [
"https://Stackoverflow.com/questions/17987884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640948/"
] | For Android 4.0 and above you cant do network operations on UI Thread and need to use background threads.
>
> You are calling the following code from the main thread instead of
> background thread therefore this exception is thrown .
>
>
>
```
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
```
**Instead create a [async task](http://developer.android.com/reference/android/os/AsyncTask.html) and perform this in the doInBackground() of the async task**
Async task performs the opertaion in background instead of performing it on the main /UI thread
```
class FetchJsonTask extends AsyncTask<Void, Void, void> {
protected Void doInBackground(Void... params) {
try {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
} catch (Exception e) {
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//code to be executed after background task is finished
}
protected void onPreExecute() {
super.onPreExecute();
//code to be executed before background task is started
}
return null;
}
```
In onCreate() call the execute the async task in the following way :
```
new FetchJsonTask().execute();
```
**Related Link:**
[How to fix android.os.NetworkOnMainThreadException?](https://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) | you have called the Web from main thread. that's why you have got
```
Caused by: android.os.NetworkOnMainThreadException
```
after android 4.0 you cant do network operations on its UIThread. you need to use background threads. i will prefer to use AsyncTask for network call.
Hope it Helps!! |
37,656,207 | In my HTML,
```
<a id="appLink" style="display:none" ></a>
```
in JS,
```
$("#appLink").prop("href", appSchemaURL);
$("#appLink").focus();
$("#appLink")[0].click();
```
How to bring the app window to front if already open? | 2016/06/06 | [
"https://Stackoverflow.com/questions/37656207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5361812/"
] | You mean *SetTimeout* that is used to run code after x amount of milliseconds ([here more](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout)).
Here is a working solution:
```
$(function() {
var global = '0'
run(); // run function run on page load.
function run(){
var cars = new Array("Saab", "Volvo", "BMW");
var wait = new Array("2000", "5000", "10000");
alert (cars[global]);
setTimeout(function(){
global++;
if (global == 3){
global = '0';
}
run();
}, wait[global]);
}
})
```
Here is [JSFiddle](https://jsfiddle.net/32ep27zm/) to it.
I moved:
```
global++;
if (global == 3){
global = '0';
}
```
Before the function call as if the call is before increment, it would call the function with *global = 0* again first. If you are unsure what I mean by that, try with JSFiddle.
Just clean a bit the code (for fun), here is my code (same code blocks just rearranged):
```
$(function() {
var cars = new Array("Saab", "Volvo", "BMW");
var wait = new Array("2000", "5000", "10000");
var global = '0'
run(); // Initial run.
function run(){
if (global == 3){
global = '0';
}
alert (cars[global]);
global++;
setTimeout(function(){
run();
}, wait[global]);
}
})
``` | ```
<script>
var index = 0;
var cars = [];
$( document ).ready(function() {
var obj = {car: "Volvo", timeout: "2000"};
cars.push(obj);
var obj = {car: "Saab", timeout: "5000"};
cars.push(obj);
var obj = {car: "BMW", timeout: "10000"};
cars.push(obj);
alertAndReRun();
});
function alertAndReRun(){
console.log(index + " " + (cars.length-1));
alert(cars[index].car);
index++;
if(index <= (cars.length-1)){
setTimeout(alertAndReRun, cars[index].timeout);
}
}
</script>
``` |
885,609 | I have a class that references a bunch of other classes. I want to be able to add these references incrementally (i.e. not all at the same time on the constructor), and I want to disallow the ability to delete the object underlying these references from my class, also I want to test for NULL-ness on these references so I know a particular reference has not been added. What is a good design to accomplish these requirements? | 2009/05/19 | [
"https://Stackoverflow.com/questions/885609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60800/"
] | I agree with other comments that you should use `boost::shared_ptr`.
However if you don't want the class holding these references to part-control the lifetime of the objects it references you should consider using `boost::weak_ptr` to hold the references then turn this into a `shared_ptr` when you want to us it. This will allow the referenced objects to be deleted before your class, and you will always know if object has been deleted before using it. | You are most likely looking for `boost::shared_ptr`. |
2,118,184 | I have been able to use Jquery with ASP.NET because I know where to drop the JQuery Library, but I am trying to integrate JQuery with Java Web Applications using JSP's,Servlets, etc.
It seems like a trivial question, but for some reason I am unable to figure out where to drop the JQuery Javascript file. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180253/"
] | If you have access to modify headers of html files you can load the jQuery library with [Google CDN for Ajax Libraries](http://code.google.com/apis/ajaxlibs/documentation/) without having to drop it physically on your server anywhere. | In modern Digital web platforms, put jquery.js in a folder /javascripts following the Twitter Bootstrap convention.
If you are using JSF 2.x then under folder /resources/javascripts |
1,235,116 | I'm loading jQuery from google on my site (<http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js>) which is minned and gzip'd. In firefox, the jquery file shows as a 19k request, but Safari shows it as a 56k request. I'm assuming then that Safari is not accepting it as a gzip'd file. What's the deal? It's coming from google and I'm pretty sure it's supposed to be gzip'd | 2009/08/05 | [
"https://Stackoverflow.com/questions/1235116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74389/"
] | Might want to have a look at [this link](http://www.webveteran.com/blog/index.php/web-coding/coldfusion/fix-for-safari-and-gzip-compressed-javascripts/).
>
> After some digging around I learned that you cannot send compressed javascripts to Safari with the extension of “gz”. It must be “jgz”
>
>
>
So seems the issue actually is with Google serving it up as "gz" rather than "jgz" like Safari wants it. | I see at least two possibilities :
* maybe safari is not sending the HTTP header that indicates "I am able to receive gzip" ; that header is `Accept-Encoding`, and its value is generally `compress, gzip`
* maybe Safari is indicating the size of the un-compressed data ?
Do you have some kind of "network sniffer", like [wireshark](http://www.wireshark.org/) *(seems there is version for MacOS)*, to really see what's going through the network ? |
7,049,960 | This is absolutely annoying me to death what can I do about this?
```
Guard is now watching at '/home/pma/Sites/somesite.com'
Starting Spork for RSpec & Cucumber
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/rspec.rb:2: warning: already initialized constant DEFAULT_PORT
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/rspec.rb:3: warning: already initialized constant HELPER_FILE
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/cucumber.rb:2: warning: already initialized constant DEFAULT_PORT
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/cucumber.rb:3: warning: already initialized constant HELPER_FILE
Using Cucumber
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/rspec.rb:2: warning: already initialized constant DEFAULT_PORT
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/rspec.rb:3: warning: already initialized constant HELPER_FILE
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/cucumber.rb:2: warning: already initialized constant DEFAULT_PORT
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/cucumber.rb:3: warning: already initialized constant HELPER_FILE
Using RSpec
Loading Spork.prefork block...
Loading Spork.prefork block...
Spork is ready and listening on 8989!
Spork is ready and listening on 8990!
Spork server for RSpec & Cucumber successfully started
Running all features
Disabling profiles...
Disabling profiles...
Exception encountered: #<Gherkin::Parser::ParseError: features/recruiting_goons.feature: Parse error at :6. Found feature when expecting one of: background, comment, scenario, scenario_outline, tag. (Current state: feature).>
backtrace:
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/parser/parser.rb:57:in `block in event'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/parser/parser.rb:99:in `event'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/parser/parser.rb:55:in `event'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/parser/parser.rb:45:in `method_missing'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/lexer/i18n_lexer.rb:23:in `scan'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/lexer/i18n_lexer.rb:23:in `scan'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/gherkin-2.4.6/lib/gherkin/parser/parser.rb:31:in `parse'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/feature_file.rb:37:in `parse'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/runtime/features_loader.rb:28:in `block in load'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/runtime/features_loader.rb:26:in `each'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/runtime/features_loader.rb:26:in `load'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/runtime/features_loader.rb:14:in `features'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/runtime.rb:132:in `features'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/runtime.rb:45:in `run!'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/cucumber-1.0.2/lib/cucumber/cli/main.rb:43:in `execute!'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.9.0.rc9/lib/spork/test_framework/cucumber.rb:24:in `run_tests'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/run_strategy/forking.rb:13:in `block in run'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/forker.rb:21:in `block in initialize'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/forker.rb:18:in `fork'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/forker.rb:18:in `initialize'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/run_strategy/forking.rb:9:in `new'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/run_strategy/forking.rb:9:in `run'
/home/pma/.rvm/gems/ruby-1.9.2-p180/gems/spork-0.8.5/lib/spork/server.rb:47:in `run'
/home/pma/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/home/pma/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/home/pma/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/home/pma/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'
/home/pma/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/drb/drb.rb:1588:in `block in main_loop'
Guard::RSpec is running, with RSpec 2!
Running all specs
```
Gemfile.lock:
```
GEM
remote: http://rubygems.org/
specs:
abstract (1.0.0)
actionmailer (3.0.9)
actionpack (= 3.0.9)
mail (~> 2.2.19)
actionpack (3.0.9)
activemodel (= 3.0.9)
activesupport (= 3.0.9)
builder (~> 2.1.2)
erubis (~> 2.6.6)
i18n (~> 0.5.0)
rack (~> 1.2.1)
rack-mount (~> 0.6.14)
rack-test (~> 0.5.7)
tzinfo (~> 0.3.23)
activemodel (3.0.9)
activesupport (= 3.0.9)
builder (~> 2.1.2)
i18n (~> 0.5.0)
activerecord (3.0.9)
activemodel (= 3.0.9)
activesupport (= 3.0.9)
arel (~> 2.0.10)
tzinfo (~> 0.3.23)
activeresource (3.0.9)
activemodel (= 3.0.9)
activesupport (= 3.0.9)
activesupport (3.0.9)
addressable (2.2.6)
arel (2.0.10)
bcrypt-ruby (2.1.4)
builder (2.1.2)
capybara (1.0.0)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (~> 0.2.0)
xpath (~> 0.1.4)
childprocess (0.2.0)
ffi (~> 1.0.6)
cucumber (1.0.2)
builder (>= 2.1.2)
diff-lcs (>= 1.1.2)
gherkin (~> 2.4.5)
json (>= 1.4.6)
term-ansicolor (>= 1.0.5)
cucumber-rails (1.0.2)
capybara (>= 1.0.0)
cucumber (~> 1.0.0)
nokogiri (>= 1.4.6)
database_cleaner (0.6.7)
devise (1.4.2)
bcrypt-ruby (~> 2.1.2)
orm_adapter (~> 0.0.3)
warden (~> 1.0.3)
diff-lcs (1.1.2)
erubis (2.6.6)
abstract (>= 1.0.0)
factory_girl (2.0.1)
ffi (1.0.9)
gherkin (2.4.6)
json (>= 1.4.6)
guard (0.5.1)
thor (~> 0.14.6)
guard-cucumber (0.5.2)
cucumber (>= 0.10)
guard (>= 0.4.0)
guard-rails (0.0.3)
guard (>= 0.2.2)
guard-rspec (0.4.1)
guard (>= 0.4.0)
guard-sass (0.2.4)
guard (>= 0.2.1)
sass (>= 3.1)
guard-spork (0.2.1)
guard (>= 0.2.2)
spork (>= 0.8.4)
guard-test (0.3.0)
guard (>= 0.2.2)
test-unit (~> 2.2)
haml (3.1.2)
i18n (0.5.0)
json (1.5.3)
json_pure (1.5.3)
launchy (2.0.4)
addressable (~> 2.2.6)
libnotify (0.5.7)
mail (2.2.19)
activesupport (>= 2.3.6)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.16)
nokogiri (1.5.0)
orm_adapter (0.0.5)
polyglot (0.3.2)
rack (1.2.3)
rack-mount (0.6.14)
rack (>= 1.0.0)
rack-test (0.5.7)
rack (>= 1.0)
rails (3.0.9)
actionmailer (= 3.0.9)
actionpack (= 3.0.9)
activerecord (= 3.0.9)
activeresource (= 3.0.9)
activesupport (= 3.0.9)
bundler (~> 1.0)
railties (= 3.0.9)
railties (3.0.9)
actionpack (= 3.0.9)
activesupport (= 3.0.9)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.4)
rake (0.9.2)
rdoc (3.9.1)
rspec (2.6.0)
rspec-core (~> 2.6.0)
rspec-expectations (~> 2.6.0)
rspec-mocks (~> 2.6.0)
rspec-core (2.6.4)
rspec-expectations (2.6.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.6.0)
rspec-rails (2.6.1)
actionpack (~> 3.0)
activesupport (~> 3.0)
railties (~> 3.0)
rspec (~> 2.6.0)
rubyzip (0.9.4)
sass (3.1.7)
selenium-webdriver (0.2.2)
childprocess (>= 0.1.9)
ffi (>= 1.0.7)
json_pure
rubyzip
spork (0.8.5)
sqlite3 (1.3.4)
term-ansicolor (1.0.6)
test-unit (2.3.1)
thor (0.14.6)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.29)
warden (1.0.5)
rack (>= 1.0)
xpath (0.1.4)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
capybara
cucumber-rails
database_cleaner
devise
factory_girl
guard
guard-cucumber
guard-rails
guard-rspec
guard-sass
guard-spork
guard-test
haml
launchy
libnotify
rails (= 3.0.9)
rspec-rails
sass
spork
sqlite3
``` | 2011/08/13 | [
"https://Stackoverflow.com/questions/7049960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75173/"
] | I'm not really sure which output you trying to cleanup, but here's what I'm seeing:
You have the standard spork messages that only happen at startup. The startup messages such as `Spork is ready and listening on 8989!` are a good thing since they tell you when spork is ready to start testing your files
Some messages about constants being initialized more than once. This may be that you are requiring something when you don't need to, but I'm guessing you'll only see them when you start guard.
The gherkin issue is with your recruiting\_goons.feature file and is likely a formatting problem. You want that output because it tells you something is wrong with your test. | I get similar warnings. Beerlington is right, mine are because I was requiring something when I didn't need to. Namely, I was requiring the model in each model spec file. I was doing so because when I run that model spec alone, unless I require the model explicitly, the partial code coverage results would end up not covering the model and produce incorrect results. When I removed the "require 'model'" line from my spec, the warnings went away. Note that for me, the file names it mentioned explicitly were my model names, which were being "required" redundantly.
Net net, look for why your "`rspec.rb`" and "`cucumber.rb`" files are required multiple times. Require them only once. |
14,947,341 | If I have a defaultdict(list)
```
from collections import defaultdict
d =defaultdict(list)
such as 1: 0
1:0.2
1: 0.3
2: 0.2
2: 0.4
2: 0.1
```
...... how I transform it into a similar defaultdict(list)
which values is the accumulation of values of the 1st dict with the same key, but never bigger than 1
```
1: 0
1: 0.2
1: 0.5
2: 0.2
2: 0.6
2: 0.7
.....
```
I have only following code so far, it is not quite right :-(
```
d2 = defaultdict(list)
for k in d.iterkeys()
v +=d(k)
d2[k]. append(v)
``` | 2013/02/18 | [
"https://Stackoverflow.com/questions/14947341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1830108/"
] | In your first code:
```
x = y
y = x + y
```
You are actually assigning `y + y` to `y`. Since the value of `x` is already overwritten. And this is not you wanted right?
---
And in your 2nd code:
```
x, y = y, x + y
```
First `y` and `x + y` on the RHS is evaluated, and then the evaluated value is assigned to `x, y` on the LHS. So, `x + y` will not have any side-effect of newly assigned value to `x`, as was happening in the first case. So, your `y` will only have `x + y`.
So, it's just the case of `evaluation` of both those expression on `RHS`, before the actual assignment is done.
And yes, the assignments outside your while loop, will not make any difference. But the 2nd way looks more appealing. | I would guess that in the second version, when it evaluates `y, x+y` it uses the original value of x in the x+y.
In the two line version, when it evaluates `x+y` x has been set to y which leads to x+y being the same as `y+y` |
15,333,824 | I am stuck on one query ,
where in i have 52 weeks data which i can arrange according to sysdate by getting the week number and comparing with datas week number.
now what i want to do is if the current week number is 10 i want to arrange all the weeks in descending order like depending on the sysdate week number week10,week9,week8.........week11,
with this query
```
select "Weekly","Quarter","SALES","Monthly",week_number from fiscal_calendar
where week_number <= TO_CHAR(TO_DATE(sysdate,'DD-mon-YYYY'),'iw')
order by week_number desc;
```
i am able to sort the data till week 1 but i want to continue the sequence like ending on week 11
so is there something i am doing wrong
please advice | 2013/03/11 | [
"https://Stackoverflow.com/questions/15333824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833043/"
] | If I understand correctly you can try
```sql
SELECT * FROM
(SELECT "Weekly","Quarter","SALES","Monthly",week_number FROM fiscal_calendar
WHERE week_number <= TO_NUMBER(TO_CHAR(SYSDATE,'IW'))
ORDER BY week_number desc) t1
UNION ALL
SELECT * FROM
(SELECT "Weekly","Quarter","SALES","Monthly",week_number FROM fiscal_calendar
WHERE week_number > TO_NUMBER(TO_CHAR(SYSDATE,'IW'))
ORDER BY week_number) t2
```
**Here is simplified [SQLFiddle example](http://sqlfiddle.com/#!4/db2f0/2)** | We can use `case()` (or `decode()`) in the order by clause ...
```
order by case
when week_number = to_number(to_char(sysdate, 'WW')) then 1
when week_number < to_number(to_char(sysdate, 'WW')) then 2
when week_number > to_number(to_char(sysdate, 'WW')) then 3
end ASC
, week_number DESC
``` |
15,765,857 | I know that maybe the title sounds a bit weird but I believe that my problem is weird indeed. I have an ASP.NET MVC 4 application (this is my first MVC real-world application) with Razor view-engine.
I have a layout view where I'm rendering two partial views like this:
```
<!-- Login -->
@Html.Action("RenderLoginPopup", "Login")
<!-- Registration -->
@Html.Action("RenderRegisterPopup", "Login")
```
Each of those actions from the Login controller just renders a partial view:
```
[ChildActionOnly]
public ActionResult RenderLoginPopup()
{
return PartialView("Partial/_LoginPopupPartial");
}
```
Just for exemplification sake (both are built the same way), the login partial view contains an ajax form like this:
```
@using (Ajax.BeginForm("Login", "Login", new AjaxOptions()
{
HttpMethod = "POST",
OnSuccess = "loginResponseReceived"
}, new { @id = "loginForm" }))
```
The Login action from the Login controller (the target of the form) is signed with the following attributes (worth to mention and notice the HttpPost one):
```
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Login(LoginModel model)
{ }
```
So far, so good... Everything works perfect - both the login and the register actions are working without any issues.
The issue that I want to speak about shows-up when I have a @Html.BeginForm() in a view that is loaded along with the main layout. For example, if I have a pure and simple form like this:
```
@using (Html.BeginForm())
{
<input type="hidden" name="name"/>
<input type="submit" value="Send"/>
}
```
along with the controller CaptionExtendedController:
```
[HttpPost]
public ActionResult Index(string nume)
{
return View();
}
```
So, in the end, in my final html generated file I will have 3 forms - 2 for login and register (ajax) and one simple form generated from the last view. Please keep in mind that all three forms are independent (meaning that they are not one in another).
The issue is that everytime I'm pressing the button "Send" from the last form all controllers that are signed with the [HttpPost] attribute from my view (Login, Register from LoginController and Index from CaptionExtendedController) gets called.
WHY??? In order to have a temporary fix, I've removed the [HttpPost] attribute from the Login and Register actions and now it's working but I don't think this is correct.
Please, there is someone who can explain me why this is happening and eventually point me to the right direction in fixing this issue?
Thank you in advance. | 2013/04/02 | [
"https://Stackoverflow.com/questions/15765857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016557/"
] | Go to [www.anindya.com](http://www.anindya.com) download \*php\_curl-5.4.3-VC9-x64.zip\* under "Fixed curl extensions:" and replace the php\_curl.dll in ext folder.
via. <http://forum.wampserver.com/read.php?2,85642> | I solved the problem installing WAMP 32 bit version on WIN 7 64BIT, in this way CURL worked. |
6,491,109 | I have one Runnable that is used by more than one thread:
```
Runnable myRunnable = new MyWorker();
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
```
How can I get all threads that are created with `myRunnable`?
(Of course the example is simplified. I create new threads with `myRunnable` on several places in different classes.)
Use case (as requested): `MyWorkerOfMyPage` is a delayed worker that is bound to a page. If the user leaves this page (e.g. by navigating to another page) all threads that belong to `MyWorkerOfMyPage` should be killed ungracefully as their result is not needed anymore. | 2011/06/27 | [
"https://Stackoverflow.com/questions/6491109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462642/"
] | As already said best way is to track this yourself. This forces you to get a clear understanding of what you are doing. A good thing if you work with threads ... hmmm ... a good thing in every case ;).
But if you **realy** want to detect the threads you can use reflection with the Thread class to get the required information. First make the method "getThreads" accessible to get all running Threads, then make the field "target" accessible to get the runnables of the Threads.
Heres an example program (but I would advise **against** the usage in a real application. You should now what threads you are starting, it might harm compability with future JDKs, might harm portability ...):
```
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("Start: " + Thread.currentThread().getName());
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
List<Thread> threads = getThreadsFor(myRunnable);
for (Thread thread : threads)
System.out.println("Found: " + thread.getName());
}
private static List<Thread> getThreadsFor(Runnable myRunnable) throws Exception {
Method getThreads = Thread.class.getDeclaredMethod("getThreads");
Field target = Thread.class.getDeclaredField("target");
target.setAccessible(true);
getThreads.setAccessible(true);
Thread[] threads = (Thread[]) getThreads.invoke(null);
List<Thread> result = new ArrayList<Thread>();
for (Thread thread : threads) {
Object runnable = target.get(thread);
if (runnable == myRunnable)
result.add(thread);
}
return result;
}
}
``` | The best way to do this is to track this yourself. Use a global singleton for instance that launches the threads and track which ones you started. |
5,804 | My wife is transferring with her current employer for two years to Ireland on a Critical Skills work permit. I will be going with her and plan on continuing to work my current US job remotely from Ireland. I am a software developer for a small US business with no foreign presence.
It seems to me that a Work Permit is not applicable in this case since I will not be working for an Irish company. | 2015/03/13 | [
"https://expatriates.stackexchange.com/questions/5804",
"https://expatriates.stackexchange.com",
"https://expatriates.stackexchange.com/users/6233/"
] | [Verizon](http://www.verizonwireless.com/b2c/store/controller?&item=prepayItem&action=viewPrepayOverview&zipRdr=y), and probably all the major carriers, offer prepaid sim only deals where $100 will keep your number for a year. At $8.50 or so a month it is probably cheaper any other plan you will find. As you only need to keep a few pennys worth of credit to keep the number, you might be able to resell, at a loss, some of the time by letting friends make calls or surf the web from your account. I am not aware of anyway to suspend your account for long periods of time. | You can use an unlocked VoIP SIP service like [Anveo.com](http://Anveo.com/), where the cost of keeping a US/Canada phone number on the *Personal Unlimited* rate plan is 2 USD per month, which includes an unlimited number of incoming voice calls for personal use, plus they even support SMS (most unlocked VoIP providers don't). The normal cost to port a number is 15 USD, but they often run a porting promotion in that they'll do the porting for free if you prepay Personal Unlimited for 12 months, e.g. it'll cost you a total 24 USD for first year, then 2 USD per month thereafter, to have an unlimited use of your phone number for incoming phone calls anywhere in the world for as long as you please. There are also other alternative SIP providers, but most of them don't support SMS.
You can use the service with any software or hardware that supports SIP. E.g., you can buy one of the many hardware phones like Cisco SPA303, or you can you an unlocked softphone on your mobile phone like Acrobits Softphone (or, if you're using Android, it may even have integrated SIP support out of the box directly within the Phone app). |
3,924,810 | I'm using this PHP/CodeIgniter library for jQuery Highcharts: <http://www.crustiz.com/php-jquery/highcharts-library-for-codeigniter/>
The way that library does things is that it builds a PHP array of options, then converts it to json using json\_encode (see line 273 of that library) which is then used by the jQuery Highcharts plugin. This is fine, except the option I'm trying to use is the tooltip formatter, which needs to be a javascript function, not a string (see <http://www.highcharts.com/ref/#tooltip>).
Since the library doesn't have a tooltip function, I created one as a test:
```
function set_tooltip() {
$this->a_options['tooltip']['formatter'] = 'function() { return this.series.name + "<br>" + this.x + ": " + this.y }';
return $this;
}
```
But this doesn't work as the JS function is output as a string, not a function. Anyone know if there is a way to have it be a function after passing through json\_encode without rewriting that part of the library? | 2010/10/13 | [
"https://Stackoverflow.com/questions/3924810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183929/"
] | JSON isn't meant to convey functions. If you take a look at the [documentation](http://www.json.org/), there are only specifications for four types - object, array, string and number - plus the values `true`, `false` and `null`.
If you insist on doing this, perhaps an article like [Sending Javascript Functions Over JSON](http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/) will give you a hand. | JSON doesn't have a "function callback" type so I think this is not possible. It knows [only the basic types](http://json.org/): `string` / `number` / `object` / `array` |
9,873,190 | I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do I always get a null value?
```
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);
if (location != null) {
System.out.println("Location is not null!");
lat = (int) (location.getLatitude() *1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
"2nd String");
CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
overlayList.clear();
} else {
System.out.println("Location is null! " + towers);
Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
.show();
}
``` | 2012/03/26 | [
"https://Stackoverflow.com/questions/9873190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240449/"
] | `getLastKnownLocation()` uses the location(s) previously found by other applications. if no application has done this, then `getLastKnownLocation()` will return null.
One thing you can do to your code to have a better chance at getting as last known location- iterate over all of the enabled providers, not just the best provider. For example,
```
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
```
If your app can't deal without having a location, and if there's no last known location, you will need to listen for location updates. You can take a look at this class for an example,
>
> <https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java>
>
>
>
See the method `onStartCommand()`, where it checks if the network provider is enabled. If not, it uses last known location. If it is enabled, it registers to receive location updates. | Try this this will not give you null current location
```
class GetLastLocation extends TimerTask {
LocationManager mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListenerTmp = new CustomLocationListener();
private final Handler mLocHandler;
public GetLastLocation(Handler mLocHandler) {
this.mLocHandler = mLocHandler;
}
@Override
public void run() {
timer.cancel();
mlocManager.removeUpdates(mlocListenerTmp);
Location location = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
{
if (mlocListenerTmp != null) {
mlocManager.removeUpdates(mlocListenerTmp);
}
currentLocation = location;
}
if (location != null) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Log.d("loc", " :" + message);
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Log.d(
"loc",
":No GPS or network signal please fill the location manually!");
location = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLocation = location;
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", true);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
} else {
Bundle b = new Bundle();
{
b.putBoolean("locationRetrieved", false);
{
Message msg = Message.obtain();
{
msg.setData(b);
mLocHandler.sendMessage(msg);
}
}
}
}
}
}
}
```
call it like this
```
timer.schedule(new GetLastLocation(mLocHandler), 3000);
```
and the customLocationclass is as follows
```
public class CustomLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
currentLocation = loc;
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
Log.d("loc", "onLocationChanged" + Text);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
``` |
3,184,727 | How do I make fields accessible across a package? Currently, even if they are declared public i'm not able to access the fields from another class in the same package. | 2010/07/06 | [
"https://Stackoverflow.com/questions/3184727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381699/"
] | You could echo the table headings before the while loop;
```
<thead>
<tr>
<th>Name:</th>
<th>Quantity:</th>
<th>Cost:</th>
</tr>
</thead>
<?php
$sqlstr = mysql_query("SELECT * FROM sales where passport = '{$therecord['passport']}'");
if (mysql_numrows($sqlstr) != 0) {
....
}
....
?>
```
This would sort your SUM issue (using mysql\_result). Currently you are only outputting the resource.
```
$sqltotal = mysql_result(mysql_query("SELECT SUM(cost) FROM sales where passport = '{$therecord['passport']}'"),0);
echo "<b>Total Owing: {$sqltotal}</b>";
``` | ```
sqlstr = mysql_query(
"SELECT * FROM sales where passport = '{$therecord['passport']}'");
if (mysql_numrows($sqlstr) != 0) {
echo "<b>Sales for {$therecord['firstname']} {$therecord['lastname']}</b>";
while ($row = mysql_fetch_array($sqlstr)) {
echo "<table><tr>";
echo "<td>{$row['product']}</td>";
echo "<td>{$row['quantity']}</td>";
echo "<td>{$row['cost']}</td>";
echo "</tr>";
echo "</table>";
}
}
echo "<b>Total Owing: ".mysql_num_rows($sqlstr)."</b>";
```
**Just have to run the number or rows as the query is the same as above!** |
35,488,772 | My data looks like this
```
Peak Ret. Time: 2.083 Min
Number of Points: 6
187.0 194009.0
188.0 308396.0
189.0 319163.0
190.0 321506.0
191.0 321962.0
192.0 321474.0
Peak Ret. Time: 2.683 Min
Number of Points: 6
187.0 194009.0
188.0 308396.0
189.0 319163.0
190.0 321506.0
191.0 321962.0
192.0 321474.0
Peak Ret. Time: 2.417 Min
Number of Points: 4
187.0 20844.0
188.0 30229.0
189.0 31131.0
190.0 30874.0
Peak Ret. Time: 2.667 Min
Number of Points: 8
187.0 59137.0
188.0 75392.0
189.0 64461.0
190.0 51970.0
191.0 41550.0
192.0 33235.0
193.0 22146.0
194.0 19069.0
```
Here I want to have a data like this
```
Peak Ret. Time: 2.083 Min 2.683 Min 2.417 Min 2.667 Min
187 194009 194009 20844 59137
188 308396 308396 30229 75392
189 319163 319163 31131 64461
190 321506 321506 30874 51970
191 321962 321962 0 41550
192 321474 321474 0 33235
193 0 0 0 22146
194 0 0 0 19069
```
At first, I want to search for the data with longest Number of point (in this case it is 8) then I use its first column to the new data. then I remove all other part from the first column because it is repeated, over and over but with different or equal length. Then I put the second column of the first part (2.083 min) then the second column part of the second etc until the end. At the end I fill the empty spaces with zeros. | 2016/02/18 | [
"https://Stackoverflow.com/questions/35488772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5918251/"
] | In python, strictly speaking, the language has only naming references to the objects, that behave as labels. The assignment operator only binds to the name. The objects will stay in the memory until they are garbage collected | Ok, first things first.
Remember, there are two types of objects in python.
1. Mutable : Whose values can be changed. Eg: dictionaries, lists and user defined objects(unless defined immutable)
2. Immutable : Whose values can't be changed. Eg: tuples, numbers, booleans and strings.
Now, when python says PASS BY OBJECT REFERENECE, just remember that
***If the underlying object is mutable, then any modifications done will persist.***
and,
***If the underlying object is immutable, then any modifications done will not persist***.
If you still want examples for clarity, scroll down or click [here](https://stackoverflow.com/a/54915890/20272640) . |
57,839,723 | So my friend got this email from OneSignal
>
> Due to a change that may occur as part of the upcoming iOS 13 release, you must update to the latest version of the iOS SDK before building your app with Xcode 11. All of OneSignal’s wrapper SDKs including React Native, Unity, and Flutter have been updated as well.
> The reason for this is that Xcode 11, which is being released alongside iOS 13, breaks a common technique that apps and libraries like OneSignal were using to get a push token for the device. If you do not use our new SDK then new users will not be able to subscribe to notifications from your app.
>
>
>
And I got curious about it.
This is the way we got the device notification token on iOS 12
```
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Notification token = \(token)")
}
```
Whats the proper way to get it on iOS 13?
Should I do the new way for my currently developing apps or the old way is still fine? | 2019/09/08 | [
"https://Stackoverflow.com/questions/57839723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6449292/"
] | Correctly capture iOS 13 Device Token in Xamarin.iOS
```
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
//DeviceToken = Regex.Replace(deviceToken.ToString(), "[^0-9a-zA-Z]+", "");
//Replace the above line whick worked up to iOS12 with the code below:
byte[] bytes = deviceToken.ToArray<byte>();
string[] hexArray = bytes.Select(b => b.ToString("x2")).ToArray();
DeviceToken = string.Join(string.Empty, hexArray);
}
```
Here is what's going on here:
1. First we have to grab all the bytes in the device token by calling
the ToArray() method on it.
2. Once we have the bytes which is an array of bytes or, byte[], we
call LINQ Select which applies an inner function that takes each
byte and returns a zero-padded 2 digit Hex string. C# can do this
nicely using the format specifier x2. The LINQ Select function
returns an IEnumerable, so it’s easy to call ToArray() to
get an array of string or string[].
3. Now just call Join() method on an array of string and we end up with
a concatenated string.
Reference: <https://dev.to/codeprototype/correctly-capture-ios-13-device-token-in-xamarin-1968>
**Solution 2: This also works fine**
```
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
byte[] result = new byte[deviceToken.Length];
Marshal.Copy(deviceToken.Bytes, result, 0, (int)deviceToken.Length);
var token = BitConverter.ToString(result).Replace("-", "");
}
``` | use `deviceToken.debugDescription` |
3,947,227 | I want to make a deep copy of an object array using a constructor.
```
public class PositionList {
private Position[] data = new Position[0];
public PositionList(PositionList other, boolean deepCopy) {
if (deepCopy){
size=other.getSize();
data=new Position[other.data.length];
for (int i=0;i<data.length;i++){
data[i]=other.data[i];
}
```
However, what I have above for some reason is not working. I have automated tests that I run, and its failing those tests. So theres an error an here that Im not sure what it is. | 2010/10/16 | [
"https://Stackoverflow.com/questions/3947227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/458960/"
] | What you have implemented is a **shallow** copy. To implement a **deep** copy, you must
change
```
data[i] = other.data[i];
```
to some thing that assigns a **copy** of `other.data[i]` to `data[i]`. How you do this depends on the `Position` class. Possible alternatives are:
* a copy constructor:
`data[i] = new Position(other.data[i]);`
* a factory method:
`data[i] = createPosition(other.data[i]);`
* clone:
`data[i] = (Position) other.data[i].clone();`
Notes:
1. The above assume that the copy constructor, factory method and clone method respectively implement the "right" kind of copying, depending on the Position class; see below.
2. The `clone` approach will only work if `Position` explicitly supports it, and this is generally regarded as an inferior solution. Besides, you need to be aware that the native implementation of `clone` (i.e. the `Object.clone()` method) does a shallow copy1.
In fact the general problem of implementing deep copying in Java is complicated. In the case of the `Position` class, one would assume that the attributes are all primitive types (e.g. ints or doubles), and therefore a deep versus shallow copying is moot. But if there are reference attributes, then you have to rely on the copy constructor / factory method / clone method to do the kind of copying that you require. In each case it needs to be programmed in. And in the general case (where you have to deal with cycles) it is difficult and requires each class to implement special methods.
There is one other *potential* way to copy an array of objects. If the objects in the array are *serializable*, then you can copy them by using `ObjectOutputStream` and `ObjectInputStream` serialize and then deserialize the array. However:
* this is expensive,
* it only works if the objects are (transitively) serializable, and
* the values of any `transient` fields won't be copied.
Copying by serialization is not recommended. It would be better to support cloning or some other method.
All in all, deep copying is best avoided in Java.
Finally, to answer your question about the `Position` classes copy constructor works, I expect it is something like this:
```
public class Position {
private int x;
private int y;
...
public Position(Position other) {
this.x = other.x;
this.y = other.y;
}
...
}
```
As @Turtle says, there's no magic involved. You implement a constructor (by hand) that initializes its state by copying from an existing instance.
---
1 - It is specified that the Object implementation of `clone()` does a shallow copy, but this may be overridden. The javadoc for `clone` specifies the "contract" as follows:
>
> *"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression: `x.clone() != x` will be true, and that the expression: `x.clone().getClass() == x.getClass()` will be true, but these are not absolute requirements. While it is typically the case that: `x.clone().equals(x)` will be true, this is not an absolute requirement."*
>
>
>
Nothing in the "contract" talks about deep versus shallow copying. So if you are going to use `clone` in this context, you need to know how the actual classes `clone` method behaves. | Instead of saying:
```
data[i]=other.data[i]
```
You will want to make a copy constructor for `Position` (in other words, a constructor for Position that takes in another `Position` and copies the primitive data inside it) and say `data[i]=new Position(other.data[i]);`
Basically your "deep copy" constructor the `PositionList` is a copy constructor, although copy constructor does tend to indicate a deep copy, so the `deepCopy` parameter is unnecessary. |
32,396,791 | My VBScript checks if the timestamp of a certain file is older then what has been passed in a argument.
If it is older then the argument allows, then the status of the log file created by this script is set to STATUS="ERROR". When STATUS="ERROR" then the tail of the error log (10 lines of code) is to be written to the Log file. So far, this works.
The problem is now that in the folder, where the scripts is running on, there are more then just .log and .txt files. One can also come across .zip or .rar files.
If one of them throws an error, the script when running tail on it gives the following
```
œšF§p#ýÃZ§‘KnÄÈÙCÓÈ7Ò-Ã"œs#GNM£S¸‘þaÓÈ%7bäì¡iä‚é–a‘F¯Îüm‹™Êh f"Ò>¨Û%þ#N™«Q,ø Ð}e
·v–‰³‘$j9Õ‡ó–i;!žBÉFëîÑ>
p“Ò(ä3óÍ.x;…&µb6òhj˜æ '½3Izô
ëùÿzjsÁ Æ÷vÌ‚F®Qe{cÍË<‹ù‰É1²F†y¿Ð"ÂÄ8jãVÒ«
```
this is of course not what I would like to see.
The questions are:
* Is there a way to make the script ignore other files extension than .log and .txt files and then just when the file extension is something else just inserts a string message?
* Is there a way to make the script open the .zip and .rar file take the newest file inside and run the tail.exe file on this file?
```vb
if(status = "ERROR") then
'Runs the tail.exe file to get the last 10 lines of text in the [sNewestFile] and insert them to the log file.
'This will only be done IF there is a status = "ERROR"
errorStr = WScript.CreateObject("WScript.Shell").Exec( _
"tail -n 10 """ & sNewestFile & """" _
).StdOut.ReadAll
objLogFile.writeline "" & vbCrLf
objLogFile.writeline "Error Message Start" & vbCrLf
objLogFile.writeline "" & errorStr & vbCrLf
objLogFile.writeline "Error Message End"
End if
```
Notes:
* I got help in here for that solution: <https://stackoverflow.com/a/32352356/3430698>
* The two variable are `sNewestFile` and `sOldestFile` that contains the newest and oldest file. They contain the entire path to the files with extension `sNewestFile = oFile.Path`
* I have a `filespec` variable that is passed in as a argument that is the file extension. So I have tried to run a if sentence around that code above that checks if the status="ERROR", the if sentence was to check
```
if (filespec <> ".txt" or file <> ".log") then
writeline "something"
else
'run the tail on the file
``` | 2015/09/04 | [
"https://Stackoverflow.com/questions/32396791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3430698/"
] | >
> Is there a way to make the script ignore other files extension than .log and .txt files
>
>
>
Yes. There is the FileSystemObject's [`GetExtensionName` function](https://msdn.microsoft.com/en-us/library/aa265296(v=vs.60).aspx):
```
ext = LCase(FSO.GetExtensionName(file))
Select Case ext
Case "log", "txt"
' we have a text file
Case "zip"
' we have a ZIP archive
Case "rar"
' we have a RAR archive
Case Else
' ignore
End Select
```
>
> Is there a way to make the script open the .zip and .rar file take the newest file inside and run the tail.exe file on this file?
>
>
>
Yes, just the same way you would do it manually:
* use the command line versions of the archive tools with WSHShell.Exec
* unpack the archive into a temporary directory (use [`GetSpecialFolder()`](https://msdn.microsoft.com/en-us/library/aa265315(v=vs.60).aspx) and [`GetTempName()`](https://msdn.microsoft.com/en-us/library/aa265319(v=vs.60).aspx))
* figure out the newest file
* run `tail.exe` on it, write your log file
* delete the temporary directory | @Tomalak
Can you see something wrong with this ? in the log file it wrote *Invalid Character*
We decided that it should just ignorer the ZIP and RAR files instead of opening them.
**CODE**
`ext = LCase(FSO.GetExtensionName(sNewestFile))
```
Select Case ext
Case "log", "txt":
if(STATUS = "ERROR") then
'Runs the tail.exe file to get the last 10 lines of text in the [sNewestFile] and insert them to the log file.
'This will only be done IF there is a status = "ERROR"
errorStr = WScript.CreateObject("WScript.Shell").Exec( _ "tail -n 10 """ & sNewestFile & """" _ ).StdOut.ReadAll
objLogFile.writeline "" & vbCrLf
objLogFile.writeline "Error Message Start" & vbCrLf
objLogFile.writeline "" & errorStr & vbCrLf
objLogFile.writeline "Error Message End"
End if
Case "zip":
if(STATUS = "ERROR") then
objLogFile.writeline "" & vbCrLf
objLogFile.writeline "This is a ERROR in the ZIP file" & vbCrLf
End if
Case "rar":
if(STATUS = "ERROR") then
objLogFile.writeline "" & vbCrLf
objLogFile.writeline "This is a ERROR in the RAR file" & vbCrLf
End if
End Select`
``` |
11,197,097 | I have to manage servos from a computer.
So I have to send manage messages from computer to Arduino. I need manage the number of servo and the corner. I'm thinking of sendin something like this : "1;130" (first servo and corner 130, delimeter ";").
Are there any better methods to accomplish this?
Here is my this code :
```cpp
String foo = "";
void setup(){
Serial.begin(9600);
}
void loop(){
readSignalFromComp();
}
void readSignalFromComp() {
if (Serial.available() > 0)
foo = '';
while (Serial.available() > 0){
foo += Serial.read();
}
if (!foo.equals(""))
Serial.print(foo);
}
```
This doesn't work. What's the problem? | 2012/06/25 | [
"https://Stackoverflow.com/questions/11197097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222982/"
] | This is a Great sub I found. This was super helpful and I hope it will be to you as well.
This is the method that calls the sub.
```
String xval = getValue(myString, ':', 0);
```
This is The sub!
```
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {
0, -1 };
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
``` | It looks like you just need to correct
```
foo = ''; >>to>> foo = "";
foo += Serial.read(); >>to>> foo += char(Serial.read());
```
I made also shomething similar..:
```
void loop(){
while (myExp == "") {
myExp = myReadSerialStr();
delay(100);
}
}
String myReadSerialStr() {
String str = "";
while (Serial.available () > 0) {
str += char(Serial.read ());
}
return str;
}
``` |
7,568,935 | How do I convert (or create) a singleton class that compiles and behaves correctly when using automatic reference counting (ARC) in Xcode 4.2? | 2011/09/27 | [
"https://Stackoverflow.com/questions/7568935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304383/"
] | Alternatively, Objective-C provides the +(void)initialize method for NSObject and all its sub-classes. It is always called before any methods of the class.
I set a breakpoint in one once in iOS 6 and dispatch\_once appeared in the stack frames. | Singleton Class : No one can create more than one object of class in any case or through any way.
```
+ (instancetype)sharedInstance
{
static ClassName *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[ClassName alloc] init];
// Perform other initialisation...
});
return sharedInstance;
}
// You need need to override init method as well, because developer can call [[MyClass alloc]init] method also. that time also we have to return sharedInstance only.
-(MyClass)init
{
return [ClassName sharedInstance];
}
``` |
9,792,409 | I want to count the WMC for a program. For this am counting the no. of "void", "return", "main", "set" and "get" between 2 " { " and " } " symbols, because they indicate the begin n end of a class. Am using the following code:-
```
namespace ConsoleApplication27
{
class Program
{
static void Main(string[] args)
{
int cflag=0,mflag=0;
string var1 = File.ReadAllText(@"c:\\Users\\kinnu\\My Documents\\program.txt");
string[] words = var1.Split(' ');
foreach (string word in words)
{
if (word == "{")
cflag++;
if (word == "}")
cflag--;
if (word == "Main")
mflag++;
if (word == "void")
mflag++;
if (word == "return")
mflag++;
if (word == "set")
mflag++;
if (word == "get")
mflag++;
if (cflag == 0)
Console.WriteLine("The number of methods are:" + mflag);
}
}
}
```
}
The problem is its identifying thw words but not " { " and " } " symbols. I have tried displayin no. of methods right after decrementing the cflag variable but of no use
Please help!!!! | 2012/03/20 | [
"https://Stackoverflow.com/questions/9792409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260907/"
] | I believe this split will work better:
```
string[] words = var1.Split(new char[] { ' ', '\r', '\n', '\t' },
StringSplitOptions.RemoveEmptyEntries);
``` | You only split on ' '. If the file you're reading is an average source file, it also contains other kinds of whitespace you should split on. Carriage returns, line feeds, tabs.
And it's perfectly possible to have a `{` directly followed by a non-space character, so you should also check for that.
And I don't see where you check that the words are not inside a literal string. |
25,702,732 | I'm new to javascript and simply trying to pull links from a webpage so I'm doing the following:
```
for(link in document.links) {
console.log(link.getAttribute("href");
}
```
But if I do this:
```
document.links.item(0).getAttribute("href")
```
It returns the link for the first `href`
What am I doing wrong?
Here is the webpage I'm testing against: <http://en.wikipedia.org/wiki/JavaScript_syntax> | 2014/09/06 | [
"https://Stackoverflow.com/questions/25702732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1492471/"
] | Just get the elements by tag name and [avoid the `for in` loop](https://stackoverflow.com/questions/5263847/javascript-loops-for-in-vs-for).
```
var links = document.getElementsByTagName('a'),
i;
for(i = 0; i < links.length; i += 1){
console.log(links[i].getAttribute("href"));
}
```
[**Example Here**](http://jsfiddle.net/j098kmnp/)
---
For your example, you would have used:
```
for(link in document.links) {
console.log(document.links[link].getAttribute("href"));
}
```
While that technically works, it returns prototype properties in addition to the link elements. This will throw errors since `.getAttribute("href")` won't work for all the return elements.
You could use the [`hasOwnProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) method and check.. but still, i'd [avoid the `for in` loop](https://stackoverflow.com/questions/5263847/javascript-loops-for-in-vs-for).
```
for (link in document.links) {
if (document.links.hasOwnProperty(link)) {
console.log(document.links[link]);
}
}
``` | ```
document.links.item
```
is an array of items.
document.links.item(0) gets the first item in that array.
document.links.item(1) gets the second item in that array.
To answer your question, what you are doing wrong is that you are not looping the links.item array as you did in your first example. |
774,311 | I had a functioning Bash prompt colored how I wanted it, but after reinstalling the background is gray rather than black like this setting should make it.
My `PS1` is
```
\[\e[33;40m\]\T \[\e[36;1m\]\u\[\e[31;40m\]@\[\e[32;1m\]\h \W> \[\e[0m\]
```
Below is a screenshot for clarification. I am talking about the gray behind the prompt.
 | 2014/06/27 | [
"https://superuser.com/questions/774311",
"https://superuser.com",
"https://superuser.com/users/339365/"
] | Your terminal's color scheme has dark gray in its "black" slot. (The rest of the terminal is actually black because the *default* background is a completely separate slot.) This used to be the default setting in GNOME Terminal until version 3.12.
Go to "Edit → Profile Preferences", open the "Color" tab, find the 16 color scheme slots, and change the "Black" slot to have actual black.
(Alternatively, don't request black background in the prompt *in the first place*. There's no need to do so since your current prompt never changes the background *from* black anyway.) | I used the ["List of colors for prompt and Bash"](https://wiki.archlinux.org/index.php/Color_Bash_Prompt#List_of_colors_for_prompt_and_Bash) from the ArchWiki, and came up with this:
```
txtylw='\e[0;33m' # Yellow
txtred='\e[0;31m' # Red
bldcyn='\e[1;36m' # Bold Cyan
bldgrn='\e[1;32m' # Bold Green
txtrst='\e[0m' # Text Reset
PS1="${txtylw}\T ${bldcyn}\u${txtred}@${bldgrn}\h \W>${txtrst} "
```
The result:
 |
11,167,465 | I want increment `#hidtr` value in jquery.
```
<script type="text/javascript">
$('#hidtr').val(parseInt($('#hidtr').val()+1));
alert($('#hidtr').val());
</script>
``` | 2012/06/23 | [
"https://Stackoverflow.com/questions/11167465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428429/"
] | Try this
```
var val = $('#hidtr').val();
$('#hidtr').val((val*1)+1);
``` | **Or another working demo** <http://jsfiddle.net/AuJv2/5/> **OR** in case of initial empty input: <http://jsfiddle.net/AuJv2/8/>
Please note `parseInt($('#hidtr').val()+1)` should be `parseInt($('#hidtr').val())+1`
Hope this helps,
**code**
```
var num = parseInt($('#hidtr').val()) || 0;
$('#hidtr').val(parseInt(num)+1);
alert($('#hidtr').val());
```
**OR**
```
$('#hidtr').val(parseInt($('#hidtr').val())+1);
alert($('#hidtr').val());
``` |
246,800 | I'm a PhD in bioinformatics, mostly self-taught, and I'm coming to a point where I want to clean up my various directory structures (i.e. my data), but I'm also thinking about how I'm storing the various bioinformatic packages I'm using. Having no formal training and having taken only a single Unix course, there's still a lot I don't know that I assume are taught in "Unix 101" or similar. I did a bit of googling, but I didn't really find answers to my questions, so I thought I'd ask them here. I am working on a Mac, so OSX (Yosemite), if that matters.
When it comes to downloading and installing the various packages I'm using, my current solution is to copy the full downloaded directory to `/Users/sajber/software` just to have all the files, `make` (if applicable; sometimes there are ready-made binaries in the downloaded directory) and then copy the binaries to `/Users/sajber/bin`. I have then set my `PATH` to include `/Users/sajber/bin`. I am not using any form of package managing software, so I do everything manually.
How "wrong" is this, and how can I improve it? What do people usually do, is there some kind of standard?
I thought about just keeping all the packages in `/Users/sajber/software` as previously, but rather add the individual packages to `PATH`, as in `PATH=$PATH:/Users/sajber/software/<package>`. When I started out, I initially did this, but then my `PATH` became this long mess of numerous paths that was hard to change without making mistakes, so I went with my current solution instead. It now occurs to me that I might just change `.bash_profile` instead, giving each package a separate line in it (as above) for easier access, if this is a "better" solution.
I also have a `/Users/sajber/scripts` folder for my various Python, R and bash scripts, which is also added to `PATH`. I have a `Git` repository in this directory for version control. Is this the way you should do things?
Sorry if these questions are all very basic! I just don't really know what is the standard way of doing things in an Unix environment, being mostly self-taught. | 2015/12/02 | [
"https://unix.stackexchange.com/questions/246800",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/145643/"
] | Agreeing that there is nothing wrong with doing it this way, there are pros and cons. I have found it useful to keep a distinction between scripts which I develop locally and programs that I obtain from other places:
* scripts that I develop locally have a change history which I need to refer to, while
* programs that I obtain from other places are maintained by others (with their own change history).
Since "my" scripts are most convenient to update in the places they are run from, then it is helpful (to me, at any rate), to have more than one bin-directory.
Before I became involved in creating packages for my programs, I used `/usr/local` for the latter, doing
```
./configure && make && sudo make install
```
and most *programs* which use autoconf-related scripts default to this scheme.
Others of course will have their own preferences: do what works best for you. | This started out as a comment but became too long and detailed...
There is nothing wrong with doing it this way for personal-use programs and scripts (i.e. that are only going to be used by your user-id). In fact, what you are doing is good practice, although you might want to symlink the binaries into /Users/saberj/bin rather than copy them - that way it'll be easier to keep track of where each binary came from (and easier to delete or upgrade them).
Programs that are intended to be used by all users on the system should be installed either as packages (if packages are available) or installed into /usr/local using a tool such as GNU [stow](https://www.gnu.org/software/stow/), which provides some of the benefits of packaging (including easy uninstall) for unpackaged software. |
10,141 | I know that motion estimation has to do with calculating motion vectors, but where does motion compensation come into play. Can't we just do it with motion vectors, since, we are still calculating the differences in the displacement of the blocks in the reference and the target frames. | 2014/02/08 | [
"https://avp.stackexchange.com/questions/10141",
"https://avp.stackexchange.com",
"https://avp.stackexchange.com/users/2161/"
] | Motion compensation is the use of the motion estimation information to achieve compression. If you can describe the motion, then you only have to describe the changes that occur after compensating for that motion.
I used [this article](http://www.cmlab.csie.ntu.edu.tw/cml/dsp/training/coding/motion/me1.html) as a primer. Basically the first involves how you determine what movement is happening and the other is then used to determine what information changed after the movement and to describe what changes need to occur for playback. | My understanding of their differences:
Motion Estimation:
* It is to generate the motion vector(s).
* It's in the *encoder only*, since decoder only *consumes* the motion vector data.
Motion Compensation:
* It's using *existing* motion vector(s) information, along with the reference image(s), to generate a predicted microblock. (The predicted block will be added to the residue block to generate a decoded microblock.)
+ This generation step can be a simple x/y translation of the single reference block. But it could be more complex when dealing with multiple reference frames/blocks or field based coding.
+ For example, in H.264, you can have two MVs with different weight, thus the compensation step to generate a predicted block would be like `PB = w1*RB1 + w2*RB2`.
* It's in the decoder. But since there's a mini-decoder in the encoder. So the encoder has this component as well.
This page on [MOTION ESTIMATION AND COMPENSATION](http://www.mpeg.org/MPEG/MSSG/tm5/Ch5/Ch5.html) provides more detailed information. Also looking at their location in an [encoder diagram](http://www.csee.wvu.edu/~xinl/courses/ee569/H264_tutorial.pdf) might also be helpful. |
4,410,629 | I'm trying to find the `n`th digit of an integer of an arbitrary length. I was going to convert the integer to a string and use the character at index n...
`char Digit = itoa(Number).at(n);`
...But then I realized the `itoa` function isn't standard. Is there any other way to do this? | 2010/12/10 | [
"https://Stackoverflow.com/questions/4410629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497934/"
] | `(number/intPower(10, n))%10`
just define the function `intPower`. | ```
const char digit = '0' + number.at(n);
```
Assuming `number.at(n)` returns a decimal digit in the range 0...9, that is. |
23,521,315 | I have the following code which I am using to populate a `ImageList` from a SQLite database with images stored as blobs.
```
Public Sub populateImagesStyles()
ShoeImages1.Images.Clear()
StyleImagesLView.Items.Clear()
Dim s As SQLiteDataReader
Dim rcount As Integer = 0
dbLocalQuery = New SQLiteCommand("SELECT id, image FROM tblImages", dbLocal)
s = dbLocalQuery.ExecuteReader()
While s.Read()
rcount += 1
ShoeImages1.Images.Add(CStr(s("id")), byte2img(s("image")))
StyleImagesLView.Items.Add(CStr(s("id")), CStr(s("id")))
End While
s.Close()
```
Here is the byte2img function...
```
Public Function byte2img(ByVal imgByte As Byte()) As Image
Dim imgMemoryStream As System.IO.MemoryStream = New System.IO.MemoryStream(imgByte)
byte2img = Drawing.Image.FromStream(imgMemoryStream)
End Function
```
The database contains over 250 images and this process is completed twice on load to populate two different `ImageList`, because I need the images displayed at two different sizes.
When the process runs on loading the form, it causes the process to consume between 800MB and 1GB of system memory, unless I manually run the process again from an form control, which seems to trigger garbage collection.
Stepping through the loading process, it is clear that it is the byte2img process that is causing the memory usage to escalate - what is the best way to mitigate this?
Also, if anyone can think of a more efficient process to execute this, i'm all ears. The images have to be stored in the database file because I need to be able to just package the .db file and send it to a remote location at a moments notice, so I can't mess with folders with images.
All help appreciated. | 2014/05/07 | [
"https://Stackoverflow.com/questions/23521315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1619795/"
] | You are creating a lot of memory streams without disposing of them. Try this:
```
Public Function byte2img(ByVal imgByte As Byte()) As Image
Dim img As Image
Try
Using ms As New MemoryStream(imgbyte)
img = Drawing.Image.FromStream(ms)
End Using ' auto dispose of the MS
Catch ex As Exception
' report possibly bad/missing imgByte()
' resulting in an error in either place
End Try
Return img
End Function
```
An imprecise way to detect this kind of thing is to watch the HANDLES count in TaskManager. | Ok, I've found a solution/workaround that seems to work - call the `PopulateImageStyles` sub when a user visits the specific `TabPage` the `ImageList` resides on.
For some arbitrary reason, when run this way (as above, when called on the form), the process never proceeds to consume more than 50-60 MB of working memory.
I'll add a Background Worker so that the process can execute without hanging the form. |
9,104,770 | I need to write these four `if`s in Python. Notice what it does, is changing between four possible states in a loop: `1,0 -> 0,1 -> -1,0 -> 0,-1` and back to first.
```
if [dx, dy] == [1,0]:
dx, dy = 0, 1
if [dx, dy] == 0, 1:
dx, dy = -1, 0
if [dx, dy] == [-1, 0]
dx, dy = 0, -1
if [dx, dy] == [0, -1]:
dx, dy = 1, 0
```
Can anyone suggest me a better/nicer way to write this? | 2012/02/01 | [
"https://Stackoverflow.com/questions/9104770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/661230/"
] | ```
dx, dy = -dy, dx
```
When in doubt, apply maths. ;) | While I would go with Magnus' answer, here's yet another approach for rotating over a set of values:
```
def rotate(*states):
while 1:
for state in states:
yield state
for dx, dy in rotate((1, 0), (0, 1), (-1, 0), (0, -1)):
pass
```
Note that there should be a `break` somewhere in the `for dx, dy` loop or else it will never end. |
15,475,792 | I am curious about the compiler efficiency in next case:
```
double total = list.Sum(x => x.Value) ?? 0;
```
Q: will compiler produce code that will execute the Sum function once or twice?
It could generate something like:
```
double total = list.Sum(x => x.Value) == null ? 0 : (double)list.Sum(x => x.Value);
```
or
```
double temp = list.Sum(x => x.Value);
total = temp == null ? 0 : (double)temp;
``` | 2013/03/18 | [
"https://Stackoverflow.com/questions/15475792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/916236/"
] | The code will execute the `Sum` once. That is the whole point of introducing a new operator into the language. You can verify this by introducing a condition with a side effect, and verifying that the side effect is applied only once:
```
int? x = 5;
int y = x++ ?? 100;
```
After executing this code, `x` is `6`, not `7`. | The `??` operator is only applicable to the nullable types, and `double` is not a nullable type, so this code won't compile.
Same, the `.Sum()` extension method will never return `null` on this list, it will always return `0`. |
21,023,759 | I got a problem that consumes a lot of time during the development i have to test somes HQL that i put in DAO, but i had to recompile all the project in eclipse and put in tomcat that takes something like 40-60seconds just to start again and if something goes wrong... again had to redeploy...
So, there is a way to test a HQL without recompile everything? like i tried the hibernate tools plugin but i don't see how to do it with annotations (the project is all with annotations, don't make use of hbm files...)
Thanks | 2014/01/09 | [
"https://Stackoverflow.com/questions/21023759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893942/"
] | Assuming you are accessing your DAO through a service I would do something like this:
```
public static void main(String[] args) {
AbstractApplicationContext factory = new ClassPathXmlApplicationContext("application-context.xml");
YourService yourservice = (YourService)factory.getBean("YourService");
YourObject obj = new YourObject("data1", "data2");
yourservice.save(obj);
YourObject foundobj = yourservice.load(1); // or yourservice.findObjectByLabel("label")
System.out.print(foundobj);
}
```
Or write a junit test. <http://www.springbyexample.org/examples/simple-spring-transactional-junit4-test-code-example.html> | What I've done in the past to test HQL is write a limited set of integration tests using an in memory db like [Hypersonic](http://hsqldb.org/) and the [Spring JUnit test extensions](http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html). [This post](http://www.cybersnippet.nl/easy-integration-testing-of-hql-with-an-in-memory-database) describes how this can be done using dbunit. You can also just brute force the data using batch JDBC operations in your setup and tear down.
Cautionary notes: I would not add these test to your suite of unit tests as the data setup and tear down can take more time than a typical unit test. These are really integration tests used to add you in development and debugging of your HQL only. I wouldn't bother testing CRUD operations using these types of tests as then you're just integration testing your ORM framework which should have already been done. |
5,832,337 | I have an array ($title, $depth)
```
$title($depth)
////////////////////////////////////
ELECTRONICS(0)
TELEVISIONS(1)
TUBE(2)
LCD(2)
PLASMA(2)
PORTABLE ELECTRONICS(1)
MP3 PLAYERS(2)
FLASH(3)
CD PLAYERS(2)
2 WAY RADIOS(2)
//////////////////////
```
How could I display this structure with `<ul><li>` | 2011/04/29 | [
"https://Stackoverflow.com/questions/5832337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/703617/"
] | Product ID (ProductCode) uniquely identifies everything in the installer package as a particular product. When you search to see if a previous version is installed search is performed on the Upgrade Code. For all items found with the particular Upgrade code Installer will note each of the Product Codes as different incarnations of the same product. So you can say a different product code of same upgrade code identifies different incarnations (versions if you will, of the same product). | This may be somewhat misguided but I did have a lot of files I was importing as components into a new WiX `Product.wxs` file. I discovered after I had created all the components with `Guid="*"` that when trying to build the installer, WiX reported the following error for each component:
>
> The component 'AjaxControlToolkit.dll' has a key file with path 'TARGETDIR\ajaxcontroltoolkit.dll'. Since this path is not rooted in one of the standard directories (like ProgramFilesFolder), this component does not fit the criteria for having an automatically generated guid.
>
>
>
I used the following PowerShell script to assign a new guid to each component. Be aware that this script will modify the `Product.wxs` file directly and a backup of the file should be kept in case something goes wrong:
```
(Get-Content Product.wxs) |
Foreach-Object { $guid = [guid]::NewGuid().ToString(); $_ -replace 'Guid="\*"',"Guid=""$guid"""} |
Out-File Product.wxs
``` |
3,882,095 | Why does this throw `NullPointerException`
```
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
```
while this doesn't
```
public static void main(String[] args) throws Exception {
Boolean b = true ? null : false;
System.out.println(b); // null
}
```
?
The solution is by the way to replace `false` by `Boolean.FALSE` to avoid `null` being unboxed to `boolean` --which isn't possible. But that isn't the question. The question is *why*? Are there any references in JLS which confirms this behaviour, especially of the 2nd case? | 2010/10/07 | [
"https://Stackoverflow.com/questions/3882095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157882/"
] | **The difference is that the explicit type of the `returnsNull()` method affects the static typing of the expressions at compile time:**
```
E1: `true ? returnsNull() : false` - boolean (auto-unboxing 2nd operand to boolean)
E2: `true ? null : false` - Boolean (autoboxing of 3rd operand to Boolean)
```
See Java Language Specification, section [**15.25 Conditional Operator ? :**](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25)
* For E1, the types of the 2nd and 3rd operands are `Boolean` and `boolean` respectively, so this clause applies:
>
> If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean.
>
>
>
Since the type of the expression is `boolean`, the 2nd operand must be coerced to `boolean`. The compiler inserts auto-unboxing code to the 2nd operand (return value of `returnsNull()`) to make it type `boolean`. This of course causes the NPE from the `null` returned at run-time.
* For E2, types of the 2nd and 3rd operands are `<special null type>` (not `Boolean` as in E1!) and `boolean` respectively, so no specific typing clause applies ([go read 'em!](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25)), so the final "otherwise" clause applies:
>
> Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).
>
>
>
+ S1 == `<special null type>` (see [§4.1](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1))
+ S2 == `boolean`
+ T1 == box(S1) == `<special null type>` (see last item in list of boxing conversions in [§5.1.7](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7))
+ T2 == box(S2) == `Boolean
+ lub(T1, T2) == `Boolean`So the type of the conditional expression is `Boolean` and the 3rd operand must be coerced to `Boolean`. The compiler inserts auto-boxing code for the 3rd operand (`false`). The 2nd operand doesn't need the auto-unboxing as in `E1`, so no auto-unboxing NPE when `null` is returned.
---
This question needs a similar type analysis:
[Java conditional operator ?: result type](https://stackoverflow.com/questions/2615498/java-conditional-operator-result-type) | From [Java Language Specification, section 15.25](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25):
>
> * If one of the second and third
> operands is of type boolean and the
> type of the other is of type Boolean,
> then the type of the conditional
> expression is boolean.
>
>
>
So, the first example tries to call `Boolean.booleanValue()` in order to convert `Boolean` to `boolean` as per the first rule.
In the second case the first operand is of the null type, when the second is not of the reference type, so autoboxing conversion is applied:
>
> * Otherwise, the second and third
> operands are of types S1 and S2
> respectively. Let T1 be the type that
> results from applying boxing
> conversion to S1, and let T2 be the
> type that results from applying boxing
> conversion to S2. The type of the
> conditional expression is the result
> of applying capture conversion
> (§5.1.10) to lub(T1, T2) (§15.12.2.7).
>
>
> |
34,659,628 | I'm trying to figure out how to change the hover color, but only when the text has a link
This is the css code, but it changes color with or without links
```
h1, h2, h3, h4 {
color:#3F3F3F;
}
h1:hover, h2:hover, h3:hover, h4:hover {
color:#000000;
}
``` | 2016/01/07 | [
"https://Stackoverflow.com/questions/34659628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5708568/"
] | Sample:
```
h1 a:hover, h2 a:hover, h3 a:hover, h4 a:hover {
color:grey;
}
``` | The anwser you are looking for is simple:
```
h1 a:hover, h2 a:hover, ect {
color:#000000;
}
```
You stated that the header when hovered should change color, which is not what you want.
Now it says that a header which contains a link (a) should change color when it is hovered. ;) |
2,975,635 | Hey. I've got the following code that populates my list box
```
UsersListBox.DataSource = GrpList;
```
However, after the box is populated, the first item in the list is selected by default and the "selected index changed" event fires. How do I prevent the item from being selected right after the list box was populated, or how do I prevent the event from firing?
Thanks | 2010/06/04 | [
"https://Stackoverflow.com/questions/2975635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139077/"
] | Well, it looks like that the first element is automatically selected after ListBox.DataSource is set. Other solutions are good, but they doesn't resolve the problem. This is how I did resolve the problem:
```
// Get the current selection mode
SelectionMode selectionMode = yourListBox.SelectionMode;
// Set the selection mode to none
yourListBox.SelectionMode = SelectionMode.None;
// Set a new DataSource
yourListBox.DataSource = yourList;
// Set back the original selection mode
yourListBox.SelectionMode = selectionMode;
``` | set `IsSynchronizedWithCurrentItem="False"` and Also `SelectedIndex=-1` and every thing should work for you |
53,190,253 | I've trained an LSTM model (built with Keras and TF) on multiple batches of 7 samples with 3 features each, with a shape the like below sample (numbers below are just placeholders for the purpose of explanation), each batch is labeled 0 or 1:
Data:
```
[
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
...
]
```
i.e: batches of m sequences, each of length 7, whose elements are 3-dimensional vectors (so batch has shape (m*7*3))
Target:
```
[
[1]
[0]
[1]
...
]
```
On my production environment data is a stream of samples with 3 features (`[1,2,3],[1,2,3]...`). I would like to stream each sample as it arrives to my model and get the intermediate probability without waiting for the entire batch (7) - see the animation below.
[](https://i.stack.imgur.com/4D0yt.gif)
One of my thoughts was padding the batch with 0 for the missing samples,
`[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,2,3]]` but that seems to be inefficient.
Will appreciate any help that will point me in the right direction of both saving the LSTM intermediate state in a persistent way, while waiting for the next sample and predicting on a model trained on a specific batch size with partial data.
---
**Update,** including model code:
```py
opt = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=10e-8, decay=0.001)
model = Sequential()
num_features = data.shape[2]
num_samples = data.shape[1]
first_lstm = LSTM(32, batch_input_shape=(None, num_samples, num_features),
return_sequences=True, activation='tanh')
model.add(first_lstm)
model.add(LeakyReLU())
model.add(Dropout(0.2))
model.add(LSTM(16, return_sequences=True, activation='tanh'))
model.add(Dropout(0.2))
model.add(LeakyReLU())
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=opt,
metrics=['accuracy', keras_metrics.precision(),
keras_metrics.recall(), f1])
```
**Model Summary:**
```
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_1 (LSTM) (None, 100, 32) 6272
_________________________________________________________________
leaky_re_lu_1 (LeakyReLU) (None, 100, 32) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 100, 32) 0
_________________________________________________________________
lstm_2 (LSTM) (None, 100, 16) 3136
_________________________________________________________________
dropout_2 (Dropout) (None, 100, 16) 0
_________________________________________________________________
leaky_re_lu_2 (LeakyReLU) (None, 100, 16) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 1600) 0
_________________________________________________________________
dense_1 (Dense) (None, 1) 1601
=================================================================
Total params: 11,009
Trainable params: 11,009
Non-trainable params: 0
_________________________________________________________________
``` | 2018/11/07 | [
"https://Stackoverflow.com/questions/53190253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115237/"
] | I think there might be an easier solution.
If your model does not have convolutional layers or any other layers that act upon the length/steps dimension, you can simply mark it as `stateful=True`
Warning: your model has layers that act on the length dimension !!
------------------------------------------------------------------
The `Flatten` layer transforms the length dimension into a feature dimension. This will completely prevent you from achieving your goal. If the `Flatten` layer is expecting 7 steps, you will always need 7 steps.
So, before applying my answer below, fix your model to not use the `Flatten` layer. Instead, it can just remove the `return_sequences=True` for the **last** LSTM layer.
The following code fixed that and also prepares a few things to be used with the answer below:
```
def createModel(forTraining):
#model for training, stateful=False, any batch size
if forTraining == True:
batchSize = None
stateful = False
#model for predicting, stateful=True, fixed batch size
else:
batchSize = 1
stateful = True
model = Sequential()
first_lstm = LSTM(32,
batch_input_shape=(batchSize, num_samples, num_features),
return_sequences=True, activation='tanh',
stateful=stateful)
model.add(first_lstm)
model.add(LeakyReLU())
model.add(Dropout(0.2))
#this is the last LSTM layer, use return_sequences=False
model.add(LSTM(16, return_sequences=False, stateful=stateful, activation='tanh'))
model.add(Dropout(0.2))
model.add(LeakyReLU())
#don't add a Flatten!!!
#model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
if forTraining == True:
compileThisModel(model)
```
With this, you will be able to train with 7 steps and predict with one step. Otherwise it will not be possible.
The usage of a stateful model as a solution for your question
-------------------------------------------------------------
First, train this new model again, because it has no Flatten layer:
```
trainingModel = createModel(forTraining=True)
trainThisModel(trainingModel)
```
Now, with this trained model, you can simply create a **new model** exactly the same way you created the trained model, but marking `stateful=True` in all its LSTM layers. And we should copy the weights from the trained model.
Since these new layers will need a fixed batch size (Keras' rules), I assumed it would be 1 (one single stream is coming, not m streams) and added it to the model creation above.
```
predictingModel = createModel(forTraining=False)
predictingModel.set_weights(trainingModel.get_weights())
```
And voilà. Just predict the outputs of the model with a single step:
```
pseudo for loop as samples arrive to your model:
prob = predictingModel.predict_on_batch(sample)
#where sample.shape == (1, 1, 3)
```
When you decide that you reached the end of what you consider a continuous sequence, call `predictingModel.reset_states()` so you can safely start a new sequence without the model thinking it should be mended at the end of the previous one.
---
Saving and loading states
-------------------------
Just get and set them, saving with h5py:
```
def saveStates(model, saveName):
f = h5py.File(saveName,'w')
for l, lay in enumerate(model.layers):
#if you have nested models,
#consider making this recurrent testing for layers in layers
if isinstance(lay,RNN):
for s, stat in enumerate(lay.states):
f.create_dataset('states_' + str(l) + '_' + str(s),
data=K.eval(stat),
dtype=K.dtype(stat))
f.close()
def loadStates(model, saveName):
f = h5py.File(saveName, 'r')
allStates = list(f.keys())
for stateKey in allStates:
name, layer, state = stateKey.split('_')
layer = int(layer)
state = int(state)
K.set_value(model.layers[layer].states[state], f.get(stateKey))
f.close()
```
Working test for saving/loading states
--------------------------------------
```
import h5py, numpy as np
from keras.layers import RNN, LSTM, Dense, Input
from keras.models import Model
import keras.backend as K
def createModel():
inp = Input(batch_shape=(1,None,3))
out = LSTM(5,return_sequences=True, stateful=True)(inp)
out = LSTM(2, stateful=True)(out)
out = Dense(1)(out)
model = Model(inp,out)
return model
def saveStates(model, saveName):
f = h5py.File(saveName,'w')
for l, lay in enumerate(model.layers):
#if you have nested models, consider making this recurrent testing for layers in layers
if isinstance(lay,RNN):
for s, stat in enumerate(lay.states):
f.create_dataset('states_' + str(l) + '_' + str(s), data=K.eval(stat), dtype=K.dtype(stat))
f.close()
def loadStates(model, saveName):
f = h5py.File(saveName, 'r')
allStates = list(f.keys())
for stateKey in allStates:
name, layer, state = stateKey.split('_')
layer = int(layer)
state = int(state)
K.set_value(model.layers[layer].states[state], f.get(stateKey))
f.close()
def printStates(model):
for l in model.layers:
#if you have nested models, consider making this recurrent testing for layers in layers
if isinstance(l,RNN):
for s in l.states:
print(K.eval(s))
model1 = createModel()
model2 = createModel()
model1.predict_on_batch(np.ones((1,5,3))) #changes model 1 states
print('model1')
printStates(model1)
print('model2')
printStates(model2)
saveStates(model1,'testStates5')
loadStates(model2,'testStates5')
print('model1')
printStates(model1)
print('model2')
printStates(model2)
```
Considerations on the aspects of the data
-----------------------------------------
In your first model (if it is `stateful=False`), it considers that each sequence in `m` is individual and not connected to the others. It also considers that each batch contains unique sequences.
If this is not the case, you might want to train the stateful model instead (considering that each sequence is actually connected to the previous sequence). And then you would need `m` batches of 1 sequence. -> `m x (1, 7 or None, 3)`. | **Note: This answer assumes that your model in training phase is not stateful. You must understand what an stateful RNN layer is and make sure that the training data has the corresponding properties of statefulness. In short it means there is a dependency between the sequences, i.e. one sequence is the follow-up to another sequence, which you want to consider in your model. If your model and training data is stateful then I think other answers which involve setting `stateful=True` for the RNN layers from the beginning are simpler.**
**Update: No matter the training model is stateful or not, you can always copy its weights to the inference model and enable statefulness. So I think solutions based on setting `stateful=True` are shorter and better than mine. Their only drawback is that the batch size in these solutions must be fixed.**
---
Note that the output of a LSTM layer over a single sequence is determined by its weight matrices, which are fixed, and its internal states which depends on the **previous processed timestep**. Now to get the output of LSTM layer for a single sequence of length `m`, one obvious way is to feed the entire sequence to the LSTM layer in one go. However, as I stated earlier, since its internal states depends on the previous timestep, we can exploit this fact and feed that single sequence chunk by chunk by getting the state of LSTM layer at the end of processing a chunk and pass it to the LSTM layer for processing the next chunk. To make it more clear, suppose the sequence length is 7 (i.e. it has 7 timesteps of fixed-length feature vectors). As an example, it is possible to process this sequence like this:
1. Feed the timesteps 1 and 2 to the LSTM layer; get the final state (call it `C1`).
2. Feed the timesteps 3, 4 and 5 and state `C1` as the initial state to the LSTM layer; get the final state (call it `C2`).
3. Feed the timesteps 6 and 7 and state `C2` as the initial state to the LSTM layer; get the final output.
That final output is equivalent to the output produced by the LSTM layer if we had feed it the entire 7 timesteps at once.
So to realize this in Keras, you can set the `return_state` argument of LSTM layer to `True` so that you can get the intermediate state. Further, don't specify a fixed timestep length when defining the input layer. Instead use `None` to be able to feed the model with sequences of arbitrary length which enables us to process each sequence progressively (it's fine if your input data in training time are sequences of fixed-length).
Since you need this chuck processing capability in inference time, we need to define a new model which shares the LSTM layer used in training model and can get the initial states as input and also gives the resulting states as output. The following is a general sketch of it could be done (note that the returned state of LSTM layer is not used when training the model, we only need it in test time):
```
# define training model
train_input = Input(shape=(None, n_feats)) # note that the number of timesteps is None
lstm_layer = LSTM(n_units, return_state=True)
lstm_output, _, _ = lstm_layer(train_input) # note that we ignore the returned states
classifier = Dense(1, activation='sigmoid')
train_output = classifier(lstm_output)
train_model = Model(train_input, train_output)
# compile and fit the model on training data ...
# ==================================================
# define inference model
inf_input = Input(shape=(None, n_feats))
state_h_input = Input(shape=(n_units,))
state_c_input = Input(shape=(n_units,))
# we use the layers of previous model
lstm_output, state_h, state_c = lstm_layer(inf_input,
initial_state=[state_h_input, state_c_input])
output = classifier(lstm_output)
inf_model = Model([inf_input, state_h_input, state_c_input],
[output, state_h, state_c]) # note that we return the states as output
```
Now you can feed the `inf_model` as much as the timesteps of a sequence are available right now. However, note that initially you must feed the states with vectors of all zeros (which is the default initial value of states). For example, if the sequence length is 7, a sketch of what happens when new data stream is available is as follows:
```
state_h = np.zeros((1, n_units,))
state_c = np.zeros((1, n_units))
# three new timesteps are available
outputs = inf_model.predict([timesteps, state_h, state_c])
out = output[0,0] # you may ignore this output since the entire sequence has not been processed yet
state_h = outputs[0,1]
state_c = outputs[0,2]
# after some time another four new timesteps are available
outputs = inf_model.predict([timesteps, state_h, state_c])
# we have processed 7 timesteps, so the output is valid
out = output[0,0] # store it, pass it to another thread or do whatever you want to do with it
# reinitialize the state to make them ready for the next sequence chunk
state_h = np.zeros((1, n_units))
state_c = np.zeros((1, n_units))
# to be continued...
```
Of course you need to do this in some kind of loop or implement a control flow structure to process the data stream, but I think you get what the general idea looks like.
Finally, although your specific example is not a sequence-to-sequence model, but I highly recommend to read the [official Keras seq2seq tutorial](https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html) which I think one can learn a lot of ideas from it. |
8,130,990 | How can I redirect to the same page using PHP?
For example, locally my web address is:
```
http://localhost/myweb/index.php
```
How can I redirect within my website to another page, say:
```
header("Location: clients.php");
```
I know this might be wrong, but do I really need to put the whole thing? What if later it is not `http://localhost/`?
Is there a way to do something like this? Also, I have a lot of code and then at the end after it is done processing some code... I am attempting to redirect using that. Is that OK? | 2011/11/15 | [
"https://Stackoverflow.com/questions/8130990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/710502/"
] | My preferred method for reloading the same page is $\_SERVER['PHP\_SELF']
```
header('Location: '.$_SERVER['PHP_SELF']);
die;
```
Don't forget to die or exit after your header();
Edit: (Thanks @RafaelBarros )
If the query string is also necessary, use
```
header('Location:'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
die;
```
Edit: (thanks @HugoDelsing)
When htaccess url manipulation is in play the value of $\_SERVER['PHP\_SELF'] may take you to the wrong place. In that case the correct url data will be in `$_SERVER['REQUEST_URI']` for your redirect, which can look like Nabil's answer below:
```
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;
```
You can also use $\_SERVER[REQUEST\_URI] to assign the correct value to `$_SERVER['PHP_SELF']` if desired. This can help if you use a redirect function heavily and you don't want to change it. Just set the correct vale in your request handler like this:
```
$_SERVER['PHP_SELF'] = 'https://sample.com/controller/etc';
``` | Simple line below works just fine:
```
header("Location: ?");
``` |
38,010,397 | So if you have this:
```
List<Integer> subList;
for example contains: [0, 6] or [2, 6] , [7, 6]
[[0, 6], [2, 6], [7, 6]]
List<List> list;
contains subLists: [0, 6], [2, 6], [7, 6] or [55, 4], [57, 5], [58, 5]
[[[0, 6], [2, 6], [7, 6]], [[55, 4], [57, 5], [58, 5]]]
```
How do you sort the List on the second value of the subList ascendingly. you can assume that the other values in other subLists are considerably far away from the previous or next subList. There are no values the same from subList to subList.
into the following:
```
[[[55, 4], [57, 5], [58, 5]], [[0, 6], [2, 6], [7, 6]]]
``` | 2016/06/24 | [
"https://Stackoverflow.com/questions/38010397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508217/"
] | ```
Collections.sort(new ArrayList<List<Integer>>(), new Comparator<List<Integer>>() {
public int compare(final List<Integer> o1, final List<Integer> o2) {
return o1.get(1) - o2.get(1);
}
});
``` | You can use a comparator that sorts based on the content of the sublist:
1. Make sure all sublists are sorted in descending order (your example seems to reflect this requirement):
`list.forEach(sublist -> Collections.sort(sublist.sort(Collections.reverseOrder())));`
2. Sort the outer list based on the first element of the sublist
`Collections.sort(list, (sublistone, sublisttwo) -> sublistone.get(0).compareTo(sublisttwo.get(0)));` |
27,160,499 | I'm attempting to inspect http (non-SSL) traffic using XCode 6.1 and iOS Simulator 8.1 using Charles and my localhost apache server.
I've got Charles working correctly, but it only captures traffic when I use my local network IP address: `192.168.1.X` as the target host for requests in iOS.
I've tried the other suggestions from the Charles article [here](http://www.charlesproxy.com/documentation/faqs/localhost-traffic-doesnt-appear-in-charles/), but none work except for the local network IP address.
"Why not just use the local network IP?", you ask?. Well, I'd like to avoid YASCE (yet another source control exception). You see, my source code has this in networking section:
```
#if DEBUG
var API_HOST = "http://localhost"
#else
var API_HOST = "https://website.com"
#endif
```
I'd like to avoid forcing every developer on the team to constantly make special considerations to avoid checking in their own personal IP address every time they are committing to source control.
Is there another way that I can convince the iOS simulator to pass `http://localhost` through Charles, or is there a better way to handle environment-specific settings with a development team? | 2014/11/26 | [
"https://Stackoverflow.com/questions/27160499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300408/"
] | Use `localhost.charlesproxy.com` instead of `localhost`. That's setup on the charlesproxy.com DNS to point to 127.0.0.1, and always will. And because it's not literally `localhost` it *should* bypass the OS's hardwired logic for `localhost`.
It is also possible to use `local.charles`, but only if Charles is actually running and you're using it as your proxy. So I prefer the `localhost.charlesproxy.com` solution.
I'll update that FAQ too. | I am using my hostname instead of localhost. To get your hostname simply type `hostname` in the terminal and then change the URL to `"http://your-host-name"` |
12,342,880 | ```
//Skip straight to main home view
MySpyHomeViewController *homeViewController = [[MySpyHomeViewController alloc] initWithNibName:nil bundle:nil];
self.navController = [[UINavigationController alloc] initWithRootViewController:homeViewController];
```
I use the above code to skip straight to a view if the user is already logged into the application.
I receive an error on the last line. local declaration of 'homeViewController' hides instance variable warning.
I have read some other threads such as this: [local declaration hides instance variable warning](https://stackoverflow.com/questions/8470502/local-declaration-hides-instance-variable-warning)
I do not understand completely why this error occurs. Can someone e | 2012/09/09 | [
"https://Stackoverflow.com/questions/12342880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523603/"
] | >
> Is there any way to turn on warnings when you implicitly use default properties?
>
>
>
No.
>
> Is there any good practice for marking variables as "this should only be used to read from the spreadsheet"?
>
>
>
Well, you could make your own variable naming convention, à la [Making Wrong Code Look Wrong](http://www.joelonsoftware.com/articles/Wrong.html), but you'll still have to check your own code visually and the compiler won't help you do that. So I wouldn't rely on this too much.
A better option is to circumvent the need for repeatedly redifining `currentCell` using `.Offset` altogether.
Instead, read the entire range of interest to a Variant array, do your work on that array, and then slap it back onto the sheet when you're done modifying it.
```
Dim i As Long
Dim j As Long
Dim v As Variant
Dim r As Range
Set r = Range("A1:D5") 'or whatever
v = r.Value 'pull from sheet
For i = 1 To UBound(v, 1)
For j = 1 To UBound(v, 2)
'code to modify or utilise element v(i,j) goes here
Next j
Next i
r.Value = v 'slap v back onto sheet (if you modified it)
```
Voilà. No use of default properties or anything that could be confused as such. As a bonus, this will speed up your code execution. | Maybe write your own custom function and use it instead ?
```
Sub offset_rng(ByRef my_rng As Range, _
Optional row As Integer, Optional col As Integer)
Set my_rng = my_rng.Offset(row, col)
End Sub
```
Can be used like this:
```
Sub test()
Dim rng As Range
Set rng = Range("A1")
offset_rng my_rng:=rng, col:=1
rng.Value = "test1"
offset_rng my_rng:=rng, col:=1
rng.Value = "test2"
offset_rng my_rng:=rng, col:=1
rng.Value = "test3"
offset_rng my_rng:=rng, col:=1
rng.Value = "test4"
End Sub
``` |
15,800,724 | I have an existing wordpress that I copied to my localhost (including databases). I changed the `wp-config.php` for localhost, but when I try to go to wordpress/wp-admin, it connects to my live site...
What do I need to change? (btw, using XAMMP) | 2013/04/04 | [
"https://Stackoverflow.com/questions/15800724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1591067/"
] | This problem, involving array allocations, comes up all the time in dealing with C/C++ and MPI. This:
```
int **array2D;
array2D = new int*[dim];
for (int i=0; i<dim; i++) {
array2D[i] = new int[dim](); // the extra '()' initializes to zero.
}
```
allocates `dim` 1d arrays, each `dim` ints in length. However, there's no reason at all why these should be laid out next to each other - the dim arrays are likely scattered across memory. So even sending `dim*dim` ints from `array2D[0]` won't work. The `all_array2D` is the same; you are creating `size*dim` arrays, each of size `dim`, but where they are in relation to each other who knows, making your displacements likely wrong.
To make the arrays contiguous in memory, you need to do something like
```
int **array2D;
array2D = new int*[dim];
array2D[0] = new int[dim*dim];
for (int i=1; i<dim; i++) {
array2D[i] = &(array2D[dim*i]);
}
```
and similarly for `all_array2D`. Only then can you start reasoning about memory layouts. | I just wanted to summarise the solution which @Hristolliev and @JonathanDursi helped me get to.
1. MPI commands like `MPI_Gatherv()` work with contiguously allocated blocks of memory, hence use of '`new`' to construct 2D arrays which then feed into MPI commands won't work since '`new`' doesn't guarantee contiguous blocks. Use instead '`calloc`' to make these arrays (see code below as an example).
2. An important point by @Hristolliev: The 1st and 4th arguments of MPI\_Gatherv() must be pointers to the first elements of type `MPI_ARRAYROW`. Dereferencing the 2D arrays by one level e.g. array2D[0] will achieve this (again, see modified working code below).
The final, working code is given below:
```
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include "mpi.h"
using namespace std;
void print_2Darray(int **array_in,int dim_rows, int dim_cols) {
cout << endl;
for (int i=0;i<dim_rows;i++) {
for (int j=0;j<dim_cols;j++) {
cout << array_in[i][j] << " ";
if (j==(dim_cols-1)) {
cout << endl;
}
}
}
cout << endl;
}
int main(int argc, char *argv[]) {
MPI::Init(argc, argv);
// Typical MPI incantations...
int size, rank;
size = MPI::COMM_WORLD.Get_size();
rank = MPI::COMM_WORLD.Get_rank();
cout << "size = " << size << endl;
cout << "rank = " << rank << endl;
sleep(1);
// Dynamically allocate a 2D square array of user-defined size 'dim'.
int dim;
if (rank == 0) {
cout << "Please enter dimensions of 2D array ( dim x dim array ): ";
cin >> dim;
cout << "dim = " << dim << endl;
}
MPI_Bcast(&dim,1,MPI_INT,0,MPI_COMM_WORLD);
// Use another way of declaring the 2D array which ensures it is contiguous in memory.
int **array2D;
array2D = (int **) calloc(dim,sizeof(int *));
array2D[0] = (int *) calloc(dim*dim,sizeof(int));
for (int i=1;i<dim;i++) {
array2D[i] = array2D[0] + i*dim;
}
// Fill the arrays with i*j+rank where i and j are the indices.
for (int i=0;i<dim;i++) {
for (int j=0;j<dim;j++) {
array2D[i][j] = i*j + rank;
}
}
// Print out the arrays.
print_2Darray(array2D,dim,dim);
// Commit a MPI_Datatype for these arrays.
MPI_Datatype MPI_ARRAYROW;
MPI_Type_contiguous(dim, MPI_INT, &MPI_ARRAYROW);
MPI_Type_commit(&MPI_ARRAYROW);
// Use another way of declaring the 2D array which ensures it is contiguous in memory.
int **all_array2D;
all_array2D = (int **) calloc(size*dim,sizeof(int *));
all_array2D[0] = (int *) calloc(dim*dim,sizeof(int));
for (int i=1;i<size*dim;i++) {
all_array2D[i] = all_array2D[0] + i*dim;
}
// Print out the arrays.
print_2Darray(all_array2D,size*dim,dim);
// Displacement vector for MPI_Gatherv() call.
int *displace;
displace = (int *)calloc(size,sizeof(int));
int *dim_list;
dim_list = (int *)calloc(size,sizeof(int));
int j = 0;
for (int i=0; i<size; i++) {
displace[i] = j;
cout << "displace[" << i << "] = " << displace[i] << endl;
j += dim;
dim_list[i] = dim;
cout << "dim_list[" << i << "] = " << dim_list[i] << endl;
}
// MPI_Gatherv call.
MPI_Barrier(MPI_COMM_WORLD);
cout << "array2D[0] = " << array2D[0] << endl;
MPI_Gatherv(array2D[0],dim,MPI_ARRAYROW,all_array2D[0],&dim_list[rank],&displace[rank],MPI_ARRAYROW,0,MPI_COMM_WORLD);
// Print out the arrays.
print_2Darray(all_array2D,size*dim,dim);
MPI::Finalize();
return 0;
}
```
Compile with `mpic++`. |
1,186,621 | Why big companies and even US government still have Internet Explorer 6 as their recommended browser?
I'm working at Cisco Systems and their recommended browser is IE6 which makes my life, as a web developer, miserable. I have to spend three times more time debugging problems for IE6 than for any other browsers and I think that they (my boss and few people for whom I'm developing applications) are thinking that I'm writing my code/css not intelligently. What can I do to persuade them to switch to FF or at least to IE7. | 2009/07/27 | [
"https://Stackoverflow.com/questions/1186621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51230/"
] | There's nearly the same question on [server fault](https://serverfault.com/questions/254/how-can-i-convince-my-it-manager-to-upgrade-the-enterprise-from-ie6-to-a-newer-br). The short answer is, the very thing you desire in IE7/IE8 (standards compliance) is what prevents the adoption - it breaks all those enterprise web apps to have IE not behave like IE (like KevMo said). | I just went though this exact same thing with a global brand. Initially I agreed with you, and wrote a whole bunch of angry emails to try and state my case, at the end of the day IE6 was clearly stated in the spec and I had no choice but to get it done properly to the clients requirements.
The biggest issue I had with IE6 was not layout, that can be fixed relativelky easily, but with the lack of support for transparent PNG's. Even that had a clever JS solution in the end and now the page looks identical in all browsers. My devs have all learned their lesson the hard way and I dounbt we will be sitting in this position again. What I try and do now is get the CSS template pages done first and tested across all platforms and browsers using a service like browsercam before handing the project over to the coders.
When the project went live it was discovered that there were issues with the new IE8 too. Since IE8 wasn't in spec because it didn't exist at the time there was talk about it not being our problem, but with the amount of money these guys pay us combined with the moral and possibly legal obligation to future proof our work we fixed that too.
Here's my take on an old business principle: since I appreciate the contracts and the money they generate, the clients are always right, even if they are stubborn and ignorant and sometimes wrong :) |
10,649,406 | ```
var num = "10.00";
if(!parseFloat(num)>=0)
{
alert("NaN");
}
else
{
alert("Number");
}
```
I want to check if a value is not a float number, but the above code always returns `NaN`, any ideas what I am doing wrong? | 2012/05/18 | [
"https://Stackoverflow.com/questions/10649406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/510785/"
] | `!parseFloat(num)` is `false` so you are comparing `false >= 0`
You could do this:
```
if(! (parseFloat(num)>=0))
```
But it would be more readable to do this:
```
if(parseFloat(num) < 0)
``` | Because `!` has a higher precedence than `>=`, so your code does
`!parseFloat(num)` which is `false`
Then
`>= 0`, `false` is coerced into `0`, and `0 >= 0` is true, thus the `alert("NaN")`
<https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence> |
72,730,693 | I would like to use `numpy` broadcasting feature on mathematical function which involves linear algebra *(bivariate gaussian distribution without the denominator part)*.
The Minimal, Reproducible Example of my code is this:
I have the following function
```
import numpy as np
def gaussian(x):
mu = np.array([[2],
[2]])
sigma = np.array([[10, 0],
[0, 10]])
xm = x - mu
result = np.exp((-1/2) * xm.T @ np.linalg.inv(sigma) @ xm)
return result
```
The function assumes that `x` is a 2x1 array.
My aim is to use the function to generate a 2D array where the individual elements are products of the function.
I apply this function as follows:
```
x, y = np.arange(5), np.arange(5)
xLen, yLen = len(x), len(y)
z = np.zeros((yLen, xLen))
for y_index in range(yLen):
for x_index in range(xLen):
element = np.array([[x[x_index]],
[y[y_index]]])
result = gaussian(element)
z[y_index][x_index] = result
```
This works but as you can see, I use two for loops for indexing. I am aware that this is bad practise and when working with bigger arrays it is terribly slow. I would like to solve this with `numpy` broadcasting feature. I attempted the following code:
```
X, Y = np.meshgrid(x, y, indexing= 'xy')
element = np.array([[X],
[Y]])
Z = gaussian(element)
```
But I am getting this error: `ValueError: operands could not be broadcast together with shapes (2,1,5,5) (2,1)` for line `xm = x - mu` of the function. I understand this error to a certain extent.
In addition, even if I solved this I would be getting another error: `ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 5 is different from 2)` for the `result = np.exp((-1/2) * xm.T @ np.linalg.inv(sigma) @ xm)` line of the fuction. Again, I understand why. `xm` would no longer be 2x1 array and multiplying it with `sigma`, which is 2x2, would not work.
Does anyone have a suggestion on how to modify my function so the broadcasting implementation works? | 2022/06/23 | [
"https://Stackoverflow.com/questions/72730693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14687313/"
] | `fgets` can be used to read each line of the file.
Use `strncmp` to compare the first characters of the line to the serial number. `strncmp` will return `0` for a match.
Upon a match, `sscanf` can parse the fields from the line. The scanset `%19[^;];` will scan up to 19 characters that are not a semi-colon, then scan the semi-colon.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( void)
{
char matricola[50] = "";
char line[100] = "";
printf("insert serial number: \n");
fgets ( matricola, sizeof matricola, stdin);
size_t length = strcspn ( matricola, "\n");
matricola[length] = 0; // remove newline
FILE *fp=fopen("prova.txt","r");
if (!fp){
printf("file doesnt exist\n");
return -1;
}
char (*matrice)[4][20] = NULL;
size_t rows = 0;
while ( fgets ( line, sizeof line, fp)) {
if ( ! strncmp ( line, matricola, length)) {
char (*temp)[4][20] = NULL;
if ( NULL == ( temp = realloc ( matrice, sizeof *matrice * ( rows + 1)))) {
fprintf ( stderr, "realloc problem\n");
free ( matrice);
return 1;
}
matrice = temp;
if ( 4 == sscanf ( line, "%19[^;];%19[^;];%19[^;];%19[^\n]"
, matrice[rows][0]
, matrice[rows][1]
, matrice[rows][2]
, matrice[rows][3])) {
++rows;
}
}
}
for ( size_t each = 0; each < rows; ++each) {
printf ( "%s\n", matrice[each][0]);
printf ( "%s\n", matrice[each][1]);
printf ( "%s\n", matrice[each][2]);
printf ( "%s\n\n", matrice[each][3]);
}
free ( matrice);
return 0;
}
``` | <https://en.cppreference.com/w/c/string/byte/strtok>:
>
> This function is destructive: it writes the '\0' characters in the elements of the string str. In particular, a string literal cannot be used as the first argument of strtok.
>
>
>
I'm pretty sure you'll be happier just reading lines using `fscanf`.
On another note, this is a semicolon-separated values file, and there's really really many libraries that read such reliably. Don't do this to yourself – C is really not a very good (or safe to use) language for string processing, and the built-in utilities like `strtok` are really not that great (they're also 50 years old!). Many people automatically switch to other languages than C when they have to do text-processing heavy tasks, just because, in all honesty, C is not that well-equipped compared to other languages for this particular set of tasks! |
153,794 | Just so you people don't think of me as a monster. I ask this question because recently I was playing [NetHack](http://en.wikipedia.org/wiki/NetHack) and there is a [magic scroll](http://nethack.wikia.com/wiki/Scroll_of_genocide) that allows you to genocide a species of monsters (usually evil bad ones that want to hurt you, like a master mind flayer).
I was trying to convey this to my friends by saying. I am having a good game so far I genocided over 16 types of monsters. They scoffed at me saying this was incorrect as genocided is not a word. What word should I use then in this case?
I've also noticed the game itself uses the word genocided, so I am not sure If they are correct or the game is correct with the usage. | 2014/02/24 | [
"https://english.stackexchange.com/questions/153794",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/66938/"
] | This actually ties in to some more general issues, so I'll start with a brief discussion of them.
The first parallel I thought of is *suicide*, which like *genocide* is mainly used as a noun. The corresponding verbal expression is normally *to commit suicide*; it's relevant that the verb *to suicide* actually is attested, although it's extremely rarely used and clearly not the preferred option. (See the following questions: [Can one conjugate and use 'suicide' as a verb?](https://english.stackexchange.com/questions/74312/can-one-conjugate-and-use-suicide-as-a-verb), [Difference between “commit suicide” and “suicide”](https://english.stackexchange.com/questions/31604/difference-between-commit-suicide-and-suicide))
Possibly more relevantly, the OED also has a couple of citations for *homicide* used as verb, one from 1470 and one from 1858.
The word *genocide* was coined relatively recently (in the 20th century), and the OED only has an entry for it as a noun.
Here is a Google Ngram chart comparing relative frequencies of *suicided*, *genocided*, and *homicided*:
[](https://i.stack.imgur.com/4qpvI.png)
My conclusion is that
1. For all of the nouns with the structure *X-cide*, the normal way of constructing the corresponding verbal expression is *commit X-cide.*
2. Sometimes, but quite rarely, we see people simply use the noun as a verb; this is attested in the OED for *suicide* and *homicide*, but not for *genocide*. This seems to be most common with *suicide*; possibly, as mentioned by some people in the linked questions above, this is due to a desire to avoid using the structure *commit [some action]* which carries a connotation of criminality.
I agree with the others who have said that *genocide* used as a transitive verb is understandable, but sounds ineloquent and informal or uneducated.
When you use the expression "commit genocide," you can't have a direct object. The equivalent to "I genocided **over 16 types of monsters**" can be expressed in more than one way, but you need to use a preposition of some sort.
The first I thought of, and the one that has been most commonly used according to the Ngram Viewer, is *against*: "I committed genocide **against over 16 types of monsters**." Other options include [*commit genocide **on***](https://www.google.com/search?q=%22commit%20genocide%20on%22&tbm=bks&lr=lang_en&gws_rd=ssl#q=%22commit%20genocide%20on%22&lr=lang_en&tbs=lr:lang_1en&tbm=bks&start=0) and [*commit genocide **upon***](https://www.google.com/search?q=%22commit%20genocide%20on%22&tbm=bks&lr=lang_en&gws_rd=ssl#q=%22commit%20genocide%20on%22&lr=lang_en&tbs=lr:lang_1en&tbm=bks&start=0). | The direct answer to your problem is that you should have said that you collected 16 different types of "Genocide Scrolls" and then used them. |
391,653 | I am updating an LWC in my dev org and adding a new property to be configured in the app builder however when I install the new version of the managed package which has more properties than the first version it raises an error.
>
> BearBonesTest: Invalid property [text2] in component [lwcManaged:bearBones]
>
>
>
This error only happens when the component is a part of the lightning page, If the component is not part of any lighting page then adding properties does not raise any error.
Is this the expected behavior and is there a way to resolve this?
v1 code for the lwc
html:
```
<template>
<lightning-card>
{text1}
</lightning-card>
</template>
```
javasript:
```
import { LightningElement, api } from 'lwc';
export default class BearBones extends LightningElement {
@api text1;
}
```
xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__AppPage">
<property name="text1" type="String" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
```
v2 code for the lwc
html:
```
<template>
<lightning-card>
{text1}
{text2}
</lightning-card>
</template>
```
javasript:
```
import { LightningElement, api } from 'lwc';
export default class BearBones extends LightningElement {
@api text1;
@api text2;
}
```
xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__AppPage">
<property name="text1" type="String" />
<property name="text2" type="String" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
``` | 2022/12/09 | [
"https://salesforce.stackexchange.com/questions/391653",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/120140/"
] | Technically you can register a Platform Event on LWC using [lighting EMP Api](https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation).
And then in finish method fire a platform event with the record Id and then display that on UI.
**But not sure of the use case, so this is just a suggestion**
Also be sure to have a limits check, because only max of 2000 concurrent users can be subscribed to Streaming api.
Check limits [here](https://developer.salesforce.com/docs/atlas.en-us.198.0.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_streaming_api.htm) | There are a few ways you can pass the id of the record inserted by the batch job to your LWC component. One approach is to use the @api decorator in your Apex controller to expose a public method that returns the id of the record. Then, in your LWC component, you can use the @wire decorator to call the Apex method and get the id of the record.
Here's an example of how you could implement this approach:
```
// Apex controller
public with sharing class MyController {
@AuraEnabled
@Api
public static Id getRecordId() {
// get the id of the record inserted by the batch job
return myRecord.Id;
}
}
// LWC component
import { LightningElement, wire } from 'lwc';
import getRecordId from '@salesforce/apex/MyController.getRecordId';
export default class MyComponent extends LightningElement {
@wire(getRecordId)
recordId;
// ... other component code goes here
}
```
In this example, the getRecordId Apex method is exposed as a public method using the @Api decorator. The LWC component uses the @wire decorator to call this method and get the id of the record inserted by the batch job. The recordId property of the LWC component is then automatically populated with the id of the record, which you can use to display it in your component.
Another approach is to use a custom event to pass the id of the record from the Apex controller to the LWC component. In your Apex controller, you can create and fire a custom event that contains the id of the record as a parameter. Then, in your LWC component, you can listen for the custom event and retrieve the id of the record from the event object.
Here's an example of how you could implement this approach:
```
// Apex controller
public with sharing class MyController {
@AuraEnabled
public static void finishMethod() {
// get the id of the record inserted by the batch job
Id recordId = myRecord.Id;
// create and fire a custom event
MyCustomEvent event = new MyCustomEvent();
event.setParam('recordId', recordId);
event.fire();
}
}
// LWC component
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
@track recordId;
connectedCallback() {
// listen for the custom event
this.template.addEventListener('myCustomEvent', this.handleEvent);
}
handleEvent(event) {
// get the id of the record from the event object
this.recordId = event.detail.recordId;
}
// ... other component code goes here
}
```
In this example, the finishMethod Apex method creates and fires a custom event called myCustomEvent that contains the id of the record as a parameter. The LWC component listens for this event and retrieves the id of the record from the event object when it is fired. The recordId property of the LWC component is then updated with the id of the record, which you can use to display it in your component. |
50,466,080 | I know that checkbox is a relatively new feature in Google Sheets, so I'm trying to find a way to automatically create checkboxes in cells.
So far, I haven't found a reference regarding this in Google Apps Script documentation.
Currently I'm doing it manually, but any suggestion using script will be much appreciated. | 2018/05/22 | [
"https://Stackoverflow.com/questions/50466080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8806682/"
] | ### UPDATE(April 2019)
You can now directly `insertCheckboxes`(or `removeCheckboxes`) on a [`Range`](https://developers.google.com/apps-script/reference/spreadsheet/range#insertcheckboxes) or [`RangeList`](https://developers.google.com/apps-script/reference/spreadsheet/range-list#insertCheckboxes()) without any workarounds. You can also change the checked value/unchecked value using alternate method signatures found in the documentation.
### Snippet:
```
SpreadsheetApp.getActive()
.getRange('Sheet2!A2:A10')
.insertCheckboxes();
``` | The checkbox is the recently added Data Validation criterion. Interestingly enough, when I attempt to call the 'getDataValidation()' method on the range that contains checkboxes, the following error is thrown:
```
var rule = range.getDataValidation();
```
>
> We're sorry, a server error occurred. Please wait a bit and try again.
>
>
>
In the meantime, you can work around this by placing a single checkbox somewhere in your sheet and copying its Data Validation to the new range. For example, if "A1" is the cell containing the checkbox and the target range consists of a single column with 3 rows:
```
var range = sheet.getRange("A1"); //checkbox template cell
var targetRange = sheet.getRange(rowIdex, colIndex, numOfRows, numOfCols);
range.copyTo(col, SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION);
var values = [["true"], ["false"], ["false"]];
targetRange.setValues(values);
``` |
27,349,165 | I'm writing a piece of code using JavaScript to check if a number is prime or not. The code correctly tells me the result for number = 1,2,3 but fails on certain others such as 10. I can't figure out what the problem is that is causing it to fail on only certain numbers. If anyone can help identify the problem and suggest a fix I would be grateful.
```
if (total < 2) {var prime = "this is not a prime number"}
if (total == 2) {prime = "this is a prime number"}
if (total == 3) {prime = "this is a prime number"}
for (var l = 2; l <= Math.sqrt(total); l++) {
if (total % l == 0) {prime = "this is not a prime number"}
else {prime = "this is a prime number"}
}
```
the code is used in a html file as part of a function | 2014/12/07 | [
"https://Stackoverflow.com/questions/27349165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258185/"
] | You should exit out of the loop as soon as you know that it's not a prime, otherwise the result will be overwritten in the next itaration. There is actually no point in having the `else` clause (as it just sets the same value over and over), just set that value before the loop:
```
prime = "this is a prime number";
for (var l = 2; l <= Math.sqrt(total); l++) {
if (total % l == 0) {
prime = "this is not a prime number";
break;
}
}
```
Side note: You don't need to check the values `2` and `3` separately before the loop, those will be catched by the first two iterations in the loop. | Guffa your approach is right but you can increase the efficiency of your algorithm for large numbers by including two conditions.
1. Check whether a number is divisible by 2.
For even numbers, it directly gives the result.
This condition already lessens the number of repetitions by half if the
number is odd.
2. There is a very interesting fact about Prime numbers, which most people
don't know. Every Prime number only comes either exactly before a multiple of 6
or exactly after that multiple of six.What I mean by that. e.g.,54 is a
multiple of 6. There must be a prime number either before or after 56.Let's
check : 54+1 = 55 , not a prime number : 54-1 = 53 a prime number.SO, the claim
is clear. Now we will use this property in reverse 'Every Prime number must
have a multiple of 6 before or after it.' If I have to check whether 105 is a
prime number or not.
a. Check whether 105+1 = 106 is a multiple of six? No
b. Check whether 105-1 = 104 is a multiple of six? No
So 105 can never be a prime number.
3. You may notice that there is an ambiguity in this algorithm. You can only
decide whether a number is not prime with this property but it does not tell
you the certainty of the number to be prime. I mentioned that you have to check
for a multiple of 6 and if it is then there should be a prime number before or
after that multiple but it is not clear whether it is before or after that. So,
you have to deal with that too. We can only check for not Prime but it can
reduce a lot of computation.
My Code:-
```js
// The following code is written in Python. But anyone beginner level Programmer can understand it.
i = '140740731462387462836487236478236487236487384783'
k = int(i)
if (int(i[-1])%2 == 0): #Get the last didgit of the number and check if it is
#even.One can also just divide the whole num by 2
print('a.Not a Prime')
elif not((k-1)%6==0 or (k+1)%6==0):#Check for multiple of six.
print('b.Not a Prime')
else :
for j in range(3,int(k**(1/2))+2,2): # Final approach.Increment index by 2
#because you have already checked for
#even numbers.
print(j)
if (k%j==0):
print('c.Not a Prime'+str(j))
check=0
break
check =1
if (check ==1):
print('A prime Number')
```
Thanks,
Mahyar Ali |
55,050,850 | I want to return False whenever the user enters the wrong input. To do this, I need to check the input and make sure it only contains specific letters. In this case I want to make sure their input only contains 'b', 'r', 'g', 'p', 'y', or 'o'. Theses letters represent colors in a "mastermind" game I am programming.
The problem is, I'm not sure how to properly use regex in python 2.7.
*How can I trigger an if-statement for any String that contains any characters other than these specific letters?*
**Example:**
```
# check for invalid letters
if re.search("^[brgpyo]", player_input_string):
return False
``` | 2019/03/07 | [
"https://Stackoverflow.com/questions/55050850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944978/"
] | ```
import string
letters = set(string.ascii_letters)
chars = ['b','r','g','p','y','o']
bad_chars = letters-set(chars)
if bad_chars in player_input_string:
return False
```
Use the set here to be able to substract list from another list. | result = re.search('[^brgpyo]\*', player\_input\_string)
if result:
return False |
50,130,077 | ```
x = IntVar()
x.set(1)
def add():
x.set(x.get()+1)
```
I am using this piece of code to update the question number on a tkinter quiz I am making.
```
self.recordNum = Label(self.quizf, text=x)
self.recordNum.pack()
self.Submit = Button(self.quizf, text = 'submit', command=lambda:[self.confirmAnswer(),add()])
```
I used `lambda` so I could have two commands in the same button which I need as `self.confirmAnswer` runs the if statement to check the answer and the `add` command activates the first piece of code displayed above.
When I run the quiz `PY_VAR4` displays instead of a number, thanks for your help! :) | 2018/05/02 | [
"https://Stackoverflow.com/questions/50130077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9552785/"
] | ```
self.recordNum = Label(self.quizf, text=x.get())
self.recordNum.pack()
self.Submit = Button(self.quizf, text = 'submit', command=lambda:[self.confirmAnswer(),add()])
```
In the label, you have to use `x.get()` instead of just `x`, as you want the value of `x`.
Just using `x` will reference to the object which is simply `PY_VAR`. The `4` at the end of the reference simply denotes the variable number to distinguish between other variables. In this case, the program in total so far has 5 variables declared, as references start from `PY_VAR0` ... all the way to... `PY_VAR4`.
Using `x.get()` will instead get the value stored in the object from which the reference points to.
So instead of: `self.recordNum = Label(self.quizf, text=x)`
use: `self.recordNum = Label(self.quizf, text=x.get())`
Possible duplicate of: [Tkinter IntVar returning PY\_VAR0 instead of value](https://stackoverflow.com/questions/24768455/tkinter-intvar-returning-py-var0-instead-of-value) | You need to use “textvariable” as argument for your variable. Then the label will update itself. |
5,916 | For any of the 4 races, how do you place your buildings/what hero do you get/what do you build first to effectively protect yourself against that all-annoying BladeMaster rush with WindWalk, early game?
I'm talking *no* peon losses, ideally causing him to have to TP. | 2010/08/19 | [
"https://gaming.stackexchange.com/questions/5916",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/3026/"
] | I haven't played in a long time so bare with me:
**Night Elf:**
```
Mana Burn (Demon Hunter)
Dust+Entangling Roots+Surround/Focus Fire (KotG)
Shadow Strike will slow allowing you to attack him with units(Warden)
Build your wells in a manner that blocks your trees so melee heroes cant get in
```
Alternatively, put lumber Wisps in random places around the map instead of at all
at your main (risky)
**Rec: DH**
**Human:**
```
Arcane Towers covering all peasants (Drains Mana)
Storm Bolt (MK)+Surround (Miltia, Footmen, Buildings)
^^His WW can run through but he won't come back out if he is weak^^
Use Water Elementals+AM Range to attack with Miltia as melee (AM)
Paladin can heal workers while they attack him
```
**Rec: MK**
**Undead:**
```
Nerubian Tower to slow (allows for easier chase damage)
Use Death Knight to heal Acolytes or nuke BM if you see a kill coming
Dreadlord can sleep/surround
Lich can slow as well
```
**Rec: DK**
Also, kite Acolytes around mine, Switching Acos location when he switchs target, Bring in Ghouls to surround/attack while DK heals Kiting Acos.
**Orc:**
```
Throw a few peons into burrow, definitely the ones he attacks
Build your initial Burrows so that they can cover your lumber and gold peons
Attack with wolves + range (FS)
Throw up wards or hex/surround (SH)
Stun/attack (TC)
```
If you go BM you can just attack him as well for solid damage.
**Rec: Whichever hero you are most comfortable with**
In general, Kiting (running around/away) the peons he attacks will help prolong there life and inflict more damage to the BM for each worker kill.
This is just good all around and should become second habit early game.
Also, Another very strong approach is to counter-harass. Using natural base defenses (Towers, Wells to heal, miltia etc) as well as kiting, fend him off the
best you can while harassing his base (hopefully more succesfully) with your hero.This will force him to retreat or put you at a significant advantage exp and resource wise.
This is micro-intensive and should only be attempted if you are confident. Failing to succeed will put you at a significant disadvantage. | Hero Rushing is a standard part of Warcraft III. To Hero Rush means to attack the enemy town, especially workers, as early as possible. Players head to the enemy town as soon as the Hero has been trained. Players are typically either Hero Rushing the enemy or defending against a Hero Rush. Sometimes players may not Hero rush or may decide to Creep instead but Hero Rushing is found in most ladder games.
Reasons for Hero Rushing include:
* Distraction
People who advance quickly up the tech-tree don't have a strong army. They need to distract and "harass" you until they are able to build their high end units. This involves doing regular hit-and-run attacks on your town. Usually if people are Hero Rushing you and they don't bring units with them, they are teching. You know it's time to go hit their base before they get whatever they are trying to build.
* Fun
Hero rushing is fun! It's fun to attack players who don't know how to handle a Hero Rush. If the enemy is really bad at the game you can totally hose them and win the whole game. In Warcraft II and StarCraft there was a "build up" time where there wasn't a lot going on. Many players found this phase of the game boring. The answer was Heroes very early so that players have something fun to do at the beginning of the game.
**Good Hero Rushers**
* Demon Hunter (Mana Burn/Immolation)
* Blademaster (Wind Walk)
* Warden (Shadow Strike/Fan of Knives)
* Keeper of the Grove (Entangling Roots)
* Far Seer (dogs)
* Shadow Hunter (Serpent Wards)
* Archmage (Blizzard the workers/Water Elementals)
* Mountain King (Storm Bolt - good in 2 vs. 2 games)
* Naga Sea Witch (Forked Lightning/Frost Arrow)
* Crypt Lord (Beetles/Impale with Ghouls)
OK Hero Rushers
Some of these might be more effective in Team Games with help.
* Blood Mage (Flame Strike)
* Death Knight (Death Coil to Heal + Ghouls)
* Tauren Chieftain (Stomp/Shockwave)
* Beastmaster
* Pandaren Brewmaster (Drunken Haze)
* Dread Lord (Sleep/Carrion Swarm with Ghouls)
* Lich (Frost Nova)
* Dark Ranger (possible if you go Life Drain first).
Semi-Bad Hero Rushers
* Priestess of the Moon (at least go Searing Arrow first and come with an ally)
* Pit Lord (gets stuck).
They are ok if they are supporting another Hero and are not being hit.
Extremely Bad Hero Rushers
* Paladin (laugh whenever you see this)
**Anti Hero Rushers**
The same Heroes that are good for Hero Rushing are also good at defending against Hero rushes typically. Some of the best anti Hero Rushers are:
* Demon Hunter (Mana Burn)
* Mountain King (Storm Bolt)
* Warden (Shadow Strike)
* Far Seer (dogs/Chain Lightning)
**Defense against Hero Rushes**
All:
Lead the enemy away until you can build up enough forces to take them on. Hit, then run away from your town. Use your Town's defenses!
Humans:
Get an Arcane Tower! Use Militia if they get close but go back to work if they run away.
Orcs:
Hop in those Burrows. Build 1-2 Watch Towers
Undead:
Run the Acolytes away. Build 1 Nerubian Tower. Use a Death Knight to heal the Acolytes
Night Elves: Use Detonate. Fight by the Moon Wells. Build your town in such a way that the Ancients of War can defend you. |
59,804,247 | ```
void sort(int *ptr, int n) {
int i,j,tmp;
for (i=0;i<n;i++)
for (j=i;j<n;j++)
if (ptr[i] > ptr[j])
{
tmp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=tmp;
}
}
```
AND
```
void sort(int *ptr, int n) {
int i,j,tmp;
for (i=0;i<n;i++)
for (j=i;j<n;j++)
if (*(ptr+i) > *(ptr+j))
{
tmp=*(ptr+i);
*(ptr + i) = *(ptr + j);
*(ptr + j)=tmp;
}
}
```
It has the same output. Both works. I've seen people using both, although obviously the first one seems more natural and intuitive than the second. Is there any problems whatsoever in using the first one over the second? Also, what are the main differences between them, if any? | 2020/01/18 | [
"https://Stackoverflow.com/questions/59804247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515106/"
] | The two pieces of code are semantically equivalent.
Section 6.5.2.1p2 of the [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) regarding the array subscript operator `[]` states:
>
> A postfix expression followed by an expression in square
> brackets `[]` is a subscripted designation of an element of an array
> object. The definition of the subscript operator `[]` is that
> `E1[E2]` is identical to `(*((E1)+(E2)))`. Because of the conversion
> rules that apply to the binary `+`operator, if `E` 1is an array
> object (equivalently, a pointer to the initial element of an
> array object) and `E2` is an integer, `E1[E2]` designates the
> `E2`-th element of `E1` (counting from zero).
>
>
>
So for example `ptr[i]` is exactly the same as `*(ptr+i)`, as well as other similar instances.
The first version of the code using array subscripting is generally preferred because it is more readable. | Nothing. It's merely a matter of style. |
17,448,269 | In SQL Server database I have a View with a lot of INNER JOINs statements. The last join uses LIKE predicate and that's why it's working too slowly. The query looks like :
```
SELECT *
FROM A INNER JOIN
B ON A.ID = B.ID INNER JOIN
C ON C.ID1 = B.ID1 INNER JOIN
...........................
X ON X.Name LIKE '%' + W.Name + '%' AND
LIKE '%' + W.Name2 + '%' AND
LIKE '%' + W.Name3 + '%'
```
I want to use CONTAINS instead of LIKE as :
```
SELECT *
FROM A INNER JOIN
B ON A.ID = B.ID INNER JOIN
C ON C.ID1 = B.ID1 INNER JOIN
...........................
X ON CONTAINS(X.Name, W.Name) AND
CONTAINS(X.Name, W.Name2) AND
CONTAINS(X.Name, W.Name3)
```
I know that CONTAINS is working faster than LIKE and also that can't use CONTAINS in JOIN statements.
Is there any workaround in this case or suggestion?
Thanks in advance. | 2013/07/03 | [
"https://Stackoverflow.com/questions/17448269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1473178/"
] | You can create a join using a LIKE..
something like this:
```
SELECT * FROM TABLE_ONE
FULL OUTER JOIN TABLE_TWO ON TABLE_ONE.String_Column LIKE '%' + TABLE_TWO.Name + '%'
```
ie - select everything from TABLE\_ONE where the string\_column is contained in the TABLE\_TWO name | In short there isn't a way to do this using CONTAINS, it simply is not allowed in a JOIN like this.
see: [TSQL - A join using full-text CONTAINS](https://stackoverflow.com/questions/5152783/tsql-a-join-using-full-text-contains)
So although there is performance hit, IMO like is the easiest solution here. |
2,796 | Ich denke, dass man bei (Arbeits-)**Stelle** im Allgemeinen explizit dazu sagt, wenn es sich um eine zeitlich **befristete** Stelle handelt.
Bei **Arbeit**, wie in
>
> Ich habe Arbeit.
>
>
>
kann man vermutlich noch nicht mal sicher sein, dass es sich um bezahlte Arbeit handelt, es kann sich dabei durchaus auch um ehrenamtliche Tätigkeiten handeln.
Wie aber sieht es mit dem Begriff **Job** aus, meint der im Allgemeinen zeitliche begrenzte Arbeiten? | 2011/10/16 | [
"https://german.stackexchange.com/questions/2796",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/104/"
] | Ich würde sagen: Der Begriff hat einen Bedeutungswandel hinter sich. War ein Job früher eine Nebenbeschäftigung oder eine befristete Anstellung, so ist die Bezeichnung "mein Job" heute auch für den Hauptberuf mit einem unbefristeten Vertrag gängig, analog zu der Bedeutung im Englischen. Siehe auch: Jobcenter, wo auch "richtige" Anstellungen vermittelt werden sollen. | Der Begriff Job ist ein wenig doppeldeutig.
Auf der einen Seite kann es ein klassisches vertragliches Arbeitsverhältnis bezeichnen, wobei es hier egal ist, ob das Ganze befristet oder unbefristet ist.
Auf der anderen Seite wird es häufig auch einfach als Alternative zum Wort "Aufgabe" verwendet ("Mein Job ist es, hier die Blumen zu pflanzen"). |
376,950 | I first noticed it earlier today at work, and now on my system at home, that the page size when searching defaults to 1 now. For example, <https://stackoverflow.com/questions/tagged/c%23> shows me 1 question per page.
Has this happened to anyone else? Was the default page size perhaps set to 1 by accident? | 2018/11/22 | [
"https://meta.stackoverflow.com/questions/376950",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/247702/"
] | Clicking on desired page size again to fixes the issue.
Looks like a bug - probably someone changed how this value is stored. I have low expectations for quick root cause or fix as there is Thanksgiving in US :) | It seems to hold the last value you use. Asking for `?pagesize=4` will hold that value as default for pagination.
That's my favourite ~~bug~~ rogue feature of the week, I must say. |
11,543,714 | I want call method path from class Path. I need set some number - array length and appropriate values of array on entrance.
This is my class:
```
class Path {
int number;
String[] path_name = new String [number];
Path (int n, String [] p){
number=n;
path_name=p;
}
public void path(){
for (int i=1; i<number; i++){
driver.findElement(By.linkText(path_name[i])).click();
}
}
```
}
This is how I try call method:
```
Path pa = new Path (6,'array value');
pa.path();
```
But I don't know how properly initiate 'array value' - I need set "one", "two","three" for example. Could someone help?
I do not know length of array on the beginning, so I can't define several Strings in the constructor | 2012/07/18 | [
"https://Stackoverflow.com/questions/11543714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1407907/"
] | Try something like:
```
Path pa = new Path(6, String[] {"one", "two", "three"} );
```
If you can change the code you can probably use varargs to make it easier:
```
Path (int n, String p...)
```
Then you could just to:
```
Path pa = new Path(6, "one", "two", "three");
``` | The n number you refer to can be eliminated if you accept the invariant that all elements of the array are valid elements to path for.
With this in mind, you can simply have
```
class Path {
final String[] pathNames;
// uses var args
Path(String... paths) {
pathNames = paths;
}
void path() {
// uses enhanced for loop
for(String path : pathNames) {
driver.findElement(By.linkText(path)).click();
}
}
}
```
Some critiques:
* You currently are creating an array of size `number` when you create the object. But number is 0 at that point. So you're creating an empty array.
* But the above point is irrelevant because you're immediately reassigning the reference...
* Because you're not defensively copying the array, some external code could modify the elements of the array. This is probably not a good thing. (This is addressed by the var args, where no outside code has access to that array. You can't stop someone from passing an array in instead of var args, but they will at least be aware of the fact that you expect var args, so they still have the ability to alter internally if they *want* to, but are unlikely to *accidentally* introduce a bug in such a manner.) |
5,639,346 | **What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?**
Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the [QuirksMode.org `readCookie()`](http://www.quirksmode.org/js/cookies.html) method (280 bytes, 216 minified.)
```
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
```
It does the job, but its ugly, and adds quite a bit of bloat each time.
The method that [jQuery.cookie](https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js) uses something like this (modified, 165 bytes, 125 minified):
```
function read_cookie(key)
{
var result;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}
```
**Note** this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid. | 2011/04/12 | [
"https://Stackoverflow.com/questions/5639346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172322/"
] | code from google analytics ga.js
```
function c(a){
var d=[],
e=document.cookie.split(";");
a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
for(var b=0;b<e.length;b++){
var f=e[b].match(a);
f&&d.push(f[1])
}
return d
}
``` | Here is the simplest solution using javascript string functions.
```
document.cookie.substring(document.cookie.indexOf("COOKIE_NAME"),
document.cookie.indexOf(";",
document.cookie.indexOf("COOKIE_NAME"))).
substr(COOKIE_NAME.length);
``` |
3,739,369 | currently I am thinking about data encapsulation in C# and I am a little bit confused.
Years ago, when I started to learn programing with C++, my professor told me:
- "Create a class and hide it data members, so it can't be manipulated directly from outside"
Example:
You are parsing an XML file and store the parsed data into some data members inside the parser class.
Now, when I am looking at C#. You have there properties. This feature makes the internal state / internal data of a class visible to outside.
There is no encapsulation anymore. Right?
```
private string _mystring;
public string MyString
{
get {return _mystring;}
set {_mystring = value;}
}
```
From my point of view there is no difference between making data members public or having public properties, which have getters and setters, where you pass your private data members through.
Can someone explaing me that please?
Thanks | 2010/09/17 | [
"https://Stackoverflow.com/questions/3739369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451089/"
] | Well so properties aren't the wild west you are taking them to be at a first glance. The unfortunate truth of OOP is that a lot of your methods are getters and setters, and properties are just a way to make this easier to write. Also you control what you'd like the property to allow someone to do. You can make a property readable but not writable, like so:
```
private string _mystring;
public string MyString
{
get {return _mystring;}
}
```
Or as mentioned by Reed you can have your set method do a transformation or checking of any amount of complexity. For instance something like
```
private long myPrime;
public long Prime {
get { return myPrime; }
set {
if (prime(value) {
myPrime = prime;
}
else {
//throw an error or do nothing
}
}
}
```
You generally have all the value you get from encapsulation, with some syntactic sugar to make some common tasks easier. You can do the same thing properties do in other languages, it just looks different. | There still is data encapsulation, if you need it to be. Encapsulating data is not about hiding it from the client of the class or making it unaccessible, it's about ensuring a consistent interface and internal object state.
Let's say you have an object representing a stick shift car, and a property to set the speed. You probably know that you should shift gears in between speed intervals, so that's where encapsulation comes in.
Instead of simply making the property public, thus allowing public access without any verification, you can use property getters and setters in C#:
```
class StickShiftCar : Car
{
public int MilesPerHour
{
get {return this._milesPerHour;}
set
{
if (vaule < 20)
this._gearPosition = 1;
else if (value > 30)
this._gearPosition = 2;
...
...
this._milesPerHour = value;
}
}
```
While this example is not necessarily compilable, I am sure you catch my drift. |
246,490 | I am working on REST call. Everything works fine but my column contains special character `&`
So rest call like below works:
```
http://mydomain/_api/web/lists/GetByTitle('MyList')/Items?$filter=ColumnA eq 'DAD'
```
But below fails:
```
http://mydomain/_api/web/lists/GetByTitle('MyList')/Items?$filter=ColumnA eq 'D&D'
```
I dont want to change my column values now. Any solution? | 2018/08/03 | [
"https://sharepoint.stackexchange.com/questions/246490",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/67615/"
] | Use something like this:
```
"http://mydomain/_api/web/lists/GetByTitle('MyList')/Items?$filter=ColumnA eq " + encodeURIComponent("D&D")
``` | Perhaps try putting the encoded value in directly. Have you tried something like this yet:
```
"http://mydomain/_api/web/lists/GetByTitle('MyList')/Items?$filter=ColumnA eq 'D%26D'"
``` |
14,414,086 | Some years ago there was an opinion, that $\_FILES[$file]['type'] contains mimetype sent from a browser, but not real mimetype, for example here:
<http://php.net/manual/ru/reserved.variables.files.php#109902>
Is it still so and do i still need to use fileinfo extension to detect mimetype?
(i am using php5.4) | 2013/01/19 | [
"https://Stackoverflow.com/questions/14414086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391074/"
] | In iOS 6 and later
```
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextColor:[UIColor whiteColor]];
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont systemFontOfSize:18.0f]];
[[UIView appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setBackgroundColor:[UIColor redColor]];
``` | ```
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
if (section == integerRepresentingYourSectionOfInterest)
[headerView setBackgroundColor:[UIColor redColor]];
else
[headerView setBackgroundColor:[UIColor clearColor]];
return headerView;
}
``` |
6,184,656 | This question is a common issue, and I have tried to look at some thread as [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference) or [How to change an attribute of a public variable from outside the class](https://stackoverflow.com/questions/3379788/how-to-change-an-attribute-of-a-public-variable-from-outside-the-class)
but in my case I need to modify a boolean variable, with a Singleton instance.
So far I have a class, and a method which changes the boolean paramter of the class. But I would like to separate this mehod in a manager. The scheme is something like:
```
public class Test{
private boolean b;
public String getb(){}
public void setb(){}
String test = ClassSingleton.getInstance().doSomething();
}
public class ClassSingleton{
public String doSomething(){
//here I need to change the value of 'b'
//but it can be called from anyclass so I cant use the set method.
}
}
```
Thanks,
David. | 2011/05/31 | [
"https://Stackoverflow.com/questions/6184656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/588925/"
] | 1. You could extract `public void setb(){}` into an interface (let's call it `BSettable`), make `Test` implement `BSettable`, and pass an argument of type `BSettable` into `doSomething`.
2. Alternatively, you could make `b` into an [`AtomicBoolean`](http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/atomic/AtomicBoolean.html) and make `doSomething` accept (a reference to) an `AtomicBoolean`. | I think your question is not very clear and your sample code is really badly done. Do you actually mean something like this?
```
public class Test{
private boolean b;
public boolean getb(){return b;}
public void setb(boolean b){this.b = b;}
String test = ClassSingleton.getInstance().doSomething(this);
}
public class ClassSingleton{
private static ClassSingleton __t__ = new ClassSingleton();
private ClassSingleton() {}
public String doSomething(Test t){
t.setb(true);
return null;
}
public static ClassSingleton getInstance(){
return __t__;
}
}
```
Do you mean your manager is a singleton? or your test class should be singleton? Please be more specific |
3,279,524 | I am currently looking for some code or a tool/service that allows me to store Log4Net Messages in a SQL Server database. Does something like this already exist or would I have to implement this on my own? I couldn't find anything on SO or Google.
Thanks in advance for any information. | 2010/07/19 | [
"https://Stackoverflow.com/questions/3279524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297303/"
] | The links from Moin Zaman show test results that are outdated (from 2008). As of my thorough testing today Gmail does support displaying embedded images for both methods.
Use base64 encoding image inline within `<img src="...">`
```
<html><body><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA9QAAADmCAIAAAC77FroAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAO..."></body></html>
```
Use base64 encoded image as attachment
```
Message-ID: <BE0243A40B89D84DB342702BC5FD6D313EA3BE1B@BYMAIL.example.com>
Accept-Language: en-US
Content-Language: en-US
X-MS-Has-Attach: yes
X-MS-TNEF-Correlator:
x-originating-ip: [xxx.xxx.xxx.xxx]
Content-Type: multipart/related;
boundary="_038_BE0243A40B89D84DB342702BC5FD6D313EA3BE1BBYMAIL_";
type="multipart/alternative"
MIME-Version: 1.0
Return-Path: email@example.com
X-OriginatorOrg: example.com
--_038_BE0243A40B89D84DB342702BC5FD6D313EA3BE1BBYMAIL_
Content-Type: multipart/alternative;
boundary="_000_BE0243A40B89D84DB342702BC5FD6D313EA3BE1BBYMAIL_"
...skipping Content-Type: text/plain which would be here for this example...
--_000_BE0243A40B89D84DB342702BC5FD6D313EA3BE1BBYMAIL_
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<html><body><img border=3D"0" width=3D"980" height=3D"230" id=3D"Picture_x0020_1" src==3D"cid:image001.png@01CDA268.204677C0"></body></html>
--_000_BE0243A40B89D84DB342702BC5FD6D313EA3BE1BBYMAIL_--
--_038_BE0243A40B89D84DB342702BC5FD6D313EA3BE1BBYMAIL_
Content-Type: image/png; name="image001.png"
Content-Description: image001.png
Content-Disposition: inline; filename="image001.png"; size=32756;
creation-date="Mon, 08 Oct 2012 15:27:07 GMT";
modification-date="Mon, 08 Oct 2012 15:27:07 GMT";
Content-ID: <image001.png@01CDA268.204677C0>
Content-Transfer-Encoding: base64
iVBORw0KGgoAAAANSUhEUgAAA9QAAADmCAIAAAC77FroAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAO
xAAADsQBlSsOGwAAf5lJREFUeF7tvQlgVdW18L+ZR20mpsSLCYlBQKwgwRCMr9TAqzg0CAl98Y9a
ikBfHxL1A/r0tUr77Feg1mDav4LUijxTk8hLRIstQ2mJhEiAWAEpNCGRa8KUSQXCzLf2cOZz7j33
5s5Zx6j3nruHtX97n33WWWfttbtdv36d4IEEkAASQAJIAAkgASSABJCA/wl0938VWAMSQAJIAAkg
ASSABJAAEkAClAAq3zgOkAASQAJIAAkgASSABJBAgAig8h0g0FgNEkACSAAJIAEkgASQABJA5RvH
...
```
To do your own testing, you can send email with inline embedded image using one of the following techniques
* Using code by [creating your own base64 image strings](http://base64converter.com/)
* Enable and use [Google Lab for Inserting Images](http://gmailblog.blogspot.com/2009/04/new-in-labs-inserting-images.html)
* Paste image into Email client like Outlook 2010
Send an email using one of the above to your Gmail account, then open the Email in Gmail Web Client (any browser that works) and use the Down-Arrow next to the Reply button to choose the Show Original option. This will show you how it is received.
I think best practice is to use the embedded image as attachment method.
In my testing with Gmail Web Client, if I sent 30 images in a single email of different sizes, a few would not load successfully showing image container but not the image. If that happens, try reloading the page.
In my testing (Windows 7)...
* Chrome (latest) needed a couple of reloads to successfully load/show all 30 images
* Opera (latest) wouldn't successfully show all 30 images regardless of number of reloads
* Firefox (latest) consistently showed all 30 images without issue
* Internet Explorer 9 (latest) consistently showed all 30 images without issue
* Safari (latest) consistently showed all 30 images without issue | ```
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
[picker addAttachmentData:UIImageJPEGRepresentation(_tempImage,1) mimeType:mimeType fileName:filename];
[picker setMessageBody:emailBody isHTML:YES];
```
If `isHTML` is `YES`, `addAttachmentData` will auto change to base64 string, in email html can see you img.
If `isHTML` is NO, `addAttachmentData` is attachment. |
20,740 | I generally have one of Fink, MacPorts, Homebrew installed. Most often for a single, small, and trivial package. I've found that all my day-to-day software exists in OS X versions.
So, which non-OS X unix software do you find is required, interesting, or otherwise always on your computer.
I'm looking to broaden my horizons. I have enough unix/linux experience to not be afraid, I just haven't found a good use-case yet.
For added clarity, I'm not looking for anything already installed with OS X. So, please, no ssh, vi, etc, unless you explain the reason you need a different version. | 2011/08/08 | [
"https://apple.stackexchange.com/questions/20740",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/669/"
] | I frequently reinstall MacPorts (e.g., when there's a new major version of Xcode) so I keep a file with a list of my essential ports for easy reinstalling.
Here's my list of essential software that doesn't come with OS X.
* [arping](http://en.wikipedia.org/wiki/Arping)
* [dnstracer](http://linux.die.net/man/8/dnstracer)
* [watch](http://en.wikipedia.org/wiki/Watch_%28Unix%29)
* [wireshark](http://en.wikipedia.org/wiki/Wireshark)
* [figlet](http://en.wikipedia.org/wiki/Figlet)
* [gnupg](http://en.wikipedia.org/wiki/GNU_Privacy_Guard)
* [ipcalc](http://www.skrenta.com/rt/man/ipcalc.1.html)
* [lynx +ssl](http://en.wikipedia.org/wiki/Lynx_%28web_browser%29)
* [minicom](http://en.wikipedia.org/wiki/Minicom)
* [mtr](http://en.wikipedia.org/wiki/MTR_%28software%29)
* [ncftp](http://en.wikipedia.org/wiki/NcFTP)
* [nmap](http://en.wikipedia.org/wiki/Nmap)
* [pstree](http://en.wikipedia.org/wiki/Pstree)
* [pwgen](http://linux.about.com/cs/linux101/g/pwgen.htm)
* [p0f](http://en.wikipedia.org/wiki/P0f)
* [sipcalc](http://unixlab.blogspot.com/2011/02/advanced-ip-subnet-calculator-sipcalc.html)
* [ssldump](http://www.rtfm.com/ssldump/Ssldump.html)
* [stunnel](http://www.stunnel.org/static/stunnel.html)
* [tcpflow](http://woss.name/2011/03/06/using-tcpflow/)
* [unrar](http://www.robertvenema.nl/journal/archive/howto-command-line-unrar-on-mac-os-x/)
* [w3m](http://w3m.sourceforge.net/MANUAL#Introduction)
* [wget](http://www.gnu.org/s/wget/)
* [wordplay](http://pwet.fr/man/linux/commandes/wordplay)
* [fortune](http://en.wikipedia.org/wiki/Fortune_%28Unix%29)
* [cowsay](http://en.wikipedia.org/wiki/Cowsay)
* [ack](http://betterthangrep.com/) | * wget (download files from inet)
* nmap (scan ip)
* unrar (It's more up to date that the GUI)
* imagemagick (way faster to do thumbs than photoshop)
* mencoder (to do some trasnformations between media formats, I use it regularly to extract audio from DVD's)
developer stuff:
git, postgresql, mongod |
40,295,830 | I am developing a website which require the use of the navigator.geolocation object through a local development environment on MACOSX. I am using Chrome 53. Considering geolocation is blocked on anything that isn't HTTPS how am I suppose to develop my website locally? The Google Developers site quotes:
>
> Does this affect local development?
>
>
> It should not, localhost has been declared as "potentially secure" in
> the spec and in our case geolocation requests served at the top level
> over localhost will still work.
>
>
>
Here's what I am seeing:
[Geolocation console warnings](https://i.stack.imgur.com/xhV38.png)
Any ideas? (aside from switch browser) | 2016/10/27 | [
"https://Stackoverflow.com/questions/40295830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024907/"
] | `http://localhost` is treated as a secure origin, so you don't need to do anything, the Geolocation will work.
If you're using another hostname that points to the localhost (Ex: `http://mysite.test`) then you should run chrome from the command line with the following option: `--unsafely-treat-insecure-origin-as-secure="http://mysite.test"`.
**Example**
```
google-chrome --unsafely-treat-insecure-origin-as-secure="http://yoursite.test"
```
More details on [Deprecating Powerful Features on Insecure Origins](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins) | Use `file:` protocol. Launch chrome with `--allow-file-access-from-files` flag set, see [Jquery load() only working in firefox?](https://stackoverflow.com/questions/32996001/jquery-load-only-working-in-firefox/32996188?s=1|2.0351#32996188). At `Settings` select `Content settings`, scroll to `Location`, select `Ask when a site tries to track your physical location (recommended)`. |
8,447,129 | I am maintaining an ASP.NET MVC project. In the project the original developer has an absolute ton of interfaces. For example: `IOrderService`, `IPaymentService`, `IEmailService`, `IResourceService`. The thing I am confused about is each of these is only implemented by a single class. In other words:
```
OrderService : IOrderService
PaymentService : IPaymentService
```
My understanding of interfaces has always been that they are used to create an architecture in which components can be interchanged easily. Something like:
```
Square : IShape
Circle : IShape
```
Furthermore, I don't understand how these are being created and used. Here is the OrderService:
```
public class OrderService : IOrderService
{
private readonly ICommunicationService _communicationService;
private readonly ILogger _logger;
private readonly IRepository<Product> _productRepository;
public OrderService(ICommunicationService communicationService, ILogger logger,
IRepository<Product> productRepository)
{
_communicationService = communicationService;
_logger = logger;
_productRepository = productRepository;
}
}
```
These objects don't seem be ever be created directly as in `OrderService orderService = new OrderService()` it is always using the interface. I don't understand why the interfaces are being used instead of the class implementing the interface, or how that even works. Is there something major that I am missing about interfaces that my google skills aren't uncovering? | 2011/12/09 | [
"https://Stackoverflow.com/questions/8447129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/594058/"
] | It's good practice to program against interfaces rather than objects. [This](https://stackoverflow.com/questions/4456424/what-do-programmers-mean-when-they-say-code-against-an-interface-not-an-objec) question gives good reasons why, but some reasons include allowing the implementation to change (ex. for testing).
Just because there's currently only 1 class that implements the interface doesn't mean that it can't change in the future.
>
> Furthermore, I don't understand how these are being created and used.
>
>
>
This is called [dependency injection](https://stackoverflow.com/questions/130794/what-is-dependency-injection) and basically means that the class doesn't need to know how or where to instantiate it's dependencies from, someone else will handle it. | These are service interfaces, which encapsulate some kind of externality. You often have just a single implementation of them in your main project, but your tests use simpler implementations that don't depend on that external stuff.
For example if your payment service contacts paypal to verify payments, you don't want to do that in a test of unrelated code. Instead you might replace them with a simple implementation that always returns "payment worked" and check that the order process goes through, and another implementation that returns "payment failed" and check that the order process fails too.
To avoid depending on the implementation, you don't create instances yourself, you accept them in the constructor. Then the IoC container that creates your class will fill them in. Look up [Inversion of Control](http://en.wikipedia.org/wiki/Inversion_of_control).
Your project has probably some code that sets up the IoC container in its startup code. And that code contains information about which class to create when you want an implementation of a certain interface. |
16,113,290 | I have an ATL COM service and in the .IDL file, I've declared an enum like so:
In Gourmet.idl
```
typedef enum Food
{
Chocolate = 0,
Doughnut,
HotDog
} Food;
```
A header file is automatically generated, creating Gourmet\_i.h.
In another .CPP file (let's just call it Decadence.cpp) of the same ATL COM project, I #include Gourmet\_i.h. I've implemented a class in this .CPP and it's under the namespace 'Chocolate'.
For example in Decadence.cpp:
```
#include "Gourmet_i.h"
namespace Chocolate {
// Constructor
void Decadence::Decadence() {}
// ... and so on
} // namespace Chocolate
```
When compiled I get the following error about Gourmet\_i.h:
```
error C2365: 'Chocolate': redefinition; previous definition was 'namespace'
```
I see this occurs because the enum for the IDL is defined in the global namespace, but is it possible to contain this definition -- so it doesn't pollute the global namespace -- and I wouldn't have this conflict? | 2013/04/19 | [
"https://Stackoverflow.com/questions/16113290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1628921/"
] | Short of renaming the namespace or enum member about the only solution for this is to wrap the contents of the generated header file in a namespace. This is not without pitfalls and depending on how the contents of your MIDL file it may eventually cause a few headaches. The cleanest way that I can see would be to create a proxy header file that declares the namespace then includes the MIDL generated header file.
`Gourmet.h`
```
namespace MIDLStuff
{
#include "Gourmet_i.h"
}
``` | If you are using C++11 you can use Scoped Enumeration by including `class`:
```
typedef enum class Food
{
Chocolate = 0,
Doughnut,
HotDog
} Food;
```
Now you need to write `Food::Chocolate` when using the value. |
46,044,959 | I am reading through Eloquent Javascript and am currently on Chapter 4 working on the exercise regarding arrays to list and vice versa. The exercise wants me to get the console to print [10, 20, 30] but I am instead getting it to print [[10],[20],[30]] and am unsure why. I suppose you could argue that it doesn't make a difference, but I would like to "p
```js
function arrayToList(arr) {
let obj = {};
for(let i = 0 ; i < arr.length; i++) {
obj.value = arr.splice(0,1);
obj.rest = arrayToList(arr);
}
return obj;
};
function listToArray(list){
let tempArray = [];
for(var node = list; node; node = node.rest) {
if (node.rest !== undefined){
tempArray.push(node.value);
}
}
return tempArray;
};
console.log(listToArray(arrayToList([10, 20, 30])));
```
ull" the values out of the array. I attempted to created another temporary array to use the .join method and then push that into my result array, but that just gives me 1 for some reason.
Here is my code:
```
function arrayToList(arr) {
let obj = {};
for(let i = 0 ; i < arr.length; i++) {
obj.value = arr.splice(0,1);
obj.rest = arrayToList(arr);
}
return obj;
};
function listToArray(list){
let tempArray = [];
for(var node = list; node; node = node.rest) {
if (node.rest !== undefined){
tempArray.push(node.value);
}
}
return tempArray;
};
console.log(listToArray(arrayToList([10, 20, 30])));
```
Can anyone explain what is happening here? | 2017/09/04 | [
"https://Stackoverflow.com/questions/46044959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8502738/"
] | Every time you get the next line from your scanner, it increases array size by one. So, entering the alphabet, you would get `a,b,c,d,e...` and so on.
After every input, your for loop outputs the entire array. So, the first time the array will have `a`, the second time it will have `a,b`, and so on. If you went on, your output would continue in this format `a,a,b,a,b,c,a,b,c,d...`. The reason you didn't have `a,b,c` outputted yet because it was waiting for the `myScanner.hasNext()` condition of your while loop.
Hope this helps, feel free to ask for clarification. | The duplication occurs because you are attempting to print all the values of the ArrayList myArray over and over again. So when the user inputs A, the myArray will store A then the for loop prints A, then on the next line, when the user inputs B, myArray = A,B, the for loop prints A and B and so on. Put the for loop outside the while loop which gets all the input of the user, let the user finished all the inputs and you must have a way for the user to get out of the loop like type 'Q' to exit. |
21,323 | We're redoing our front room in our house. We're thinking of going with a 'seaside cottage' feel and installing some wainscoting on the walls about 2/3rds the way up.
The catch is that our house currently has doors with casings, but the windows are using a finished sheetrock return. They do have a stool, but not casings around the outside.
Is there a typical way to handle finishing wainscoting around a caseless window short of tearing out all the sheetrock and actually fully framing the windows?
I had two ideas:
1. Bring the wainscoting up around the windows but stop short 1" or so to the corner. Allow the sheetrock to be exposed around the window.
2. Do the same, but extend the wainscoting right to the corner, and then apply a small (easily removable) trim piece to cover the outside corner around the window.
Has anyone done/seen that type of finish detail? Any other typical solutions for this? | 2012/12/07 | [
"https://diy.stackexchange.com/questions/21323",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/1209/"
] | [houzz.com](http://www.houzz.com/Wainscoting)

It appears to be just a matter of how you trim it out. You can do something detailed like in the photo or as simple as 1/4 round trim to cover the edge. | I didn't have pics of how I did the window area but here is pic which shows one method of edging: I would make an apron for under the window sill and for beside the window - experiment with widths that look good for the particular style of wainscot you are using. If it is stain grade wainscot - you should be able to pick up stock to make it out of.
 |
28,787 | *NOTE: I asked this question this morning with respect to EC2 boxes, but only got back links to tools to start and stop instances, so I'll rephrase...*
I have a few Linux boxes that do nightly processing jobs for one of my projects. From time to time, I'll need to get in, make some code changes, configure some things, move files around, etc.
My toolset for these operations is painfully sparse (SSH into the box, edit files in VIM, WGET remote files that I need), and I suspect there is a much better way to do it. I'm curious to hear what other people in my position are doing.
Are you using some form of Windowing system and remote-desktop equivalent to access the box, or is it all command line? Managing remote Windows boxes is trivial, since you can simply remote desktop in and transfer files over the network. Is there an equivalent to this in the Linux world?
Are you doing your config file changes/script tweaks directly on the machine? Or do you have something set up on your local box to edit these files remotely? Or are you simply editing them remotely then transferring them at each save?
How are you moving files back and forth between the server and your local environment? FTP? Some sort of Mapped Drive via VPN?
I'd really need to get some best practices in place for administering these boxes. Any suggestions to remove some of the pain would be most welcome! | 2009/06/19 | [
"https://serverfault.com/questions/28787",
"https://serverfault.com",
"https://serverfault.com/users/6681/"
] | If you're looking for a nice GUI to work with file management via SSH from Windows boxes, have a look at WinSCP: <http://winscp.net>
I don't administer any EC2 instances, but in general if I have more than a single machine performing a role I'll try and write a script to perform work on all the like boxes, in lieu of making changes box-for-box.
I'd like to get started using Puppet (<http://reductivelabs.com/products/puppet/>), because it makes system administration more of a configuration management exercise. I haven't had the spare cycles to have a look at it in detail yet, but I've heard very good things. | SSH has always been enough for me. There are other options X11 is essentially remote desktop though it's inherently insecure as it alone is not encrypted. However it can be tunneled through an SSH connection (and you get the benefit of not having to open up additional ports). This of course assumes that you have an X environment installed on the server.
SFTP (which is ftp over SSH so once again no additional ports need to be opened) can be used to put files on the server rather than pull them a good windows sftp client can be found at <http://filezilla-project.org/> |
82,387 | I am a beginner photographer and I decided to start experimenting with light. I want to buy two cheap inexpensive flashes and I found this Yongnuo model: YN560III.
I don't have any knowledge about flashes and pairing them with another one. I just know that this is a manual flash model. Can somebody explain to me:
* Is this model suitable for Canon 750d?
* Is this flash good? Is there any better model? What is the difference between YN560III and YN560 IV?
* Do I need to purchase triggers to control remotely these flashes? If so, what triggers should I buy?
Thank you for everything! | 2016/08/31 | [
"https://photo.stackexchange.com/questions/82387",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/56273/"
] | * Yes, this flash and the IV are fine for the 750D
* That depends on your definition of good. The YNs are excellent flashes *for the money*. I have 3 of them, a III and two IVs, and the III has failed (it is stuck on full power, a common problem). But they are dirt cheap, pretty well made, and have all the features you need to get in to flash. You just get what you pay for, namely, patchy quality control and pretty much no customer service. Buy through someone with a good returns policy.
* The only difference between the III and IV is that you can use the IV on-camera as a master to trigger other, off-camera flashes.
* Yes, you need either the RF603 II C (for Canon, not N for Nikon) which is a simple radio trigger, or the 560TX, which is a unit that allows you to remote control the settings for off-camera flashes, as well as trigger them. | >
> Is this model suitable for Canon 750d?
>
>
>
Depends on your definition of suitable. It will work on a 750D and won't hurt the camera.
>
> Is this flash good?
>
>
>
It does what it's designed to do, and is decent value for the money if you're a hobbyist and planning on occasional usage; for a pro doing hard daily usage, maybe not so much. The main headline features are that it has a radio receiver built in that lets you control the power and zoom of the flash remotely if you trigger it with a YN-560-TX or YN-560IV on camera.
>
> Is there any better model?
>
>
>
There are ***many*** models that have better feature sets and reliability but they'll be more expensive. At the same price, personally, I'd say the Godox TT600 is probably a better value at the moment, but that could change any day because gear at this level turns over fast—new models appear all the time. The cheap Chinese side of lights is a continually shifting landscape.
The Godox TT600 is also a manual-only speedlight with a built-in radio receiver, only the Godox X transmitters can remotely control the power setting and give HSS capability. But more importantly, the Godox triggers can do TTL (automatic power setting based on metering) and HSS (high-speed sync—the ability to use a shutter speed faster than 1/250s with flash), and Godox is building them into all their current flashes, both manual and TTL, speedlights, bare bulb flashes, and studio strobes. There's a lot more room for expansion than with the Yongnuo system. The X triggers also come in Canon, Nikon, Pentax, Sony, Olympus/Panasonic, and Fuji flavors, and any lights with an X trigger built-in can switch between the systems. Yongnuo only comes in Canon and Nikon and Yongnuo lights don't system-switch.
>
> What is the difference between YN560III and YN560 IV?
>
>
>
The difference between the III and IV is that the IV can be used as a radio master as well as a slave. Unlike the YN-560-TX, however, it can only control three groups.
>
> Do I need to purchase triggers to control remotely these flashes? If so, what triggers should I buy?
>
>
>
Yes, you need an RF master unit on the camera hotshoe to fire these flashes off camera. And the only triggers you can buy that work with the built-in receivers in the 560s are the RF-603/603II/605 and the YN-560-TX. And those triggers do not work with Yongnuo's YN-622 or RT triggers. So if you decide later that the limits of a manual-only flash are bugging you and you want to upgrade, you'll have to rebuy everything. Which is why I think a Godox TT600/X transmitter combo is better value.
BUT. I'd also say that for a first or only flash, get one that has TTL/HSS capability, not a YN-560; and if you care about warranty service, future compatibility, and resale value, an OEM unit (e.g., 430EX III-RT). Because a YN-560 is a manual-only flash, it has a *lot* of limitations upon use, both on- and off-camera. To me, manual-only cheapies are great as 2nd, 3rd, and 4th flashes for studio-style off-camera setups. But for on-camera bouncing with run'n'gun event shooting, TTL makes life a lot easier, and having HSS capability can be nice [for thin DOF in bright sunlight](https://photo.stackexchange.com/questions/82319).
See also:
* [What are the Yongnuo flash naming conventions?](https://photo.stackexchange.com/questions/47702/what-are-the-yongnuo-flash-naming-conventions)
* [What features should one look for when selecting a flash?](https://photo.stackexchange.com/questions/17722/what-features-should-one-look-for-when-selecting-a-flash)
* [What does an expensive flash unit buy over a cheap one?](https://photo.stackexchange.com/questions/33842/what-does-an-expensive-flash-unit-buy-over-a-cheap-one)
* [Flash Havoc's overview of the Godox X system](http://flashhavoc.com/godox-flash-system-overview/)
* [Flash Havoc's gear guides](http://flashhavoc.com/gear-guides/) |
2,461,616 | I have added paypal pro (uk) express to my Magento shopping cart. The paypal button now appears below the checkout button in the shopping cart.
The problem is when I click the paypal button I get a 404 error.
Any ideas? | 2010/03/17 | [
"https://Stackoverflow.com/questions/2461616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239768/"
] | Yes you can, use Reachability APIs in SystemConfiguration.framework. See [here](http://developer.apple.com/mac/library/DOCUMENTATION/Networking/Conceptual/SystemConfigFrameworks/SC_ReachConnect/SC_ReachConnect.html). A sample code (for iphone) is available [here](http://developer.apple.com/iphone/library/samplecode/Reachability/). The parts concerning the reachability APIs should be usable for OS X, too.
To use the APIs, you need to understand an OS X specific concept of "run loops." See [here](http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html). | I found a way of getting network change event using growl framework.
Added code on top of it to receive network change event.
Growl framework can be found at <http://growl.info/documentation/developer/> |
63,263,946 | An array of costs was given. You can either take two jumps forward or one jump backward. If you land on a particular index, you have to add the cost to your total. Find the minimum cost needed to cross the array or reach the end of the array.
**Input:**
```
5 (Number of elements in the array)
[9,4,6,8,5] (Array)
1 (Index to start)
```
**Output:**
```
12
```
Explanation: We start from index 1, jump to 3 and then jump out for a total cost of 8+4=12.
How can we build the DP solution for this? | 2020/08/05 | [
"https://Stackoverflow.com/questions/63263946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11703262/"
] | ```
function solve(A_i) {
A_i.sort((a,b) => a-b);
let totalcost = A_i[0];
for(let i=2; i<A_i.length;i++) {
if(i + 1 == A_i.length -1) {
totalcost = totalcost + A_i[i];
break;
}
const preSum = A_i[i] + A_i[i+2];
const postSum = A_i[i] + A_i[i-1] + A_i[i+1];
if(preSum <= postSum) {
totalcost = totalcost + A_i[i];
i++;
} else {
totalcost = totalcost + A_i[i];
i = i-2;
console.log(i)
}
}
return totalcost;
}
``` | **JAVA Solution: The solution takes O(n2)**
```
int minCost[] = new int[N];
Arrays.fill(minCost,Integer.MAX_VALUE);
for(int i=0;i<A.length;i++){
for(int j=0;j<A.length;j++){
if(j == 0){
minCost[j] = 0;
continue;
}
if(j-2>=0 && minCost[j-2]!=Integer.MAX_VALUE){
minCost[j] = Math.min(minCost[j-2]+A[j-2],minCost[j]);
}
if(j+1<A.length && minCost[j+1]!=Integer.MAX_VALUE){
minCost[j] = Math.min(minCost[j+1]+A[j+1],minCost[j]);
}
}
}
if(minCost[A.length-2]!= Integer.MAX_VALUE && minCost[A.length-1]!= Integer.MAX_VALUE){
return Math.min(A[A.length-2]+minCost[A.length-2],minCost[A.length-1]+A[A.length-1]);
}
if(minCost[A.length-2]!= Integer.MAX_VALUE){
return minCost[A.length-1]+A[A.length-1];
}
if(minCost[A.length-1]!= Integer.MAX_VALUE){
return A[A.length-2]+minCost[A.length-2];
}
return -1;
``` |
6,909,306 | I'm still relatively new to Java, so please bear with me.
My issue is that my Java application depends on two libraries. Let's call them Library 1 and Library 2. Both of these libraries share a mutual dependency on Library 3. However:
* Library 1 requires exactly version 1 of Library 3.
* Library 2 requires exactly version 2 of Library 3.
This is exactly the definition of [JAR hell](http://en.wikipedia.org/wiki/Java_Classloader#JAR_hell) (or at least one its variations).
As stated in the link, I can't load both versions of the third library in the same classloader. Thus, I've been trying to figure out if I could create a new classloader within the application to solve this problem. I've been looking into [URLClassLoader](http://download.oracle.com/javase/6/docs/api/java/net/URLClassLoader.html), but I've not been able to figure it out.
Here's an example application structure that demonstrates the problem. The Main class (Main.java) of the application tries to instantiate both Library1 and Library2 and run some method defined in those libraries:
**Main.java (original version, before any attempt at a solution):**
```
public class Main {
public static void main(String[] args) {
Library1 lib1 = new Library1();
lib1.foo();
Library2 lib2 = new Library2();
lib2.bar();
}
}
```
Library1 and Library2 both share a mutual dependency on Library3, but Library1 requires exactly version 1, and Library2 requires exactly version 2. In the example, both of these libraries just print the version of Library3 that they see:
**Library1.java:**
```
public class Library1 {
public void foo() {
Library3 lib3 = new Library3();
lib3.printVersion(); // Should print "This is version 1."
}
}
```
**Library2.java:**
```
public class Library2 {
public void foo() {
Library3 lib3 = new Library3();
lib3.printVersion(); // Should print "This is version 2." if the correct version of Library3 is loaded.
}
}
```
And then, of course, there are multiple versions of Library3. All they do is print their version numbers:
**Version 1 of Library3 (required by Library1):**
```
public class Library3 {
public void printVersion() {
System.out.println("This is version 1.");
}
}
```
**Version 2 of Library3 (required by Library2):**
```
public class Library3 {
public void printVersion() {
System.out.println("This is version 2.");
}
}
```
When I launch the application, the classpath contains Library1 (lib1.jar), Library2 (lib2.jar), and version 1 of Library 3 (lib3-v1/lib3.jar). This works out fine for Library1, but it won't work for Library2.
What I somehow need to do is replace the version of Library3 that appears on the classpath before instantiating Library2. I was under the impression that [URLClassLoader](http://download.oracle.com/javase/6/docs/api/java/net/URLClassLoader.html) could be used for this, so here is what I tried:
**Main.java (new version, including my attempt at a solution):**
```
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args)
throws MalformedURLException, ClassNotFoundException,
IllegalAccessException, InstantiationException,
FileNotFoundException
{
Library1 lib1 = new Library1();
lib1.foo(); // This causes "This is version 1." to print.
// Original code:
// Library2 lib2 = new Library2();
// lib2.bar();
// However, we need to replace Library 3 version 1, which is
// on the classpath, with Library 3 version 2 before attempting
// to instantiate Library2.
// Create a new classloader that has the version 2 jar
// of Library 3 in its list of jars.
URL lib2_url = new URL("file:lib2/lib2.jar"); verifyValidPath(lib2_url);
URL lib3_v2_url = new URL("file:lib3-v2/lib3.jar"); verifyValidPath(lib3_v2_url);
URL[] urls = new URL[] {lib2_url, lib3_v2_url};
URLClassLoader c = new URLClassLoader(urls);
// Try to instantiate Library2 with the new classloader
Class<?> cls = Class.forName("Library2", true, c);
Library2 lib2 = (Library2) cls.newInstance();
// If it worked, this should print "This is version 2."
// However, it still prints that it's version 1. Why?
lib2.bar();
}
public static void verifyValidPath(URL url) throws FileNotFoundException {
File filePath = new File(url.getFile());
if (!filePath.exists()) {
throw new FileNotFoundException(filePath.getPath());
}
}
}
```
When I run this, `lib1.foo()` causes "This is version 1." to be printed. Since that's the version of Library3 that's on the classpath when the application starts, this is expected.
However, I was expecting `lib2.bar()` to print "This is version 2.", reflecting that the new version of Library3 got loaded, but it still prints "This is version 1."
Why is it that using the new classloader with the right jar version loaded still results in the old jar version being used? Am I doing something wrong? Or am I not understanding the concept behind classloaders? How can I switch jar versions of Library3 correctly at runtime?
I would appreciate any help on this problem. | 2011/08/02 | [
"https://Stackoverflow.com/questions/6909306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393005/"
] | I can't believe that for more than 4 years no one has answered this question correctly.
<https://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html>
>
> The ClassLoader class uses a delegation model to search for classes
> and resources. Each instance of ClassLoader has an associated parent
> class loader. When requested to find a class or resource, a
> ClassLoader instance will delegate the search for the class or
> resource to its parent class loader before attempting to find the
> class or resource itself. The virtual machine's built-in class loader,
> called the "bootstrap class loader", does not itself have a parent but
> may serve as the parent of a ClassLoader instance.
>
>
>
Sergei, the problem with your example was that Library 1,2 & 3 were on the default class path, so the Application classloader which was the parent of your URLClassloder was able to load the classes from Library 1,2 & 3.
If youremove the libraries from the classpath, the Application classloader won't be able to resolve classes from them so it will delegate resolvation to its child - the URLClassLoader. So that is what you need to do. | Trying to get rid of `classpath lib2` and invoke the `bar()` method by reflection:
```
try {
cls.getMethod("bar").invoke(cls.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
```
gives following output:
```
Exception in thread "main" java.lang.ClassNotFoundException: Library2
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 java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at Main.main(Main.java:36)
```
This means you're in fact loading `Library2` from `classpath` using default classloader, not your custom `URLClassLoader`. |
10,745,661 | I'm curious if I'll have to roll my own or if there's a pre-made PHP SQL library that I'm overlooking whereby I can pass in a sql select query and have it give me back a JSON object (or String) as a result.
In pseudo code what I want is this:
```
$startIndex = 0;
$myJSON = magicSqlToJSON("select first_name, last_name, phone, (select count(id) from users) as total from users limit $startIndex, 2");
```
$myJSON is now:
```
{"users":[
{"first_name":"Peter", "last_name":"O'Tool","phone":"1234567890","total":"100"},
{"first_name":"Gary", "last_name":"Shandling","phone":"1234567890","total":"100"}
]}
```
I know it wouldn't take very long to write this myself, but I kind of figured that this is just too common a need that it wouldn't already exist. | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59947/"
] | PHP
---
PHP has the `json_encode()` and `json_decode()` functions for this purpose, but you would need to manually loop over your data with a `foreach` or similar.
MySQL
-----
You can make use of a User Defined Function such as [lib\_mysqludf\_json](http://www.mysqludf.org/lib_mysqludf_json/index.php), which would allow you return a JSON array from a query like so:
```
select json_array(
customer_id
, first_name
, last_name
, last_update
) as customer
from customer
where customer_id =1;
```
Yields this result:
```
+------------------------------------------+
| customer |
+------------------------------------------+
| [1,"MARY","SMITH","2006-02-15 04:57:20"] |
+------------------------------------------+
```
There is also a `json_object` function in that UDF, which should give you a very close representation of the sample in your question. | Ill assume you use PDO
```
echo json_encode($pdo->exec($sql)->fetchAll());
```
otherwise, the general pattern is
```
$handle = execute_query($sql);
$rows = array();
while ($row = get_row_assoc($handle)) {
$rows[] = $row;
}
echo json_encode($rows);
``` |
22,083,090 | I am building a Django application that exposes a REST API by which users can query my application's models. I'm following the instructions [**here**](http://www.django-rest-framework.org/tutorial/quickstart#testing-our-api).
My Route looks like this in myApp's url.py:
```
from rest_framework import routers
router = routers.DefaultRouter() router.register(r'myObjects/(?P<id>\d+)/?$', views.MyObjectsViewSet)
url(r'^api/', include(router.urls)),
```
My Model looks like this:
```
class MyObject(models.Model):
name = models.TextField()
```
My Serializer looks like this:
```
class MyObjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MyObject
fields = ('id', 'name',)
```
My Viewset looks like this:
```
class MyObjectsViewSet(viewsets.ViewSet):
def retrieve(self,request,pk=None):
queryset = MyObjects.objects.get(pk=pk).customMyObjectList()
if not queryset:
return Response(status=status.HTTP_400_BAD_REQUEST)
else:
serializer = MyObjectSerializer(queryset)
return Response(serializer.data,status=status.HTTP_200_OK)
```
When I hit /api/myObjects/60/ I get the following error:
>
> `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.model` or `.queryset` attribute.
>
>
>
I understand from [**here**](http://www.django-rest-framework.org/api-guide/routers) that I need a base\_name parameter on my route. But from the docs, it is unclear to me what that value of that base\_name parameter should be. Can someone please tell me what the route should look like with the base\_name? | 2014/02/27 | [
"https://Stackoverflow.com/questions/22083090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1742777/"
] | Try doing this in your urls.py. The third parameter 'Person' can be anything you want.
```
router.register(r'person/food', views.PersonViewSet, 'Person')
``` | An alternative solution might be to use a [ModelViewSet](http://www.django-rest-framework.org/api-guide/viewsets#modelviewset) which will derive the basename automatically from the model.
Just make sure and tell it which model to use:
>
> Because ModelViewSet extends GenericAPIView, you'll normally need to
> provide at least the queryset and serializer\_class attributes, or the
> model attribute shortcut.
>
>
> |
71,055,853 | I have been wondering how to extract string in R using stringr or another package between the exact word "to the" (which is always lowercase) and the very second comma in a sentence.
For instance:
String: "This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want"
Desired output: "THIS IS WHAT I WANT, DO YOU SEE IT?"
I have this vector:
```
x<-c("This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want",
"HYU_IO TO TO to the I WANT, THIS, this i dont, want", "uiui uiu to the xxxx,,this is not, what I want")
```
and I am trying to use this code
```
str_extract(string = x, pattern = "(?<=to the ).*(?=\\,)")
```
but I cant seem to get it to work to properly give me this:
```
"THIS IS WHAT I WANT, DO YOU SEE IT?"
"I WANT, THIS"
"xxxx,"
```
Thank you guys so much for your time and help | 2022/02/09 | [
"https://Stackoverflow.com/questions/71055853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15587184/"
] | You were close!
```
str_extract(string = x, pattern = "(?<=to the )[^,]*,[^,]*")
# [1] "THIS IS WHAT I WANT, DO YOU SEE IT?"
# [2] "I WANT, THIS"
# [3] "xxxx,"
```
The look-behind stays the same, `[^,]*` matches anything but a comma, then `,` matches exactly one comma, then `[^,]*` again for anything but a comma. | Alternative approach, by far not comparable with Gregor Thomas approach, but somehow an alternative:
1. vector to tibble
2. separate twice by first `to the` then by `,`
3. paste together
4. pull for vector output.
```
library(tidyverse)
as_tibble(x) %>%
separate(value, c("a", "b"), sep = 'to the ') %>%
separate(b, c("a", "c"), sep =",") %>%
mutate(x = paste0(a, ",", c), .keep="unused") %>%
pull(x)
```
```
[1] "THIS IS WHAT I WANT, DO YOU SEE IT?"
[2] "I WANT, THIS"
[3] "xxxx,"
``` |
20,553,725 | As I know, if we want to prevent robots accessing our web sites we have to parse 'User-Agent' header in http request then check whether the request coming from robots or browsers.
I think we can not completely prevent robot accessing our web sites because someone can program to use any http client to send Http request with FAKE browser user-agent so for this case, we can not know fake user-agent is real user-agent coming from a browser or coming from a robot program (by programmed).
My question is there is any way to prevent completely robot accessing our web sites? | 2013/12/12 | [
"https://Stackoverflow.com/questions/20553725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3018377/"
] | You cannot eliminate the bots, but you can greatly reduce them.
Obvious option you're already using is user-agent detection
You could also load your page content through ajax using JavaScript which would eliminate any bot that cannot process javascript. So just have an empty div with the id="content" and on page ready do an ajax call to insert the content. This means if anyone uses curl or similar to scrape your page content it wouldn't work. IF the bot is built for your site specifically it's easy to work around but most random bots wouldn't get through it probably.
You could also obfuscate the target url in JS... and/or make it automatic by using location.href to tell ajax to look for a content file by the same name in a different folder.
You could of course to a captcha before a user (or bot) could enter the site, but that's annoying to users.
IF it's less about accessing the page and has to do with form submission then captcha is a great choice or you could do a honey-pot where you put in a form field that is hidden by css and the robot will fill out that field but the human won't (because it's hidden) and you can detect that. | I think that autentication with captcha is the easier way and the most used. Other options would be to ask simply questions to the user (simply to humans but not to bots). However all these methods are annoying for human users. |
20,963,162 | I need to ask a problem on the operator "choice when" in Apache Camel route. In the following example, if I have two soap-env:Order elements which have 1, 2 value, then I want to create two xml file named output\_1.xml and output\_2.xml. However, the code can only create one file output\_1.xml.
Can anyone give me any ideas or hints? Thanks for any help.
```
public void configure() {
...
from("direct:a")
.choice()
.when(ns.xpath("//soap-env:Envelope//soap-env:Order='1'"))
.to("file://data?fileName=output_1.xml")
.when(ns.xpath("//soap-env:Envelope//soap-env:Order='2'"))
.to("file://data?fileName=output_2.xml")
.when(ns.xpath("//soap-env:Envelope//soap-env:Order='3'"))
.to("file://data?fileName=output_3.xml")
}
``` | 2014/01/07 | [
"https://Stackoverflow.com/questions/20963162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1241673/"
] | There is nothing wrong with the DSL and you dontt need end blocks here. I would look at your data and trace through why all calls are ending up in the same when block. Put a couple of log lines in or enable the tracer and look at the exchanges going through. | In Camel root choice() if you have multiple when() cases you have to write otherwise(). Please refer below.
```
from("direct:a")
.choice()
.when(header("foo").isEqualTo("bar"))
.to("direct:b")
.when(header("foo").isEqualTo("cheese"))
.to("direct:c")
.otherwise()
.to("direct:d")
.end;
```
The above mentioned solution will check all three conditions even if first one pass. |
21,889,835 | Im trying to get the to populate with companyName from an array. I am not seeing any changes.
Javascript:
```
var webName = {
coinstar: {
companyName: "Coinstar",
projectName: "Online App",
role: "Web Developer",
detailText: "This is some text"
},
google: {
companyName: "Google",
projectName: "AdWord Security",
role: "Web Developer",
detailText: "This is some text"
},
amazon: {
companyName: "Amazon",
projectName: "Internal Site",
role: "Web Developer",
detailText: "This is some text"
}
}
// The is supposed to grab the company name from the above list.
var search = function(coName){
for(var prop in coName){
if(webName[prop].companyName === coName){
document.getElementById("companyName").innerHTML = companyName;
}
}
}
var detailTitle = function(){
search("coinstar");
```
HTML:
// Click this div to populate
```
// After div is pressed this heading should say "Coinstar".
<h1 id="companyName">Company name here</h1>
``` | 2014/02/19 | [
"https://Stackoverflow.com/questions/21889835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3328590/"
] | For now, I'll ignore the fact that `id="companyName>` is missing an ending quote.
In the function:
```
var search = function(coName) {
for(var prop in coName) {
```
`coName` is the string `coinstar`:
```
search("coinstar");
```
You're attempting to iterate through each property in a `string`, which is probably not what you want.
Perhaps you meant to iterate through your collection of companies:
```
var search = function(coName) {
for(var prop in webName) {
```
With that said, there's not really a reason to iterate through the collection to find your company name, when you already key the collection by company name. `webName[coName]` should get you what you want without the `for` loop. | try this.
```
var search = function(coName){
for(var prop in webName){
if(webName[prop].companyName === coName){
document.getElementById("companyName").innerHTML = webName[prop].companyName;
}
}
}
``` |
102,331 | I applied for an entry level software engineer position, and before even getting an interview with a company, they asked me to complete what I'd consider to be a rather significant coding project. I am given two days to build an application stack using SQL database, node.js, REST APIs, front end UI with react.js. I'm certain it's doable in time frame, but to me it seems like this is overkill. No other interviews I've had included a coding challenge of this size. Is this a common practice before even talking with someone at the company? | 2017/11/09 | [
"https://workplace.stackexchange.com/questions/102331",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/79396/"
] | They might be trying to get you to do some work for free, without having any intention of calling you in for an interview. Or they may have so many talented applicants that they only want the very best.
I'd be a little bit cautious in this instance because of the minimal contact that you've had with them. I would typically expect this to be a "step 2" kind of thing, after an interview. But ask yourself how the market for developers is in your area (is it a software hub where lots of devs come for work?).
Generally speaking I would consider a coding test for an ***entry level position*** overkill. You're new at the whole development thing, and by definition have lots to learn. So what do they expect to see in the code of a novice whom they should have the expectation of having to train?
You will now have to decide whether this is **worth your time**. This is something that many people don't seem to remember when looking for a job - you don't ***have*** to put in all that time and effort! It's entirely your choice whether you want to sacrifice those 2 days for a shot at an interview. After all, no one is paying you for that effort! This could very well be interpreted as a lack of respect for your time.
If you're getting other interviews, you may wish to tell them ***"thanks but no thanks"***, and focus on other opportunities. Or you could contact them and request more information about the company and their policies before you engage in this exercise (I'd do this at a minimum). After all, if they're not willing to put some time in for you, why would you put two days in for them?
If, however, this looks like it might be the job of your dreams, do your best on that test.
---
The more I think about it, the more I think that this sort of request for a junior position is a total scam. Full stack app, and two days of work for an entry level position? Unless this is Google or Amazon, or it pays insanely well, it's not worth it IMO. | Let's not talk about 2 **days**, because nobody really will work 48 hours straight on it.
Let's assume you're unemployed, you got time, and you sink 4 hours per day into it. 8 hours of work.
Did they give you any specifications? If not, a smart programmer will be spending that 8 hours hammering out the specs. Not a single line of code will be written after 2 days.
If they push back and say "Well, I wanted to test your coding skills." You then reply "Planning **IS** a coding skill. A very important one at that!"
Let's also try on the interviewer's perspective.
You just got dumped a bunch of people's code they wrote over 2 days. Let's assume it is a light day. You get 20 applicants.
What the hell? How are you going to review this kind of code? Run it and see if it works? My god, it has a DB! It's a full stack application! It's not compiled! What if it opens a freaking backdoor to your corporate network? WTF? How are you gonna test it?
You don't. You just randomly pick a handful of guys and interview them.
Extremely unrealistic scenario. If this is pre-interview, they'll be getting massive amount of code. It's probably analyzed based on some sort of stats like LOC or something equally useless.
I would go for plan A and hope it is a trick question. If not, then spend some time doing it and, if you get interviewed, ask them how much of your code did they read. Ask them how they secured the testing environment and not have viruses infect their network. |
34,334 | Is it possible to attain stream-entry if one is only following "the 5 precepts"?
Are there any suttas that seem to address this question? | 2019/07/29 | [
"https://buddhism.stackexchange.com/questions/34334",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/14288/"
] | "entering the stream" means you understood the main point of Buddhism and started applying that point to your entire life.
Which point? -- That you should stop creating causes for future dukkha.
Which causes create dukkha? -- Whatever leads to increase of conflict, increase of side-taking, increase of attachment, increase of obsession, increase of aversion, increase of ignorance - leads to increase of dukkha. Whatever leads to maintenance of conflict, maintenance of side-taking, maintenance of attachment, maintenance of obsession, maintenance of aversion, maintenance of ignorance - leads to maintenance of dukkha. Whatever leads to cessation of conflict, cessation of side-taking, cessation of attachment, cessation of obsession, cessation of aversion, cessation of ignorance - leads to cessation of dukkha.
The nature of dukkha is conflict, clash, mismatch - so if you are setting in motion forces that will set up conditions for arising of conflict, clash, mismatch - then that's what you will get. Once you get that - there's suffering. Correspondingly, when you are laying down causes in the here and now that are by nature conducive to harmony - then that's what you'll get. It is that simple. We create Dukkha by ourselves, so once we stop creating Dukkha we may still get some Dukkha created in the past, but eventually all the past causes will run out and the new causes will come to effect, and so gradually we will attain the natural harmonious state - Nirvana.
Once you really "get" this, once you see it clearly, then you stop acting like that, because you know it's for your own benefit. It's not just blindly following the five precepts. It's about getting the principle. Sometimes you may still make mistakes and create trouble - but as long as you got the principle in the overall - you will keep making progress.
This is when we say you are "in the stream" leading to Nirvana. | **Would experiential faith in the Buddha, the Teaching, the Sangha and following the 5 precepts be enough for stream-entry?**
I'd like to say "yes" -- and that "experiential faith" is already *a lot* and must be enough to begin to work with.
What troubles me, about that answer, is that maybe there is something else important -- i.e. meeting or knowing an arya person.
Is it also necessary to to meet or know, interact with, to learn from, to try to help, an arya person? Or is that hard to say?
In the Buddha's day you probably wouldn't hear the dhamma except in person; so the case wouldn't arise (can you even *have* "experiential faith in the sangha", without *meeting* "the sangha"?); but now ...
[This answer](https://buddhism.stackexchange.com/a/34326/254) mentions ...
>
> In fact, cleaning the thoughts is really the first time somebody does an activity with good karma, unless there is dana to some arya because this is easier (when aryas are here).
>
>
>
... which I can't deny from experience, and might be canonical.
And granted that, I wonder if that's universally/always *another* requirement.
A reason I'm not happy with *that* as an answer ("you need to meet an arya") is that it might lead the question, "how should I meet an arya?", and so on, and heading off to search for one instead of maybe accepting your own knowledge of the dhamma.
I mean it might be a reasonable desire, but it might be a craving and eventually a not-good kind of some guru-worship.
Maybe it's a good thing to think about, though -- people you know who are ethical, people you have known and learned from, or could know. |
7,587,442 | my development style brings me to write a lot of **throw-away "assisting" code**,
whether for automatic generation of code parts, semi-automated testing, and generally to build dummies, prototypes or temporary "sparring partners" for the main development; **I know I'm not the only one...**
since I frequently work both under windows and Unicies, I'd like to non-exclusively focus on a **single "swiss army knife"** tool that can work in both the environments with limited differences, that would allow me to do usual stuff like **text parsing, db access, sockets, nontrivial filesystem and process manipulation**
until now under unix I've used a bit of perl and massive amounts of shell scripts, but the latter are a bit limited and perl... despite being very capable and having modules for an incredible array of duties, sincerely I find it too "hostile" *for me* for something that goes beyond 100 lines of code.
***what would you suggest?***
scripting is not a requirement, it would be ok to use more static-styled languages IF it makes development faster (getting programs to actually do their work and possibly in a **human readable state**) and **if it doesn't become nightmarish to handle errors/exception and to adapt to dynamic environments** (e.g. I don't like to hardwire data /db table structure in my code, especially by hand).
I've been intrigued by **python, ruby, but maybe groovy** (with its ability to access the huge class library and his compact syntax) or something else is better suited
thanks a lot in advance!
(meanwhile, on a completely different note, **scala** looks really tempting just for the cleanliness of it, but that's - probably - a completely different story, unless you tell me the opposite...?) | 2011/09/28 | [
"https://Stackoverflow.com/questions/7587442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/120747/"
] | The problem is that you're displaying `time()`, which is a UNIX timestamp based on GMT/UTC. That’s why it doesn’t change. `date()` on the other hand, *formats* the time based on that timestamp.
A *timestamp* is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
```php
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
``` | In PHP DateTime (PHP >= 5.3)
```
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->getTimestamp();
``` |
13,248,094 | I am developing an app where I am using customized listview. First i will go with code and i will ask my question(at bottom).
Main.java (using adapter class to set data to listview)
```
Myadapter adapter = new Myadapter();
listview.setAdapter(adapter);
```
}
custom.xml
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:background="#adadad"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
```
Myadapter class:
```
public class Myadapter extends BaseAdapter{
public int getCount() {
// TODO Auto-generated method stub
return startarr.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
int i;
LayoutInflater layoutinflater = getLayoutInflater();
v = layoutinflater.inflate(R.layout.custom,null);
TextView aptdate = (TextView)v.findViewById(R.id.textView1);
TextView apttime = (TextView)v.findViewById(R.id.textView2);
TextView aptname = (TextView)v.findViewById(R.id.textView3);
TextView aptid = (TextView)v.findViewById(R.id.textView4);
//Button btn = (Button)v.findViewById(R.id.button1);
final String arlstdate[] = startarr.get(position).split("~");
for (i = 0; i < arlstdate.length; i++) {
aptdate.setText(arlstdate[i]);
try {
// Getting Array of Contacts
JSONObject json = new JSONObject(response);
contacts = json.getJSONArray("schedule");
// looping through All Contacts
for(int j = 0; j < contacts.length(); j++){
JSONObject c = contacts.getJSONObject(j);
// Storing each json item in variable
final String id = c.getString("scheduleId");
String startTime = c.getString("startDateTime");
String endTime = c.getString("endDateTime");
String type = c.getString("scheduleType");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startedTime = sdf.parse(startTime);
Date endedTime = sdf.parse(endTime);
int getstartdate = startedTime.getDate();
int getstartmonth = startedTime.getMonth();
int getstartyear = startedTime.getYear();
int getday = startedTime.getDay();
final int getstartingtime = startedTime.getHours();
final int getstartingmin = startedTime.getMinutes();
long diff = endedTime.getTime() - startedTime.getTime();
int hours = (int)(diff/(60*60*1000));
testselectID = String.valueOf(hours);
hoursarray.add(testselectID);
starttimearray.add(String.valueOf(getstartingtime+":"+getstartingmin));
calendar = Calendar.getInstance();
calendar.setTime(startedTime);
System.out.println((calendar.get(Calendar.YEAR))+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+(calendar.get(Calendar.DAY_OF_MONTH)));
if(arlstdate[i].equals((calendar.get(Calendar.YEAR))+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+(calendar.get(Calendar.DAY_OF_MONTH))))
{
aptid.append(id+"\n");
apttime.append(testselectID+"Hrs"+"\n");
aptname.append((String.valueOf(getstartingtime+":"+getstartingmin))+"\n");
}
}
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(), "schedule error is " + e, Toast.LENGTH_SHORT).show();
}
}
return v;
}
}
```
Here I am appending the data to textviews and output of the following code is ...
\
Upto here everything works good. But what my question is.....
When i click on custom list view the values need to display in seperate toast message. As i have some idea regarding list view click listener, but here if using that code it is taking last appeneded data details. for example if i click on first one (in image) it is displaying 16:40.not displyaing 12:0. what i want is I need to display two of them differently with different toast message.
Can anyone help me with this.... | 2012/11/06 | [
"https://Stackoverflow.com/questions/13248094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You make your live very hard yourself in NOT implementing a proper Model. You should parse your Json outside the Adapter and make Java-classes out of these informations. Then pass a List or an Array as data to your Adapter, while returning Model-objects in `getItem(position)`!
This way you flawlessly can implement an `OnItemClickListener` and gather whatever data you want.
You also just completely ignore the `convertView` Parameter. You should take this View instead of inflating a new one if it is NOT null for performance optimization! | ```
for that you have to implement the OnItemClickListener event on listview .
listview.OnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
}
});
Now you have position of your listview then Whatever the list position that corresponding value is diplays in toast.
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.