text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Angular inject service after loading
I have written a generic controller.
For context only, it's not part of the question: I extend the controller by way of setting call back functions during initialization, which the controller then calls upon specific events occurring. As such, when I wrote the controller (because it is generic), I don't know what services I might require.
So, how can I, after instantiating the controller in the view (using ngController), then inject a service. Obviously I will have a variable called myApp, and the result of myApp.controller(...).
Once injected, I then have a reference to scope when my callback functions get called. I could also add arguments to pass along something else if necessary. How access the service?
Thank you
Sample code:
// Html:
ng-init="controller.init('myExtension')"
// then in the generic/abstract controller:
this.init=function(extensionName){
window["extend_"+tag]($scope, this);
}
.... later on .....
this.callBackFunction($scope)
// and finally (in a separate js file that is project specific):
function extend_myExtension(scope, controller){
controller.callBackFunction=function(scope){
// this is where I would like to use the service
}
}
// this is where I would like to inject a service that
// I didn't know about when I wrote the generic/abstract controller
A:
When Angular bootstraps, this is done in two phases:
The config phase: all services/controllers etc are registered, config blocks are called and the injector is initialized. You can only inject providers and constants in the config blocks because the services that will be returned by the providers are not
The run phase: all run blocks are executed and controllers/directives etc are executing (starting from ng-app). So there may be services injected as well.
What you want is impossible. The only thing you can do is to configure a provider in a config block. The configuration determines how the service will look like when it is injected in the run phase. See https://docs.angularjs.org/guide/providers
Could you elaborate on what problem you are actually want to solve? Having a generic controller that has no idea what to have injected sounds like a bad pattern. It isn't even 'unit testable'.
| {
"pile_set_name": "StackExchange"
} |
Q:
CUDA/Thrust: How to sum the columns of an interleaved array?
Using Thrust it's straighforward to sum the rows of an interleaved (i.e. backed by a vector) array, as shown in the example here.
What I would like to do instead is sum the columns of the array.
I tried using a similar construction, i.e.:
// convert a linear index to a column index
template <typename T>
struct linear_index_to_col_index : public thrust::unary_function<T,T>
{
T C; // number of columns
__host__ __device__
linear_index_to_col_index(T C) : C(C) {}
__host__ __device__
T operator()(T i)
{
return i % C;
}
};
// allocate storage for column sums and indices
thrust::device_vector<int> col_sums(C);
thrust::device_vector<int> col_indices(C);
// compute row sums by summing values with equal row indices
thrust::reduce_by_key
(thrust::make_transform_iterator(thrust::counting_iterator<int>(0), linear_index_to_col_index<int>(C)),
thrust::make_transform_iterator(thrust::counting_iterator<int>(0), linear_index_to_col_index<int>(C)) + (R*C),
array.begin(),
col_indices.begin(),
col_sums.begin(),
thrust::equal_to<int>(),
thrust::plus<int>());
However this results in only summing the first column, the rest are ignored.
My guess for why this happens is that, as noted in the reduce_by_key docs:
For each group of consecutive keys in the range [keys_first, keys_last) that are equal, reduce_by_key copies the first element of the group to the keys_output. [Emphasis mine]
If my understanding is correct, because the keys in the row iterator are consecutive (i.e. indexes [0 - (C-1)] will give 0, then [C - (2C-1)] will give 1 and so on), they end up being summed together.
But the column iterator will map indexes [0 - (C-1)] to [0 - (C-1)] and then start again, indexes [C - (2C-1)] will be mapped to [0 - (C-1)] etc. making the values produced non-consecutive.
This behavior is un-intuitve for me, I expected all data points assigned to the same key to be grouped together, but that's another discussion.
In any case, my question is: how would one sum the columns of an interleaved array using Thrust?
A:
These operations (summing rows, summing columns, etc.) are generally memory-bandwidth bound on the GPU. Therefore, we may want to consider how to construct an algorithm that will make optimal use of the GPU memory bandwidth. In particular we would like our underlying memory accesses generated from thrust code to be coalesced, if possible. In a nutshell, this means that adjacent GPU threads will read from adjacent locations in memory.
The original row-summing example displays this property: adjacent threads spawned by thrust will read adjacent elements in memory. For example, if we have R rows, then we can see that the first R threads created by thrust will all be reading the first "row" of the matrix, during the reduce_by_key operation. Since the memory locations associated with the first row are all grouped together, we get coalesced access.
One approach to solving this problem (how to sum the columns) would be to use a similar strategy to the row-summing example, but use a permutation_iterator to cause the threads that are all part of the same key sequence to read a column of data instead of a row of data. This permutation iterator would take the underlying array and also a mapping sequence. This mapping sequence is created by a transform_iterator using a special functor applied to a counting_iterator, to convert the linear (row-major) index into a column-major index, so that the first C threads will read the elements of the first column of the matrix, instead of the first row. Since the first C threads will belong to the same key-sequence, they will get summed together in the reduce_by_key operation. This is what I call method 1 in the code below.
However, this method suffers the drawback that adjacent threads are no longer reading adjacent values in memory - we have broken coalescing, and as we shall see, the performance impact is noticeable.
For large matrices stored in row-major order in memory (the ordering we have been discussing in this problem), a fairly optimal method of summing the columns is to have each thread sum an individual column with a for-loop. This is fairly straightforward to implement in CUDA C, and we can similarly perform this operation in Thrust with an appropriately defined functor.
I'm referring to this as method 2 in the code below. This method will only launch as many threads as there are columns in the matrix. For a matrix with a sufficiently large number of columns (say 10,000 or more) this method will saturate the GPU and efficiently use the available memory bandwidth. If you inspect the functor, you will see that is a somewhat "unusual" adaptation of thrust, but perfectly legal.
Here's the code comparing both methods:
$ cat t994.cu
#include <thrust/device_vector.h>
#include <thrust/reduce.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/functional.h>
#include <thrust/sequence.h>
#include <thrust/transform.h>
#include <iostream>
#define NUMR 1000
#define NUMC 20000
#define TEST_VAL 1
#include <time.h>
#include <sys/time.h>
#define USECPSEC 1000000ULL
long long dtime_usec(unsigned long long start){
timeval tv;
gettimeofday(&tv, 0);
return ((tv.tv_sec*USECPSEC)+tv.tv_usec)-start;
}
typedef int mytype;
// from a linear (row-major) index, return column-major index
struct rm2cm_idx_functor : public thrust::unary_function<int, int>
{
int r;
int c;
rm2cm_idx_functor(int _r, int _c) : r(_r), c(_c) {};
__host__ __device__
int operator() (int idx) {
unsigned my_r = idx/c;
unsigned my_c = idx%c;
return (my_c * r) + my_r;
}
};
// convert a linear index to a column index
template <typename T>
struct linear_index_to_col_index : public thrust::unary_function<T,T>
{
T R; // number of rows
__host__ __device__
linear_index_to_col_index(T R) : R(R) {}
__host__ __device__
T operator()(T i)
{
return i / R;
}
};
struct sum_functor
{
int R;
int C;
mytype *arr;
sum_functor(int _R, int _C, mytype *_arr) : R(_R), C(_C), arr(_arr) {};
__host__ __device__
mytype operator()(int myC){
mytype sum = 0;
for (int i = 0; i < R; i++) sum += arr[i*C+myC];
return sum;
}
};
int main(){
int C = NUMC;
int R = NUMR;
thrust::device_vector<mytype> array(R*C, TEST_VAL);
// method 1: permutation iterator
// allocate storage for column sums and indices
thrust::device_vector<mytype> col_sums(C);
thrust::device_vector<int> col_indices(C);
// compute column sums by summing values with equal column indices
unsigned long long m1t = dtime_usec(0);
thrust::reduce_by_key(thrust::make_transform_iterator(thrust::counting_iterator<int>(0), linear_index_to_col_index<int>(R)),
thrust::make_transform_iterator(thrust::counting_iterator<int>(R*C), linear_index_to_col_index<int>(R)),
thrust::make_permutation_iterator(array.begin(), thrust::make_transform_iterator(thrust::make_counting_iterator<int>(0), rm2cm_idx_functor(R, C))),
col_indices.begin(),
col_sums.begin(),
thrust::equal_to<int>(),
thrust::plus<int>());
cudaDeviceSynchronize();
m1t = dtime_usec(m1t);
for (int i = 0; i < C; i++)
if (col_sums[i] != R*TEST_VAL) {std::cout << "method 1 mismatch at: " << i << " was: " << col_sums[i] << " should be: " << R*TEST_VAL << std::endl; return 1;}
std::cout << "Method1 time: " << m1t/(float)USECPSEC << "s" << std::endl;
// method 2: column-summing functor
thrust::device_vector<mytype> fcol_sums(C);
thrust::sequence(fcol_sums.begin(), fcol_sums.end()); // start with column index
unsigned long long m2t = dtime_usec(0);
thrust::transform(fcol_sums.begin(), fcol_sums.end(), fcol_sums.begin(), sum_functor(R, C, thrust::raw_pointer_cast(array.data())));
cudaDeviceSynchronize();
m2t = dtime_usec(m2t);
for (int i = 0; i < C; i++)
if (fcol_sums[i] != R*TEST_VAL) {std::cout << "method 2 mismatch at: " << i << " was: " << fcol_sums[i] << " should be: " << R*TEST_VAL << std::endl; return 1;}
std::cout << "Method2 time: " << m2t/(float)USECPSEC << "s" << std::endl;
return 0;
}
$ nvcc -O3 -o t994 t994.cu
$ ./t994
Method1 time: 0.034817s
Method2 time: 0.00082s
$
It's evident that for a sufficiently large matrix, method 2 is substantially faster than method 1.
If you're unfamiliar with permutation iterators, take a look at the thrust quick start guide.
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting Views of Rendered Mesh Faces
I'm working on a project that requires me to project a picture spherically around a dodecahegon and then get images of each of the twelve faces so I can make bitmap files of the design each face contains.
I first tried setting up twelve cameras and pretty much just taking screenshots of the views, but getting the cameras oriented in exactly the same way so there was no skewing in the pictures was nearly impossible.
As a second resort, I tried to unwrap the mesh and lay the picture that I projected to the mesh on the UV map, but since it was flat, the faces didn't contain the same design on the UV map compared to the Spherical Projection.
So, is there any way I can get precise, non-skewed views of the rendered version of each face of my mesh?
This is my first time using Blender, so if I overlooked something simple, or didn't explain something correctly, let me know and I'll try to clarify :)
Edit: Here are some pictures of what I'm trying to do. I want 12 separate pictures of the outside faces as they show in my rendered view. So far I took 3 photos of the faces, two of which you can see below
A:
I suggest using custom transform orientations and a track-to constraint to get the cameras pointed at the faces. Please see the demonstration here: https://youtu.be/1Mu6loumKj0
| {
"pile_set_name": "StackExchange"
} |
Q:
How to install Automapper for .net 3.5
I would like to use Automapper with .net 3.5.
I have found a branch on Git hub, thanks to this post by the creator Jimmy Bogard:
...but I can't figure out how to install it.
The .net 4 version is installed using nuget
Anyone know how I install the .net 3.5 version?
Do I just build it myself, and use it as my own project?
If so how do I build it? Do I need to create a NuGet package?
A:
https://github.com/downloads/AutoMapper/AutoMapper/AutoMapper.dll
This .dll is version 1.1 which according to the site is the last .net 3.5 version. Just reference it in your project and it should work.
A:
No need to build the source yourself. AutoMapper 1.1 is available on NuGet at http://nuget.org/packages/AutoMapper/1.1.0.118
PM Console command is
PM> Install-Package AutoMapper -Version 1.1.0.118
A:
Do I just build it myself, and use it as my own project?
Yes, although you don't need to include the AutoMapper project in your solution;
If so how do I build it? Do I need to create a NuGet package?
NuGet package not required.
You need to download the source for AutoMapper for .net3.5 from here
Once downloaded, you can open the sln file under the src folder and build the AutoMapper project (just that project will do)
You can then copy the dll produced (i.e., found at src\AutoMapper\bin\Debug) to your shared lib folder and reference that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Yii relation — MySQL foreign key
Tables in MySQL:
field:
id pk
field_option
id pk
feild_id int(11)
ALTER TABLE `field_option` ADD CONSTRAINT `option_field` FOREIGN KEY ( `feild_id` ) REFERENCES `agahi_fixed`.`field` (
`id`
) ON DELETE CASCADE ON UPDATE RESTRICT;
Relation Field model:
return array(
'fieldOption' => array(self::HAS_MANY, 'FieldOption', 'feild_id'),
);
Relation FieldOption model:
return array(
'feild' => array(self::BELONGS_TO, 'Field', 'feild_id'),
);
In controller:
if(Field::model()->exists('cat_id = :catId', array(":catId"=>$_POST['catid']))){
$criteria=new CDbCriteria;
//$criteria->select='*';
$criteria->condition='cat_id=:catId';
$criteria->params=array(':catId'=>$_POST['catid']);
$criteria->with = 'fieldOption';
$field=Field::model()->findAll($criteria);
header('Content-type: application /json');
$jsonRows=CJSON::encode($field);
echo $jsonRows;
}
but it does not work with just select records in field table.
Why?
A:
this way you won't achive what your looking for,
when you fetch your records using with it will fetch associated records, meaning : eager loading not lazy, but when you json encode your model, It will get attributes of your main model, not any relations, If you want any related data to get encoded with the model, you have to explicitly say so. I suggest make an empty array :
$result = array();
make a loop over your model and append to this result, from model to related model
foreach($field as $model)
{
$record = $model->attributes; // get main model attributes
foreach($model->fieldOption as $relation)
$record['fieldOption'][] = $relation->attributes; // any related records, must be explicitly declared
$result[] = $record;
}
now you have exactly what you need, then echo it
echo CJSON::encode($result);
| {
"pile_set_name": "StackExchange"
} |
Q:
Is ed25519 a "hash signature"
Writing my last question, I saw the hash-signature tag.
I tried to research it best I could, but I'm simply overwhelmed in this field. I don't think it means to simply hash data before signing, but any detail beyond that is beyond me.
Is ed25519 a hash signature with respect to the tag? If so, is it believed to be resistant to quantum computers?
A:
Ed25519 or more general the EdDSA (Edwards-curve Digital Signature Algorithm) approach can be considered as a variant of ElGamal signatures (such as Schnorr or DSA). They all are signatures following the hash-then-sign approach. This simply means that you can sign arbitrary length messages by hashing them to a constant size string using a secure cryptographic hash function and then applying the signing algorithm to the hash value. Such as other ElGamal type signature schemes like ECDSA, when implemented using elliptic curve groups, the security relies on the elliptic curve discrete logarithm problem on the respective curve group.
The hash-then-sign approach, however, must not be confused with quantum resistant hash-based signatures such as Merkle signatures, Lamport signatures or the Winternitz one-time signature scheme. Such signatures do not rely on any (number theoretic) computational hardness assumption such as factoring or discrete logarithm assumption and thus are not susceptible to quantum attacks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Smooth interpolating spline has weird extremities
I'm building a soft to reject some trajectories that turn too fast.
I managed to smooth them with scipy splrep and splev, but I have some weirdness at the beginning and the end, with some points that does not follow at all the original trajectory.
Any idea where it comes from or how to correct it ? Can I correct it with the "weight" parameter of splrep ? I avoid this problem by analysing the trajectory without the 10 firsts and lasts points of the original one, but it's a bit annoying...
Here is my code :
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
pointsx = [19.96, 19.45, 18.94, 18.43, 17.92, 17.4, 17.02, 16.51, 16.0, 15.48, 14.97, 14.46, 13.95, 13.56, 13.05, 12.54, 12.03, 11.51, 11.13, 10.62, 9.98, 9.59, 9.08, 8.57, 8.06, 7.67, 7.16, 6.78, 6.27, 5.75, 5.24, 4.86, 4.35, 3.83, 3.32, 2.81, 2.43, 1.91, 1.53, 1.02, 0.51, 0.12, -0.38, -0.76, -1.28, -1.79, -2.17, -2.56, -3.07, -3.45, -3.96, -4.35, -4.86, -5.24, -5.63, -6.01, -6.4, -6.78, -7.29, -7.55, -7.93, -8.44, -8.83, -9.21, -9.59, -9.85, -10.24]
pointsy = [-13.18, -13.05, -13.05, -13.05, -13.05, -13.05, -13.18, -13.18, -13.18, -13.05, -13.05, -13.05, -13.18, -13.18, -13.18, -13.18, -13.18, -13.31, -13.31, -13.31, -13.31, -13.31, -13.31, -13.31, -13.31, -13.31, -13.43, -13.43, -13.56, -13.56, -13.56, -13.56, -13.56, -13.56, -13.69, -13.69, -13.69, -13.82, -13.82, -13.82, -13.95, -13.95, -13.95, -14.08, -14.08, -14.2, -14.2, -14.2, -14.33, -14.46, -14.46, -14.46, -14.59, -14.72, -14.72, -14.84, -14.84, -14.97, -14.97, -15.1, -15.1, -15.23, -15.35, -15.48, -15.61, -15.74, -15.87]
degree = 5
lenx = len(pointsx)
x = np.array(pointsx)
y = np.array(pointsy)
w = range(lenx)
ipl_t = np.linspace(0.0, lenx - degree, 1000)
print y.max(), y.min(), ">", abs(y.max()) - abs(y.min())
smooth = 20
x_tup, fpx, ierx, msgx = interpolate.splrep(w, x, k=degree, full_output=1)
y_tup, fpy, iery, msgy = interpolate.splrep(w, y, k=degree, per=1,full_output=1, s=smooth, task = 0)
x_i = interpolate.splev(ipl_t, x_tup)
y_i = interpolate.splev(ipl_t, y_tup)
fg, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
ax1.plot(pointsx, pointsy, 'k.')
ax1.set_title("original")
ax2.plot(x_i, y_i, 'y.')
ax2.set_title("bsplined smooth=%.2f" % smooth)
ax3.plot(pointsx, pointsy, 'k', x_i, y_i,'y')
ax3.set_title("both")
plt .show()
And the result :
And some others results with more relevant smoothed trajectories but with still the same gap at the end and beginning: Trajectory2
A:
Your interpolation for y-values has parameter per=1. This means
data points are considered periodic ... and a smooth periodic spline approximation is returned.
Obviously your y-values are not periodic at all, so forcing the spline to be periodic makes it deviate from the data. Removing the per parameter fixes the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails 3 after_destroy observer not being called
Here is my model...
app/controllers/registrations_controller.rb
def destroy
@registration = Registration.find(params[:id])
@registration.cancelled = true
@registration.save
respond_to do |format|
format.html { redirect_to root_url, notice: 'Registration was successfully canceled.' }
format.json { head :no_content }
NsoMailer.after_cancellation_email(@registration).deliver
end
end
app/models/registration_observer.rb
class RegistrationObserver < ActiveRecord::Observer
#close registration after seats are filled
def after_create(registration)
if registration.orientation != nil
@orientation = registration.orientation
close_orientation if seats_equal_zero
end
end
#opens registration if a registration is removed
def after_destroy(registration)
if registration.orientation != nil
@orientation = registration.orientation
open_orientation if seats_equal_zero == false
end
end
...the after_create action is working fine, but after_destroy is not. This is just name based correct? Naming the action in the observer 'after_destroy' links it the the corresponding controller action 'destroy' no?
I also added puts statements in both the controller and observer actions. I am making it to the controller action OK, but not the observer.
A:
It doesn't link it to controller action destroy. It links it to the model.
In order for after_destroy to execute, you should do
@registration.destroy
You can have an after_save callback and have the same effect
def after_save(registration)
return unless registration.cancelled
if registration.orientation != nil
@orientation = registration.orientation
open_orientation if seats_equal_zero == false
end
end
You can have a look at the documentation for more information
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Camera PreviewCallBack display image in dialog
I have a class that extends Camera.PreviewCallBack
In the onPreviewFrame, I call an AsyncTask, that checks for a QR Code
@Override
public void onPreviewFrame(byte[] bytes, Camera camera) {
System.out.println("onPreviewFrame, should now decode");
Camera.Size previewSize = camera.getParameters().getPreviewSize();
new DecodeAsyncTask(previewSize.width, previewSize.height).execute(bytes);
}
If the decode is succesfull, It calls;
cameraManager.c.takePicture(shutterCallback, rawCallback,jpegCallback);
The method for takePicture is below;
public void onPictureTaken(byte[] data, Camera camera) {
LayoutInflater inflater = (LayoutInflater) cxt.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Dialog settingsDialog = new Dialog(cxt);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
settingsDialog.getLayoutInflater().inflate(R.layout.qrimageviewer, null);
settingsDialog.show();
Drawable image = new BitmapDrawable(BitmapFactory.decodeByteArray(data, 0, data.length));
imageview = (ImageView) activity.findViewById(R.id.qrimageview);
imageview.setImageDrawable(image);
try {
System.out.println("TAKING PICTURE");
Bitmap t1 = BitmapFactory.decodeByteArray(data , 0, data.length);
Bitmap bitmap = Bitmap.createBitmap(t1);//.createBitmap(t1,0, 0, 400, 100);
File myExternalFile = new File(cxt.getExternalFilesDir("/MyFileStorage/"), System.currentTimeMillis()+". jpg");
myExternalFile.createNewFile();
FileOutputStream fos = new FileOutputStream(myExternalFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When takePicture is called, I am trying to display the picture taken, in a dialog so the user can choose to save the image or not.
I am having trouble accessing the imageview to change its resource to a bitmap, created from a byte array.
the inflated layout, qrimageviewer.xml;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/qrimageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:onClick="dismissListener"/>
</LinearLayout>
This is one of my several attempts to create and show the dialog;
Dialog settingsDialog = new Dialog(cxt);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
settingsDialog.getLayoutInflater().inflate(R.layout.qrimageviewer, null);
settingsDialog.show();
Drawable image = new BitmapDrawable(BitmapFactory.decodeByteArray(data, 0, data.length));
imageview = (ImageView) activity.findViewById(R.id.qrimageview);
imageview.setImageDrawable(image);
Sorry if have made any mistakes, or not provided enough info.
Thank You
--------UPDATE-------
It see that my problem now, is when I find the view.
I am getting this error;
04-03 14:23:33.800: E/AndroidRuntime(26060): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
I think it is because I am trying to find the view from an AsyncTask and it is failing and returning null, because the layout is inflated by the dialog.
Should i be trying to get the inflated view from the dialog?
Am i taking the wrong approach completely?
Or is it just not possible?
Thank You
A:
Ok, it was my own fault for reading to much and trying too many examples.
I was infalating a custom layout to use for the dialog.
Instead, I needed to programmatically create an ImageView, then add it to the dialog.
Much simpler when you stop stressing and look at it in a different light.
Adding code for future reference.
LayoutInflater inflater = (LayoutInflater) cxt.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Dialog settingsDialog = new Dialog(cxt);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
ImageView imageView = new ImageView(cxt);
Bitmap bitmapa = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmapa);
settingsDialog.addContentView(imageView, new LayoutParams( LayoutParams.FILL_PARENT , LayoutParams.FILL_PARENT ));
settingsDialog.show();
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the Asynchronous mode is better than the Synchronous one when handling clients requests?
I have a client-server project and was searching for the better way to handle the requests from the clients. Some people advised that the Asynchronous mode is better than the synchronous one and the thread pool mode.
My question is why? And are there disadvantages in the Asynchronous mode ?
A:
Yes, asynchronous requests can often be handled without the expense of a thread. The operating system has special support for them, features like overlapped I/O and completion ports. What they essentially do is leverage the expense of a kernel thread, one that's needed anyway because a driver needs to be able to handle multiple requests from multiple user mode programs. The .NET framework readily takes advantage of that in its BeginXxx() methods.
Using threadpool threads is cheap too, but you are subject to the behavior of the threadpool scheduler. Which doesn't much like starting more TP threads then there are cores. TP threads should never be used for code that can stay blocked for a while, pretty typical for CS tasks like making a connection.
Error handling is very difficult in asynchronous code. You typically have very little context when the EndXxxx() method raises an exception. It happens on a callback thread, very far away from the main logic. Okay when you can shrug "didn't happen, lets log it", total bedlam and redrum when the program's state depends on it. Always choose synchronous mode in the latter case.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get alternate single words during dictation in SAPI 5.4 using C#?
I am running a user study with speech recognition and new technologies. During the laboratory tests, I need to display all the dictated text using an interface that I programmed.
Currently, I can get the alternate whole sentences in C# but I need to get the single words. For example, if someone says "Hello, my name is Andrew", I want to get an alternate word for "Hello", "my", "name", "is" and "Andrew", instead of an alternate for the complete sentence.
Here is a code snippet of the handler I'm using.
public void OnSpeechRecognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)
{
int NUM_OF_ALTERNATES = 5; // Number of alternates sentences to be read
string recognizedSentence = Result.PhraseInfo.GetText(0, -1, true);
// Get alternate sentences
ISpeechPhraseAlternates phraseAlternates = Result.Alternates(NUM_OF_ALTERNATES);
}
Any ideas are appreciated.
A:
You need to specify the element count and index in the Result.Alternates call.
E.g.,
public void OnSpeechRecognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)
{
int NUM_OF_ALTERNATES = 5; // Number of alternates sentences to be read
string recognizedSentence = Result.PhraseInfo.GetText(0, -1, true);
// Get alternate sentences
int elementCount = Result.PhraseInfo.Elements.Count();
for (int i = 0; i < elementCount; ++i)
{
ISpeechPhraseAlternates phraseAlternates = Result.Alternates(NUM_OF_ALTERNATES, i, 1);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
codeigniter textfield with disappearing default text
I am creating a form using codeigniter, I wanted to know whether there is a way that we can create atext field having a default text and as soon as user clicks on that field the default text disappears. I was wondering whether there is any method in codeigniter that allows us to do this?
Thanks
Any efforts will be appreciated
A:
Important Note: This solution was posted many years ago and is no longer applicable. Please see the edits below for an alternative solution using HTML5.
You need jQuery for DOM functionalities. The cool thing about jQuery is that many of the functionalities we see everyday on Web 2.0 sites already have their jQuery plugin counterparts. BTW, Codeigniter is a PHP framework while jQuery is javascript framework so you won't be needing Codeigniter for this specific feature.
What you need is an in-label plugin for jQuery. This is the best I've tried so far: http://fuelyourcoding.com/scripts/infield/
As for the code this is basically the only thing you need:
$("label").inFieldLabels();
Instead of removing the text outright, it fades the inline label slowly or until you type in something. Check it out.
To date, the solution above is no longer necessary. using HTML5, users can use the following HTML codes:
<input type="text" name="name" placeholder="Enter your name here" />
| {
"pile_set_name": "StackExchange"
} |
Q:
An Old Irish Blessing, reasked (without using encodings)
How much can you golf a program to print "An Old Irish Blessing" without using unprintable ASCII characters?
That restricts us to ASCII characters 32-126 (better still, 32,65-90,97-122 and 13(CR))
For reference that version of the proverb is 205 characters long (excl. newlines).
I'm curious if anything beats Huffman-encoding incl. spaces.
A:
Golfscript, 198 characters
[]"-!9 4(% 2/!$<)3A50H/ -%%4 9/5
XXXN7).X\"?!,7I3>4UU2I!#+
[[[S35.;(`A[2- 50/.]]]&]%
YO2!U3F|,`/&4ZZZZZK)%,$3
!.$ }4),ze-%%Z!'!k\n-!9 '/S(/]hh )o4(%GG,/7 /&A)3;!v"{.32>{.58<{32+}{56-~1$>2<}if}*+}/+
Output:
$ ruby golfscript.rb blessing.gs
MAY THE ROAD RISE UP TO MEET YOU
MAY THE WIND BE ALWAYS AT YOUR BACK
MAY THE SUN SHINE WARM UPON YOUR FACE
THE RAINS FALL SOFT UPON YOUR FIELDS
AND UNTIL WE MEET AGAIN
MAY GOD HOLD YOU IN THE HOLLOW OF HIS HAND
The poem is compressed to 158 characters by using part of the ASCII range for back-references (of fixed length 2). The coding scheme is as follows:
[10] : newline (unencoded)
[32] : space (unencoded)
[33..57] : literal (33=A, 34=B, ... 57=Y, Z not needed)
[58..126] : back-reference relative to the end of the decompressed string so far.
The remaining 40 characters make up the decompression code which can probably be golfed a little further, since this is my first attempt at Golfscript.
Case-sensitive version, 207 characters
Same concept, but trading some of the back-reference range for lower case letters at the cost of some compression.
[]"-AY THE ROAD RISaUPhO MEET YOU
xxxnWINxB_ALWiS^TuuRiACK
{{{sSUN[HINa{RM UPON}}}F}E
4HoRAuS fLL SOFTzzzzzkIELDS
!NDlNTIwWE MEEzAGAIN
-AY 'OsHOLxYOU k THEggLOW OF (ISeAND"{.32>{.90<{32+}{88-~1$>2<}if}*+}/+
Output:
$ ruby golfscript.rb blessing-casesensitive.gs
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand
| {
"pile_set_name": "StackExchange"
} |
Q:
Reproduce WordArt in Inkscape (trapezoid shape)
I try to convert an old logo to a vector format using Inkscape. The logo was originally made using WordArt. The text is transformed to a trapezoid shape.
I tried to use "Modify Path -> Perspective" but it doesn't end up correctly because the transformation is perspective (i.e. the character widths are not equal).
An example (black = goal, gray = to compare the character widths, orange = current version):
As you can see the left-most character is as wide as the one in the middle.
Is it possible to do this translation in Inkscape or do I have to use a different tool?
A:
You could solve this with Extensions ⇒ Modify Path ⇒ Envelope which works (somewhat) like Envelope Distort in Illustrator.
The drawback to Envelope is that it will only work with 4 points. So instead of doing 1 transform, do 2 (one for the left and one for the right).
Make your text, create your 2 envelopes, do 2 transforms. It will make the vertical warp without introducing the horizontal distortion that you get with Perspective.
Source text converted to paths:
Left envelope path:
Right envelope path:
Modify Path ⇒ Envelope applied to the pair on the left and the pair on the right:
Final output juxtaposed with duplicate of source object to show the lack of horizontal distortions1:
1. I rarely dabble in Inkscape so my example image has some slight distortions but I think this is due to my lack of proficiency with the tool rather than a shortcoming in the Envelope extension itself.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET TreeView javascript before postback
I'm trying to code what I think is a fairly routine AJAX pattern using TreeViews and UpdatePanels. My situation is this:
I have a TreeView within an UpdatePanel. I have a Literal within another UpdatePanel. When the user clicks on a node within the TreeView, the contents of the Literal are updated. Now, since the whole thing is asynchronous, there is of course a time lag between the click and the update of the Literal contents. During this time, I'd like to do two things:
1) Show an UpdateProgress, and
2) Clear the contents of the Literal
This is so that the user doesn't have to stare at the old contents while the new text is getting loaded asynchronously.
I can't seem to figure out an easy way to accomplish (2). I've been reading up on client side callbacks and using GetCallbackEventReference, but it seems like a very complicated approach to what is seemingly a simple problem.
Ideally, I would like to leave TreeView alone to do it's work. I don't want to get the contents myself and add them to the TreeView using JS. I'd just like to detect the node change event at the client side, clear up the Literal, and let TreeView go about with its normal operation.
Is this possible? Or are client call backs my only option?
A:
You'll be wanting to play with the PageRequestManager from the ASP.NET AJAX library. Here's the MSDN reference for the PRM - http://msdn.microsoft.com/en-us/library/bb311028.aspx.
Just be for warned Microsoft have stated that the TreeView can be problematic within the UpdatePanel and you'll also want to be very careful of the performance, particularly if you have a large TreeView (see my article on optimising the UpdatePanel performance - http://www.aaron-powell.com/blog.aspx?id=1195). You should really look at something like a jQuery plugin (eg: http://bassistance.de/jquery-plugins/jquery-plugin-treeview/).
But to actually answer you're question you need to:
Have a BeginRequest event handler which will then clear your literal and can even show a Loading (I'm not a fan of the UpdateProgress, I prefer much more granular control I get from doing it myself)
Use the EndRequest event to ensure that the Loading component vanises
You could also make the TreeView a AsyncPostbackTrigger of the 2nd UpdatePanel on the page, or just call the Update method on it during the async postback of the TreeView
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA subfunctions Error handling
I have a neat example I need help with. I am trying to find a way to handle my errors but keep my subfunctions modular(not needing to know about the rest of my code to work properly)
In Excel VBA, there's no Try/Catch functionality. There are native functions in VBA that return an error if they fail. I am looking to make the following example neat
Function wrapperForFunction(input As Variant) As Boolean
On Error goto returnTrue
fancyFunctionThatReturnsError(input As Variant)
wrapperForFunction = False
LINE OF CODE THAT SETS ERROR BACK TO WHAT IT WAS BEFORE CHANGING IT TO returnTrue
Return
returnTrue:
wrapperForFunction = True
LINE OF CODE THAT SETS ERROR BACK TO WHAT IT WAS BEFORE CHANGING IT TO returnTrue
End Function
Sub MainProgram()
On Error goto errorHandlerMain
'' do stuff
if wrapperForFunction(input) then 'do stuff
'' do morestuff
if wrapperForFunction(input) then 'do stuff
errorHandlerMain:
'non-erroring cleanup code
End Sub
Sub NestedSub()
On Error goto errorHandlerNestedSub
'' do stuff
if wrapperForFunction(input) then 'do stuff
errorHandlerNestedSub:
'non-erroring cleanup code
End Sub
What I am trying to avoid is this kind of solution
Function wrapperForFunction(input As Variant) As Boolean
On Error goto returnTrue
fancyFunctionThatReturnsError(input As Variant)
wrapperForFunction = False
Return
returnTrue:
wrapperForFunction = True
End Function
Sub MainProgram()
On Error goto errorHandlerMain
'' do stuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerMain ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
'' do morestuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerMain ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
errorHandlerMain:
'non-erroring cleanup code
End Sub
Sub NestedSub()
On Error goto errorHandlerNestedSub
'' do stuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerNestedSub ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
errorHandlerNestedSub:
'non-erroring cleanup code
End Sub
Any suggestions?? Is there a way to find out what the current "On Error goto x" state is and reset it back to what it was before you changed it?
Like in
Function foobar()
Dim errorLine As Long: errorLine = CURRENT_ERROR_LINE
On Error goto 40
'do stuff
On Error goto errorLine
Return
40'cleanup code
End Function
A:
A couple of points to note about Error Handling in VBA:
The Scope of an On Error Goto <x> statement is the procedure in which the statement is contained and any procedures called from within that procedure.
As an extension to the previous point: If an error occurs it will 'bubble' up the call stack until it reaches a procedure in which error handling is defined, if no procedure on the stack has defined error handling it will display a generic message box.
With the above behaviour in mind it's not necessary to re-state On Error Goto <x> after each call to a procedure as any change the called procedure makes to its error handling will have gone out of scope by the time it has completed.
Working with the following example:
Public Sub Subroutine1()
Dim a As Double, b As Double, c As Double
On Error GoTo Err_Subroutine
a = 10
b = 2
c = Divide(a, b)
c = c / 0
Exit_Subroutine:
Exit Sub
Err_Subroutine:
Select Case Err.Number
Case 11 'DIV/0
MsgBox "DIV/0 error in Sub Subroutine1()"
Resume Exit_Subroutine
Case Else
MsgBox "Unhandled error in Subroutine1()"
Resume Exit_Subroutine
End Select
End Sub
'Returns a/b or 0 if an error occurs
Public Function Divide(a, b)
On Error GoTo Err_Divide
Divide = a / b
Exit_Divide:
Exit Function
Err_Divide:
Select Case Err.Number
Case 11 'DIV/0
MsgBox "DIV/0 error in Function Divide()"
Divide = 0
Resume Exit_Divide
Case Else
MsgBox "Unhandled error in Function Divide()"
Divide = 0
Resume Exit_Divide
End Select
End Function
Despite the fact that Divide has been called and the statement On Error GoTo Err_Divide executed, when the DIV/0 error occurs on the following line the error will still be directed to Err_Subroutine.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make PHPUnit + Selenium run faster?
I'm using PHPUnit's Selenium extension to do web testing. I'm finding it very slow, taking seconds for a single test method. Part of the issue appears to be that its starting a new Selenium session between each test method (getNewBrowserSession), as part of runTest(). This is expensive. I'm ok with running a class or even a whole suite's worth of test methods in a single selenium session.
Can this be done? Are there other tips for speeding up PHPUnit + Selenium?
Thanks.
A:
Have you tried using the browserSessionReuse option? E.g. starting selenium with
java -jar ./selenium-server.java -browserSessionReuse
| {
"pile_set_name": "StackExchange"
} |
Q:
Since when is asking a question about a Telerik product worth a down-vote?
I have recently had two questions involving a Telerik product voted down. Telerik namespace not found in deployed MVC3 application, and Very odd event behaviour for onChange on Telerik MVC DatePicker. I see nothing wrong with the questions and the only thing they have in common is that they are both tagged Telerik, a not too uncommon tag on SO. What is with this kind of behaviour? Is Microsoft one of the elite vendors that questions about their products are OK, but other vendors not?
A:
You got one downvote... This is not suspicious behavior, and it does not indicate any type of "trend". There is no Microsoft-led conspiracy against Telerik or any other products/companies.
People can choose to downvote questions for whatever reasons they choose. The entire meaning of a downvote is expressed in the tooltip that you'll see if you hover over the arrow. It says:
This question does not show any research effort; it is unclear or not useful.
And since downvotes are merely an expression of the personal feelings or opinions of the user who casts them, one can only assume from the examples that you've shown us that someone out there thought that your questions were "unclear" and/or "not useful". (I don't think research effort is the problem here, but who knows? Personally, I think the questions are fine and wouldn't have downvoted them, if that helps.)
So no, there's nothing wrong with either behavior—your questions or the downvote they each received.
What there is something wrong with is your comment. This one:
Ah, a driveby downvote by someone too cowardly to leave a comment.
Downvotes are anonymous for a reason. To attempt to label people who choose to retain that anonymity as "cowards" is quite offensive. There is no guaranteed relationship between downvotes and comments. They are left at the sole discretion of the downvoting user; you can leave negative comments without downvoting just as you can downvote without leaving comments. There's nothing wrong with either.
There is something wrong with calling the users who choose to do so "cowards", although it does highlight quite nicely why it is important that downvotes remain anonymous. In particular, the likelihood of retaliation. Here you are on Meta complaining about a single downvote (albeit to two different questions) and calling the user who cast that downvote a "coward". Imagine what you'd do if you knew who it was!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a mpfr array?
I searched for some hours on internet and through the docs, but I didn't see mention to create an array/list of MPFR (GMP) objects.
I am using C, not C++.
I you would please help me, I'd only need to get and set values from and to that array, and perhaps a "malloc" once..
A:
In this GNU MPFR 4.0.2, i found:
The C data type for such objects is mpfr_t, internally defined as a one-element array of a structure (so that when passed as an argument to a function, it is the pointer that is actually passed), and mpfr_ptr is the C data type representing a pointer to this structure.
And at 5.1 initialization function:
An mpfr_t object must be initialized before storing the first value in it. The functions mpfr_init and mpfr_init2 are used for that purpose.
Function: void mpfr_init2 (mpfr_t x, mpfr_prec_t prec)
Initialize x, set its precision to be exactly prec bits and its value to NaN. (Warning: the corresponding MPF function initializes to zero instead.)
Normally, a variable should be initialized once only or at least be cleared, using mpfr_clear, between initializations. To change the precision of a variable which has already been initialized, use mpfr_set_prec. The precision prec must be an integer between MPFR_PREC_MIN and MPFR_PREC_MAX (otherwise the behavior is undefined).
Function: void mpfr_inits2 (mpfr_prec_t prec, mpfr_t x, ...)
Initialize all the mpfr_t variables of the given variable argument va_list, set their precision to be exactly prec bits and their value to NaN. See mpfr_init2 for more details. The va_list is assumed to be composed only of type mpfr_t (or equivalently mpfr_ptr). It begins from x, and ends when it encounters a null pointer (whose type must also be mpfr_ptr).
One example:
{
mpfr_t x, y;
mpfr_init (x); /* use default precision */
mpfr_init2 (y, 256); /* precision exactly 256 bits */
…
/* When the program is about to exit, do ... */
mpfr_clear (x);
mpfr_clear (y);
mpfr_free_cache (); /* free the cache for constants like pi */
}
Hope it can help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
What --server do I use on meteor build --server=:?
I'm trying to build my app for Android and I believe it is not connecting to the proper server when I build it. I'm hosting it in AWS and it works in the browser from that site.
meteor build <build-output-directory> --server=<host>:<port>
I've tried using the domain without the port, and the static IP address.
A:
Meteor appears to be having a problem assigning ROOT_URL in the build process when building for mobile. @MasterAM pointed me to this thread where I found the following work around:
meteor run android-device --mobile-server http://whatever.com:3000
meteor build ../apk --server http://whatever.com:3000
The first line sets ROOT_URL references that remain active during the build process.
HTTPS does matter as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I save the headers and values in Html
I'm new to writing code. Using slenium and beautifulsoup, I managed to reach the script I want among dozens of scripts on the web page. I am looking for script [17]. When these codes are executed, the script [17] gives a result as follows.
the last part of my codes
html=driver.page_source
soup=BeautifulSoup(html, "html.parser")
scripts=soup.find_all("script")
x=scripts[17]
print(x)
result, output
note: The list of dates is ahead of the script [17]. slide the bar. Dummy Data
Dummy Data
<script language="JavaScript"> var theHlp='/yardim/matris.asp';var theTitle = 'Piyasa Değeri';var theCaption='Cam (TL)';var lastmod = '';var h='<a class=hisselink href=../Hisse/HisseAnaliz.aspx?HNO=';var e='<a class=hisselink href=../endeks/endeksAnaliz.aspx?HNO=';var d='<center><font face=symbol size=1 color=#FF0000><b>ß</b></font></center>';var u='<center><font face=symbol size=1 color=#008000><b>İ</b></font></center>';var n='<center><font face=symbol size=1 color=#00A000><b>=</b></font></center>';var fr='<font color=#FF0000>';var fg='<font color=#008000>';var theFooter=new Array();var theCols = new Array();theCols[0] = new Array('Hisse',4,50);theCols[1] = new Array('2012.12',1,60);theCols[2] = new Array('2013.03',1,60);theCols[3] = new Array('2013.06',1,60);theCols[4] = new Array('2013.09',1,60);theCols[5] = new Array('2013.12',1,60);theCols[6] = new Array('2014.03',1,60);theCols[7] = new Array('2014.06',1,60);theCols[8] = new Array('2014.09',1,60);theCols[9] = new Array('2014.12',1,60);theCols[10] = new Array('2015.03',1,60);theCols[11] = new Array('2015.06',1,60);theCols[12] = new Array('2015.09',1,60);theCols[13] = new Array('2015.12',1,60);theCols[14] = new Array('2016.03',1,60);theCols[15] = new Array('2016.06',1,60);theCols[16] = new Array('2016.09',1,60);theCols[17] = new Array('2016.12',1,60);theCols[18] = new Array('2017.03',1,60);theCols[19] = new Array('2017.06',1,60);theCols[20] = new Array('2017.09',1,60);theCols[21] = new Array('2017.12',1,60);theCols[22] = new Array('2018.03',1,60);theCols[23] = new Array('2018.06',1,60);theCols[24] = new Array('2018.09',1,60);theCols[25] = new Array('2018.12',1,60);theCols[26] = new Array('2019.03',1,60);theCols[27] = new Array('2019.06',1,60);theCols[28] = new Array('2019.09',1,60);theCols[29] = new Array('2019.12',1,60);theCols[30] = new Array('2020.03',1,60);var theRows = new Array();
theRows[0] = new Array ('<b>'+h+'30>ANA</B></a>','1,114,919,783.60','1,142,792,778.19','1,091,028,645.38','991,850,000.48','796,800,000.38','697,200,000.34','751,150,000.36','723,720,000.33','888,000,000.40','790,320,000.36','883,560,000.40','927,960,000.42','737,040,000.33','879,120,000.40','914,640,000.41','927,960,000.42','1,172,160,000.53','1,416,360,000.64','1,589,520,000.72','1,552,500,000.41','1,972,500,000.53','2,520,000,000.67','2,160,000,000.58','2,475,000,000.66','2,010,000,000.54','2,250,000,000.60','2,077,500,000.55','2,332,500,000.62','3,270,000,000.87','2,347,500,000.63');
theRows[1] = new Array ('<b>'+h+'89>DEN</B></a>','55,200,000.00','55,920,000.00','45,960,000.00','42,600,000.00','35,760,000.00','39,600,000.00','40,200,000.00','47,700,000.00','50,460,000.00','45,300,000.00','41,760,000.00','59,340,000.00','66,600,000.00','97,020,000.00','81,060,000.00','69,300,000.00','79,800,000.00','68,400,000.00','66,900,000.00','66,960,000.00','71,220,000.00','71,520,000.00','71,880,000.00','60,600,000.00','69,120,000.00','62,640,000.00','57,180,000.00','89,850,000.00','125,100,000.00','85,350,000.00');
theRows[2] = new Array ('<b>'+h+'269>SIS</B></a>','4,425,000,000.00','4,695,000,000.00','4,050,000,000.00','4,367,380,000.00','4,273,120,000.00','3,644,720,000.00','4,681,580,000.00','4,913,000,000.00','6,188,000,000.00','5,457,000,000.00','6,137,000,000.00','5,453,000,000.00','6,061,000,000.00','6,954,000,000.00','6,745,000,000.00','6,519,000,000.00','7,851,500,000.00','8,548,500,000.00','9,430,000,000.00','9,225,000,000.00','10,575,000,000.00','11,610,000,000.00','9,517,500,000.00','13,140,000,000.00','12,757,500,000.00','13,117,500,000.00','11,677,500,000.00','10,507,500,000.00','11,857,500,000.00','9,315,000,000.00');
theRows[3] = new Array ('<b>'+h+'297>TRK</B></a>','1,692,579,200.00','1,983,924,800.00','1,831,315,200.00','1,704,000,000.00','1,803,400,000.00','1,498,100,000.00','1,803,400,000.00','1,884,450,000.00','2,542,160,000.00','2,180,050,000.00','2,069,200,000.00','1,682,600,000.00','1,619,950,000.00','1,852,650,000.00','2,040,600,000.00','2,315,700,000.00','2,641,200,000.00','2,938,800,000.00','3,599,100,000.00','4,101,900,000.00','5,220,600,000.00','5,808,200,000.00','4,689,500,000.00','5,375,000,000.00','3,787,500,000.00','4,150,000,000.00','3,662,500,000.00','3,712,500,000.00','4,375,000,000.00','3,587,500,000.00');
var thetable=new mytable();thetable.tableWidth=650;thetable.shownum=false;thetable.controlaccess=true;thetable.visCols=new Array(true,true,true,true,true);thetable.initsort=new Array(0,-1);thetable.inittable();thetable.refreshTable();</script>
My purpose is to extract this output into a table and save it as a csv file. How can i extract this script as i want?
all dates should be on top, all names should be on the far right, all values should be between the two.
Hisse 2012.12 2013.3 2013.4 ...
ANA 1,114,919,783.60 1,142,792,778.19 1,091,028,645.38 ...
DEN 55,200,000.00 55,920,000.00 45,960,000.00 ....
.
.
.
A:
Solution
The custom-function process_scripts() will produce what you are looking for. I am using the dummy data given below (at the end). First we check that the code does what it is expected and so we create a pandas dataframe to see the output.
You could also open this Colab Jupyter Notebook and run it on Cloud for free. This will allow you to not worry about any installation or setup and simply focus on examining the solution itself.
1. Processing A Single Script
## Define CSV file-output folder-path
OUTPUT_PATH = './output'
## Process scripts
dfs = process_scripts(scripts = [s],
output_path = OUTPUT_PATH,
save_to_csv = False,
verbose = 0)
print(dfs[0].reset_index(drop=True))
Output:
Name 2012.12 ... 2019.12 2020.03
0 ANA 1,114,919,783.60 ... 3,270,000,000.87 2,347,500,000.63
1 DEN 55,200,000.00 ... 125,100,000.00 85,350,000.00
2 SIS 4,425,000,000.00 ... 11,857,500,000.00 9,315,000,000.00
3 TRK 1,692,579,200.00 ... 4,375,000,000.00 3,587,500,000.00
[4 rows x 31 columns]
2. Processing All the Scripts
You can process all your scripts using the custom-define function process_scripts(). The code is given below.
## Define CSV file-output folder-path
OUTPUT_PATH = './output'
## Process scripts
dfs = process_scripts(scripts,
output_path = OUTPUT_PATH,
save_to_csv = True,
verbose = 0)
## To clear the output dir-contents
#!rm -f $OUTPUT_PATH/*
I did this on Google Colab and it worked as expected.
3. Making Paths in OS-agnostic Manner
Making paths for windows or unix based systems could be very different. The following shows you a method to achieve that without having to worry about which OS you will run the code. I have used the os library here. However, I would suggest you to look at the Pathlib library as well.
# Define relative path for output-folder
OUTPUT_PATH = './output'
# Dynamically define absolute path
pwd = os.getcwd() # present-working-directory
OUTPUT_PATH = os.path.join(pwd, os.path.abspath(OUTPUT_PATH))
4. Code: custom function process_scripts()
Here we use the regex (regular expression) library, along with pandas for organizing the data in a tabular format and then writing to csv file. The tqdm library is used to give you a nice progressbar while processing multiple scripts. Please see the comments in the code to know what to do if you are running it not from a jupyter notebook. The os library is used for path manipulation and creation of output-directory.
#pip install -U pandas
#pip install tqdm
import pandas as pd
import re # regex
import os
from tqdm.notebook import tqdm
# Use the following line if not using a jupyter notebook
# from tqdm import tqdm
def process_scripts(scripts,
output_path='./output',
save_to_csv: bool=False,
verbose: int=0):
"""Process all scripts and return a list of dataframes and
optionally write each dataframe to a CSV file.
Parameters
----------
scripts: list of scripts
output_path (str): output-folder-path for csv files
save_to_csv (bool): default is False
verbose (int): prints output for verbose>0
Example
-------
OUTPUT_PATH = './output'
dfs = process_scripts(scripts,
output_path = OUTPUT_PATH,
save_to_csv = True,
verbose = 0)
## To clear the output dir-contents
#!rm -f $OUTPUT_PATH/*
"""
## Define regex patterns and compile for speed
pat_header = re.compile(r"theCols\[\d+\] = new Array\s*\([\'](\d{4}\.\d{1,2})[\'],\d+,\d+\)")
pat_line = re.compile(r"theRows\[\d+\] = new Array\s*\((.*)\).*")
pat_code = re.compile("([A-Z]{3})")
# Calculate zfill-digits
zfill_digits = len(str(len(scripts)))
print(f'Total scripts: {len(scripts)}')
# Create output_path
if not os.path.exists(output_path):
os.makedirs(output_path)
# Define a list of dataframes:
# An accumulator of all scripts
dfs = []
## If you do not have tqdm installed, uncomment the
# next line and comment out the following line.
#for script_num, script in enumerate(scripts):
for script_num, script in enumerate(tqdm(scripts, desc='Scripts Processed')):
## Extract: Headers, Rows
# Rows : code (Name: single column), line-data (multi-column)
headers = script.strip().split('\n', 0)[0]
headers = ['Name'] + re.findall(pat_header, headers)
lines = re.findall(pat_line, script)
codes = [re.findall(pat_code, line)[0] for line in lines]
# Clean data for each row
lines_data = dict()
for line, code in zip(lines, codes):
line_data = line.replace("','", "|").split('|')
line_data[-1] = line_data[-1].replace("'", "")
line_data[0] = code
lines_data.update({code: line_data.copy()})
if verbose>0:
print('{}: {}'.format(script_num, codes))
## Load data into a pandas-dataframe
# and write to csv.
df = pd.DataFrame(lines_data).T
df.columns = headers
dfs.append(df.copy()) # update list
# Write to CSV
if save_to_csv:
num_label = str(script_num).zfill(zfill_digits)
script_file_csv = f'Script_{num_label}.csv'
script_path = os.path.join(output_path, script_file_csv)
df.to_csv(script_path, index=False)
return dfs
5. Dummy Data
## Dummy Data
s = """
<script language="JavaScript"> var theHlp='/yardim/matris.asp';var theTitle = 'Piyasa Değeri';var theCaption='Cam (TL)';var lastmod = '';var h='<a class=hisselink href=../Hisse/HisseAnaliz.aspx?HNO=';var e='<a class=hisselink href=../endeks/endeksAnaliz.aspx?HNO=';var d='<center><font face=symbol size=1 color=#FF0000><b>ß</b></font></center>';var u='<center><font face=symbol size=1 color=#008000><b>İ</b></font></center>';var n='<center><font face=symbol size=1 color=#00A000><b>=</b></font></center>';var fr='<font color=#FF0000>';var fg='<font color=#008000>';var theFooter=new Array();var theCols = new Array();theCols[0] = new Array('Hisse',4,50);theCols[1] = new Array('2012.12',1,60);theCols[2] = new Array('2013.03',1,60);theCols[3] = new Array('2013.06',1,60);theCols[4] = new Array('2013.09',1,60);theCols[5] = new Array('2013.12',1,60);theCols[6] = new Array('2014.03',1,60);theCols[7] = new Array('2014.06',1,60);theCols[8] = new Array('2014.09',1,60);theCols[9] = new Array('2014.12',1,60);theCols[10] = new Array('2015.03',1,60);theCols[11] = new Array('2015.06',1,60);theCols[12] = new Array('2015.09',1,60);theCols[13] = new Array('2015.12',1,60);theCols[14] = new Array('2016.03',1,60);theCols[15] = new Array('2016.06',1,60);theCols[16] = new Array('2016.09',1,60);theCols[17] = new Array('2016.12',1,60);theCols[18] = new Array('2017.03',1,60);theCols[19] = new Array('2017.06',1,60);theCols[20] = new Array('2017.09',1,60);theCols[21] = new Array('2017.12',1,60);theCols[22] = new Array('2018.03',1,60);theCols[23] = new Array('2018.06',1,60);theCols[24] = new Array('2018.09',1,60);theCols[25] = new Array('2018.12',1,60);theCols[26] = new Array('2019.03',1,60);theCols[27] = new Array('2019.06',1,60);theCols[28] = new Array('2019.09',1,60);theCols[29] = new Array('2019.12',1,60);theCols[30] = new Array('2020.03',1,60);var theRows = new Array();
theRows[0] = new Array ('<b>'+h+'30>ANA</B></a>','1,114,919,783.60','1,142,792,778.19','1,091,028,645.38','991,850,000.48','796,800,000.38','697,200,000.34','751,150,000.36','723,720,000.33','888,000,000.40','790,320,000.36','883,560,000.40','927,960,000.42','737,040,000.33','879,120,000.40','914,640,000.41','927,960,000.42','1,172,160,000.53','1,416,360,000.64','1,589,520,000.72','1,552,500,000.41','1,972,500,000.53','2,520,000,000.67','2,160,000,000.58','2,475,000,000.66','2,010,000,000.54','2,250,000,000.60','2,077,500,000.55','2,332,500,000.62','3,270,000,000.87','2,347,500,000.63');
theRows[1] = new Array ('<b>'+h+'89>DEN</B></a>','55,200,000.00','55,920,000.00','45,960,000.00','42,600,000.00','35,760,000.00','39,600,000.00','40,200,000.00','47,700,000.00','50,460,000.00','45,300,000.00','41,760,000.00','59,340,000.00','66,600,000.00','97,020,000.00','81,060,000.00','69,300,000.00','79,800,000.00','68,400,000.00','66,900,000.00','66,960,000.00','71,220,000.00','71,520,000.00','71,880,000.00','60,600,000.00','69,120,000.00','62,640,000.00','57,180,000.00','89,850,000.00','125,100,000.00','85,350,000.00');
theRows[2] = new Array ('<b>'+h+'269>SIS</B></a>','4,425,000,000.00','4,695,000,000.00','4,050,000,000.00','4,367,380,000.00','4,273,120,000.00','3,644,720,000.00','4,681,580,000.00','4,913,000,000.00','6,188,000,000.00','5,457,000,000.00','6,137,000,000.00','5,453,000,000.00','6,061,000,000.00','6,954,000,000.00','6,745,000,000.00','6,519,000,000.00','7,851,500,000.00','8,548,500,000.00','9,430,000,000.00','9,225,000,000.00','10,575,000,000.00','11,610,000,000.00','9,517,500,000.00','13,140,000,000.00','12,757,500,000.00','13,117,500,000.00','11,677,500,000.00','10,507,500,000.00','11,857,500,000.00','9,315,000,000.00');
theRows[3] = new Array ('<b>'+h+'297>TRK</B></a>','1,692,579,200.00','1,983,924,800.00','1,831,315,200.00','1,704,000,000.00','1,803,400,000.00','1,498,100,000.00','1,803,400,000.00','1,884,450,000.00','2,542,160,000.00','2,180,050,000.00','2,069,200,000.00','1,682,600,000.00','1,619,950,000.00','1,852,650,000.00','2,040,600,000.00','2,315,700,000.00','2,641,200,000.00','2,938,800,000.00','3,599,100,000.00','4,101,900,000.00','5,220,600,000.00','5,808,200,000.00','4,689,500,000.00','5,375,000,000.00','3,787,500,000.00','4,150,000,000.00','3,662,500,000.00','3,712,500,000.00','4,375,000,000.00','3,587,500,000.00');
var thetable=new mytable();thetable.tableWidth=650;thetable.shownum=false;thetable.controlaccess=true;thetable.visCols=new Array(true,true,true,true,true);thetable.initsort=new Array(0,-1);thetable.inittable();thetable.refreshTable();</script>
"""
## Make a dummy list of scripts
scripts = [s for _ in range(10)]
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving In Magento Taking A Very Very Long Time
In Magento I write a number of small command line scripts to do things like set a new attribute on a number of products. I am finding that the time it takes to update 900 products takes about 6 hours to complete.
The time it takes to load the individual products goes as fast as I would except, but the act of saving once I have made the change takes a very long time.
I am attaching how I am loading the products in case there is something I can do to better optimize the process. Any help here would be greatly appreciated.
$product = Mage::getModel('catalog/product')->load($magento_id);
$product->setMadeInUsa(1);
try {
$product->save();
} catch(Exception $e) {
echo "ERROR: " . $e->getMessage() . "\n";
}
The code runs without error, but it takes forever.
A:
Mage::getSingleton('catalog/product_action')
->updateAttributes(array($product->getId()), $attributesData, $storeId);
This code only updates the attributes you want to change. The first paramater is an array of product IDs, the second is an array of attribute names and values, and then the third is the store ID you wish to update.
This is MUCH faster than saving the entire model.
| {
"pile_set_name": "StackExchange"
} |
Q:
linear regression - underfitting with one hot encoding
I am trying to fit a hypothesis to my data in order to predict the duration for a certain event.
My data is strictly categorical and I used one-hot encoding for all features.
After using one-hot encoding the dataset now has the dimensions 20.000x414.
First I tried linear regression with regular gradient descent. However, both training and cross validation error is large.
I concluded that this is a case of high bias (underfitting).
Now I want to try a polynomial of higher order but I think that it would not make any difference because all of the features are either '1' or '0'.
If I use the square or the cube of those features they will still be '1' or '0', right?
Is there something else I can try in order to deal with the high bias?
A:
I concluded that this is a case of high bias (underfitting).
This can be checked. Suppose you train your dataset on increasing-sized chunks of your data, and test on some fixed-sized chunk you left out, then plot the train and test errors as a plot of the size of the train chunks.
High bias will appear as the error decreasing to some level and staying there.
High variance might appear as a large gap between the train and test errors.
If this indeed looks like high bias, you could try random forests, for example, which might find interaction patterns between the features (binary or otherwise). You might find XGBoost, in particular, convenient for use.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does an image classifier select relevant features?
I am trying to understand cascade classifiers for computer vision. I use OpenCV Traincascade for now and successfully trained some cascades.
However I am trying to grasp the whole process. One thing I do not understand about the cascade training is how the features are selected on each stage.
How does an image classifier select only relevant features?
A:
There is no single answer. A cascade is a very simple idea: it basically represents a bunch of classifiers, applied sequentially.
You are free to decide how each individual cascade will work. You could design the cascade so that every classifier uses the same set of features. Or, you could design the cascade so that each classifier has a different subset of features. They're both considered cascades.
In the standard cascades I've seen used in computer vision, there is one set of features. Each stage in the cascade is a single classifier which is trained on the entire feature vector. Part of the training involves selecting a subset of the features (perhaps only a few features) to use at that stage of the cascade. The training process is responsible for that, and there are many different algorithms for training out there. One example is ADAboost, with decision stumps as the weak classifier; you could take a look at that to see how it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic array with struct that contains a union in C
I'm kind of new to C, so please bear with me.
I have a struct that contains union of other structs with variable sizes like this:
typedef struct _obj_struct {
struct_type type;
union obj {
struct1 s1;
struct2 s2;
struct3 s3;
} s_obj;
} obj_struct;
typedef struct _t_struct {
unsigned int number_of_obj;
obj_struct* objs;
other_struct os;
unsigned int loop;
} t_struct;
The struct_type is the type of the struct we use in the union.
How do I go through all elements in the objs?
Is this the right way to do this:
struct1 s1;
struct2 s2;
struct3 s3;
for (j=0; j<t_struct.number_of_obj; j++)
{
switch (t_struct.obj[j].type) {
case STRUCT1:
s1 = t_struct.objs[j].s_obj.s1;
break;
case STRUCT2:
s2 = t_struct.objs[j].s_obj.s2;
break;
}
}
A:
Unless you need the copy of each structure, use pointers instead:
struct1 *s1;
// ...
s1 = &t_struct.objs[j].s_obj.s1;
Please note, that you have to specify an element of the union as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I check if file exists in ccperl?
I need to check if file exists in ccperl.
I tried to use 'if exists' but it didn't work.
I know sometimes we use " ' " in the beginning and the end of the command, but is there another way?
Thanks
A:
What you probably want is -f 'myfile', which returns true if the name corresponds to a file.
There is a number of these tests, and you can use -e to check that the name exists, but it could be either a file or a directory (or perhaps a link or a pipe on Unix).
| {
"pile_set_name": "StackExchange"
} |
Q:
What formula does the E operator stand for?
I have been trying to get into stats for a while now, but I seem to have missed this information and it must be something so simple that I can't see to find it spelled out.
Does $E(Y)$ stand for $\frac{\sum^n_{i=1}(Y_i)}{n}$? for a set known or calculable values Y.
If so, what does $E(f(x))$ mean for any given formula I do not have samples for (e.g., $f(x)=X^2$)?
A:
$E(Y)$ is a probability theory result. That means $Y$ (written in caps) is a random variable having a density function $f_Y$. $E(Y) = \int y f_Y$. The integration is the Riemann-Stieltjes integral. In other words, if $Y$ is discrete, it boils down to a summation, if $Y$ is continuously valued, it's a standard integral. Also in probability theory, lower case $y$ is treated as a specific value in the sample space of the random variable $Y$, and it is not random. So $E(f(y)) = f(y)$ which is some arbitrary probability constant or probability differential.
When you deal with a sample, you move out of probability theory and into statistics. So if you index a vector of observations $Y_i$, we are assuming that they are observed and the goal is inference about a probabilistic quantity. You might assume, for instance, that each of the $Y_i$ in a fixed sample of size $n$, $1 \le i \le n$, is independent and identically distributed as is often the case with a simple random sample. The sample mean $\bar{Y} = \sum_{i=1}^n Y_i/n$ is a consistent estimator of $\mu_Y = E[Y]$ by the LLN, but it is a purely theoretical quantity.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tesseract parse image and return null
I have problem in tesseract method. i use below code and my application directly stop.Below is my jni.cpp file.
struct native_data_t {
native_data_t() : image_obj(NULL), image_buffer(NULL) {}
tesseract::TessBaseAPI api;
jbyteArray image_obj;
jbyte* image_buffer;
int width, height, bpp;
char bBWFilter; // 0=disable, 1=enable
char bHorizontalDisplay;
};
native_data_t *nat = get_native_data(env, thiz);
if (nat->api.Init("/sdcard/","eng")) {
LOGE("could not initialize tesseract!");
res = JNI_FALSE;
}
can you help me?And what is datapath in this init method? thanks in advance.
my LogCat is as below.
09-03 11:52:53.186: VERBOSE/MLOG: AssetsManager.java:(2263): isAssetsInstalled(): Assets are already correctly installed
09-03 11:52:53.186: VERBOSE/MLOG: OCR.java:(2263): GetLanguage(): eng
09-03 11:52:53.206: VERBOSE/MLOG: OCR.java:(2263): setLanguage to eng
09-03 11:52:53.206: VERBOSE/MLOG: OCR.java:(2263): noLangs=1
09-03 11:52:53.206: VERBOSE/OcrLib(native)(2263): ocr_open
09-03 11:52:53.206: INFO/OcrLib(native)(2263): lang eng
09-03 11:52:53.246: ERROR/OcrLib(native)(2263): IN BASE CPP
09-03 11:52:53.246: ERROR/OcrLib(native)(2263): IN 2nd if BASE CPP
09-03 11:52:53.326: INFO/ActivityThread(2253): Publishing provider com.google.android.maps.SearchHistoryProvider: com.google.googlenav.provider.SearchHistoryProvider
09-03 11:52:54.076: INFO/ActivityManager(123): Start proc com.android.voicedialer for broadcast com.android.voicedialer/.VoiceDialerReceiver: pid=2274 uid=10016 gids={3002}
09-03 11:52:54.206: INFO/ActivityManager(123): Stopping service: com.android.vending/.util.WorkService
09-03 11:52:54.336: INFO/ActivityManager(123): Process com.temp.unique.ocr (pid 2263) has died.
09-03 11:52:54.366: DEBUG/Zygote(122): Process 2263 exited cleanly (1)
09-03 11:52:54.756: INFO/dalvikvm(2274): Debugger thread not active, ignoring DDM send (t=0x41504e4d l=38)
09-03 11:52:54.766: DEBUG/vending(261): [43] LocalAssetCache.updateOnePackage(): No local info for com.temp.unique.ocr
and my package is com.temp.unique.ocr. My application process is directly died.
A:
There's already a JNI wrapper for Tesseract 2.04 named Tesjeract. You may want to look at its source code to see how they did it.
The datapath is the path to tessdata folder, which contains all the language data files.
There's also a JNA-based solution named Tess4J, if you're interested.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to learn what some code does (Lua)
What does this code do?
It's all Lua for World of Warcraft 3.5.5
function __(r) local d = string.sub(r,0x0001,string.len(r)-0x0040) local k = string.sub(r,string.len(r)-0x003F, string.len(r)) d = string.gsub(d, '[^'..k..'=]', '') return (d:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(k:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end _={_=_G} _._["\108\111\097\100\115\116\114\105\110\103"](_._["\095\095"]("SuperLongStringThatWasRemovedForPrivacyReasons"))()
Now what I am guessing is that this is some sort of encrypted code or something? I am not really sure. What do you guys think it is? / Do you know what this code would do when ran?
NOTE: The really long string... really is long. It's about 150,000 characters long.
A:
The code is equivalent to
loadstring(
decode_from_base64(
("SuperLongStringThatWasRemovedForPrivacyReasons"):sub(1, -65)
)
)()
So, SuperLongStringThatWasRemovedForPrivacyReasons is actually a base-64 encoded Lua program (program may be Lua source or Lua bytecode).
You can easily decode it yourself, there are a lot of online base-64 decoders available.
| {
"pile_set_name": "StackExchange"
} |
Q:
Did Snowden reveal that ISIS is a USA-Israel tactic?
This reports claims regarding ISIS which evolved since 2003 assuming erstwhile names like ISI,ISIS and now IS:
The former employee at US National Security Agency (NSA), Edward Snowden, has revealed that the British and American intelligence and the Mossad worked together to create the Islamic State of Iraq and Syria (ISIS).
This news is being spread by many small time news houses like Gulf Daily News, and Iranian fars news agency who is obviously vociferously against ISIS, All of these reports originate from "fars" Iranian news agency.
But I am yet to see any official confirmation from Snowden nor any NSA documents as a proof. Hence is this claim truthful based on the available evidences or how likely is this to be a true claim and can the leaked NSA documents be searched for this?
A:
The report you cite makes reference to an operation called "The Hornet's Nest".
However I was not able to find any reference to an operation by that name.
No mention of a “hornet’s nest” plot can be found in Snowden’s leaked trove of U.S. intelligence documents, and even though Snowden has not publicly refuted the claim, it is safe to assume that the quoted interview never took place.
Time.com
It appears this rumor was started by irna.ir and made popular by the tehrantimes.com running a front page on the story citing irna.ir as the source.
A:
Wikileaks, which is closely associated with Snowden, states that the story is false:
Ground zero for false "Snowden docs show ISIS leader trained by
Mossad" story goes back to last month in Algeria
http://www.algerie1.com/actualite/snowden-le-chef-de-leiil-al-baghdadi-a-ete-forme-par-le-mossad/
…
It has also tweeted the following, which would suggest it wouldn't want to deny the story if it were true.
(ISIS, like other anti-Syrian militant groups may have received
support from Israel, but released Snowden docs don't show it)
| {
"pile_set_name": "StackExchange"
} |
Q:
Usermanager find async error
i'm trying to authenticate on a .net api with Oauth token and i get the following error when i'm accessing the /auth route:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 50 - Local Database Runtime error occurred.
The specified LocalDB instance does not exist.
All day long i tried to fix this but with no success. I'll be glad if i get some help.
So, this is the code where i get the error:
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
AspnetUserService service = new AspnetUserService();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); <---- here, when i send via Postman, i'll wait ~2 minutes to get a response. When the response arrived, this above error appears.
What is weird is that i tried to make a new registration on DB with identity and it worked. I tried to get some values from DB, worked too.
I run a SQL server locally, these are my two connection strings:
<add name="AuthContext" connectionString="Server=localhost;Initial Catalog=SeeMe2;User ID=SeeMe2;Password=password;" providerName="System.Data.SqlClient" />
<add name="SeeMe2Entities" connectionString="metadata=res://*/Context.SeeMe.csdl|res://*/Context.SeeMe.ssdl|res://*/Context.SeeMe.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=SeeMe2;persist security info=True;user id=SeeMe2;password=password;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I tried to debug the code, all the variables seem to have the right values.
Any suggestions? Thanks a lot !
A:
You have a trouble with your SQL connectin string.
Your connection string is:
<add name="AuthContext" connectionString="localhost;Initial Catalog=SeeMe2;User ID=SeeMe2;Password=password;" providerName="System.Data.SqlClient" />
There you have not Server and Database attribute.
The correct connection string is:
<add name="AuthContext" connectionString="Server=localhost;Database=SeeMe2;User ID=SeeMe2;Password=password;" providerName="System.Data.SqlClient" />
More information about connection string is here.
Also check your SeeMe2Entities connection string.
As I can see it has incorrect values on connection section (you have missed Server and Database also).
| {
"pile_set_name": "StackExchange"
} |
Q:
Entity states between EJB and Jersey
I'm a novice.
Does Jersey and EJB hold the same EntityManager scope?
Should I have to pass the EntityManager to EJB for same persistence context?
The primary target usage is JTA.
@Stateless
class MyEJB {
public MyEntity find(Long id) {
...
}
@PersistenceContext;
EntityManager entityManager;
}
class MyResource {
@GET
@Path("/myentity/{id}");
public MyEntity get(@PathParam("id") final long id) {
final MyEntity found = myEjb.find(id);
// is found's state detached?
// should I have to reattach?
found.setDate(new Date());
return found;
}
@EJB
private MyEjb myEjb;
@PersistenceContext;
EntityManager entityManager;
}
A:
Does Jersey and EJB hold the same EntityManager scope?
Should I have to pass the EntityManager to EJB for same persistence context?
I don't think that your wording is correct, but they can share the same EntityManager instance, and you have chosen the right way (through injection). Have a look at this chapter of the Java EE 6 Tutorial:
To obtain an EntityManager instance, inject the entity manager into the application component:
@PersistenceContext
EntityManager em;
So, once again, your approach is correct. With regards to the questions in the code comments: the fact that MyEntity is attached or detached, it depends on the implementation of the find method in your EJB. If you do the following, it will be attached:
public MyEntity find(Long id) {
return entityManager.find(MyEntity.class, id);
}
Finally, doing this way, if you have chosen JTA to use container managed transactions, the transactions will be automatically bounded with the natural boundaries of MyBean's methods. In order to have JTA transactions, you have to use this line in persistence.xml file:
<persistence-unit name="em" transaction-type="JTA">
| {
"pile_set_name": "StackExchange"
} |
Q:
How to record x days in a loop with ZoneMinder?
I would like to keep a trail of 7 days in ZoneMinder. Therfore I would like to set the record mode to: "record" (to be recording all the time). How can I get ZoneMinder to store no more than 7 days?
Thanks!
A:
The solution for a "recordig loop" is the "purge when full filter" in ZoneMinder:
http://www.zoneminder.com/wiki/index.php/FAQ#How_can_I_stop_ZoneMinder_filling_up_my_disk.3F (via)
With this filter you can define the criteria for deleting old events, e.g. "when partition is 75% full", etc. Very versatile tool!
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the ordering of pixel-rows for common image formats?
Is there any popular or most-reliable source that has say the top-10 image formats spec statistics? Or are virtually all formats top-to-bottom? I've run across at least one bottom-to-top and below the TGA info shows either-or, and I'm getting bogged down with multiple levels of flipping coordinate space, so I'm totally uncertain.
Here's the TGA reference, that describes a flag for screen origin:
http://www.paulbourke.net/dataformats/tga/
byte offset 17, bit 5 specifies if the image's pixels are laid out with origin being top-left or bottom-left. I don't know across general use of TGA if there is a typical standard origin across most image applications and libraries.
Considering PNG files, and checking the reference
http://www.w3.org/TR/PNG/#4Concepts.Sourceimage
4.1.b states PNG pixel scan lines are ordered top-to-bottom.
The goal of asking this question is better insight for writing procedural generated pixels into any arbitrary pre-stored image file after it has been loaded into memory.
As a side note, I'm not certain about the easiest way to describe this in graphics terminology. The layout of the pixels onto the screen relative to an origin, I'd personally call it the image pixel orientation, or pixel row order. Maybe there is no single best term.
A:
Sadly, both are in common use today.
Windows BMP, for example, are bottom-up.
Even once loaded into memory, different APIs expect different formats. OpenFX, for example, is bottom-up as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Aggregate most relevant results with MySQL's fulltext search across many tables
I am running fulltext queries on multiple tables on MySQL 5.5.22. The application uses innodb tables, so I have created a few MyISAM tables specifically for fulltext searches.
For example, some of my tables look like
account_search
===========
id
account_id
name
description
hobbies
interests
product_search
===========
id
product_id
name
type
description
reviews
As these tables are solely for fulltext search, they are denormalized. Data can come from multiple tables and are agregated into the search table. Besides the ID columns, the rest of the columns are assigned to 1 fulltext index.
To work around the "50%" rule with fulltext searches, I am using IN BOOLEAN MODE.
So for the above, I would run:
SELECT *, MATCH(name, type, description, reviews) AGAINST('john') as relevance
FROM product_search
WHERE MATCH(name, type, description, reviews) AGAINST('john*' IN BOOLEAN MODE) LIMIT 10
SELECT *, MATCH(name, description, hobbies, interests) AGAINST('john') as relevance
FROM account_search
WHERE MATCH(name, description, hobbies, interests) AGAINST('john*' IN BOOLEAN MODE) LIMIT 10
Let's just assume that we have products called "john" as well :P
The problem I am facing are:
To get meaningful relevance, I need to use a search without IN BOOLEAN MODE. This means that the search is subjected to the 50% rule and word length rules. So, quite often, if I most of the products in the product_search table is called john, their relevance would be returned as 0.
Relevances between multiple queries are not comparable. (I think a relevance of 14 from one query does not equal a relevance of 14 from another different query).
Searches will not be just limited to these 2 tables, there are other "object types", for example: "orders", "transactions", etc.
I would like to be able to return the top 7 most relevant results of ALL object types given a set of keywords (1 search box returns results for ALL objects).
Given the above, what are some algorithms or perhaps even better ideas for get the top 7?
I know I can use things like solr and elasticsearch, I have already tried them and am in the proces of integrating them into the application, but I would like to be able to provide search for those who only have access to MySQL.
A:
So after thinking about this for a while, I decided that the relevance ranking has to be done with 1 query within MySQL.
This is because:
Relevance between seperate queries can't be compared.
It's hard to combine the contents of multiple searches together in meaningful ways.
I have switched to using 1 index table dedicated to search. Entries are inserted, removed, and updates depending on inserts, removals and updates to the real underlying data in the innodb tables (this is all automatic).
The table looks like this:
search
==============
id //id for the entry
type //the table the data came from
column //column the data came from
type_id //id of the row the in the original table
content //text
There's a full text index on the content column. It is important to realize that not all columns from all tables will be indexed, only things that I deem to be useful in search has been added.
Thus, it's just a simple case of running a query to match on content, retrieve what we have and do further processing. To process the final result, a few more queries would be required to ask the parent table for the title of the search result and perhaps some other meta data, but this is a workable solution.
I don't think this approach will really scale (updates and inserts will need to update this table as well), but I think it is a pretty good way to provide decent application wide search for smaller deployments of the application.
For scalability, use something like elastic search, solr or lucene.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python and XML (LandXML)
Ok, I have some XML file looks like this, actually it is LandXML file, but works like any other XML. I need to parse it with python (currently I'm using ElementTree lib) in that way to cycle through sub-element <CoordGeom></CoordGeom> and make lists dependent on child - it can be lineList, spiralList and curveList. Content of that lists is atribute values (don't need names) as nested list for every object. Something like:
lineList=[[10.014571204947,209.285340662374,776.719431311241 -399.949629732524,813.113864060552 -193.853052659974],[287.308329990254,277.363320844698,558.639337133827 380.929458057393,293.835705515579 463.448840215686]]
Here is a sample code:
<?xml version="1.0"?>
<LandXML xmlns="http://www.landxml.org/schema/LandXML-1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.landxml.org/schema/LandXML-1.2 http://www.landxml.org/schema/LandXML-1.2/LandXML-1.2.xsd" date="2015-05-15" time="09:47:43" version="1.2" language="English" readOnly="false">
<Units>
<Metric areaUnit="squareMeter" linearUnit="meter" volumeUnit="cubicMeter" temperatureUnit="celsius" pressureUnit="milliBars" diameterUnit="millimeter" angularUnit="decimal degrees" directionUnit="decimal degrees"></Metric>
</Units>
<Project name="C:\Users\Rade\Downloads\Situacija i profili.dwg"></Project>
<Application name="AutoCAD Civil 3D" desc="Civil 3D" manufacturer="Autodesk, Inc." version="2014" manufacturerURL="www.autodesk.com/civil" timeStamp="2015-05-15T09:47:43"></Application>
<Alignments name="">
<Alignment name="Proba" length="1201.057158008475" staStart="0." desc="">
<CoordGeom>
<Line dir="10.014571204947" length="209.285340662374">
<Start>776.719431311241 -399.949629732524</Start>
<End>813.113864060552 -193.853052659974</End>
</Line>
<Spiral length="435.309621307305" radiusEnd="300." radiusStart="INF" rot="cw" spiType="clothoid" theta="41.569006803911" totalY="101.382259815422" totalX="412.947724836996" tanLong="298.633648469722" tanShort="152.794210168398">
<Start>813.113864060552 -193.853052659974</Start>
<PI>865.04584458778 100.230482065888</PI>
<End>785.087350093002 230.433054310499</End>
</Spiral>
<Curve rot="cw" chord="150.078507004323" crvType="arc" delta="28.970510103309" dirEnd="299.475054297727" dirStart="328.445564401036" external="9.849481983234" length="151.689236185509" midOrd="9.536387074322" radius="300." tangent="77.502912753511">
<Start>785.087350093002 230.433054310499</Start>
<Center>529.44434090873 73.440532656728</Center>
<End>677.05771309169 334.61153478517</End>
<PI>744.529424397382 296.476647100012</PI>
</Curve>
<Spiral length="127.409639008589" radiusEnd="INF" radiusStart="300." rot="cw" spiType="clothoid" theta="12.166724307463" totalY="8.989447716697" totalX="126.8363181841" tanLong="85.141254974713" tanShort="42.653117896421">
<Start>677.05771309169 334.61153478517</Start>
<PI>639.925187941987 355.598770007863</PI>
<End>558.639337133827 380.929458057393</End>
</Spiral>
<Line dir="287.308329990254" length="277.363320844698">
<Start>558.639337133827 380.929458057393</Start>
<End>293.835705515579 463.448840215686</End>
</Line>
</CoordGeom>
<Profile name="Proba">
<ProfAlign name="Niveleta">
<PVI>0. 329.48636525895</PVI>
<CircCurve length="69.993187715052" radius="5000.">512.581836381869 330.511528931714</CircCurve>
<CircCurve length="39.994027682446" radius="5000.">948.834372016349 337.491569501865</CircCurve>
<PVI>1201.057158008475 339.509351789802</PVI>
</ProfAlign>
</Profile>
</Alignment>
</Alignments>
</LandXML>
A:
This example is far from production ready, but it should contain everything you need everything you need for implementing the full solution. This only searches for lines only, does not know which attributes it needs to look for on other kinds of geometry and hasn't got any kind of error handling.
And it's not pretty.
from lxml import etree
doc = etree.parse('/tmp/stuff.xml')
geometry = doc.find('.//{http://www.landxml.org/schema/LandXML-1.2}CoordGeom')
line_list = []
for child in geometry:
child_list = []
if child.tag == '{http://www.landxml.org/schema/LandXML-1.2}Line':
child_list.append(float(child.attrib['dir']))
child_list.append(float(child.attrib['length']))
start, end = child.find('{http://www.landxml.org/schema/LandXML-1.2}Start'), child.find('{http://www.landxml.org/schema/LandXML-1.2}End')
child_list.extend([float(coord) for coord in start.text.split(' ')])
child_list.extend([float(coord) for coord in end.text.split(' ')])
line_list.append(child_list)
print line_list
If you want to extend this example, have a thorough read-thru of the lxml tutorial. Everything I've used is in the tutorial.
| {
"pile_set_name": "StackExchange"
} |
Q:
Entity Framework DbContext Override SaveChanges For Each Model
I have a couple models associated with a DbContext. How can I override SaveChanges to do something different based on the model being saved?
For example, let's say I have two models, Document and Paragraph. How can I override SaveChanges so that a directory is created when a Document is added and that a file is created when a Paragraph is added.
Here is my attempt at doing this so far.
public int override SaveChanges()
{
ChangeTracker.DetectChanges();
var context = ((IObjectContextAdapter)this).ObjectContext;
var stateEntries = context.ObjectStateManager.GetObjectStateEntries(
EntityState.Added
| EntityState.Modified
| EntityState.Deleted
).ToList();
foreach (var entry in stateEntries)
{
if (!entry.IsRelationship)
{
switch (entry.State)
{
case EntityState.Added:
break;
case EntityState.Modified:
break;
case EntityState.Deleted:
break;
}
}
}
return base.SaveChanges();
}
A:
The entry has Entity property which holds instance of your processed entity so you can check instance's type and theoretically do whatever logic you want to do.
You should not use SaveChanges to do anything else than processing your entities for persistence to database - that breaks the separation of concerns. The context is adapter between your application logic and database - nothing more. Moreover whole this idea of integrating file system operations with database operations needs much more complex and careful handling to solve the situation when any operation fails. In your current scenario any failure in call to base.SaveChanges will result in orphan directories or files in your file system - you need to use transactional file system and run but database and file system operation in the same transaction or you must implement manual file system compensation.
Another problem with your code is that you must process Document instances prior to Paragraph to make sure that directories are created before you want to insert files, etc. Simply this logic doesn't belong to SaveChanges method and should not be called from SaveChanges method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to build the release build in react native android
Task :react-native-device-information:verifyReleaseResources FAILED
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':react-native-device-information:verifyReleaseResources'.
A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
1 exception was raised by workers:
com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
C:\Users\navee.gradle\caches\transforms-2\files-2.1\bad4888d8074cc6f9c866f449fedf067\appcompat-1.0.2\res\values-v26\values-v26.xml:5:5-8:13: AAPT: error: resource android:attr/colorError not found.
A:
You have values for compileSdkVersion which are clashing in your MY_PROJECT_NAME/build.gradle file.
The first value you have looks something like this:
android {
compileSdkVersion 27
and further down you have some dependencies which are using/need a HIGHER compileSdkVersion value.
SOLUTION:
Try using the newest SDK, 29 as of this answer. Edit your project/build.gradle (although instead of project you will have a folder named for your specific React Native project/app).
android {
compileSdkVersion 29
defaultConfig {
targetSdkVersion 29
}
...
}
I got this information here:
https://developer.android.com/about/versions/10/setup-sdk#update-build
Explanation:
If some package/dependency you're using needs to be able to use certain android APIs that are only available in SDK 29+ but your project/build.gradle is saying "use SDK 27", your dependencies would be expecting to use APIs which wouldn't exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
A question concerning a set connected to a sequence of measurable functions
I came across the following problem in my study of measurable functions:
If $\{f_n\}$ is a sequence of measurable functions on $X$, then $\{x : \lim_{n \to \infty}f_n(x) \mbox{ exists}\}$ is measurable.
I know how to prove this result if we assume the $f_n$ are $\overline{\mathbb{R}}$-valued, since there are particularly nice results about the limit inferior and the limit superior of such functions in this case. I suspect these (lim sup and lim inf) will factor into the more general case, but I was wondering how the proof would proceed!
A:
Expanding on Srivastans comment: Let $C$ be the set of points $x$ where $(f_n(x))$ converges. This is the case if and only if $(f_n(x))$ is Cauchy: $$C=\big\{x:\forall\epsilon>0 \exists N\forall m> N\forall n>N:|f_n(x)-f_m(x)|<\epsilon\big\}$$
$$C=\big\{x:\forall k \exists N\forall m>N\forall n>N:|f_n(x)-f_m(x)|<1/k\big\}$$
$$C=\bigcap_{k=1}^\infty\bigcup_{N=1}^\infty\bigcap_{n=N+1}^\infty\bigcap_{m=N+1}^\infty\{x:|f_n(x)-f_m(x)|<1/k\}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set the start default fragment of Bottom Navigation Bar to the center/middle fragment?
I am implementing the following GitHub repo in my project.
https://github.com/jaisonfdo/BottomNavigation I didn't paste my code here because I have other features in my project which are not important to the question. This repo is implementing a bottom navigation bar along pageViewer so that we can change the fragments with swipe left/right.
Now the issue is, I want the default/initial screen to be the middle tab and the 2nd fragment. I tried changing the "android:checked" of the second tab to be "true", still at the start, I am getting the 1st tab as default. I also tried changing the order in which the fragments are added initially but still, I am getting the first one as default. The picture is attached below. I want the "CHATS" to be displayed as pink and show the "ChatsFragment" in place of "ContactsFragments".
I want it in middle due to the UI requirements. Any help would be highly appreciated.
1
[]
A:
I see the code at git repo you just need to set the viewpager item. try this code on setupViewPager() method after setting viewpager adapter
viewPager.setCurrentItem(1);
| {
"pile_set_name": "StackExchange"
} |
Q:
The purpose behind the bit data in the Artemis ECS
What is the purpose behind the bit member in the Component Type, and the TypeBit and SystemBit members in the Entity for the Artemis ECS?
These are some screen shots for the git repository of the Artemis ECS that refer to ComponentType and Entity:
For ComponentType
For Entity
Here is the link to the git.
A:
Look into https://github.com/gemserk/artemis/blob/master/src/com/artemis/EntityManager.java
- at addComponent function. It calls
e.addTypeBit(type.getBit());
Also removeComponent() calls:
e.removeTypeBit(type.getBit());
So it's just an id for a component inside entity. The other id is for collecting component types in the EntityManager.
Anyway, it's a bit old implementation. Take a look at fork called artemis-odb which is greater in performance and actively developed. ComponentType is also refactored.
| {
"pile_set_name": "StackExchange"
} |
Q:
Logging on ISP Config broke my PHP sessions and cookies forever
To explain my problem I have to add some context info:
We have a website, it works with sessions and has been working for 7 years with no problems, except for our server administrator, he can not login, and we never knew why... until now...
Our Server administrator is on vacations, so I had to do some of his works, it include login on ISP Config which is located on the same server and domain using a different port (8080), I logged there, to check some values and then when I go back to our website, I could not login, just as our server administrator.
Doing some debug I found it is a problem with sessions, on every refresh session_id() changes.
using ini_get I got session.cookie_domain and session.cookie_secure are empty.
If I do a print_r($_COOKIE) there is no PHPSESSID, if I set it to any value it dissapears, even if I write a long expiration It is not saved, If I set 2 cookies like this:
setcookie("PHPSESSID", "MYSESSION", time()+365*24*60*60, '/');
setcookie("a", "b", time()+365*24*60*60, '/');
and then print_r($_COOKIE); I get this:
Array ( [a] => b )
I don't have any .htaccess, so there is no rules in my side, seems like there is something in ISP config what changed the way I store cookies.
I could ask on webmasters.stackexchange.com but I need a PHP answer to set the new values when someone log in my website after logging in ISP config.
This is my current code to test:
<?php
session_set_cookie_params(3600,"/");
session_start();
//$_SESSION[b_id]=1;
setcookie("PHPSESSID", "GTS", time()+365*24*60*60, '/');
setcookie("a", "b", time()+365*24*60*60, '/');
echo "<div>b_id: $_SESSION[b_id]</div>";
echo "<div>session_id: ".session_id()."</div>";
echo "<div>cookie_domain: ".ini_get('session.cookie_domain')."</div>";
echo "<div>save_path: ".ini_get('session.save_path')."</div>";
echo "<div>cookie_secure: ".ini_get('session.cookie_secure')."</div>";
print_r($_COOKIE);
/*echo "<pre>";
print_r(ini_get_all());
echo "</pre>";*/
?>
This is the output, (session_id value changes each time):
b_id:
session_id: du95eljbkct54qktvcd18a7ej0
cookie_domain:
save_path: /var/lib/php/sessions
cookie_secure:
Array ( [a] => b )
This is the output of ini_get_all() function:
[session.auto_start] => Array (
[global_value] => 0
[local_value] => 0
[access] => 2
)
[session.cache_expire] => Array (
[global_value] => 180
[local_value] => 180
[access] => 7
)
[session.cache_limiter] => Array (
[global_value] => nocache
[local_value] => nocache
[access] => 7
)
[session.cookie_domain] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
[session.cookie_httponly] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
[session.cookie_lifetime] => Array (
[global_value] => 0
[local_value] => 3600
[access] => 7
)
[session.cookie_path] => Array (
[global_value] => /
[local_value] => /
[access] => 7
)
[session.cookie_secure] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
[session.entropy_file] => Array (
[global_value] => /dev/urandom
[local_value] => /dev/urandom
[access] => 7
)
[session.entropy_length] => Array (
[global_value] => 32
[local_value] => 32
[access] => 7
)
[session.gc_divisor] => Array (
[global_value] => 1000
[local_value] => 1000
[access] => 7
)
[session.gc_maxlifetime] => Array (
[global_value] => 1440
[local_value] => 1440
[access] => 7
)
[session.gc_probability] => Array (
[global_value] => 0
[local_value] => 0
[access] => 7
)
[session.hash_bits_per_character] => Array (
[global_value] => 5
[local_value] => 5
[access] => 7
)
[session.hash_function] => Array (
[global_value] => 0
[local_value] => 0
[access] => 7
)
[session.lazy_write] => Array (
[global_value] => 1
[local_value] => 1
[access] => 7
)
[session.name] => Array (
[global_value] => PHPSESSID
[local_value] => PHPSESSID
[access] => 7
)
[session.referer_check] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
[session.save_handler] => Array (
[global_value] => files
[local_value] => files
[access] => 7
)
[session.save_path] => Array (
[global_value] => /var/lib/php/sessions
[local_value] => /var/lib/php/sessions
[access] => 7
)
[session.serialize_handler] => Array (
[global_value] => php
[local_value] => php
[access] => 7
)
[session.upload_progress.cleanup] => Array (
[global_value] => 1
[local_value] => 1
[access] => 2
)
[session.upload_progress.enabled] => Array (
[global_value] => 1
[local_value] => 1
[access] => 2
)
[session.upload_progress.freq] => Array (
[global_value] => 1%
[local_value] => 1%
[access] => 2
)
[session.upload_progress.min_freq] => Array (
[global_value] => 1
[local_value] => 1
[access] => 2
)
[session.upload_progress.name] => Array (
[global_value] => PHP_SESSION_UPLOAD_PROGRESS
[local_value] => PHP_SESSION_UPLOAD_PROGRESS
[access] => 2
)
[session.upload_progress.prefix] => Array (
[global_value] => upload_progress_
[local_value] => upload_progress_
[access] => 2
)
[session.use_cookies] => Array (
[global_value] => 1
[local_value] => 1
[access] => 7
)
[session.use_only_cookies] => Array (
[global_value] => 1
[local_value] => 1
[access] => 7
)
[session.use_strict_mode] => Array (
[global_value] => 0
[local_value] => 0
[access] => 7
)
[session.use_trans_sid] => Array (
[global_value] => 0
[local_value] => 0
[access] => 7
)
[session.cookie_domain] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
[session.cookie_httponly] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
[session.cookie_lifetime] => Array (
[global_value] => 0
[local_value] => 3600
[access] => 7
)
[session.cookie_path] => Array (
[global_value] => /
[local_value] => /
[access] => 7
)
[session.cookie_secure] => Array (
[global_value] =>
[local_value] =>
[access] => 7
)
How to go back my session system to default as before logging in ISP config?
Answering Iłya Bursov questions
Opening page in incognito mode let me login normally and PHPSESSID doesn't change.
Clearing cookies didn't work, PHPSESSID still changing.
phpinfo gave me some relevant info:
Set-Cookie: PHPSESSID=ositfoouhvosgcklk2k14r7t25; expires=Fri, 07-Dec-2018 19:28:01 GMT; Max-Age=3600; path=/
// This is the same time it was created, so it is creating and expiring inmediately!
Expires: Thu, 19 Nov 1981 08:52:00 GMT
// 1981!?
I have a co-worker (in the same network) who can login in my website.
After 2 days, I am unable to fix the problem, we made a new test today to reproduce this error, our web developer logged on ISP Config and now he is unable to log in in my system!!
Same error as me and our server administrator.
I am using Chrome in Windows 10.
ISP Config version 3.1.11
It seems like this guy had the same issue 6 years ago: PHPSESSID not being saved to cookie
A:
Well, four months later of testing, I going to answer my own question to help others having this issue.
ISP Config uses the default PHP name session id, so, if you run a different system in the same domain you can not use the same id.
the first way to solve this problem is doing what @misorude said in his comment, change all the session names to a different name before starting any session:
session_name('MySystem'); // your session string ID
session_start();
For your session string ID use any string you want, use always the same on your whole system and do not use a the default value "PHPSESSID".
Session expired too fast, this is because I was running 2 systems in the same domain as second2none link commented.
shorter session.gc_maxlifetime time, will be used for all the systems in the domain.
this question shows a second alternative way to solve it changing the session directory, calling the session_save_path() function.
There is a third way if you do not want to change the session name id or the session directory in all your files, you can also change the session.save_path configuration as Álvaro González suggested.
| {
"pile_set_name": "StackExchange"
} |
Q:
Command not found for alias
I recently installed the apache2 package using the Software Centre, I want to create an alias apacheres which will replace the more cumbersome command /etc/init.d/apache2 restart.
I opened the .bashrc file in my home directory, and it contains the following lines:
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
So I created a .bash_aliases file in my home directory, and added only this line:
alias apacheres ='/etc/init.d/apache2 restart'
When I started my terminal, I get this error message:
bash: alias: apacheres: not found
bash: alias: =/etc/init.d/apache2 restart: not found
The shell has obviously read the file, otherwise it wouldn't know of its existence. I have checked the directory path and I can find the file apache2 there. What do I need to do to make this alias work?
A:
You need to remove the space before the = in the alias assignment
alias apacheres='/etc/init.d/apache2 restart'
| {
"pile_set_name": "StackExchange"
} |
Q:
Show a Toast when user change setting in preferences activity
I have a preferences Activity with a ListPreference on it and I use this preferences in another activity,
But I want to show a Toast whenever, user changing option in preference Activity.
For example, when user clicks on second radio button in ListPreference, suddenly a toast shown and says "second".
A:
What is the problem?
Resolve the preference and set a listener that does the toast?
Something like this for example
ListPreference listPreference = findPreference(key);
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Toast.makeText(SettingsActivity.this, "second", Toast.LENGTH_LONG).show();
return true;
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create method like Html.TextBox that adds attributes to textbox rendered?
I'm familiar with using the Html.TextBox method to render a textbox. Suppose that I want to write a method that is similar to Html.TextBox, but takes a single additional string attribute called Abc which renders a TextBox just like one rendered by TextBox, but adds an attribute called data-abc with the value specified by Abc.
What is a good way to do this?
A:
Here's what I came up with that seems to work:
public static MvcHtmlString MyTextBox<T>(this HtmlHelper helper, string name, string value, object htmlAttributes, string Abc)
{
IDictionary<string, object> myHtmlAttributes = new RouteValueDictionary(htmlAttributes);
myHtmlAttributes.Add("data-abc", Abc);
return helper.TextBox(propertyName, value, myHtmlAttributes);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to implement google + , facebook login in rails with devise
I am a beginner to Ruby On Rails want to implement facebook and google+ login with devise gem.Application work fine loaclly but when deploy to heroku gives an error Error: redirect_uri_mismatch
A:
You should really ask for a more specific question regarding any code. This is too general!
Every gem that respect himself has decent documentation for it's use.
usually github (it's repository) starts with a really good README file and from than start exploring the tool you're working with.
i.g: https://github.com/plataformatec/devise
| {
"pile_set_name": "StackExchange"
} |
Q:
How set swagger client claims with identityServer4
I'm protecting a .NET Core Web API with an access token issued by an IDS4.
It works and I added some claims in the client configuration, as follows:
// ... other code
new Client
{
ClientId = "apiclient",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = {
new Secret("mysupersecret".Sha256())
},
AllowedScopes = {
"joinot",
JwtClaimTypes.Role,
},
Claims = new List<Claim>() { new Claim("role", "WonderWoman"), new Claim("VatId", "123abc") },
},
// ... other code
These are the claims that I see in the webapi.
I found what I added with the prefix "client_".
For testing purposes I'm using swagger and I have this config for it:
new Client {
ClientId = "swagger_api_client",
ClientName = "Swagger API Client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = {"http://localhost:57303/swagger/oauth2-redirect.html"},
AllowedScopes = {
"joinot",
JwtClaimTypes.Role,
},
Claims = new List<Claim>() { new Claim("role", "ManOfSteel"), new Claim("VatId", "abc123") },
RequireConsent = false
},
This means that I have to authenticate with an interactive user and than I can call the webapi.
When I do it, the claims I found in the webapi are not as I expected.
"client_role" and "client_VatId" are not in the list.
How can I insert the claims for both the console and the swagger client?
A:
You can set AlwaysSendClientClaims to true :
Claims = new List<Claim>() { new Claim("role", "WonderWoman"), new Claim("VatId", "123abc") },
AlwaysSendClientClaims =true,
If set, the client claims will be sent for every flow. If not, only for client credentials flow (default is false) . So your console application which use client credential flow would work even not set that property.
Reference document : http://docs.identityserver.io/en/latest/reference/client.html
| {
"pile_set_name": "StackExchange"
} |
Q:
How to map an XML to Java objects by XPaths?
Given the XML example:
<fooRoot>
<bar>
<lol>LOLOLOLOL</lol>
</bar>
<noob>
<boon>
<thisIsIt></thisIsIt>
</boon>
</noob>
</fooRoot>
Which should be mapped to:
class MyFoo {
String lol;
String thisIsIt;
Object somethingUnrelated;
}
Constraints:
XML should not be transformed, it is provided as a parsed org.w3c.dom.Document object.
Class does not and will not map 1:1 to the XML.
I'm only interested to map specific paths of the XML to specific fields of the object.
My dream solution would look like:
@XmlMapped
class MyFoo {
@XmlElement("/fooRoot/bar/lol")
String lol;
@XmlElement("/noob/boon/thisIsIt")
String thisIsIt;
@XmlIgnore
Object somethingUnrelated;
}
Does anything likewise exists? What I've found either required a strict 1:1 mapping (e.g. JMX, JAXB) or manual iteration over all fields (e.g. SAX, Commons Digester.)
JiBX binding definitions come the nearest to what I'm lokking for. However, this tool is ment to marshall/unmarshall complete hierarchy of Java objects. I only would like to extract parts of an XML document into an existing Java bean at runtime.
A:
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You can do this with MOXy:
@XmlRootElement(name="fooRoot")
class MyFoo {
@XmlPath("bar/lol/text()")
String lol;
@XmlElement("noob/boon/thisIsIt/text()")
String thisIsIt;
@XmlTransient
Object somethingUnrelated;
}
For More Information
http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html
http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
| {
"pile_set_name": "StackExchange"
} |
Q:
How to detect double click on WebBrower control?
In a WinForms application I need to detect when the contents of a System.Windows.Forms.WebBrowser is double clicked which in turn opens custom winform dialog box.
I note that WebBrowserBase disables the Control.DoubleClick event but I've not worked out how to override this behaviour.
A:
MouseDown is disabled too. That's because mouse events are sent to the DOM. You can subscribe to DOM events with the HtmlElement.AttachEventHandler() method. For example:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
webBrowser1.Url = new Uri("http://stackoverflow.com");
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
webBrowser1.Document.Body.AttachEventHandler("ondblclick", Document_DoubleClick);
}
void Document_DoubleClick(object sender, EventArgs e) {
MessageBox.Show("double click!");
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript file input is not working in IE
I am not able to have below code working in IE. It works fine on Firefox and Chrome.
Anyone can help, how can make this function work on IE?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.width(160)
.height(152);
};
reader.readAsDataURL(input.files[0]);
}
}
A:
I've had a similar problem in the past. FileReader is not yet supported in IE:
http://html5demos.com/
You might need to rework your solution if IE support is required to include a regular file upload.
| {
"pile_set_name": "StackExchange"
} |
Q:
Objective-C CFMutableBitVector to ints
Let's say I have an image represented by a CFMutableBitVector. That means that ever 0 bit represents an off pixel, and every 1 bit represents an on pixel.
Is there a way to, easily and quickly convert this CFMutableBitVector to a low level array of ints where an on-bit represents an all-on-bit integer, and an off-bit represents an all-off-bit integer?
The CFMutableBitVector [0,0,0,1,1,0,1,0];
would translate to:
int[8] =
[
00000000000000000000000000000000,
00000000000000000000000000000000,
00000000000000000000000000000000,
11111111111111111111111111111111,
11111111111111111111111111111111,
00000000000000000000000000000000,
11111111111111111111111111111111,
00000000000000000000000000000000,
];
Now, this being an image from a video stream, this will have to happen very quickly -- What's the fastest way to do such a conversion in Objective-C?
A:
Here's the sample conversion ...
u_int32_t sample = UINT32_MAX;
CFBitVectorRef bv = CFBitVectorCreate( NULL, ( const u_int8_t * )&sample, sizeof( u_int32_t ) * 8 );
CFIndex bitCount = CFBitVectorGetCount( bv );
u_int32_t *a = malloc( bitCount * sizeof( u_int32_t ) );
for ( CFIndex i = 0 ; i < bitCount ; i++ ) {
a[i] = CFBitVectorGetBitAtIndex( bv, i ) * UINT32_MAX;
}
for ( int i = 0 ; i < bitCount ; i++ ) {
NSLog( @"Index: %d Number: %u", i, a[i] );
}
free( a );
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the differences between these 2 queries to publish/unpublish nodes?
I found these 2 queries to publish or unpublish a node programmatically:
db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
,array(':nid'=>$node->nid));
db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND `vid` =:vid;"
,array(':nid'=>$node->nid,'vid'=> $node->vid));
I do not understand the difference, and not sure which one use.
Any suggestions?
A:
Let me explain you with all details....
Your First Query is update statement on node table in drupal database which sets node to publish for a particular nid...
db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
,array(':nid'=>$node->nid));
Node table is a base table which stores node related information..
Your Second Query is on node_revision table which stores node revisions if you track node revisions which are nothing but updates...
db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND `vid` =:vid;"
,array(':nid'=>$node->nid,'vid'=> $node->vid));
It's discouraged in Drupal to run queries directly on Drupal for certain actions.. For example in your case you are updating a node and setting status to published.. Drupal works using concept of hooks which are events and actions.. If any module is implementing any node related hooks they won't fire if you run queries directly.. So it's discouraged..
Right way of doing above action is using node_save api function in Drupal 7...
$node = node_load($nid);
$node->status = 1;
node_save($node);
| {
"pile_set_name": "StackExchange"
} |
Q:
Script - Print out commands also
I'm trying to use the script command to run some tests on a C program I wrote and save the shell history to a file.
The problem I'm facing is that the resulting file does not show the actual commands, it only shows the outputs...
I'm currently using :
$ script -c `./tests.sh` shell.txt
Where tests.sh is a bash script containing tests.
But that only writes what should appear on the standard output (similar as if I'd used a > redirection...
Do you know what I'm doing wrong, or if I've misread a man page ?
Cheers
A:
Try script -c "bash -v ./tests.sh" shell.txt.
The -v flag ensures that commands are displayed while ./tests.sh is executed.
Alternatively, I believe you could add set -x at the beginning of ./tests.sh and add set +x at the end. However, this approach would always echo commands as they are executed any time ./tests.sh is run.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get aspnet_Users.UserId for an anonymous user in ASP.NET membership?
I am trying to get the aspnet membership UserId field from an anonymous user.
I have enabled anonymous identification in web.config :
<anonymousIdentification enabled="true" />
I have also created a profile:
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ApplicationServices"
applicationName="/" />
</providers>
<properties>
<add name="Email" type="System.String" allowAnonymous="true"/>
<add name="SomethingElse" type="System.Int32" allowAnonymous="true"/>
</properties>
</profile>
I see data in my aspnetdb\aspnet_Users table for anonymous users that have had profile information set.
Userid PropertyNames PropertyValuesString
36139818-4245-45dd-99cb-2a721d43f9c5 Email:S:0:17: [email protected]
I just need to find how to get the 'Userid' value.
It is not possible to use :
Membership.Provider.GetUser(Request.AnonymousID, false);
The Request.AnonymousID is a different GUID and not equal to 36139818-4245-45dd-99cb-2a721d43f9c5.
Is there any way to get this Userid. I want to associate it with incomplete activity for an anonymous user. Using the primary key of aspnet_Users is preferable to having to create my own GUID (which I could do and store in the profile).
This is basically a dupe of this question but the question was never actually answered.
A:
You can get the UserId for an anonymous user with this:
string userId = Request.AnonymousID
| {
"pile_set_name": "StackExchange"
} |
Q:
How to debug failed wifi connection?
I am using Ubuntu 16.04 on an Asus ZenBook UX305. I have recently changed my router to a HUAWEY HG633 and I am unable to connect to the wifi network. The same router works fine through the Ethernet connection. The same wifi connections work fine on other Windows laptops and a few mobile phones but not on Linux.
After running dmesg I get the following message
[ 2879.219757] wlan0: authenticate with 60:83:34:2d:d6:fc
[ 2879.226060] wlan0: send auth to 60:83:34:2d:d6:fc (try 1/3)
[ 2879.226517] wlan0: authenticated
[ 2879.230953] wlan0: associate with 60:83:34:2d:d6:fc (try 1/3)
[ 2879.232039] wlan0: RX AssocResp from 60:83:34:2d:d6:fc (capab=0x411 status=0 aid=3)
[ 2879.234649] wlan0: associated
[ 2879.234718] IPv6: ADDRCONF(NETDEV_CHANGE): wlan0: link becomes ready
[ 2879.240962] wlan0: disassociated from 60:83:34:2d:d6:fc (Reason: 14)
[ 2904.309137] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
I am unable to move forward and identify further steps to debug the problem. Any help would be greatly appreciated.
A:
When I read that a new router has been installed, I get nervous because often, routers are put in place with default settings that work fine for most wireless devices but may not work well with Linux drivers that are often very sensitive to settings in the router or other access point.
Please check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly not TKIP. Second, if your router is capable of N speeds, you may have better connectivity with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz, although it is likely to affect N speeds. I also have better luck with a fixed channel, either 1, 6 or 11, rather than automatic channel selection. Also, be certain the router is not set to use N speeds only; auto B, G and N is preferred. After making these changes, reboot the router.
Next, I recommend that your regulatory domain be set explicitly. Check yours:
sudo iw reg get
If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Then set it temporarily:
sudo iw reg set IS
Of course, substitute your country code if not Iceland. Set it permanently:
gksudo gedit /etc/default/crda
Use nano or kate or leafpad if you don't have the text editor gedit.
Change the last line to read:
REGDOMAIN=IS
Proofread carefully, save and close the text editor.
Next, I'd set IPv6 to Ignore in Network Manager: http://docs.fedoraproject.org/en-US/Fedora/18/html/Installation_Guide/images/netconfig/network-connections-ipv6-ignore.png This example is for ethernet, but you want wireless.
After making these changes, let us hear if connectivity is improved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex - Why are the named groups located at the end of the group array?
Why are the named groups located at the end of the group array?
Pattern for example (with named and unnamed groups):
(?<digit>\d+)\|(?<main>\d+)\|(\d+)\|(?<abc>\d+)\|(\d+)
And text:
123|456|789|10|11
Why "789" and "11" located at the beginning of array?
See demo systemtextregularexpressions.com
Sorry for my english :)
A:
Well... it's simply an implementation choice made in the .NET Framework.
The documentation explains the algorithm:
Both unnamed and named capturing groups can be accessed by number. Unnamed groups are numbered from left to right starting with 1. (The capturing group in index 0 (zero) represents the match as a whole.) Named groups are then numbered from left to right starting with a number that is one greater than the number of unnamed capturing groups.
The same does not necessarily apply for other flavors, for instance PCRE assigns group numbers in the order they appear in the pattern whether they're named or not.
| {
"pile_set_name": "StackExchange"
} |
Q:
What should our policy be on identification questions?
A new user asked a question about what a mechanism in a picture was. I'm sure we have had such questions before, and I think we have generally allowed them, but a recent one attracted several "unclear what you are asking" down votes.
Many other sites have an identification tag †, so I have created one for this kind of question, even though it would probably be considered a meta tag, which are now explicitly discouraged.
I think it would be useful to agree whether, as a community, we want identification questions, or whether we consider them off-topic.
† Feel free to tag (or suggest a tag on) any questions you find, to help us understand how common this kind of question is.
Result
As of September '19 there were 3 votes for and no votes against allowing identification questions.
Identification questions are considered on-topic.
A:
Yes, we should allow identification questions
identification questions are notoriously difficult to answer via a simple google search.
Many other Stack Exchange sites allow these kinds of questions.
Points in support of this stance:
Not knowing the name of a thing is a practical, answerable question based on a problem someone actually faces. The best way to handle these questions might be to add as much of a description of the thing as possible when asking or answering such that the question is returned when searching with a description of the device in the future. Any long-term users could flag new questions asking about the same device as duplicates. We could then try to use the description in the new question to supplement the existing description, again to try to get the question to come up when a user searches for the description.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Generics: Explicitly check for raw type
I want to be able to set at runtime which type of item I want to instantiate. Below is a much simplified example of what I want to do, because the functionality is not the most relevant part of my question (and it already works correctly if you input a subclass of Administrable).
public class Role {
private Class<? extends Administrable> admin;
public Class<? extends Administrable> getAdmin() {
return admin;
}
public void setAdmin(Class<? extends Administrable> admin) {
this.admin = admin;
}
public Administrable getAdministrable() throws InstantiationException, IllegalAccessException {
return admin.newInstance();
}
}
I'm trying to make the test below fail with a ClassCastException (or any other Exception, really), but I was doubly surprised that my test code compiles, and runs without throwing any RuntimeException.
public class RoleTest {
// this works already
@Test
public void testAdmin() {
// Site is a subclass of Administrable
Class<? extends Administrable> clazz = Site.class;
role.setAdmin(clazz);
assertEquals(clazz, role.getAdmin());
}
// this works already
@Test
public void testAdminNull() {
role.setAdmin(null);
assertNull(role.getAdmin());
}
// this test succeeds, i.e. it does not throw any exception
@Test(expectedExceptions = RuntimeException.class) // using TestNG
public void testAdminIllegal() {
Class clazz = String.class;
// I thought that this wouldn't even compile
role.setAdmin(clazz);
// But the strangest thing is that it seems to work at runtime, too !
assertEquals(clazz, role.getAdmin());
}
}
This means that I've got no explicit check in the setter for a raw type, and I really want one there. Is it possible to implement this check, and if so, how ? I've tried a few reflection techniques to get to see whether clazz is a ParameterizedType, with casting, etc, but nothing seems to work to satisfaction.
A:
Passing the raw type Class:
Class clazz = String.class;
// I thought that this wouldn't even compile
role.setAdmin(clazz);
Wont throw any exception, but your compiler will warn you that you use an unchecked type. If you actually gave a generic class Class<?>, it would not compile.
To check the type passed as parameter, change your method as follows:
public void setAdmin(Class<? extends Administrable> admin) {
if (admin != null && !Administrable.class.isAssignableFrom(admin)) {
throw new IllegalArgumentException("The parameter " + admin.getName() + " should be administrable.");
}
this.admin = admin;
}
Or if you want to make your test fail (without check), call a method from Administrable on an admin instance:
class Administrable {
public void test(){}
}
public void testAdminIllegal() throws IllegalAccessException, InstantiationException {
Class clazz = String.class;
// I thought that this wouldn't even compile
role.setAdmin(clazz);
role.getAdministrable().test();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Correct word order and subject-verb agreement: "..his associate volunteers..."
Please consider the sentence below:
Mr. Moretti has to go to Washington on a business trip unless his associate volunteers to go.
This is a quote from the book: English Grammar Digest, by Trudy Aronson, page 28.
Is this sentence incorrect?
I think the author has meant:
Mr. Moretti has to go to Washington on a business trip unless his associate volunteers [have] to go.
Edit: I think that way because books are at the highest level of confidance for reading and it very rarely happens to see a grammar mistake in a grammar book. Besides, it's the only remedy in my mind (for the time being) to be able to consider the sentence correct.
Do you agree please?
A:
The original sentence is fine.
Let's treat it as two phrases, joined together by the conjunction "unless":
Mr. Moretti has to go to Washington on a business trip.
His associate volunteers to go.
The first sentence is good, and you recognize that. As for the second? You have a subject ("his associate"), a verb in the third-person present tense ("volunteers"), and the verb "to go", which stays in the infinitive because it's preceded by a verb that has already been conjugated. This sentence is good as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento UNION SQL
I'm using Magento and I have problem with using sql command UNION with my collections. I have two collections:
$collection = Mage::getModel('sales/order')->getCollection();
$collection->getSelect()->joinRight(
array('sfi' => 'sales_flat_invoice'),
'main_table.entity_id = sfi.order_id AND
NOW()<= DATE_ADD(main_table.created_at, INTERVAL 3 MONTH)',
array()
);
$collection->getselect()->joinLeft(
array('ztr'=>'zdg_tv_report'),
'ztr.type=\'TV\' AND ztr.number=main_table.increment_id',
array('*')
);
$collection->addFieldToSelect(new Zend_Db_Expr('main_table.increment_id'));
and
$collection2 = Mage::getModel('sales/order')->getCollection();
$collection2->getSelect()->joinRight(
array('sfc'=>'sales_flat_creditmemo'),
'main_table.entity_id= sfc.order_id AND
NOW()<= DATE_ADD(main_table.created_at, INTERVAL 3 MONTH)',
array()
);
$collection2->getSelect()->joinLeft(
array('ztr'=>'zdg_tv_report'),
'ztr.type=\'Reverse_TV\' AND ztr.number=main_table.increment_id',
array('*')
);
$collection2->addFieldToSelect(new Zend_Db_Expr('main_table.increment_id'));
I tried to use
$collection->getSelect()->union(array($collection2->getSelect()));
but SQL select I got seems to be completely messed up:
SELECT main_table.increment_id, `ztr`.*SELECT main_table.increment_id, `ztr`.* FROM `sales_flat_order` AS `main_table` RIGHT JOIN `sales_flat_creditmemo` AS `sfc` ON main_table.entity_id= sfc.order_id AND NOW()<= DATE_ADD(main_table.created_at, INTERVAL 3 MONTH) LEFT JOIN `zdg_tv_report` AS `ztr` ON ztr.type='Reverse_TV' AND ztr.number=main_table.increment_id FROM `sales_flat_order` AS `main_table` RIGHT JOIN `sales_flat_invoice` AS `sfi` ON main_table.entity_id = sfi.order_id AND NOW()<= DATE_ADD(main_table.created_at, INTERVAL 3 MONTH) LEFT JOIN `zdg_tv_report` AS `ztr` ON ztr.type='TV' AND ztr.number=main_table.increment_idSELECT main_table.increment_id, `ztr`.*SELECT main_table.increment_id, `ztr`.* FROM `sales_flat_order` AS `main_table` RIGHT JOIN `sales_flat_creditmemo` AS `sfc` ON main_table.entity_id= sfc.order_id AND NOW()<= DATE_ADD(main_table.created_at, INTERVAL 3 MONTH) LEFT JOIN `zdg_tv_report` AS `ztr` ON ztr.type='Reverse_TV' AND ztr.number=main_table.increment_id FROM `sales_flat_order` AS `main_table` RIGHT JOIN `sales_flat_invoice` AS `sfi` ON main_table.entity_id = sfi.order_id AND NOW()<= DATE_ADD(main_table.created_at, INTERVAL 3 MONTH) LEFT JOIN `zdg_tv_report` AS `ztr` ON ztr.type='TV' AND ztr.number=main_table.increment_id
I also tried to use
$unionSelect = new Varien_Db_Select();
$unionSelect->union(array($collection->getSelect(), $collection2->getSelect()));
but then I don't know how to put such select into collection. Could anybody help me?
A:
You can try use the following variant to perform the UNION statement within Magento:
$collection = Mage::getModel('sales/order')->getCollection();
$select1 = clone $collection->getSelect();
$select1->joinRight...
$select2 = clone $collection->getSelect();
$select2->joinRight...
$collection->getSelect()->reset();
$collection->getSelect()->union(array($select1, $select2));
| {
"pile_set_name": "StackExchange"
} |
Q:
Square of a second derivative is the fourth derivative
I have a simple question for you guys, if I have this:
$$\left(\frac{d^2}{{dx}^2}\right)^2$$
Is it equal to this:
$$\frac{d^4}{{dx}^4}$$
Such that if I have an arbitrary function $f(x)$ I can get:
$$\left(\frac{d^2 f(x)}{{dx}^2}\right)^2 = \frac{d^4 f(x)}{{dx}^4}$$
Sorry if it's a pretty simple question, but I was trying to simplify something like this:
$$\left(a \cdot \frac{d^2}{{dx}^2} - f(x)\right)^2 g(x)$$ that's where it came up.
A:
It depends on what you mean by "square" and it's basically a problem of notation. When you write $\left(\frac{d^2}{{dx}^2}\right)^2 $, implicitly the "square" means that you compose the operator $\frac{d^2}{{dx}^2}$ with itself, i.e. you consider $\frac{d^2}{{dx}^2} \circ \frac{d^2}{{dx}^2}$. This is of course equal to $\frac{d^4}{{dx}^4}$: differentiating four times is the same thing as differentiating twice then differentiating twice again. Applied to some function $f$, this then gives $\frac{d^2}{{dx}^2} \left( \frac{d^2 f(x)}{{dx}^2} \right) = \frac{d^4 f(x)}{{dx}^4}$, which is true.
On the other hand, where you write $\left(\frac{d^2 f(x)}{{dx}^2}\right)^2$, the "square" is implicitly multiplication, i.e. you're considering $\left(\frac{d^2 f(x)}{{dx}^2}\right) \cdot \left(\frac{d^2 f(x)}{{dx}^2}\right)$. This is not equal to the first thing, as simple counterexamples show (e.g. $f(x) = x^3$: $f''(x) = 6x$ thus $(d^4f)/(dx^4)(x) = 0$ while $((d^2f)/(dx^2)(x))^2 = (6x)^2 = 36x^2$). So you need to be careful with your notations.
A:
I'm afraid not. Consider calculating the two quantities for
$$f(x)=x^3.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
connect to website purely by raw socket connection
Language -> C++11 or C++98 {NOT C}
OS -> Linux embedded system
Restriction-> NO use of any 3rd party library.
Overview -> to establish connection with website.
I have an Linux embedded system and Its not allowed to download any libraries like poco or libcurl or boost to establish connection with website and extract information. So I am wondering if someone can direct me to how to establish connection purely by raw sockets in C++ [not c] and retrieve information from page.
Parsing the information and retrieving exact information is not a challenge for me, my main problem is how would I establish connection over http protocol. If I am right , to connect to website I need http protocol rather than TCP/IP.
Could some one please point me to right direction.
Thanks
A:
You can communicate with HTTP with raw TCP socket.Since you didn't provide code, I can't provide code either. If you already know how to connect, send and receive data from server, it should be easy. Just follow the steps below.
Let's assume you want to connect to www.cnn.com.
1. Convert the the domain name of the website to an IP Address.
2. Connect to that IP address with port 80.
3. Send the string GET / HTTP/1.1\r\nHost: www.cnn.com\r\nConnection: close\r\n\r\n
4. Read from the socket/server. If the server is available, it will respond with the page or html code on that webpage.
5. Close socket connection.
Note that some websites will not respond or will even block you if you don't provide the User-Agent/Web browser name you are using.
To fix this, in step add, add User-Agent:MyBrowserName \r\n header to the string. You can fake browsers. You must put \r\n after each header.
For example, the Chrome browser I am using is Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36.
Your new string that will be sent in Step 3 should look something like this GET / HTTP/1.1\r\nHost: www.cnn.com\r\nConnection: close\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36\r\n\r\n. You should notice that there is \r\n after each header. The last header ends with \r\n\r\n instead of \r\n.
Other useful headers are Connection: Keep-Alive\r\n , Accept-Language: en-us\r\n, Accept-Encoding: gzip, deflate\r\n ,
Replace port 80 with 443 if the website is https instead of http. Things get complicated from here because you have to implement the SSL protocol.
Assuming you want to access page in another directory instead of the home page and the url is http://www.cnn.com/2016/05/13/health/healthy-eating-quiz/index.html
The string to send should look like this:
GET /2016/05/13/health/healthy-eating-quiz/index.html HTTP/1.1\r\nHost: www.cnn.com\r\nConnection: close\r\n\r\n
If you are using proxy, you have to put the whole url after GET command:
GET GET http://www.cnn.com/2016/05/13/health/healthy-eating-quiz/index.html HTTP/1.1\r\nHost: www.cnn.com\r\nConnection: close\r\n\r\n
| {
"pile_set_name": "StackExchange"
} |
Q:
Connection lost. Saving has been disabled... (Updating Posts/Pages)
I've been developing for Wordpress for a few years now without any trouble on an old XP/WAMP development server (v1.7.4) but recently have been getting the error "Connection lost. Saving has been disabled until you’re reconnected" whenever I try to update either Wordpress Posts or Pages. The majority of what I've turned up on the subject points to plugins as the source of the problem, Sadly, I find that even in a clean install of wordpress 3.8.1, in a new DB, without any plugins the problem persists. Next logical culprit then is the server. I check the logs, and find nothing. In the process of migrating my workflow to a newer Windows 7 platform (WAMP v2.2.22) I created a new install there, and the problem is gone. I've run the php.ini's from both servers through a difference engine hoping to suss out the cause, but I'm afraid it's a bit beyond me where the issue might be, nor how to share the results of the comparison here, either as a flat file, or CSV.
Any thoughts?
A:
That message is a result of your server throwing a 503 error and the WordPress Heartbeat API catching that error. See https://core.trac.wordpress.org/ticket/25660 for the background on the fix that WordPress introduced to save offline edits.
Things to check on your computer are if WAMP is actually running when you're getting this message (check the status icon in the system tray). You should also check to make sure no other programs are trying to take over the port WAMP uses. Reports of Skype and TeamViewer taking control of ports 80 & 443 abound, as well as fixes for each of them.
If you haven't checked out the WAMP forums, here's a page that outlines the debugging steps for the 503 server error, and fixes for Skype and TeamViewer: http://forum.wampserver.com/read.php?2,115474,115576.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why won't my \mathrlap stay overlapping?
I've defined a \boxstar command as follows:
\newcommand{\boxstar}{\mathrlap{\boxplus}\boxtimes}
This looks quite nice on its own.
However, when I have a line of boxstars and other symbols, the boxstars stop overlapping properly.
$$\boxstar \boxstar \boxtimes \boxtimes \boxtimes \boxtimes \boxtimes $$
What's going on here?
(Using amssymb and mathtools.)
A:
You have to group the two symbols together. Here I do this using \mathbin to indicate to TeX, that \boxstar is a binary operator. If you fail to do this, the spacing around \boxtimes is influenced by the symbol following after it which makes the \boxplus go off center.
\documentclass{article}
\usepackage{mathtools}
\usepackage{amssymb}
\newcommand{\boxstar}{\mathbin{\mathrlap{\boxplus}\boxtimes}}
\begin{document}
\[ \boxstar \boxstar \boxtimes \boxtimes \boxtimes \boxtimes \boxtimes \]
\end{document}
I recommend to overlay symbols using \ooalign, because this overlays them with respect to the center (\mathrlap overlay with respect to the left boundary).
\documentclass{article}
\usepackage{mathtools}
\usepackage{amssymb}
\makeatletter
\newcommand*\boxstar{\mathpalette\@boxstar\relax}
\newcommand*\@boxstar[2]{%
\mathbin{%
\ooalign{%
$\m@th#1\boxplus$\cr
\hidewidth$\m@th#1\boxtimes$\hidewidth\cr
}%
}%
}
\makeatother
\begin{document}
\[ \boxstar \boxstar \boxtimes \boxtimes \boxtimes \boxtimes \boxtimes \]
\end{document}
A:
Never use $$ in LaTeX
When you do \boxstar \boxstar \boxtimes \boxtimes you have the following sequence of atoms, due to the fact that your \boxstar is composed by an ordinary symbol (O) followed by a binary operation (B):
O (m) B (m) O (m) B (m) B (0) B
TeX will insert a medium space (m) where indicated, but zero space between the two last B's, because they are incompatible with binary operations, so they're treated as O.
How do you solve the issue? By stating how the new symbol should behave and using braces around \boxtimes so it effectively becomes an ordinary symbol:
\newcommand{\boxstar}{\mathbin{\mathrlap{\boxplus}{\boxtimes}}}
The braces are not really needed here, because a subformula consisting of OB will become OO (by the same rules mentioned above), but is conceptually better to have them.
This works because \boxplus and \boxtimes have the same width. In order to superimpose symbols with different widths, the simplest method is to exploit \ooalign, see https://tex.stackexchange.com/a/22375/4427 for a quick course on it.
Your example
\[
\boxstar \boxstar \boxtimes \boxtimes \boxtimes \boxtimes \boxtimes
\]
will now become
B B B B B B B
that's transformed into
O (m) B (m) O (m) B (m) O (m) B (m) O
because of incompatible BB sequences.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the advantages of lighttpd over Apache
Youtube use lighttpd rather than the common Apache.
What are the advantages of Light vs Apache? Are there other alternatives to Apache?
A:
YouTube uses lighttpd only for its static assets (like images and videos). The main site is still using Apache httpd:
$ lynx -head -dump http://www.youtube.com|grep ^Server
Server: Apache
There are several reasons for using a more lightweight webserver than Apache httpd one being that they could be more efficient in serving static files. An interesting source of information about YouTube's architecture can be found on highscalability.com
It might surprise you, but there are several more companies using webservers other than Apache httpd. Take a look at the Netcraft web server survey or the lighttpd wiki for examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a palindrome off a string that is INSIDE of an array
I am supposed to change every element of an array arr to be a palindrome.
I've tried making a for loop to make a new array, and made another for loop to make a palindrome off of the elements of the array, but apparently it doesn't really work out.
public static String [] changeArrayToPalindrome(String [] arr){
int length =arr.length;
String[]newarray= new String[length];
for(int i=0; i<length; i++){
String a=arr[i];
int n=a.length();
if(a==null){
System.out.println("null");
}
else if(a.equals("")){
System.out.println("");
}
String newString="";
for(int j=0; j<=n/2-1; j++){
newString+=a.charAt(j);
newString+=a.charAt(n/2+j);
newarray[j]=newString;
}
}
return newarray;
}
The tester is
String [] array={"street", null, "break", "oha", "", "pit", null,"atOyotA"};
System.out.println(Arrays.toString(changeArrayToPalindrome(array)));
Supposed to print out
//[street, null, break, oha, , pit, null, atOyotA]
//[strrts, null, brerb, oho, , pip, null, atOyOta]
I know I'm not supposed to put System.out.println for the null or the empty string, but I have no idea how to do it as a return statement.
Any help to achieve the purpose of the assignment would be appreciated.
A:
Your code can be updated to this.
import java.util.Arrays;
public class Test {
public static String [] changeArrayToPalindrome(String [] arr){
int length =arr.length;
String[]newarray= new String[length];
for(int i=0; i<length; i++){
String a=arr[i];
if(a==null){
newarray[i]=null;
}
else if(a.equals("")){
newarray[i]="";
} else {
int n=a.length();
String newString="";
if (n%2==0) {
//for even
newString=a.substring(0,n/2);
} else {
newString=a.substring(0,n/2+1);
}
for(int j=n/2-1; j>=0; j--){
newString+=a.charAt(j);
}
newarray[i]=newString;
}
}
return newarray;
}
public static void main(String[] args) {
String [] array={"street", null, "break", "oha", "", "pit", null,"atOyotA"};
System.out.println(Arrays.toString(changeArrayToPalindrome(array)));
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Weird CSS issue involving inline overrides in IE
http://searchdatacenter.techtarget.com/informationCenter/0,296712,sid80_iid371,00.html
On this page the ad on the bottom right with the black background header doesn't pickup the inline styles in IE. So it's the custom grey and black text in IE but the correct black background and white text in Firefox.
The default styles come from a stylesheet....the overrides come inline. Any reason why this isn't being picked up by IE?
Edit: Thanks, missed the overrides come inlinedoctype. Any reason why this isn't being picked up by IE?
A:
The style tag is only valid inside the head section of the page, and the linked stylesheet just above it should be in the head as well. You're lucky what you have works in anything.
If this is difficult to change, your best bet is probably removing your style block and using the style attribute on the div instead:
<div class="cltHeader" style="background-color: black;">
| {
"pile_set_name": "StackExchange"
} |
Q:
Fonts not looking right on brand new laptop in . Help please
I just got a new HP Probook 450 G2.
One of the tasks I got it for, was to use Google Docs and google scripts.
I've noticed when using Google script editor, on Chrome and Firefox,
My fonts are not looking right. The tops of the letters are funny. The equals sign is darker at the top than the bottom. I've had a play with font and cleartype settings and can't fix it.
Sorry am running windows 8.1 64bit
Any suggestions?
Firefox screen shot
Large picture
Chromes screenshot
Large picture
A:
So I found the solution to the Chrome issue, on this link
solution to chrome issue on super user
[...]
The main issue here is that Chrome uses Windows GDI to render fonts while most modern web browsers that run on Windows use DirectWrite instead.
The Chrome development team has integrated full support for DirectWrite into Chrome Beta -- and Dev and Canary as well -- but have not enabled it by default.A
[...]
Type or paste chrome://flags into the browser's addressbar and hit enter.
Hit F3 and type directwrite. Chrome should jump to the Enable DirectWrite experiment right away.
Click on the enable link to activate it.
A relaunch now button appears that you need to click on to restart the browser.
[...]
I was struggling to find the solution for Firefox. I had a play with direct write settings in firefox, using 'about:Config' but this didn't solve it.
I found a sort of solution to the problem. It forces a manual font choice that displays ok in Firefox.
- Go to your Firefox options and choose Content.
- In Content choose advanced settings.
- In Advanced settings, make sure to uncheck the box that says:
'Allow pages to choose their own fonts, instead of my selections above. After unchecking the box, click ok'
This fixed my font display issues in firefox
I found this information while searching on this link
Firefox font fix link
| {
"pile_set_name": "StackExchange"
} |
Q:
why is my kivy program not calling the function from another class?
I think this is more of a python question, then a kivy question.
class Keyboard is sharing a method from class GUI. I created an GUI instance called "self.a" to connected the 2 classes in class Keyboard. Also, I created a keyboard class instance, "self.key in class MainApp.
when I use this method, "print ("Return button is pressed")" the "return" button was able to do the print statement. I understand why it works. When I use the "self.a.up()" in the method, the return button does not called the up() method from class GUI. It's probably a small detail or a concept that I am missing. There is not error from the rest of the program. Please help and thanks in advance.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.lang.builder import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.modules import keybinding
from kivy.core.window import Window
class GUI(BoxLayout):
main_display = ObjectProperty()
text_input = ObjectProperty()
def plus_1(self):
self.value = int(self.main_display.text)
self.main_display.text = str(self.value + 1)
print (self.main_display.text)
def minus_1(self):
self.value = int(self.main_display.text)
self.main_display.text = str(self.value - 1)
def up(self):
self.main_display.text = self.text_input.text
self.text_input.text = ''
class Keyboard(Widget):
def __init__(self,):
super().__init__()
self.a = GUI()
self.keyboard = Window.request_keyboard(None, self)
self.keyboard.bind(on_key_down=self.on_keyboard_down)
def on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'enter':
self.a.up()
# print ("Return button is pressed")
return True
class MainApp(App):
def build(self):
key = Keyboard()
return GUI()
if __name__=="__main__":
app = MainApp()
app.run()
A:
I think it works fine but in another object that you can't see. The problem is that you show one object of GUI class on screen. And for the Keyboard class you have created another object that you can't see. So the solution is to use one object of GUI class and operate with it in both of MainApp and Keyboard classes. Something like:
class MainApp(App):
def build(self):
# here we create an object...
self.gui = GUI()
# ...send it to Keyboard class
key = Keyboard(self.gui)
# and return it
return self.gui
class Keyboard(Widget):
def __init__(self, gui):
super().__init__()
# and here we receive that object instead of creating new one
self.a = gui
| {
"pile_set_name": "StackExchange"
} |
Q:
A Question on Normal Operators
Let $T$ be a compact operator on a Hilbert space $H$. I want to prove the following:
If there exists Orthonormal Basis from the eigen vectors of $T$, then $T$ is normal operator.
A:
I'll assume a complex Hilbert space $H$. If $\{ e_n \}_{n=1}^{\infty}$ is an orthnormal basis of $H$ with $Te_n =\lambda_n e_n$, then there is a constant $M$ such that $|\lambda_n| \le M$ for all $n$ because $T$ must be bounded, which ensures the norm converges of all vector sums in this post, such as
$$
T x = \lim_{N} T\sum_{n=1}^{N}\langle x,e_n\rangle e_n = \lim_N\sum_{n=1}^{N}\lambda_n \langle x,e_n\rangle e_n =\sum_{n=1}^{\infty}\lambda_n\langle x,e_n\rangle e_n
$$
Therefore,
\begin{align}
\langle Tx,y\rangle & =\lim_N \langle \sum_{n=1}^{N}\lambda_n\langle x,e_n\rangle e_n,y\rangle \\
& = \lim_N\sum_{n=1}^{N}\lambda_n\langle x,e_n \rangle\langle e_n,y\rangle \\
& = \lim_N\langle x,\sum_{n=1}^{N}\overline{\lambda_n}\langle y,e_n\rangle e_n\rangle \\
& = \langle x,\sum_{n=1}^{\infty}\overline{\lambda_n}\langle y,e_n\rangle e_n\rangle
\end{align}
Hence $T^*$ is given by
$$
T^*y = \sum_{n=1}^{\infty}\overline{\lambda_n}\langle y,e_n\rangle e_n
$$
Consequently,
$$
\|Tx\|^2 = \sum_{n=1}^{\infty}|\lambda_n|^2|\langle x,e_n\rangle|^2 = \|T^*x\|^2.
$$
That's enough to imply $T^*T=TT^*$. (Alternatively, you can directly verify $T^*Tx = TT^*x$ for all $x$ using the known forms of $T$ and $T^*$.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Are all of these sentences grammatical?
He was charged with killing 13 people.
He was charged with having killed 13 people.
He was charged with the crime he killed 13 people.
I suppose the phrase no. 1 is correct but the others also make sense or are they grammatically wrong?
A:
1 and 2 are correct.
3 is wrong. You could break it into two sentences:
He was charged with the crime. He killed 13 people.
But I think what you really mean is:
He was charged with the crime of killing 13 people.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that the only $3×3$ matrices which commute with any $3×3$ matrices are of the form $cI$ for some scalar $c$....
Prove that the only $3×3$ matrices which commute with any $3×3$ matrices are of the form $cI$ for some scalar $c$.
-My professor's hint for me was that if $A$ is such a matrix. That by choosing $B$ wisely, comparing $AB$ to $BA$ should narrow the choices for the entries of $A$ fairly quickly.
-I understand that I could find a particular matrix for which this condition would fit, although I do not see how I could prove this for all A matrices, any help is appreciated.
A:
Let $A:=(a_{i,j})_{1\leqslant i,j\leqslant n}\in\mathbb{R}^{n\times n}$ and assume that: $$\forall B\in\mathbb{R}^{n\times n},AB=BA.$$
For all $(i,j)\in\{1,\ldots,n\}^2$ let define: $$E_{i,j}:=(\delta_{i,k}\delta_{j,l})_{1\leqslant k,l\leqslant n}\in\mathbb{R}^{n\times n}.$$
$E_{i,j}$ is a square matrix of order $n$ with $0$ everywhere except on the entry $(i,j)$ where it has a $1$. Notice that for all $(i,j)\in\{1,\ldots,n\}^2$, one has: $$AE_{i,j}=\begin{pmatrix}0 & \ldots & 0 & a_{1,i} & 0 & \ldots & 0\\
\vdots & \ddots & \vdots & \vdots & \vdots & \ddots & \vdots\\
0 & \ldots & 0 & {a_{n,i}} & 0 & \ldots & 0\end{pmatrix},$$
where the entries of $A$ are on the $j$th column. Moreover, one has:
$$E_{i,j}A=\begin{pmatrix}0 & \ldots & 0\\
\vdots & \ddots & \vdots\\
0 & \ldots & 0\\
a_{j,1} & \ldots & a_{j,n}\\
0 & \ldots & 0\\
\vdots & \ddots & \vdots\\
0 & \ldots & 0\\
\end{pmatrix},$$
where the entries of $A$ are on the $i$th row. Assuming $i\neq j$, since $AE_{i,j}=E_{i,j}A$ (by hypothesis), by checking the entry $(j,j)$, one has: $$a_{j,i}=0.$$
From there, the entries of $A$ are $0$ everywhere except on its diagonal. I let you conclude from there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fancyhdr, problem with chapter titles
I've asked my first question on the forum yesterday and I've done several mistakes in it, making the subject not understandable so I've decided to delete the question and start again properly....
I'm trying to set up the headers for my master thesis having page numbers and chapter titles for the even pages and section titles for the odd in it, with two different styles for the frontmatter and the mainmatter. I'm close to obtain what I want but I remain with several issues related to the titles in the frontmatter.
I'm trying to get rid of the "CHAPTER 0" wich remain before every title in the header as I just want to keep the title it self. I'm also trying to have the name of the chapter in capital letters but the name of the sections in small letters as it is (and works very well) in the mainmatter.
I shall say that for each section I've used \pagestyle{frontmatter} and \pagestyle{mainmatter}.
I cannot see the mistake I've done in the following preambule:
\documentclass[a4paper,12pt]{book}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage[frenchb]{babel}
\usepackage[T1]{fontenc}
\usepackage[pdftex]{graphicx}
\usepackage[top=2.5cm, bottom=2.5cm, right=2.5cm, left=2.5cm, headheight = 20pt]{geometry}
\usepackage{pifont}
\usepackage{xspace}
\usepackage{setspace}
\usepackage{mathptmx}
% Mise en page du livre
\usepackage{fancyhdr}
\fancypagestyle{frontmatter}{%
\fancyhf{}
\renewcommand{\chaptermark}[1]{\markboth{##1}{}}
\renewcommand{\sectionmark}[1]{\markright{##1}}
\renewcommand{\headrulewidth}{.4pt}
\renewcommand{\footrulewidth}{0pt}
\fancyhead[LO,RE]{\thepage}
\fancyhead[RO]{\leftmark}
\fancyhead[LE]{\rightmark}
}
\fancypagestyle{mainmatter}{%
\fancyhf{}
\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\chaptername\ \thechapter.\ ##1}}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection{} \ ##1}}
\renewcommand{\headrulewidth}{.4pt}
\renewcommand{\footrulewidth}{0pt}
\fancyhead[LO,RE]{\thepage}
\fancyhead[RO]{\leftmark}
\fancyhead[LE]{\rightmark}
}
%************************************************
% *
% COMMANDES PERSONNALISÉES *
% *
%************************************************
% Insérer des guillemets français
\newcommand{\g}[1]{\og#1\fg}
\begin{document}
\frontmatter
\pagestyle{frontmatter}
\setcounter{secnumdepth}{0}
\chapter{Introduction}
\section{Première section}
Nihil morati post haec militares avidi saepe turbarum adorti sunt Montium primum, qui divertebat in proximo, levi corpore senem atque morbosum, et hirsutis resticulis cruribus eius innexis divaricaturn sine spiramento ullo ad usque praetorium traxere praefecti.
Tempore quo primis auspiciis in mundanum fulgorem surgeret victura dum erunt homines Roma, ut augeretur sublimibus incrementis, foedere pacis aeternae Virtus convenit atque Fortuna plerumque dissidentes, quarum si altera defuisset, ad perfectam non venerat summitatem.
Et quoniam inedia gravi adflictabantur, locum petivere Paleas nomine, vergentem in mare, valido muro firmatum, ubi conduntur nunc usque commeatus distribui militibus omne latus Isauriae defendentibus adsueti. circumstetere igitur hoc munimentum per triduum et trinoctium et cum neque adclivitas ipsa sine discrimine adiri letali, nec cuniculis quicquam geri posset, nec procederet ullum obsidionale commentum, maesti excedunt postrema vi subigente maiora viribus adgressuri.
Exsistit autem hoc loco quaedam quaestio subdifficilis, num quando amici novi, digni amicitia, veteribus sint anteponendi, ut equis vetulis teneros anteponere solemus. Indigna homine dubitatio! Non enim debent esse amicitiarum sicut aliarum rerum satietates; veterrima quaeque, ut ea vina, quae vetustatem ferunt, esse debet suavissima; verumque illud est, quod dicitur, multos modios salis simul edendos esse, ut amicitiae munus expletum sit.
Inter quos Paulus eminebat notarius ortus in Hispania, glabro quidam sub vultu latens, odorandi vias periculorum occultas perquam sagax. is in Brittanniam missus ut militares quosdam perduceret ausos conspirasse Magnentio, cum reniti non possent, iussa licentius supergressus fluminis modo fortunis conplurium sese repentinus infudit et ferebatur per strages multiplices ac ruinas, vinculis membra ingenuorum adfligens et quosdam obterens manicis, crimina scilicet multa consarcinando a veritate longe discreta. unde admissum est facinus impium, quod Constanti tempus nota inusserat sempiterna.
Quare talis improborum consensio non modo excusatione amicitiae tegenda non est sed potius supplicio omni vindicanda est, ut ne quis concessum putet amicum vel bellum patriae inferentem sequi; quod quidem, ut res ire coepit, haud scio an aliquando futurum sit. Mihi autem non minori curae est, qualis res publica post mortem meam futura, quam qualis hodie sit.
Mensarum enim voragines et varias voluptatum inlecebras, ne longius progrediar, praetermitto illuc transiturus quod quidam per ampla spatia urbis subversasque silices sine periculi metu properantes equos velut publicos signatis quod dicitur calceis agitant, familiarium agmina tamquam praedatorios globos post terga trahentes ne Sannione quidem, ut ait comicus, domi relicto. quos imitatae matronae complures opertis capitibus et basternis per latera civitatis cuncta discurrunt.
Emensis itaque difficultatibus multis et nive obrutis callibus plurimis ubi prope Rauracum ventum est ad supercilia fluminis Rheni, resistente multitudine Alamanna pontem suspendere navium conpage Romani vi nimia vetabantur ritu grandinis undique convolantibus telis, et cum id inpossibile videretur, imperator cogitationibus magnis attonitus, quid capesseret ambigebat.
Circa hos dies Lollianus primae lanuginis adulescens, Lampadi filius ex praefecto, exploratius causam Maximino spectante, convictus codicem noxiarum artium nondum per aetatem firmato consilio descripsisse, exulque mittendus, ut sperabatur, patris inpulsu provocavit ad principem, et iussus ad eius comitatum duci, de fumo, ut aiunt, in flammam traditus Phalangio Baeticae consulari cecidit funesti carnificis manu.
Eminuit autem inter humilia supergressa iam impotentia fines mediocrium delictorum nefanda Clematii cuiusdam Alexandrini nobilis mors repentina; cuius socrus cum misceri sibi generum, flagrans eius amore, non impetraret, ut ferebatur, per palatii pseudothyrum introducta, oblato pretioso reginae monili id adsecuta est, ut ad Honoratum tum comitem orientis formula missa letali omnino scelere nullo contactus idem Clematius nec hiscere nec loqui permissus occideretur.
Horum adventum praedocti speculationibus fidis rectores militum tessera data sollemni armatos omnes celeri eduxere procursu et agiliter praeterito Calycadni fluminis ponte, cuius undarum magnitudo murorum adluit turres, in speciem locavere pugnandi. neque tamen exiluit quisquam nec permissus est congredi. formidabatur enim flagrans vesania manus et superior numero et ruitura sine respectu salutis in ferrum.
Eo adducta re per Isauriam, rege Persarum bellis finitimis inligato repellenteque a conlimitiis suis ferocissimas gentes, quae mente quadam versabili hostiliter eum saepe incessunt et in nos arma moventem aliquotiens iuvant, Nohodares quidam nomine e numero optimatum, incursare Mesopotamiam quotiens copia dederit ordinatus, explorabat nostra sollicite, si repperisset usquam locum vi subita perrupturus.
Post quorum necem nihilo lenius ferociens Gallus ut leo cadaveribus pastus multa huius modi scrutabatur. quae singula narrare non refert, me professione modum, quod evitandum est, excedamus.
Ut enim quisque sibi plurimum confidit et ut quisque maxime virtute et sapientia sic munitus est, ut nullo egeat suaque omnia in se ipso posita iudicet, ita in amicitiis expetendis colendisque maxime excellit. Quid enim? Africanus indigens mei? Minime hercule! ac ne ego quidem illius; sed ego admiratione quadam virtutis eius, ille vicissim opinione fortasse non nulla, quam de meis moribus habebat, me dilexit; auxit benevolentiam consuetudo. Sed quamquam utilitates multae et magnae consecutae sunt, non sunt tamen ab earum spe causae diligendi profectae.
Excogitatum est super his, ut homines quidam ignoti, vilitate ipsa parum cavendi ad colligendos rumores per Antiochiae latera cuncta destinarentur relaturi quae audirent. hi peragranter et dissimulanter honoratorum circulis adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
Unde Rufinus ea tempestate praefectus praetorio ad discrimen trusus est ultimum. ire enim ipse compellebatur ad militem, quem exagitabat inopia simul et feritas, et alioqui coalito more in ordinarias dignitates asperum semper et saevum, ut satisfaceret atque monstraret, quam ob causam annonae convectio sit impedita.
Haec ubi latius fama vulgasset missaeque relationes adsiduae Gallum Caesarem permovissent, quoniam magister equitum longius ea tempestate distinebatur, iussus comes orientis Nebridius contractis undique militaribus copiis ad eximendam periculo civitatem amplam et oportunam studio properabat ingenti, quo cognito abscessere latrones nulla re amplius memorabili gesta, dispersique ut solent avia montium petiere celsorum.
Et quia Mesopotamiae tractus omnes crebro inquietari sueti praetenturis et stationibus servabantur agrariis, laevorsum flexo itinere Osdroenae subsederat extimas partes, novum parumque aliquando temptatum commentum adgressus. quod si impetrasset, fulminis modo cuncta vastarat. erat autem quod cogitabat huius modi.
Post haec indumentum regale quaerebatur et ministris fucandae purpurae tortis confessisque pectoralem tuniculam sine manicis textam, Maras nomine quidam inductus est ut appellant Christiani diaconus, cuius prolatae litterae scriptae Graeco sermone ad Tyrii textrini praepositum celerari speciem perurgebant quam autem non indicabant denique etiam idem ad usque discrimen vitae vexatus nihil fateri conpulsus est.
Eodem tempore etiam Hymetii praeclarae indolis viri negotium est actitatum, cuius hunc novimus esse textum. cum Africam pro consule regeret Carthaginiensibus victus inopia iam lassatis, ex horreis Romano populo destinatis frumentum dedit, pauloque postea cum provenisset segetum copia, integre sine ulla restituit mora.
Nihil morati post haec militares avidi saepe turbarum adorti sunt Montium primum, qui divertebat in proximo, levi corpore senem atque morbosum, et hirsutis resticulis cruribus eius innexis divaricaturn sine spiramento ullo ad usque praetorium traxere praefecti.
Tempore quo primis auspiciis in mundanum fulgorem surgeret victura dum erunt homines Roma, ut augeretur sublimibus incrementis, foedere pacis aeternae Virtus convenit atque Fortuna plerumque dissidentes, quarum si altera defuisset, ad perfectam non venerat summitatem.
Et quoniam inedia gravi adflictabantur, locum petivere Paleas nomine, vergentem in mare, valido muro firmatum, ubi conduntur nunc usque commeatus distribui militibus omne latus Isauriae defendentibus adsueti. circumstetere igitur hoc munimentum per triduum et trinoctium et cum neque adclivitas ipsa sine discrimine adiri letali, nec cuniculis quicquam geri posset, nec procederet ullum obsidionale commentum, maesti excedunt postrema vi subigente maiora viribus adgressuri.
Exsistit autem hoc loco quaedam quaestio subdifficilis, num quando amici novi, digni amicitia, veteribus sint anteponendi, ut equis vetulis teneros anteponere solemus. Indigna homine dubitatio! Non enim debent esse amicitiarum sicut aliarum rerum satietates; veterrima quaeque, ut ea vina, quae vetustatem ferunt, esse debet suavissima; verumque illud est, quod dicitur, multos modios salis simul edendos esse, ut amicitiae munus expletum sit.
Inter quos Paulus eminebat notarius ortus in Hispania, glabro quidam sub vultu latens, odorandi vias periculorum occultas perquam sagax. is in Brittanniam missus ut militares quosdam perduceret ausos conspirasse Magnentio, cum reniti non possent, iussa licentius supergressus fluminis modo fortunis conplurium sese repentinus infudit et ferebatur per strages multiplices ac ruinas, vinculis membra ingenuorum adfligens et quosdam obterens manicis, crimina scilicet multa consarcinando a veritate longe discreta. unde admissum est facinus impium, quod Constanti tempus nota inusserat sempiterna.
Quare talis improborum consensio non modo excusatione amicitiae tegenda non est sed potius supplicio omni vindicanda est, ut ne quis concessum putet amicum vel bellum patriae inferentem sequi; quod quidem, ut res ire coepit, haud scio an aliquando futurum sit. Mihi autem non minori curae est, qualis res publica post mortem meam futura, quam qualis hodie sit.
Mensarum enim voragines et varias voluptatum inlecebras, ne longius progrediar, praetermitto illuc transiturus quod quidam per ampla spatia urbis subversasque silices sine periculi metu properantes equos velut publicos signatis quod dicitur calceis agitant, familiarium agmina tamquam praedatorios globos post terga trahentes ne Sannione quidem, ut ait comicus, domi relicto. quos imitatae matronae complures opertis capitibus et basternis per latera civitatis cuncta discurrunt.
Emensis itaque difficultatibus multis et nive obrutis callibus plurimis ubi prope Rauracum ventum est ad supercilia fluminis Rheni, resistente multitudine Alamanna pontem suspendere navium conpage Romani vi nimia vetabantur ritu grandinis undique convolantibus telis, et cum id inpossibile videretur, imperator cogitationibus magnis attonitus, quid capesseret ambigebat.
Circa hos dies Lollianus primae lanuginis adulescens, Lampadi filius ex praefecto, exploratius causam Maximino spectante, convictus codicem noxiarum artium nondum per aetatem firmato consilio descripsisse, exulque mittendus, ut sperabatur, patris inpulsu provocavit ad principem, et iussus ad eius comitatum duci, de fumo, ut aiunt, in flammam traditus Phalangio Baeticae consulari cecidit funesti carnificis manu.
Eminuit autem inter humilia supergressa iam impotentia fines mediocrium delictorum nefanda Clematii cuiusdam Alexandrini nobilis mors repentina; cuius socrus cum misceri sibi generum, flagrans eius amore, non impetraret, ut ferebatur, per palatii pseudothyrum introducta, oblato pretioso reginae monili id adsecuta est, ut ad Honoratum tum comitem orientis formula missa letali omnino scelere nullo contactus idem Clematius nec hiscere nec loqui permissus occideretur.
Horum adventum praedocti speculationibus fidis rectores militum tessera data sollemni armatos omnes celeri eduxere procursu et agiliter praeterito Calycadni fluminis ponte, cuius undarum magnitudo murorum adluit turres, in speciem locavere pugnandi. neque tamen exiluit quisquam nec permissus est congredi. formidabatur enim flagrans vesania manus et superior numero et ruitura sine respectu salutis in ferrum.
Eo adducta re per Isauriam, rege Persarum bellis finitimis inligato repellenteque a conlimitiis suis ferocissimas gentes, quae mente quadam versabili hostiliter eum saepe incessunt et in nos arma moventem aliquotiens iuvant, Nohodares quidam nomine e numero optimatum, incursare Mesopotamiam quotiens copia dederit ordinatus, explorabat nostra sollicite, si repperisset usquam locum vi subita perrupturus.
Post quorum necem nihilo lenius ferociens Gallus ut leo cadaveribus pastus multa huius modi scrutabatur. quae singula narrare non refert, me professione modum, quod evitandum est, excedamus.
Ut enim quisque sibi plurimum confidit et ut quisque maxime virtute et sapientia sic munitus est, ut nullo egeat suaque omnia in se ipso posita iudicet, ita in amicitiis expetendis colendisque maxime excellit. Quid enim? Africanus indigens mei? Minime hercule! ac ne ego quidem illius; sed ego admiratione quadam virtutis eius, ille vicissim opinione fortasse non nulla, quam de meis moribus habebat, me dilexit; auxit benevolentiam consuetudo. Sed quamquam utilitates multae et magnae consecutae sunt, non sunt tamen ab earum spe causae diligendi profectae.
Excogitatum est super his, ut homines quidam ignoti, vilitate ipsa parum cavendi ad colligendos rumores per Antiochiae latera cuncta destinarentur relaturi quae audirent. hi peragranter et dissimulanter honoratorum circulis adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
\mainmatter
\pagestyle{mainmatter}
\setcounter{secnumdepth}{2}
\chapter{C'est le chapitre 1}
\section{La section 1}
Emensis itaque difficultatibus multis et nive obrutis callibus plurimis ubi prope Rauracum ventum est ad supercilia fluminis Rheni, resistente multitudine Alamanna pontem suspendere navium conpage Romani vi nimia vetabantur ritu grandinis undique convolantibus telis, et cum id inpossibile videretur, imperator cogitationibus magnis attonitus, quid capesseret ambigebat.
Circa hos dies Lollianus primae lanuginis adulescens, Lampadi filius ex praefecto, exploratius causam Maximino spectante, convictus codicem noxiarum artium nondum per aetatem firmato consilio descripsisse, exulque mittendus, ut sperabatur, patris inpulsu provocavit ad principem, et iussus ad eius comitatum duci, de fumo, ut aiunt, in flammam traditus Phalangio Baeticae consulari cecidit funesti carnificis manu.
Eminuit autem inter humilia supergressa iam impotentia fines mediocrium delictorum nefanda Clematii cuiusdam Alexandrini nobilis mors repentina; cuius socrus cum misceri sibi generum, flagrans eius amore, non impetraret, ut ferebatur, per palatii pseudothyrum introducta, oblato pretioso reginae monili id adsecuta est, ut ad Honoratum tum comitem orientis formula missa letali omnino scelere nullo contactus idem Clematius nec hiscere nec loqui permissus occideretur.
Horum adventum praedocti speculationibus fidis rectores militum tessera data sollemni armatos omnes celeri eduxere procursu et agiliter praeterito Calycadni fluminis ponte, cuius undarum magnitudo murorum adluit turres, in speciem locavere pugnandi. neque tamen exiluit quisquam nec permissus est congredi. formidabatur enim flagrans vesania manus et superior numero et ruitura sine respectu salutis in ferrum.
Eo adducta re per Isauriam, rege Persarum bellis finitimis inligato repellenteque a conlimitiis suis ferocissimas gentes, quae mente quadam versabili hostiliter eum saepe incessunt et in nos arma moventem aliquotiens iuvant, Nohodares quidam nomine e numero optimatum, incursare Mesopotamiam quotiens copia dederit ordinatus, explorabat nostra sollicite, si repperisset usquam locum vi subita perrupturus.
Post quorum necem nihilo lenius ferociens Gallus ut leo cadaveribus pastus multa huius modi scrutabatur. quae singula narrare non refert, me professione modum, quod evitandum est, excedamus.
Ut enim quisque sibi plurimum confidit et ut quisque maxime virtute et sapientia sic munitus est, ut nullo egeat suaque omnia in se ipso posita iudicet, ita in amicitiis expetendis colendisque maxime excellit. Quid enim? Africanus indigens mei? Minime hercule! ac ne ego quidem illius; sed ego admiratione quadam virtutis eius, ille vicissim opinione fortasse non nulla, quam de meis moribus habebat, me dilexit; auxit benevolentiam consuetudo. Sed quamquam utilitates multae et magnae consecutae sunt, non sunt tamen ab earum spe causae diligendi profectae.
Excogitatum est super his, ut homines quidam ignoti, vilitate ipsa parum cavendi ad colligendos rumores per Antiochiae latera cuncta destinarentur relaturi quae audirent. hi peragranter et dissimulanter honoratorum circulis adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
Unde Rufinus ea tempestate praefectus praetorio ad discrimen trusus est ultimum. ire enim ipse compellebatur ad militem, quem exagitabat inopia simul et feritas, et alioqui coalito more in ordinarias dignitates asperum semper et saevum, ut satisfaceret atque monstraret, quam ob causam annonae convectio sit impedita.
Haec ubi latius fama vulgasset missaeque relationes adsiduae Gallum Caesarem permovissent, quoniam magister equitum longius ea tempestate distinebatur, iussus comes orientis Nebridius contractis undique militaribus copiis ad eximendam periculo civitatem amplam et oportunam studio properabat ingenti, quo cognito abscessere latrones nulla re amplius memorabili gesta, dispersique ut solent avia montium petiere celsorum.
Et quia Mesopotamiae tractus omnes crebro inquietari sueti praetenturis et stationibus servabantur agrariis, laevorsum flexo itinere Osdroenae subsederat extimas partes, novum parumque aliquando temptatum commentum adgressus. quod si impetrasset, fulminis modo cuncta vastarat. erat autem quod cogitabat huius modi.
Post haec indumentum regale quaerebatur et ministris fucandae purpurae tortis confessisque pectoralem tuniculam sine manicis textam, Maras nomine quidam inductus est ut appellant Christiani diaconus, cuius prolatae litterae scriptae Graeco sermone ad Tyrii textrini praepositum celerari speciem perurgebant quam autem non indicabant denique etiam idem ad usque discrimen vitae vexatus nihil fateri conpulsus est.
Eodem tempore etiam Hymetii praeclarae indolis viri negotium est actitatum, cuius hunc novimus esse textum. cum Africam pro consule regeret Carthaginiensibus victus inopia iam lassatis, ex horreis Romano populo destinatis frumentum dedit, pauloque postea cum provenisset segetum copia, integre sine ulla restituit mora.
Nihil morati post haec militares avidi saepe turbarum adorti sunt Montium primum, qui divertebat in proximo, levi corpore senem atque morbosum, et hirsutis resticulis cruribus eius innexis divaricaturn sine spiramento ullo ad usque praetorium traxere praefecti.
Tempore quo primis auspiciis in mundanum fulgorem surgeret victura dum erunt homines Roma, ut augeretur sublimibus incrementis, foedere pacis aeternae Virtus convenit atque Fortuna plerumque dissidentes, quarum si altera defuisset, ad perfectam non venerat summitatem.
Et quoniam inedia gravi adflictabantur, locum petivere Paleas nomine, vergentem in mare, valido muro firmatum, ubi conduntur nunc usque commeatus distribui militibus omne latus Isauriae defendentibus adsueti. circumstetere igitur hoc munimentum per triduum et trinoctium et cum neque adclivitas ipsa sine discrimine adiri letali, nec cuniculis quicquam geri posset, nec procederet ullum obsidionale commentum, maesti excedunt postrema vi subigente maiora viribus adgressuri.
Exsistit autem hoc loco quaedam quaestio subdifficilis, num quando amici novi, digni amicitia, veteribus sint anteponendi, ut equis vetulis teneros anteponere solemus. Indigna homine dubitatio! Non enim debent esse amicitiarum sicut aliarum rerum satietates; veterrima quaeque, ut ea vina, quae vetustatem ferunt, esse debet suavissima; verumque illud est, quod dicitur, multos modios salis simul edendos esse, ut amicitiae munus expletum sit.
Inter quos Paulus eminebat notarius ortus in Hispania, glabro quidam sub vultu latens, odorandi vias periculorum occultas perquam sagax. is in Brittanniam missus ut militares quosdam perduceret ausos conspirasse Magnentio, cum reniti non possent, iussa licentius supergressus fluminis modo fortunis conplurium sese repentinus infudit et ferebatur per strages multiplices ac ruinas, vinculis membra ingenuorum adfligens et quosdam obterens manicis, crimina scilicet multa consarcinando a veritate longe discreta. unde admissum est facinus impium, quod Constanti tempus nota inusserat sempiterna.
Quare talis improborum consensio non modo excusatione amicitiae tegenda non est sed potius supplicio omni vindicanda est, ut ne quis concessum putet amicum vel bellum patriae inferentem sequi; quod quidem, ut res ire coepit, haud scio an aliquando futurum sit. Mihi autem non minori curae est, qualis res publica post mortem meam futura, quam qualis hodie sit.
Mensarum enim voragines et varias voluptatum inlecebras, ne longius progrediar, praetermitto illuc transiturus quod quidam per ampla spatia urbis subversasque silices sine periculi metu properantes equos velut publicos signatis quod dicitur calceis agitant, familiarium agmina tamquam praedatorios globos post terga trahentes ne Sannione quidem, ut ait comicus, domi relicto. quos imitatae matronae complures opertis capitibus et basternis per latera civitatis cuncta discurrunt.
Emensis itaque difficultatibus multis et nive obrutis callibus plurimis ubi prope Rauracum ventum est ad supercilia fluminis Rheni, resistente multitudine Alamanna pontem suspendere navium conpage Romani vi nimia vetabantur ritu grandinis undique convolantibus telis, et cum id inpossibile videretur, imperator cogitationibus magnis attonitus, quid capesseret ambigebat.
Circa hos dies Lollianus primae lanuginis adulescens, Lampadi filius ex praefecto, exploratius causam Maximino spectante, convictus codicem noxiarum artium nondum per aetatem firmato consilio descripsisse, exulque mittendus, ut sperabatur, patris inpulsu provocavit ad principem, et iussus ad eius comitatum duci, de fumo, ut aiunt, in flammam traditus Phalangio Baeticae consulari cecidit funesti carnificis manu.
Eminuit autem inter humilia supergressa iam impotentia fines mediocrium delictorum nefanda Clematii cuiusdam Alexandrini nobilis mors repentina; cuius socrus cum misceri sibi generum, flagrans eius amore, non impetraret, ut ferebatur, per palatii pseudothyrum introducta, oblato pretioso reginae monili id adsecuta est, ut ad Honoratum tum comitem orientis formula missa letali omnino scelere nullo contactus idem Clematius nec hiscere nec loqui permissus occideretur.
Horum adventum praedocti speculationibus fidis rectores militum tessera data sollemni armatos omnes celeri eduxere procursu et agiliter praeterito Calycadni fluminis ponte, cuius undarum magnitudo murorum adluit turres, in speciem locavere pugnandi. neque tamen exiluit quisquam nec permissus est congredi. formidabatur enim flagrans vesania manus et superior numero et ruitura sine respectu salutis in ferrum.
Eo adducta re per Isauriam, rege Persarum bellis finitimis inligato repellenteque a conlimitiis suis ferocissimas gentes, quae mente quadam versabili hostiliter eum saepe incessunt et in nos arma moventem aliquotiens iuvant, Nohodares quidam nomine e numero optimatum, incursare Mesopotamiam quotiens copia dederit ordinatus, explorabat nostra sollicite, si repperisset usquam locum vi subita perrupturus.
Post quorum necem nihilo lenius ferociens Gallus ut leo cadaveribus pastus multa huius modi scrutabatur. quae singula narrare non refert, me professione modum, quod evitandum est, excedamus.
Ut enim quisque sibi plurimum confidit et ut quisque maxime virtute et sapientia sic munitus est, ut nullo egeat suaque omnia in se ipso posita iudicet, ita in amicitiis expetendis colendisque maxime excellit. Quid enim? Africanus indigens mei? Minime hercule! ac ne ego quidem illius; sed ego admiratione quadam virtutis eius, ille vicissim opinione fortasse non nulla, quam de meis moribus habebat, me dilexit; auxit benevolentiam consuetudo. Sed quamquam utilitates multae et magnae consecutae sunt, non sunt tamen ab earum spe causae diligendi profectae.
Excogitatum est super his, ut homines quidam ignoti, vilitate ipsa parum cavendi ad colligendos rumores per Antiochiae latera cuncta destinarentur relaturi quae audirent. hi peragranter et dissimulanter honoratorum circulis adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
\end{document}
A:
The following seems to achieve what you're after. Here's a run-down of the solution approach:
Break out the \*mark macros from the frontmatter page style into a separate \frontmattermarks macro
\newcommand{\frontmattermarks}{%
\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\ ##1}}{}}
\renewcommand{\sectionmark}[1]{\markright{##1}}
}
which you then use after setting \pagestyle{frontmatter}.
Here is a complete minimal example showing the suggestions above.
\documentclass[a4paper,12pt]{book}
\usepackage[top=2.5cm, bottom=2.5cm, right=2.5cm, left=2.5cm, headheight = 20pt]{geometry}
\usepackage{xcolor,graphicx,pifont,xspace,setspace,mathptmx,lipsum,etoolbox,fancyhdr}
\newcommand{\frontmattermarks}{%
\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\ ##1}}{}}
\renewcommand{\sectionmark}[1]{\markright{##1}}
}
\fancypagestyle{frontmatter}{%
\fancyhf{}
\renewcommand{\headrulewidth}{.4pt}
\renewcommand{\footrulewidth}{0pt}
\fancyhead[LO,RE]{\thepage}
\fancyhead[RO]{\leftmark}
\fancyhead[LE]{\rightmark}
}
\fancypagestyle{mainmatter}{%
\fancyhf{}
\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\chaptername\ \thechapter.\ ##1}}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection\ ##1}}
\renewcommand{\headrulewidth}{.4pt}
\renewcommand{\footrulewidth}{0pt}
\fancyhead[LO,RE]{\thepage}
\fancyhead[RO]{\leftmark}
\fancyhead[LE]{\rightmark}
}
%************************************************
% *
% COMMANDES PERSONNALISÉES *
% *
%************************************************
\begin{document}
\frontmatter
\pagestyle{frontmatter}
\setcounter{secnumdepth}{0}
\frontmattermarks
\chapter{Introduction}
\section{Première section}
\lipsum[1-20]
\mainmatter
\pagestyle{mainmatter}
\setcounter{secnumdepth}{2}
\chapter{C'est le chapitre 1}
\section{La section 1}
\lipsum[1-20]
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to bring back soft keyboard after hiding using InputMethodManager
I'm new to Android Programming so was just making a simple app.
In the app I have an EditText component which slides up as the keyboard pops up and i don't want it to slide up so i searched for it and got an work around of using,
In OnCreate method
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
But the issue was after using this line the EditText was in place after clicking on enter the keyboard didn't went away.So, I search for it and got this method for hiding the keyboard
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
But now the issue is the keyboard is hiding successfully but is not visible after i re click on EditText.So, I was searching on the net but no luck and started started searching methods in Android Studio for making the keyboard visible and figured out some what this
public static void showSoftKeyboard(Activity activity){
InputMethodManager inputMethodManager1 =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager1.showSoftInputFromInputMethod(
activity.getCurrentFocus().getWindowToken(), 0);
But it's not working is throwing NullPointerException.
So please can anyone help me on this.
And also is it there any alternative for keeping the EditText on its position without sliding up. So that there is no need of applying this hide and show method and if not can you please tell me how to bring back the keyboard.
A:
Comment your logic, and please try with below approach,
Write below line in your activity tag in Android Manifest like below
<activity android:name=".yourActivityName"
android:windowSoftInputMode="adjustPan">
</activity>
Then add this line to your edittext xml in your layout
android:imeOptions="actionDone"
like below
<EditText
android:id="@+id/edt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edittext"
android:singleLine="true"
android:maxLines="1"
android:imeOptions="actionDone"/>
Or set it from your code
yourEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
On click on done button in soft keyboard, it will be automatically close.
And below is the code of click event of Soft Keyboard done button.
yourEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_DONE){
// write your code here
}
return false;
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Стоит ли работать со структурой, содержащей внутри себя другие структуры, если потом работать с этой структурой через двусвязный список?
Получил задание по курсовой - реализовать на С++ динамическую структуру, которая содержит информацию: факультет, группа, число студентов, число стипендий, средний балл группы, фамилия старосты через двусвязные списки.
Сейчас хочу выбрать, как стоит представить узел списка - как структуру, содержащую все эти поля, т.е. представляющую собой отдельную группу (назову ее простой) или же как структуру, которая содержит в себе поле названия факультета и вложенную структуру с группами, которая в свою очередь уже содержит поля относящиеся к группе(назовем ее сложной).
Поскольку не знаком с тонкостями реализации двусвязных списков (без использования классов и STL, так как предмет - не ООП, т.е. делать все вручную), мне хотелось бы понимать, насколько сложнее будет реализовать задачу с узлом, представляющим собой сложную структуру. Сложный вариант мне нравится больше, но из-за недостатка опыта, опасаюсь, что не хватит знаний его реализовать и я просто потеряю время. Подскажите, как лучше сделать, и если есть возможность, подкиньте материалов о том, как реализовывать двусвязный список (не в общем случае, где данные представляют собой инты, а в подобном моему), и как делать это со "сложной" структурой.
A:
А это точно C++?
Если нельзя использовать конструкторы, деструкторы, операторы, то проще писать на Си наверное. Там как раз будут только структуры.
Про двусвязные списки - вместо int используете указатели на ваши структуры, вам нужно разобраться как выделять память под структуры, как освобождать эту память, и всё (new/delete плюсовые или malloc/free сишные).
Дальше просто плодите структуры под ваши сущности, и пишите функции которые их создают, заполняют, удаляют и т.п.
Судя по заданию от Вас требуется сделать список групп, то есть одна структура описывает группу (простая Вашими словами), другая(ие) структуры требуются для создания двусвязного списка из этих структур.
Пример:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct{
int a;
char* text;
}data;
data* create_data(int a, const char* text){
data* ret = malloc(sizeof(data));
ret->a = a;
size_t text_len = strlen(text);
ret->text = malloc(sizeof(char) * (text_len + 1));
ret->text = strcpy(ret->text, text);
return ret;
}
void free_data(data* d){
if (d->text != NULL){
free(d->text);
d->text = NULL;
}
}
typedef struct node{
data* d;
struct node* next;
struct node* prev;
}node;
node* create_node(data* d){
node* ret = malloc(sizeof(node));
ret->next = NULL;
ret->prev = NULL;
ret->d = d;
return ret;
}
void free_node(node* n){
if (n->d != NULL){
free_data(n->d);
free(n->d);
n->d = NULL;
}
}
typedef struct{
node* head;
node* tail;
}linked_list;
linked_list* create_list(){
linked_list* ret = malloc(sizeof(linked_list));
ret->head = NULL;
ret->tail = NULL;
return ret;
}
void free_list(linked_list* l){
node* cur = l->head;
while (cur != NULL){
free_node(cur);
cur = cur->next;
if (cur != NULL){
if (cur->prev != NULL)
free(cur->prev);
}
}
}
linked_list* add_to_tail(linked_list* l, data* d){
node* new_node = create_node(d);
new_node->next = NULL;
new_node->prev = l->tail;
if (l->tail == NULL){
l->tail = new_node;
l->head = new_node;
}else{
l->tail->next = new_node;
l->tail = new_node;
}
return l;
}
void print_list(linked_list* l){
node* cur = l->head;
while (cur != NULL){
printf("node a:%d text:%s\n", cur->d->a, cur->d->text);
cur = cur->next;
}
return;
}
int main()
{
linked_list* list = create_list();
for (int i = 0; i < 10; i++){
list = add_to_tail(list, create_data(i, "hello"));
}
print_list(list);
free_list(list);
free(list);
return 0;
}
Вывод:
node a:0 text:hello
node a:1 text:hello
node a:2 text:hello
node a:3 text:hello
node a:4 text:hello
node a:5 text:hello
node a:6 text:hello
node a:7 text:hello
node a:8 text:hello
node a:9 text:hello
| {
"pile_set_name": "StackExchange"
} |
Q:
What does this awk command do?
What does this awk command do?
awk 'NR > 1 {for(x=1;x<=NF;x++) if(x == 1 || (x >= 4 && x % 2 == 0))
printf "%s", $x (x == NF || x == (NF-1) ? "\n":"\t")}' depth.txt
> depth_concoct.txt
I think
NR > 1 means it starts from second line,
for(x=1;x<=NF;x++) means for every fields,
if(x == 1 || (x >= 4 && x % 2 == 0)) means if x equals 1 or (I don' understand the codes from this part and so on)
and I know that the input file for awk is depth.txt and the output of awk will be saved to depth_concoct.txt.
What does the codes in the middle mean?
A:
$ awk '
NR > 1 { # starting from the second record
for(x=1;x<=NF;x++) # iterate every field
if(x == 1 || (x >= 4 && x % 2 == 0)) # for 1st, 4th and every even-numbered field after 4th
printf "%s", # print the field and after it
$x (x == NF || x == (NF-1) ? "\n":"\t") # a tab or a newline if its the last field
}' depth.txt > depth_concoct.txt
(x == NF || x == (NF-1) ? "\n":"\t") is called conditional operator, in this context it's basically streamlined version of:
if( x == NF || x == (NF-1) ) # if this is the last field to be printed
printf "\n" # finish the record with a newline
else # else
printf "\t"` # print a tab after the field
| {
"pile_set_name": "StackExchange"
} |
Q:
Will I need a transit visa for transit in Stockholm in a trip from Turkey to Russia?
I have a flight from Istanbul (Turkey) to Saint Petersburg in Russia. I have two nationalities
I booked my ticket on my Syrian passport because I entered Turkey with it, and I will carry my Russian passport with me to enter Russia.
My flight is from Istanbul to Stockholm then after 3 hours I will change the plan to heading to Saint Petersburg.
Shall I need a transit visa for three hours in Stockholm?
A:
According to Timatic, you don't need a transit visa because you transit to another country:
Visa required, except for holders of a valid "D" visa issued by
another Schengen Member State For details, click here . TWOV (Transit
Without Visa): Visa required, except for Holders of onward tickets
transiting
For details, click here on the same calendar day *Note: TWOV is not
possible when arriving from a non-Schengen Member State AND departing
to a Schengen Member State For details, click here
| {
"pile_set_name": "StackExchange"
} |
Q:
Django Rest Framework writable nested field using create()
I'm trying to write a create method that will write my nested fields but am finding that the nested object isn't written.
This is the sample I was using:
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('username', 'email', 'profile')
def create(self, validated_data):
profile_data = validated_data.pop('profile')
user = User.objects.create(**validated_data)
Profile.objects.create(user=user, **profile_data)
return user
But I'm failing to understand what the user=user refers to.
Here is my code:
class MessagesSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(source='pk', read_only=True)
suggested_songs = SongSerializer()
class Meta:
model = Messages
fields = ('id','owner','url','suggested_songs',)
#fields = ('id','url','suggested_songs',)
def create(self, validated_data):
song_data = validated_data.pop('suggested_songs')
message = Messages.objects.create(**validated_data)
Song.objects.create(**song_data)
return message
class SongSerializer(serializers.HyperlinkedModelSerializer):
#id = serializers.IntegerField(source='pk', read_only=True)
class Meta:
model = Song
fields = ('id','title','artist','album','albumId','num_votes','cleared')
read_only_fields = ('song_id')
class Messages(models.Model):
owner = models.OneToOneField(User, primary_key=True, related_name='user_messages', editable=False) #TODO, change owner to 'To'
#suggested_songs = models.ManyToManyField(Song, related_name='suggested_songs')
suggested_songs = models.ForeignKey(Song, null=True, blank=True)
# If a user is added, this runs.
@receiver(post_save, sender=User)
def create_friend_for_user(sender, instance=None, created=False, **kwargs):
if created:
Messages.objects.get_or_create(owner=instance)
# Same as above, but for deletion
@receiver(pre_delete, sender=User)
def delete_friend_for_user(sender, instance=None, **kwargs):
if instance:
Messages.objects.get(owner=instance).delete()
class Song(models.Model):
"""
A model which holds information about the songs.
"""
#song_id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=150, blank=True, default='')
artist = models.CharField(max_length=150, blank=True, default='')
album = models.CharField(max_length=150, blank=True, default='')
albumId = models.CharField(max_length=150, blank=True, default='')
num_votes = models.IntegerField(default=0, blank=True)
cleared = models.BooleanField(default=False, blank=True)
class Meta:
ordering = ('title',)
#managed=True
A:
I think that the issue might be in the MessageSerializer.create method:
def create(self, validated_data):
# here you are popping the suggested songs
song_data = validated_data.pop('suggested_songs')
# so when you create the message here the foreign key is set to NULL
message = Messages.objects.create(**validated_data)
# and here you create the Song instance correctly but it is not
# associated with the message
Song.objects.create(**song_data)
return message
You need to pass the foreign key to the Messages.create method like in the example you have.
def create(self, validated_data):
song_data = validated_data.pop('suggested_songs')
song = Song.objects.create(**song_data)
# song need to be created first because the foreign key is in
# the Messages model
message = Messages.objects.create(suggested_songs=song, **validated_data)
return message
I hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I enable a greyed out datasheet button?
On my list the datasheet button is greyed out. How do I go about enabling it?
A:
Just on the off chance: You are using Internet Explorer, right?
If not, I'm afraid this is an IE-specific function; as I discovered when trying to pry it open with Chrome's dev tools.
A:
As SPDoctor stated - it sounds like an issue with 64 bit install of Office.
You cannot view a list in Datasheet view after you install the 64-bit version of Office 2010
Try installing the 2007 Office System Driver: Data Connectivity Components
A:
Do you have the Microsoft Office client software (32-bit version) installed on your computer? This is necessary to support this function. You may also need to enable ActiveX controls if this is disabled in your browser.
| {
"pile_set_name": "StackExchange"
} |
Q:
What exactly do I have to pay attention for when choosing Windows Hosting Provider?
This is my first time choosing a hosting company. It is for a web site made in asp.net mvc3.
So I was thinking choosing a provider would be easy since I found this page
http://www.microsoft.com/web/Hosting/Home which contains hosting offers.
Now hours later, I am still searching.
The reason is that as soon as I start investigating about particular company, something stands out that I do not like.
Here are some examples what I noticed when checking various companies in more detail:
Company "about us" page is lacking in information about their company.
Few of them had just general description what they do and nothing else, while some others had information like company name but had no address.
Checking company name in Business Registry Searches gave no results.
Two of the companies I checked had both company name and address but I was unable to find them in the registry.
Putting company domain into Google gave mostly results from that domain or web hosting review sites but not much else.
I am assuming that good companies should have search results from other sites too.
Low Alexa Traffic Rank.
There was one company which had a site that looked very professional but their alexa traffic ranking was like 2 million.
Are there any other factors I should pay attention to when choosing a hosting company?
Do I have legitimate concerns or am I just too paranoid?
A:
None of the concerns you identified seem particularly relevant for choosing a hosting company, especially traffic rank. Hosting companies host websites that gain traffic; they don't provide content themselves. Consequently, I wouldn't expect them to rank particularly high in a Google or Alexa search.
I would be more concerned with things like:
What hosting features do you provide? Can I run SSMS and access my SQL Server instance directly? What versions of ASP.NET MVC do you support, and do you keep them current? Can I expect my application DLL to run properly in your hosting environment?
How well does your service scale, and what are the service options? Many people choose the cheapest service they can find, and then are surprised when their website suddenly falls down because it's being accessed by more than a dozen people (a good problem to have, by the way). Some providers allow you to have your own machine; you can even configure it yourself, if you have the need.
What does your security model look like? Do you run regular security sweeps of your equipment and software? How do you protect your customers from hackers? What if I am hosting data that is subject to privacy concerns under HIPAA, or the Sarbanes Oxley act?
What is your customer service like? Can I readily contact you if I have a genuine problem?
If you're just starting out with a basic site, I would try and find genuine recommendations from people who are hosting their own ASP.NET MVC website. Small companies are just fine, and may actually be better for a little website. Avoid hosting with a phone company.
A:
Having chosen hosts a number of times, my recommendations:
(1) Avoid both the high end and low end prices. Low enders don't have the staff to support their customers, and high enders can be absurdly higher priced than the crowd.
(2) Don't overbuy capacity you don't need. You can always shift hosts or packages when you find you actually do need more. If you operate your site a few years, you'll end up changing anyway for one reason or another. There is no "final solution".
| {
"pile_set_name": "StackExchange"
} |
Q:
Display CR and LF rather than "EOL" in ':set list'
Rather than choosing one character to be displayed as the EOL character, I'd like one to display for both CR and LF separately and regardless of if the file is unix or dos. Is this possible?
A:
With some caveats, you can do this using Vim's binary mode. It seems you might want to use the command
vim -b +'set list' somefile
Alternatively, you can put the following in your .vimrc:
:set binary
:set list
The important thing is that binary mode must get set before the file in question is read into a buffer. Once Vim has read the file in, it's too late; this trick relies on changing how Vim reads the file in. Specifically, what you need is for Vim to not attempt to guess the file's particular type of <EOL>.
Binary mode does what you want, disabling this automatic line-separator detection, but it does quite a few other things as well:
sets 'textwidth' to 0
sets 'wrapmargin' to 0
unsets 'modeline'
unsets 'expandtab'
So you might not want to have this in your .vimrc; it might be better to use the command-line version, and only for those files where you need this special kind of display.
For more information:
:help 'binary'
:help edit-binary
:help file-read
:help file-formats
:help 'fileformat'
| {
"pile_set_name": "StackExchange"
} |
Q:
excel concatenate text with newline character and changing format of few lines
I have excel sheet as follow
cell a1 has text- 1234
cell d1 has text- abc.com
cell f1 has text- AZ, USA 85663
I created a formula in cell i1 as =CONCATENATE("Gaaa Reference No. I-20-",A1,CHAR(10),D1,CHAR(10),F1)
Then used steps in this link to concatenate three columns with newline character in between lines.
I want the first line to be bold, second line in italics. The output should be times new roman font. I tried changing formatting of columns a and d, but it didnt help
How could I change the formatting? The current output is as below
I have an excel sheet with multiple rows populated. I would like to have same format for the entire column I
It seems that this requires VBA code. Please provide that
A:
Insert a new code module in VBA and use the following code...
Option Explicit
Sub FormatConcatColumn()
Dim i&, rows&, LF, v1, v2, v3, vOut, r As Range
rows = 60 '<-- change to 200 or however many rows you need
ReDim vOut(1 To rows, 1 To 1)
ReDim LF(1 To rows, 1 To 2)
With [a1].Resize(rows)
v1 = .Value2
v2 = .Offset(, 3).Value2
v3 = .Offset(, 5).Value2
For i = 1 To rows
vOut(i, 1) = v1(i, 1) & vbLf & v2(i, 1) & vbLf & v3(i, 1)
LF(i, 1) = Len(v1(i, 1))
LF(i, 2) = LF(i, 1) + Len(v2(i, 1))
Next
With .Offset(, 8)
.Clear
.Value2 = vOut
.Font.Name = "Times New Roman"
i = 0
For Each r In .Cells
i = i + 1
r.Characters(1, LF(i, 1)).Font.FontStyle = "Bold"
r.Characters(LF(i, 1) + 1, LF(i, 2) - 2).Font.FontStyle = "Italic"
DoEvents
Next
End With
End With
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Compiling njit nopython version of function fails due to data types
I'm writing a function in njit to speed up a very slow reservoir operations optimization code. The function is returning the maximum value for spill releases based on the reservoir level and gate availability. I am passing in a parameter size that specifies the number of flows to calculate (in some calls it's one and in some its many). I'm also passing in a numpy.zeros array that I can then fill with the function output. A simplified version of the function is written as follows:
import numpy as np
from numba import njit
@njit(cache=True)
def fncMaxFlow(elev, flag, size, MaxQ):
if (flag == 1): # SPOG2 running
if size==0:
if (elev>367.28):
return 861.1
else: return 0
else:
for i in range(size):
if((elev[i]>367.28) & (elev[i]<385)):
MaxQ[i]=861.1
return MaxQ
else:
if size==0: return 0
else: return MaxQ
fncMaxFlow(np.random.randint(368, 380, 3), 1, 3, np.zeros(3))
The error I'm getting:
Can't unify return type from the following types: array(float64, 1d, C), float64, int32
What is the reason for this? Is there any workaround or some step I'm missing so I can use numba to speed things up? This function and others like it are being called millions of times so they are a major factor in the computational efficiency. Any advice would help - I'm pretty new to python.
A:
A variable within a numba function must have consistent type including the return variable. In your code you can either return MaxQ (an array), 861.1 (a float) or 0 (an int).
You need to refactor this code so that it always returns a consistent type regardless of code path.
Also note that in several places where you are comparing a numpy array to a scalar (elev > 367.28), what you are getting back is an array of boolean values, which is going to cause you issues. Your example function doesn't run as a pure python function (dropping the numba decorator) because of this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using the Pythons email.message API, how do you remove a specific part of the message
I have email message with an unwanted attachment (a PKCS-7 signature in this particular case). I can detect the signature in the email with this piece of code:
payloads = mail.get_payload()
for index in xrange(len(payloads)):
if payloads[index].get_content_type() == "application/pkcs7-signature":
print("Found PKCS-7 Signature", index)
How would I remove this particular payload from the message? The email.message API seems to only have methods for reading and writing whole payloads: get_payload() and set_payload(). Neither of these allow specifying payload index of what to read or write.
A:
One possible solution:
def remove_signature(mail):
payload = mail.get_payload()
if isinstance(payload, list):
for part in payload:
if part.get_content_type().startswith('application/pkcs7-signature'):
payload.remove(part)
return mail
| {
"pile_set_name": "StackExchange"
} |
Q:
data-target is not working using bootstrap
Ho friends.
I am using navbar in Bootstarp. for collapsing a div element calling data-toogle and data-target attributes. but i don't find these attributes in my page because of these reason collapse is not working. can some one help what is missing in my code and why these attributes are not showing while typing these attributes.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="../Content/bootstrap.css" rel="stylesheet" />
<link href="../Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<link href="../Content/bootstrap-theme.css" rel="stylesheet" />
<script src="../Scripts/angular-ui-router.js"></script>
<script src="../Scripts/angular-ui-router.min.js"></script>
<script src="../Scripts/Collapse.JS"></script>
</head>
<body>
<div>
<nav class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-target="#mynavbar" data-toogle="collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="mynavbar">
<ul class="nav navbar-nav">
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Gallery</a></li>
<li><a href="">Contact</a></li>
</ul>
<ul class="nav navbar-right navbar-nav">
<li><a href="#">Login/SignUp</a></li>
</ul>
</div>
</nav>
</div>
</body>
</html>
A:
You have a typo in your button it says data-toogle it should say data-toggle.
<button type="button" class="navbar-toggle" data-target="#mynavbar" data-toggle="collapse">
| {
"pile_set_name": "StackExchange"
} |
Q:
Impact of semantics changes of Alloy 4.2 on exercise A.1.6 of the Alloy book?
According to the release notes for Alloy 4.2, there are semantics changes related to integers. These changes seem to have an impact on exercise A.1.6 of the Alloy book.
In this exercise, the following code is given as a basis (I added the "Int" at the very end to show my problem). When running the "show" predicate, the visualizer displays an instance, but this instance contains, in addition to integers, two more atoms "Univ0" and "Univ1".
module exercises/spanning
pred isTree(r: univ->univ) {}
pred spans(r1, r2: univ->univ) {}
pred show(r, t1, t2: univ->univ) {
spans[t1,r] and isTree[t1]
spans[t2,r] and isTree[t2]
t1 != t2
}
run show for 3 Int
What is the meaning of these two atoms "Univ0" and "Univ1"? Why are they there? They do not appear with the same code executed on Alloy 4.1.10.
A:
When there are no user-defined sigs, Alloy automatically synthesizes a new sig called "Univ". This is a convenient feature since it lets you write formulas over the whole universe without having to introduce any sigs.
When you explicitly give a scope for Int, then the universe will certainly contain all Int atoms within the given scope. If additionally there are no user-defined sigs, you'll end up having the synthesized Univ sig as well. It is debatable whether it makes sense to synthesize the Univ sig when a scope for Int is explicitly used.
To work around your problem, you have several options:
If you don't care what is the type of your graph nodes (i.e., you don't explicitly want the nodes to be Ints), then you can simply change the run command to say
run show for 3 instead of run show for 3 Int.
If you do that, you'll have no Int atoms, and only Univ atoms. If you don't like the Univ sig, simply introduce a new sig, e.g., sig Node {} in which case all atoms will be of type Node.
If you really want your graph to be over Ints only, you can change univ->univ to Int->Int in all your predicates.
If you really want your universe to contain only Int atoms (in which case you can keep univ->univ in your predicates), you can introduce a dummy signature and add a fact that ensures that its cardinality is zero.
sig Dummy {}
fact { no Dummy }
This small change will ensure that the Univ sig is not automatically synthesized and will not affect the rest of you model.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
hiding a control which has focus in ms access 2007
I have a combobox on a form. Clicking on a particular label should hide this combobox. The problem is that if the combobox has focus, clicking on the button which hides this combobox gives error.How can I resolve this runtime error?
A:
Move the focus. If necessary, create a very small control to receive the focus.
Me.SomeControlThatIsNotTheCombobox.SetFocus
Re Comments
Note that this label is not associated with a control.
Private Sub Label1_Click()
Me.Text1.SetFocus
Me.Label1.Visible = False
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to add an empty column with no values in the beginning of a .CSV file?
How do I add an empty column at the beginning of a .CSV file using awk? I am trying the following code, but that doesn't help.
awk '{",",print $0}' file1.csv > file2.csv
Please help...
A:
Another awk
awk '{print ","$0}' file1.csv > file2.csv
or
awk '{$0=","$0}1' file1.csv > file2.csv
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows .NET / Win32 UI development
I've been battling trying to figure out how to visually create a table. It's a weird table that is sortable by column but only rows are selectable.
For people using uTorrent it looks something like this
I can't find this anywhere in Visual Studio! If it's not avialiable, how would I go about creating it myself?
A:
Looks like a regular ListView with the View property = Details with FullRowSelect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Database for streets world wide?
I use the downloadable Geonames database for all countries, states, counties and cities in the world, but I wonder if there is a database for streets?
So you could pick: country -> state/department/district -> (county/region) -> city -> street in whatever country you like.
Because when I do a search for a street in Google Maps I can see all the upper levels (country/region/city). Is there a database you could download for MySQL for this?
There has to be a database for this, cause there are always national companies that provide this kind of information. Where did they get it from?
A:
Have you checked out OpenStreetMap? It is free and has a export screen that lets you download the data in XML and other formats.
Those concerned with the accruacy of the OpenStreetMap data may want to read what ITO has to say about OpenStreetMap's data for Haiti.
Enter OpenStreetMap, the wiki map of the world, CrisisMappers and an impromptu community of volunteers who collaborated to produce the most authoritative map of Haiti in existence.
If you have 5 minutes you may want to watch this TED video by Tim Berners-Lee talking about what is being done with OpenStreetMap data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to save layout_weight in an xml?
I need to change the layout_weight of 3 views in a layout, according to the physical size of the screen. The views have the weight of 0-1-0, but this has to change to 0.2-0.6-0.2 when the layout is used in an xlarge screen.
I tried saving the layout_weight inside different copies of the dimensions.xml (one in values/dimensions and an other one in values-xlarge/dimensions), but it looks like I cannot give a dimension without setting dp/px or w/e (cannot save a "raw" number like 1, or 0.2).
Is it possible to do via xml somehow, or do I have to work programmatically in order to achieve that?
A:
Try an integer resource file. It is very similar to dimensions.
http://developer.android.com/guide/topics/resources/more-resources.html
A:
Create a file in your corresponding values folders i.e. values, values-large, values-xlarge, .... Add a resources file with content similar to this example:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<item type="integer" name="layout_weight_xy">7</item>
</resources>
and then call
android:layout_weight="@integer/layout_weight_xy"
in your layout file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does setting a nulalble DateTime to DateTime.Max cause a pgsql parsing error?
When I set a nullable date time to DateTime.Max and save it to a database field of postgres type
timestamp without time zone
it saves it as
10000-01-01 00:00:00
Then when I reload a page that merely reads from this table I get the following error:
System.InvalidCastException: Specified cast is not valid.
a) Is DateTime? the correct C# conversion type?
b) What is the best way to set the DateTime value?
I checked the docs here http://www.postgresql.org/docs/9.2/static/datatype-datetime.html and it specifies the max value is 294276 AD... but that's lower than is currently set so it can't be that breaking it. I am using the latest version of NpgSql and entity framework
Many thanks
A:
The problem lies within your C# code. According to MSDN:
The DateTime.MaxValue field represents the largest possible value of
DateTime, which is December 31, 9999 in the Gregorian calendar.
Your date value is just above this value, hence the exception.
I would suggest explicitly saving a very large date value in the database, e.g. December 31, 9999, in case the date value is not available.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error in $_SERVER['HTTP_REFERER']
i just tried
echo $_SERVER['HTTP_REFERER'];
but it returned an error
Notice: Undefined index: HTTP_REFERER in C:\Program Files\....
What is the problem an why is it showing an error.
A:
This is because HTTP_REFERER is not set
you can try
if(isset($_SERVER['HTTP_REFERER']))
echo $_SERVER['HTTP_REFERER'];
else
echo 'HTTP_REFERER in not set';
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Numpy with pypy
I am using some numpy tools (mainly arrays) and I wanted to run the script with pypy, but i can't make it work.
The error that i get is: ImportError: No module named multiarray.
I checked if the multiarray.so file was in the core folder.
Can someone tell me if first: is possible to do what I am trying to do and second: How can I do it?
A:
I've just posted a blog post explaining what's the status and what's the plan. In short numpy will not work with PyPy's cpyext and even if it does, it would be too slow for usage.
A:
The other answers are quite old.
Here is the the completely unscientific measure of "implemented functions" on numpypy status page
Some posts from the pypy blog about numpy:
MAY 4, 2011
MAY 5, 2011
APRIL 17, 2012
SEPTEMBER 4, 2012
NOVEMBER 1, 2012
MARCH 18, 2013
MAY 11, 2013
DECEMBER 10, 2013
A:
Numpy status and build instruction has been changed recently. There is a special version of numpy which is ported to PyPy. If you want to get latest instruction just check PyPy blog for a latest article about Numpy. For the time of writing the latest instruction are in this post, which compiles to:
pip install git+https://bitbucket.org/pypy/numpy.git
For what is implemented and what not you can check this page: http://buildbot.pypy.org/numpy-status/latest.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I add an extension method to a LIST<>?
I have this code:
public static List<Phrase> selectedPhrases;
and
if (!App.selectedPhrases.Any(x => x.Viewed == false))
return;
Is there any way that I could change the way I declare selectedPhrases so that I could do that last check in this way:
if (App.selectedPhrases.AllViewed())
return;
I heard about extension methods but is that possible to create one for a List like in my code?
A:
You can write extension method on List, for your example, Phrase
public static class Extension
{
public static bool AllViewed(this List<Phrase> source)
{
return source.All(x=>x.Viewed)
}
}
Btw, You don't need to check !Any(x=>c.Viewed==false), there is the option to use .All() Extension method as shown in the code above
You can read more on the syntax of extension methods here.
You might be also interested to read on how Linq extension methods are implemented by looking at some of source code at referencesource .
| {
"pile_set_name": "StackExchange"
} |
Q:
URL Rewrite with 3 parameters for forum .htaccess
I am trying to URL Rewrite to the following URL
Http://***.com/index.php?p=forum&mod=view_posts&page=$3&name=$2&id=$1
Http://***.com/forum/{id}-{name}/{page}
Http://***.com/forum/1-Hello-World/1
I have tryed the following code and have had no joy
RewriteRule ^forum/([^-]+)-([^&]+)/([^-]+)$ index.php?p=forum&mod=view_posts&page=$3&orderby=$2&id=$1
Thanks
A:
That regex isn't very good: you see, the "([^&]+)" says: "one or more characters, up until the first ampersand", while you have no ampersands in the subject. Also, the "([^-]+)$" says "one or more characters before a hyphen", while you don't intend to end the subject with a hyphen.
Try this one:
^forum/([^-]+)-([^/]+)/(.+)$
But note that this actually captures any characters in the id and page positions, so you might be better off with
^forum/([0-9]+)-([^/]+)/([0-9]+)$
as that allows only numbers in those positions.
Also, you probably meant "index.php?p=forum&mod=view_posts&page=$3&name=$2&id=$1" instead of "index.php?p=forum&mod=view_posts&page=$3&orderby=$2&id=$1"
| {
"pile_set_name": "StackExchange"
} |
Q:
Коридор – это длинные сени (об истории слов)
По словам Карамзина, коридор (в конце XVIII века) – это длинные сени, слово достаточно новое, еще требует пояснения. Само же слово «сени» образовалось от русского "сень" - проход, галерея, навес, кров в XIV – XVI веках. Какое-то время они существовали вместе, но потом «сени» ушли из языка. Почему именно так сложилась история этих двух слов? Можно ли более точно указать временные пределы их существования и первое употребление в языке?
Примеры:
«Мне надлежало идти через длинные сени или коридор, где в печальном сумраке представились глазам моим распятия и лампады угасающие» [Н. М. Карамзин. Письма русского путешественника (1793)].
«…а падчерицу свою она вывела в сени и посадила в чулан под корыто, дабы король не мог ее увидеть [Сказка о Строевой дочери (1794-1795)].
Спасибо.
A:
Ну да, коридор - это длинные сени, если речь идёт о... первом этаже. А хоть бы даже цокольном.
А вот младенчик Тургенев коридором пробирался в сени: «Я находился в таком страхе, в таком ужасе, что ночью решил бежать. Я уже встал, потихоньку оделся и в потёмках пробрался по коридору в сени…»
Временные рамки трудно обозначить: где есть изба, там и сени будут. А где-то ещё и дома такие уцелели, с сенями, - их по-другому и не назвать.
А этимологически слово сѣнь восходит к праславянскому языку (тут и тут). Исконное то есть. И ещё не мёртвое.
Ф. И. Буслаев в «Исторической грамматике русского языка. Синтаксис»
писал: «...Одно и то же слово в различные времена, или по различным
наречиям одного и того же языка, имеет различные значения: так слово
сѣни в древнерусском имеет значение залы или жилой комнаты вообще
(откуда выражение: сенные девушки), а теперь означает, напротив того,
такую комнату, в которой не живут, но которая с надворья ведет к жилым
покоям...»
Нашла интересное на форуме:
...Сени, похоже, не всегда были просто холодным пристроем к избе. Вот,
например, что находится на сени в фольклоре:
Пошол-то Владимир на широкой двор:
У Чурила первы сени решетчатые,
У Чурила друти сени серебряные,
У Чурила третьи сени были на золоти.
Ко полуночи и двор поспел:
Три терема златоверховаты,
Да трои сени
косящетые,
Да трои сени решетчатые.
Хорошо в теремах изукрашено:
На
небе солнце — в тереме солнце,
На небе месяц — в тереме месяц,
На
небе звезды — в тереме звезды,
На небе заря — в тереме заря
И вся
красота поднебесная.
В таком контексте явно не просто бытовой чуланчик упоминается, скорее
это важный, парадный элемент дома...
У Даля:
Сенница или сень -
навес у дома на столбах, крытое крыльцо, галерея, балкон... и там же прихожая.
Исчезли из языка сени в значении дом вообще; судебное место; архиерейское подворье; паперть; княжий дворец.
Справка о сенях на сегодняшний день:
А вот это уже похоже на современный коридор:
Сени с переходами встарь связывали разные части барских хором и
примыкали к терему...
С коридором - проще.
Лев Успенский:
КОРИДОР
Если перевести буквально, получится "бегалище". Слово это пришло к
нам из Франции или Германии, но в его основе лежит латинское
"куррэрэ": в Италии оно дало слово "corridore" - длинное узкое
помещение, галерея. Вам, вероятно, попадалось в литературе испанское
слово "коррида" - "бой быков"? Оно того же корня и, собственно, значит
"беготня".
Да, ещё как разговорное фиксируется обзывание городской прихожей коридором, - незачот... (По ссылке - все лексические значения.)
Коридор в русском лет на семьсот моложе сеней, год его рождения зафиксирован:
Происходит от итал. corridore «бегун», от correre «бежать», далее из
лат. currere «бегать, бежать», из праиндоевр. *kers- «бежать». Русск.
коридор — впервые в 1710 г.; заимств. через нем. Korridor или
франц. corridor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Textarea readonly but change background color back to white
I am trying to make a textarea readonly but do not like the gray background and want to make it white again... Is this possible because everything I am trying fails and it stays gray.
http://jsfiddle.net/ma42koz3/
HTML
<div class="col-xs-6">
<div class="row">
<div id="DToday" class="col-xs-12">
<label class="centered" for="DueToday">DUE TODAY @ 5:00</label>
<textarea type="text" name="DueToday" id="DueToday" class="form-control" rows="7"></textarea>
</div>
<div id="DTmrw" class="col-xs-12">
<label class="centered" for="DueTmrw">DUE <span id="delivery-date"></span> @ 5:00</label>
<textarea type="text" name="DueTmrw" id="DueTmrw" class="form-control" rows="7"></textarea>
</div>
</div>
</div>
JS
$(document).ready(function() {
$('#DueToday').attr('readonly', true);
$('#DueToday').addClass('input-disabled');
$('#DueTmrw').attr('readonly', true);
$('#DueTmrw').addClass('input-disabled');
});
CSS
.input-disabled{
background-color:#FFF;
}
A:
Use !important in your rule in order to override the browsers default value:
.input-disabled{
background-color:#FFF !important;
}
FIDDLE
A:
Try this http://jsfiddle.net/ma42koz3/2/
CSS
.form-control[disabled], .form-control[readonly], fieldset[disabled] .form-control {
background-color: white;
}
EDIT:
You can add class for example no-grayon textarea you don't want to be gray http://jsfiddle.net/ma42koz3/4/
and use this
CSS
.form-control[readonly].no-gray {
background-color:white;
}
HTML
<textarea type="text" name="DueToday" id="DueToday" class="form-control no-gray" rows="7"></textarea>
| {
"pile_set_name": "StackExchange"
} |
Q:
blogdown::serve_site() throws 'html_dependency not found' error | htmlwidgets threejs
While trying to re-build an old .Rmd file, with (only) an updated header-info i.e. blog-categories, I'm getting this error:
Error: path for html_dependency not found: C:/Users/Username/Documents/R/win-library/3.4/threejs/htmlwidgets/lib/threejs-83
The same .Rmd file, prior to updating header-info now, generated html-content successfully months ago, with no issues. I think, the updated blogdown package isn't able to locate the dependency libraries i.e. three.js v83 vs three.js v85
If this is the issue, I'd really appreciate if someone could advise which file I need to update to fix this. Below snapshot shows the error message, and also the Windows file-location of required library.
A:
It turned out that you cached the code chunk that generated the HTML widget. When caching HTML widgets, you need to be careful about the versions of HTML dependencies. If you cache a widget, basically the next time it will not be created again but directly loaded from the cache database. It will not know any changes outside in the future, such as an update in a certain JS library. When it is loaded from cache, it will still use all paths stored from the last time. In your case, threejs-83 was changed to threejs-85, but your cached widget didn't know it, and was still looking for threejs-83 (hence the error).
In general, I don't recommend that you cache HTML widgets, due to the other caching mechanism in blogdown, which should make it fast enough to build a website locally, plus that caching HTML widgets can be tricky.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do you need to pay taxes on income paid outside the US?
Non american here. I currently work in a country outside the US in Country A. I have a company training for 10 weeks coming up that is in the US office. During the time, I will be getting paid the same salary in Country A's local currency paid to my Country A bank account.
My question is, do I need to pay the US taxable income on the salary that I make during my stay in the US?
A:
Assuming you are not US citizen or tax payer.
Your visa is a business visa, then there is no taxes applicable for you.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.