text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: access 2016 System resource exceeded I am try to migrate from access 2003 to 2016 When I am importing my objects everything is fine. Only,on the process of importing 3 tables, I am getting this error.
System resource exceeded
They are big tables too.
There is no hotfix for access 2016, Total table quantity around 100 tables
If you help me I really appreciate
A: Found solution here:
https://answers.microsoft.com/en-us/msoffice/forum/all/ms-access-2016-system-resource-exceeded/df80f64a-f233-467e-89df-f05a8d58bc77
In short:
task manager/processes tab, find msaccess, right click and select set affinity.... option. I had 6 CPUs ticked (0 to 5). I un-ticked them all and just ticked the 0 CPU.
A: Not sure if this will help you, but I've managed to resolve this error by wrapping fields referenced in the WHERE clause with Nz e.g.
instead of
WHERE ReportDate = Date
use
WHERE Nz(ReportDate,ReportDate) = Date
It's strange but it seems to work for me, I've found the issue is often related to indexed fields, so I always add it to those fields first
A: Since currently there is no hot fix for 2016 version you have to merge either to 2010 or 2013. Then you can try merging to 2016.
Please check this link:
https://social.technet.microsoft.com/Forums/en-US/aedecca8-aa7d-417f-9f03-6e63e36f0c5d/access-2016-system-resources-exceeded?forum=Office2016setupdeploy&prof=required
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34665422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: load RetainFragment in a Fragment Hello Android Developer,
i follow the Display Images Guide from Android Developers and want to load my initialized cache from a RetainFragment if i rotate my device. A do this in my ListFragments onActivityCreated() method but the fragment is every time new created and not reused.
I do something like this:
RetainFragment
class RetainFragment extends Fragment {
private static final String TAG = "RetainFragment";
public LruCache mRetainedCache;
public RetainFragment() {}
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
And this: ListFragment
@Override
public void onActivityCreated( Bundle savedInstanceState )
{
super.onActivityCreated( savedInstanceState );
RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getFragmentManager());
LruCache mMemoryCache = RetainFragment.mRetainedCache;
if (mMemoryCache == null)
{
mMemoryCache = new LruCache(cacheSize);
mRetainFragment.mRetainedCache = mMemoryCache;
}
else
{
mMemoryCache = mRetainFragment.mRetainedCache;
}
...
}
A: It looks to me like they forgot to actually attach that RetainFragment somehow to the Activity so FragmentManager has a chance to find it. Fragments that are not attached don't survive configuration changes.
Not sure if but it should work with the addition below
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
// add this line
fm.beginTransaction().add(fragment, TAG).commit();
}
return fragment;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11959890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Drawing a physics body's path? I've been working on a first-person shooter game with Bullet and OpenGL, and now have it to the point of being able to fire bullets through the scene. I'm now looking to draw the path these bullets take, from starting position to their ending position, with the entire path staying drawn until the next bullet is fired (so that the screen isn't cluttered).
I'm basically just looking for something like a red line that extends to the bullet's new position each frame, or something like that. So, by the time the bullet has gone from the gun to its final stopping place, the red line will show the exact path it took, what it bounced off of, etc.
I've tried looking for examples but I can't find anything useful. I've seen mention of leaving a trail behind an object using an accumulation buffer, but that's not really what I want.
How can this be done? Does everyone know of any examples or tutorials for this?
A: just make vbo of points
and then
...
glVertexAttribPointer(.., 1, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_POINTS,0,.. );
Use math you have to assign each.
But it's not so easy. I think it can be done with deploy of second pair of shaders /vao. OpenGL multiple draw calls with unique shaders gives blank screen
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43573875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ggplot: using geom_smooth to plot variance I am making a time series plot with ggplot. I have the mean and the variance of the 5 variables of interest. I can plot the variance with error bars, but when I try to do it with geom_smooth()/stat_smooth() it doesn't work well.
ggplot(data = df4, aes(x = times, y = value, colour = variable)) + geom_line()+
geom_errorbar(aes(ymin = value-var, ymax = value+var))+
geom_errorbarh(aes(xmin = value-var, xmax = value+var))+ geom_smooth()
Output figure
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36341006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a relationship beetween radiobuttons? Please, help with this situation: how can I make relations (using jquery) between payment and delivery types? For example, if user choose "Pre Order" in payment - in delivery automatically checked "Pre Order, delivery not available". And if user choose "PayPal" he is given a choice between "Mail Service" and "AIR MAIL", but "Pre Order, delivery not available" is readonly. I appreciate your help.
<label>Payment type:</label>
<input type="radio" name="payment" value="10" class="payment-item" id="pay-type-10" onclick="shEvOrd('payment',this)"><label class="label" for="pay-type-10">Pre Order</label>
<input type="radio" name="payment" value="11" class="payment-item" id="pay-type-11" onclick="shEvOrd('payment',this)"><label class="label" for="pay-type-11">PayPal</label>
<br>
<label>Delivery type:</label>
<input type="radio" name="delivery" value="7" class="delivery-item" id="del-type-7" onclick="shEvOrd('delivery',this,1)"><label class="label" for="del-type-7">Pre Order, delivery not available</label>
<input type="radio" name="delivery" value="6" class="delivery-item" id="del-type-6" onclick="shEvOrd('delivery',this,1)"><label class="label" for="del-type-6">Mail Service</label>
<input type="radio" name="delivery" value="5" class="delivery-item" id="del-type-5" onclick="shEvOrd('delivery',this,1)"><label class="label" for="del-type-5">AIR MAIL</label>
<input type="button" value="Place order" id="order-button" onclick="shopCheckOut();this.order.reset">
A: You can try this
// attach a click event to the payment radio group
$(".payment-item").click(function(){
var payment = $("input:radio[name='payment']:checked").val(), // check the current value
isPaypal = payment !== "10", // a simple check to see what was selected
delivery = $("#del-type-7"); // get the radio element with the pre-order option
return delivery.prop({
// Disabled if `isPaypal` is true
disabled: isPaypal,
// Checked if `isPaypal` is true
checked: !isPaypal
});
});
Have a look at the demo http://jsfiddle.net/jasonnathan/3s3Nn/2/
A: jsBin demo
All you need:
var $delType7 = $("#del-type-7"); // Cache your elements
$("[name='payment']").click(function(){
var PPal = $("[name='payment'][value='10']").is(':checked'); // Boolean
$delType7.prop({checked:!PPal, disabled:PPal}); // boolean to toggle states
});
Remove onclick from HTML
http://api.jquery.com/checked-selector/
http://api.jquery.com/prop/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24341254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WordPress regex not working as expected I need to put a string like user-profile/id=3 into regex form. I tried 'user-profile/id=\d+$' and also 'user-profile/([a-z][.][0-9]+)/?$', but none of them are working. What is the correct way?
A: Since your string is always in the format as above, you do not need a regex. Use a mere explode:
explode("/", $s)[1]
See this demo.
Another non-regex approach: use strstr to get the substring after and including /, and then get the substring from the 1 char:
substr(strstr($s, "/"),1);
See another PHP demo
A: Your problem is that you aren't escaping the / character with a backslash.
Another problem you could face immediately after solving that one, is that you are using the $ character, which means end of line. If there are more characters afterwards, even just a single space, then it won't match.
If you try:
user-profile\/(id=\d+)
You'll probably find that it matches just fine. The brackets I added in will capture id=3 in capture group #1.
A: If you just want to extract id=3 I recommend to use preg_replace. Like:
$str = 'user-profile/id=3';
$after_preg = preg_replace('/user-profile\//', '', $str);
echo $after_preg;
If you want to get just a number it can be as follows:
$str = 'user-profile/id=3';
$after_preg = preg_replace('/user-profile\/id=/', '', $str);
echo $after_preg;
More about it you can read in PHP Manual: preg_replace
If you want to check if you string is like user-profile/id=3 you can use regex:
user-profile\/id=\d*
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40671232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flutter: can't find class "FlutterFragment" I have a Flutter app create by flutter create command.
I have the MainActivity (which extends from FlutterActivity) and also a native activity that I opens it via MethodChannel.
Now I need to call another FlutterActivity embedded with a FlutterFragment but the class FlutterFragment simply doesn't exists.
My page stack would be like that:
*
*MainActivity(FlutterActivity) -> NativeActivity (with native code and layout) -> AnotherFlutterActivity.
I am following this tutorial: https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps
Ayone know why this is happening?
[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [versão 10.0.17763.379], locale pt-BR)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] IntelliJ IDEA Community Edition (version 2019.1)
[√] VS Code (version 1.30.1)
[√] Connected device (1 available)
A: This is probably because you haven't imported FlutterFragment in your activity, please add this line in your import statements.
import io.flutter.embedding.android.FlutterFragment;
Also, make sure to extend your activity from FlutterFragmentActivity. You will have to import it, add this line at the top of your file along with the other import statements.
Like so:
...
import io.flutter.app.FlutterFragmentActivity;
...
Hope this helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55594797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Notepad ++ Insert New Line Before 'else if' I'm trying to insert a new line before every instance of the phrase 'else if'. I know how to do this for a single word using
Find: else
Replace: \r
But I can't figure out how to search for a multi word string in the Find.
Apologies if these is really obvious; I've had a good hunt around regular expressions guides for Notepad ++ but I haven't been able to get anywhere.
A: Find: else if
Replace: \r\nelse if
Search Mode: Extended
A: Have a try with:
Find what: (\belse if\b)
Replace with: \n$1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24279904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback unable to get the data on postman Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
"There was an unexpected error (type=Not Found, status=404) .
I executed multiple students detail on spring boot and then tried to run it on localhost:8080 but getting the error as written above.
used controller and mapping already still unable to resolve
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73578232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vb.net DateTimePicker remove time 12:00:00 AM im having a problem when viewing date on my listview.
on my SQL its okay that on my column "2016-28-11" that is fine
but when i view it on my listview in vb.net it said that "2016-28-11 12:00:00 am"
on my datetimepicker
Value: 11/28/2016
custom format: yyyy-MM-dd
format: custom
when i save the date it adds that time. can anyone help me?
A: When you add the date in your listview just use something like that:
Dim NewItem As New ListViewItem
NewItem.Text = "My Item"
NewItem.SubItems.Add(mydate.tostring("yyyy-MM-dd"))
ListView1.Items.Add(NewItem)
Just keep in mind mydate.tostring("yyyy-MM-dd") where mydate is a datetime.
Considerate your comments, here is the code:
.SubItems.Add(ds.Tables("studnum").Rows(i).Item(4).ToString)
Dim MyDate As DateTime = CDate(ds.Tables("studnum").Rows(i).Item(5).ToString)
.SubItems.Add(MyDate.ToString("yyyy-MM-dd"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40844536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I find out which data record goes into which cluster in R using kohonen and means I have clustered my data with an SOM and kmeans
install.packages("kohonen")
library(kohonen)
set.seed(7)
som_grid <- somgrid(xdim = 8, ydim=8, topo="hexagonal")
som_model <- som(umfrage_veraendert_kurz,
grid=som_grid,
rlen=500,
alpha=c(0.05,0.01),
keep.data = TRUE )
I get from my som_model the "codes" and clustered it with kmeans
mydata <- som_model$codes
clusterzentren <- kmeans(mydata, center=3)
head(clusterzentren)
I have now 3 clusters but I don't know which data record goes to which cluster? How can I find it out?
Thanks for any help
A: The return value of kmeans is a S3 object which contains not only the centers, but also the cluster assignment.
See the R manual of kmeans for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41464689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to keep aliases in multiple shell sessions? I want to set up some alias and would like to keep them so I don't have to reset them every time I have a new Terminal open. How can I do that? Would it require modifying hidden files?
EDIT: I'm using Mac, I found a bashrc under /etc, is it the one?
A: Yup – you'll need to put it in ~/.bash_profile:
alias ls='ls --color=auto'
A: It depends on your shell/system e.g., for bash on Ubuntu check out ~/.bashrc, ~/.bash_profile files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1441679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make TextField in libGDX java I've got problem with making TextField in my libGDX project. So I just take some compleate example of initialize Label from web. And it's work well.
public ItemCreateScreen()
{
Label.LabelStyle Label1Style = new Label.LabelStyle();
BitmapFont myFont = new BitmapFont();
myFont.scale(2);
Label1Style.font = myFont;
Label1Style.fontColor = Color.RED;
Label Label1 = new Label("Title (BitmapFont)",Label1Style);
Label1.setSize(Gdx.graphics.getWidth(),row_height);
Label1.setPosition(0,Gdx.graphics.getHeight()-row_height*2);
Label1.setText("Hello folks");
mLabels.add(Label1);
}
@Override
public void drawn(SpriteBatch fBatch)
{
mLabels.get(0).draw(fBatch,255);
}
When i just replace textually "Label" with "TextField", and feel great because compilation isnt show any error.
public ItemCreateScreen()
{
TextField.TextFieldStyle TextField1Style = new
TextField.TextFieldStyle();
BitmapFont myFont = new BitmapFont();
myFont.scale(2);
TextField1Style.font = myFont;
TextField1Style.fontColor = Color.RED;
TextField TextField1 = new TextField("Title (BitmapFont)",TextField1Style);
TextField1.setSize(Gdx.graphics.getWidth(),row_height);
TextField1.setPosition(0,Gdx.graphics.getHeight()-row_height*2);
TextField1.setText("Hello folks");
mTextFields.add(TextField1);
}
@Override
public void drawn(SpriteBatch fBatch)
{
mTextFields.get(0).draw(fBatch,255);
}
But after build i dont see any TextField like it was before with Label.
What i have done wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51124117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Promise Chaining / Cascading to RxJS angular 1 to angular 2 I'm currently trying to convert some good old $http Promises into rxJs observables in angular2.
A very simple example of something I used to do frequently in angular 1:
// Some Factory in Angular 1
var somethings = [];
var service = {
all: all
};
return service;
function all() {
return $http
.get('api/somethings')
.then(function(response) {
somethings = parseSomethings(response.data);
return somethings;
});
}
// Some Controller in Angular 1
var vm = this;
vm.somethings = [];
vm.loading = true;
loadThings();
function loadThings() {
SomeFactory
.all()
.then(function(somethings) {
vm.somethings = somethings;
})
.finally(function() {
vm.loading = false;
})
}
Now I can achieve something similar with angular2 using RxJs Observable and Subject. But I am unsure on how to return 'completion hooks' down to the caller. (E.g.: The loading in the angular1 controller)
What I tried with for angular2 is something similar:
// Some Service in Angular 2
export class SomeService {
private _somethings$: Subject<Something[]>;
private dataStore: {
somethings: Something[]
};
constructor(private http: Http) {}
get _somethings$() : Observable<Something[]> {
return this._somethings$.asObservable();
}
loadAll() {
this.http
.get(`api/somethings`)
.map(response => response.json())
.subscribe(
response => {
this.dataStore.somethings = parseSomethings(response.data);
this._somethings$.next(this.dataStore.somethings);
}
);
}
}
//Some Component in Angular 2
export class SomeComponent() {
constructor(private someService: SomeService) {}
ngOnInit() {
this.someService.loadAll();
this.somethings = this.someService.somethings$;
}
}
Note
I used a Subject / Observable here so that when I create / update / remove 'something' I can call .next to notify the subscribers.
E.g.:
create(something: Something) : Observable<Something>{
return this.http.post(`api/somethings`, JSON.stringify(something))
.map(response => response.json())
.do(
something => {
this.dataStore.somethings.push(something);
this._somethings$.next(this.dataStore.somethings); //Notify the subscribers
}
);
}
Note
Here I used .do in the method and when calling the method in a 'form component' I subscribe just to get completion handler:
this.someService.create(something).subscribe(
(ok) => ...
(error) => ...
() => stop loading indicator
)
Questions
*
*How can we pass down a completion-hook to callers (e.g. angular 1 controller) in angular 2 with RxJs
*What alternative paths do exist to achieve similar behaviour ?
A: Your last code example is fine. Just use map() instead of subscribe() and subscribe at call site.
You can use
return http.post(...).toPromise(val => ...))
or
return http.post(...).map(...).toPromise(val => ...))
to get the same behavior as in Angular where you can chain subsequent calls with .then(...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38589565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular: add class to span selector I have the below code, I want to add a class to a span selector, but I have this error
Cannot read property 'classList' of null
<th *ngFor="let column of columns;"
<ng-container *ngIf="column?.sortable">
<span [id]="'sort-'+column?.field" (click)="sortArray(column?.field)"></span>
</ng-container>
</th>
if (this.columns) {
this.columns.forEach(column => {
if (column.sortable) {
const parent: HTMLElement = document.getElementById("sort-" + column.field);
this.renderer.setElementClass(parent, "sorting_asc", true);
}
})
}
A: I think you have overly complicated your code, You are using angular and I believe its not a good practice to access DOM elements using document.getElementById().
For your code to work, you will need to ensure that the view has loaded before you can access the DOM elements. You need to move your code to the AfterViewInit life cycle hook.
Below is how I would refactor the code
<th *ngFor="let column of columns;"
<ng-container *ngIf="column?.sortable">
<span [class.sorting_asc]="column?.sortable" (click)="sortArray(column?.field)"></span>
</ng-container>
</th>
We simply bind to [class.sorting_asc]="column?.sortable" and let angular apply the classes for us
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64631885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I am trying to apply constraints on some random packets (I could apply to fixed packets) that I have to send to DUT The following code has two classes - packet and packet_1; packet class has properties length and mode, packet class has the constraints that are required for length and mode. In packet_1 class I want to create 30 such packets and want to apply a constraint of length=6 for 10 random packets, I could do it for one particular(not random) packet, please let me know if this is the correct way and how to do it for 10 random packets ?
Following code generated 30 packets with 4th packet having length=6 and complying with the other constraints, but how can do the same thing for 1 random packet (not a fixed 4th packet) or 10 random packets out of 30 .
class packet;
rand bit[1:0] mode;
rand int length;
int num;
constraint mod_len {mode==0 -> length inside {[1:5]};
mode==1 -> length inside {[6:10]};
mode==2 -> length inside {[11:15]};
mode==3 -> length inside {[16:20]};};
endclass
class packet_1;
packet p1;
task pack();
p1=new;
p1.num=0;
repeat(30)
begin
p1.num++;
if(p1.num==4)
p1.randomize with {(p1.length==6);} ;
else
p1.randomize ;
$display("packet is %p",p1);
end
endtask
endclass
module a;
packet_1 p2;
initial
begin
p2=new();
p2.pack();
end
endmodule
A: If you want exactly specific number of packets, then we can use a queue/array that stores random indices of constrained value to be stored.
class packet_1;
packet p1;
int NUM_CONSTRAINED_PKTS=10; // Number of pkts to be constrained
int NUM_TOTAL_PKTS=30; // total number of pkts to be generated
rand int q[$];
constraint c1{
q.size == NUM_CONSTRAINED_PKTS; // random indices = total constrained pkts generated
foreach(q[i]){q[i]>=0; q[i]<NUM_TOTAL_PKTS;} // indices from 0-total_pkts
unique {q}; // unique indices
};
task pack();
p1=new;
p1.num=0;
this.randomize(); // randomize indices in q
for(int i=0;i<NUM_TOTAL_PKTS;i++) begin
if(i inside {q}) begin // check if index matches
p1.randomize with {(p1.length==6);} ;
p1.num++; // debug purpose
end
else
p1.randomize ;
$display("packet is %p",p1);
end
if(p1.num != NUM_CONSTRAINED_PKTS) $error("Error: p1.num=%0d",p1.num); // 10 pkts with constrained value
else $display("Pass!!");
endtask
endclass
Another method is to use dist operator on length variable with some glue logic to generate a weighted distribution in the output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56896576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JNI - Async task crashing I'm trying to do the following :
*
*Run Java app on Android
*Call native C++ code from that Java app
*Create and run a native thread from that natice code
*return immediatly while the thread keeps running
*Call a java method from native code once the thread is finished
Here is my code :
#include <jni.h>
#include <pthread.h>
#include <unistd.h> /* sleep() */
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{
#endif
JNIEXPORT jstring JNICALL Java_xxx_asynctasktest_MainActivity_runAsyncTask( JNIEnv * env, jobject that, jstring oDummyStr );
#ifdef __cplusplus
}
#endif
JavaVM * g_jvm;
jobject g_obj;
jmethodID g_mid;
void * threadProc( void * pArg )
{
JNIEnv * env = 0;
int res = g_jvm->AttachCurrentThread( & env, NULL );
sleep( 3 );
jobject oStr = (jobject)pArg;
env->CallObjectMethod( g_obj, g_mid, oStr );
env->DeleteGlobalRef( oStr );
env->DeleteGlobalRef( g_obj );
g_jvm->DetachCurrentThread();
return 0;
}
JNIEXPORT jstring JNICALL Java_xxx_asynctasktest_MainActivity_runAsyncTask( JNIEnv * env, jobject that, jstring oDummyStr )
{
env->GetJavaVM( & g_jvm );
g_obj = env->NewGlobalRef( that );
g_mid = env->GetMethodID( env->GetObjectClass( that ), "onTaskFinished", "(Ljava/lang/String;)Ljava/lang/String;" );
if( g_mid == NULL )
{
fprintf( stderr, "No such method" );
}
else
{
pthread_t thread = 0;
pthread_create( & thread, NULL, threadProc, (void *)env->NewGlobalRef( oDummyStr ) );
}
return env->NewStringUTF( "lolol" );
}
My problem is that when i call env->CallObjectMethod( g_obj, g_mid, oStr ); eclipse tries to open Handler.class in the class file editor and says not found and the thread doesn't call the Java method.
What am I doing wrong ? Thank you.
EDIT : Forgot to mention that my Java callback creates a dialog as follows :
AlertDialog.Builder dlgAlert = new AlertDialog.Builder( this );
dlgAlert.setMessage( msgBoxText );
dlgAlert.setTitle( "" );
dlgAlert.setPositiveButton( "OK", null );
dlgAlert.setCancelable( true );
dlgAlert.create().show();
And i'm having a runtime exception somewhere in "Handler" at line 121, source file not available.
EDIT : I'm actually reaching the Java callback, but it crashes when i start creating my dialog.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28700534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redisson client injects weird characters at the beginning of strings I'm using Redisson client to publish String messages on a topic, but for some reasons, the published messages always contain some weird characters at the beginning:
eg: when I publish the string "{"event":"notification"}"
at the redis level I end up with this:
"\x04>\x18{"event":"notification"}"
1) "pmessage"
2) "*"
3) "active_project_users:1"
4) "\x04>\x18{\"event\":\"notification\"}"
Any idea how I can make those weird chars go away?
My java code looks like this:
private void publish(String channel, String message) {
RTopic topic = redissonClient.getTopic(channel);
topic.publish("{\"event\":\"notification\"}");
}
I'm using redis:3.2 & radisson-spring-boot-starter 3.16.1
Thanks
A: It seems I have to set the encoding for this to work properly:
RTopic topic = redissonClient.getTopic(channel, StringCodec.INSTANCE);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69768475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: WPF - error: [xxx] "does not contain a definition for [zzz] and no extension method [zzz] could be found I get an error while compiling:
'SimulatorUi.MainWindow' does not contain a definition for 'UserCtrlSimulator' and no extension method 'UserCtrlSimulator' accepting a first argument of type 'SimulatorUi.MainWindow' could be found (are you missing a using directive or an assembly reference?)
I got this error while compiling a user control and its owning window in the same project.
Why ?
A: The problem is the naming of the userControl in its owning Window. I named as:
Name="UserCtrlSimulator"
instead of:
x:Name="UserCtrlSimulator"
You can find the bug and a more useful error message by removing the reference of that badly named object (remove any reference to the object named without the "x:").
I can't tell the exact reason why it is like this ??? But my solution works fine.
Hope it can help anybody because I lost a lots of time with this weird bug.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20643149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Google Sheet - limit certain users from organization from editing/viewing? I have the following issue.
I have a Google Sheet that is shared with everyone within my organization(300 people) and they have to have edit rights.
But, certain users from that organization should not be able to edit or even access the file, even tho it's okay if they can just view it.
I'm currently battling this by using a script that checks the users mail(Session.getEffectiveUser().getEmail()) and if they match the address in the array that contains all the addresses it fires an alert modal telling the user they are not eligible.
However, this works but if the users simply closes the alert he/she can continue editing the sheet. Which is not desirable. :)
I've searched but i failed to find a working solution or at least the idea to prevent those few users from the organization to edit this Sheet.
Appreciate any input, thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48763097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: core Plot:Decrease distance between bar in bar graph ios i am plotting 2 data set on bar graph and i want them to be like histogram ,so can anyone guide me to the solution asap.
i have 2 datasets(google and Apple)in 1 datasets.I am not getting any spaces between bars of 1 dataset but i am getting too much spacing between 2 datasets.
here is my code,
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ((fieldEnum == CPTBarPlotFieldBarTip) && (index < [[[CPDStockPriceStore sharedInstance] datesInWeek] count]))
{
if ([plot.identifier isEqual:CPDTickerSymbolAAPL])
{
NSLog(@"apple index:%@",[[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL] objectAtIndex:index]);
return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
}
else if ([plot.identifier isEqual:CPDTickerSymbolGOOG])
{
NSLog(@"google index:%@",[[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG] objectAtIndex:index]);
return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG] objectAtIndex:index];
}
}
return [NSDecimalNumber numberWithUnsignedInteger:index];
-(void)viewDidLoad
{
[super viewDidLoad];
[self initPlot];
}
#pragma mark - Chart behavior
-(void)initPlot
{
self.hostView.allowPinchScaling = YES;
[self configureGraph];
[self configurePlots];
[self configureAxes];
graphData=[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL];
NSLog(@"google:%@",graphData);
}
-(void)configureGraph {
// 1 - Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
graph.plotAreaFrame.masksToBorder = NO;
self.hostView.hostedGraph = graph;
// 2 - Configure the graph
[graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
graph.paddingBottom = 30.0f;
graph.paddingLeft = 30.0f;
graph.paddingTop = -1.0f;
graph.paddingRight = -5.0f;
CGFloat xMin = 0.0f;
CGFloat xMax = [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
CGFloat yMin = 0.0f;
CGFloat yMax = 800.0f; // should determine dynamically based on max price
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xMin) length:CPTDecimalFromFloat(xMax)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin) length:CPTDecimalFromFloat(yMax)];
}
-(void)configurePlots
{
// 1 - Set up the three plots
self.aaplPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:105.0f/255.0f green:252.0f/255.0f blue:144.0f/255.0f alpha:1.0] horizontalBars:NO];
self.aaplPlot.identifier = CPDTickerSymbolAAPL;
self.googPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor colorWithComponentRed:103.0f/255.0f green:103.0f/255.0f blue:103.0f/255.0f alpha:1.0] horizontalBars:NO];
self.googPlot.identifier = CPDTickerSymbolGOOG;
// 2 - Set up line style
CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
barLineStyle.lineColor = [CPTColor lightGrayColor];
barLineStyle.lineWidth = 0.5;
// 3 - Add plots to graph
CPTGraph *graph = self.hostView.hostedGraph;
CGFloat barX = CPDBarInitialX;
NSArray *plots =[NSArray arrayWithObjects:self.aaplPlot, self.googPlot, nil];
for (CPTBarPlot *plot in plots)
{
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = CPTDecimalFromDouble(CPDBarWidth);
plot.barOffset = CPTDecimalFromDouble(barX);
plot.lineStyle = barLineStyle;
[graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
barX += CPDBarWidth;
}
}
-(void)configureAxes
{
// 1 - Configure styles
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = @"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:1];
// 2 - Get the graph's axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
// 3 - Configure the x-axis
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.xAxis.title = @"Days of Week (Mon - Fri)";
axisSet.xAxis.titleTextStyle = axisTitleStyle;
axisSet.xAxis.titleOffset = 10.0f;
axisSet.xAxis.axisLineStyle = axisLineStyle;
// 4 - Configure the y-axis
axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
axisSet.yAxis.title = @"Price";
axisSet.yAxis.titleTextStyle = axisTitleStyle;
axisSet.yAxis.titleOffset = 5.0f;
axisSet.yAxis.axisLineStyle = axisLineStyle;
}
-(void)hideAnnotation:(CPTGraph *)graph
{
if ((graph.plotAreaFrame.plotArea) && (self.priceAnnotation)) {
[graph.plotAreaFrame.plotArea removeAnnotation:self.priceAnnotation];
self.priceAnnotation = nil;
}
}
A: With CPDBarWidth = 0.15, two bars take up only 30% of the space between successive bar locations. Increase the barWidth to reduce the space between neighboring bars.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26120551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NameError: name 'redis' is not defined - PySpark - Redis I am using the addPyFile method in pyspark to load the redis.zip file.
I am able to load the file using
sc.addPyFile("/home/path/to/redis.zip")
But while running the code using ./pyspark, it is showing the error:
NameError: name 'redis' is not defined
The zip(redis.zip) contains .py files(client.py, connection.py,exceptions.py, lock.py,utils.py and others).
Python version is - 3.5 and spark is 2.7
A: If you pack py files into zip and add it using sc.addPyFile you should import modules using import client, import connector, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42572577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lifestyle of NLog wrapper class I have five different logger and a wrapper class for them :
internal class CommonNLogResolver : ICommonLogger
{
private readonly NLog.Logger commonLog;
private readonly NLog.Logger errorLog;
private readonly NLog.Logger dataBaseLog;
private readonly NLog.Logger logExceptionLogger;
private readonly NLog.Logger clientLogger;
public CommonNLoggerResolver()
{
commonLog = NLog.LogManager.GetLogger(Constants.CommonLog);
errorLog = NLog.LogManager.GetLogger(Constants.ErrorLog);
dataBaseLog = NLog.LogManager.GetLogger(Constants.DBLog);
logExceptionLogger = NLog.LogManager.GetLogger(Constants.LogExceptionLog);
clientLogger = NLog.LogManager.GetLogger(Constants.ReportLog);
}
}
I look at the LogFactory.cs in NLog and since it has a cache for logger I don't know what lifestyle is appropriate for my wrapper class.
so my question is should I register this class singleton , transient or scope?
also I'm using SimpleInjector for Dependency Injection.
A: NLog is thread-safe, so you can safely reuse your logger. You can make it Singleton.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42409020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse added jar to referenced libraries but still getting ClassNotFoundException Hi I'm following this tutorial using eclipse. I've included the derby.jar and derbyclient.jar files and I can clearly see them appearing under referenced libraries. Oddly, I'm still geting java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver even though the jar files are clearly there. I tried looking online but nothing were useful.
My steps of adding jar to referenced libraries: Right click project > properties > Java build path > Modulepath > Add External JARs. I've also tried adding it to Classpath instead of Modulepath and importing the package but either approaches doesn't seem to work at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60883717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ESLint throwing unpredicted errors with Hardhat I recently began a project which uses hardhat. I ran npx hardhat ., and went with the advanced TS project.
Everything works fine, from the types to the solidity compiling, but ESLint always complains...
This is the kind of error I keep seeing:
As you can see the types are there, but ESLint continues to throw errors. This luckily doesn't stop the app to run.
Here is my config file:
module.exports = {
env: {
browser: false,
es2021: true,
mocha: true,
node: true
},
plugins: ['@typescript-eslint'],
extends: ['standard', 'plugin:node/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12
},
rules: {
'node/no-unsupported-features/es-syntax': [
'error',
{ ignores: ['modules'] }
]
}
}
A: I've spent a lot of time on this issue, and the best method for me was to remove everything.
1 - Create a .ptettierrc.json file the root of your project.
2 - Run yarn remove eslint-plugin-promise eslint-plugin-node eslint-plugin-import eslint-config-standard eslint-config-prettier
3 - Change your ESLint config to the one below:
module.exports = {
env: {
browser: false,
es2021: true,
mocha: true,
node: true
},
plugins: ['@typescript-eslint'],
extends: ['plugin:prettier/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12
},
rules: {
'node/no-unsupported-features/es-syntax': [
'error',
{ ignores: ['modules'] }
]
}
}
Keep in mind this is for a fresh config, if you've already changed your config, just remove any mentions of the package we removed on step 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70850275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What Datatype is created? What data type does "two_days_in_a_row" create in Python? Does it create a list or a tuple, or any other datatype
In my Advanced Data Science with Python on Coursera Course 1, Week 4, Distributions lecture, prof said that two_days_in_a_row = 0 will create a list. I am still figuring why will be the case, why a list will be created. Help me know the answer. Thanks in advance!!!
two_days_in_a_row = 0
#creates a list
A: You have assigned a integer value to that variable.
Using type() will tell you what data type you have.
I.E: type(two_days_in_a_row) --> returns int
A: Don't confuse, Check below data types in python
two_days_in_a_row = 0
type(two_days_in_a_row): int
two_days_in_a_row = []
type(two_days_in_a_row): list
two_days_in_a_row = None
type(two_days_in_a_row): NoneType
two_days_in_a_row = ""
type(two_days_in_a_row): str
two_days_in_a_row = {}
type(two_days_in_a_row): dict
two_days_in_a_row = ()
type(two_days_in_a_row): tuple
two_days_in_a_row = 0.0
type(two_days_in_a_row): float
two_days_in_a_row = 2+3j
type(two_days_in_a_row): complex
two_days_in_a_row = True
type(two_days_in_a_row): bool
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56172503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Combine forEach callback parameter with function parameter I am trying to combine a forEach callback parameter (HTMLAnchorElement/HTMLTableCellElement objects) with a function parameter (string).
What I am doing is getting the href of an a tag in one function call, and then textContent of a td tag in another function call, using the same function.
Here is my code:
// example usage of function
await scraper.scraper(args, 'a[href]', 'href') // get href
await scraper.scraper(args, 'table tr td', 'textContent') // get textContent
// scraper function
const scraper = async (urls, regex, property) => {
const promises = []
const links = []
urls.forEach(async url => {
promises.push(fetchUrls(url))
})
const promise = await Promise.all(promises)
promise.forEach(html => {
const arr = Array.from(new JSDOM(html).window.document.querySelectorAll(regex))
arr.forEach(tag => {
links.push(tag.href) // how about textContent?
})
})
return links
}
Is there a way of some how combining the callback parameter tag from the forEach with the function parameter property?
The code below works. But what if I want to do further function calls to other properties? I don't want to add an if statement every time I make another function call, that kind of defeats the purpose of my function to be reusable.
property === 'textContent' ? links.push(tag.textContent) : links.push(tag.href)
Any attempt in trying to combine the two seems to go wrong. Is it not possible?
A: Use the property value you pass in as computed key of your el object (tag in your code), in order to pass the property value for the element inside the forEach dynamically, depending on the property you passed in
arr.forEach(el => {
links.push(el[property]);
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54356950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Deleting Cloudwatch logs using boto3 I am trying to delete Cloudwatch logs irrespective of the Log group.
Is there any method available with boto3 using which I can search for a pattern(keyword) in the Log group name?
A: You'll need to call describe_log_groups() and do the filtering within your code.
The only filter available is the ability to specify a logGroupNamePrefix.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62949479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I want to assign 1 day after checkin date for check out date in bootstrap datepicker I have the HTML as follows
<div class="booking-date-fields-container col-xs-12 col-sm-6" id="dp3">
<input type="hidden" data-date-format="MM/DD/YYYY" name="dateArrival" id="dateArrival">
</div>
<div class="booking-date-fields-container col-xs-12 col-sm-6" id="dp4">
<input type="hidden" data-date-format="MM/DD/YYYY" name="dateDeparture" id="dateDeparture">
</div>
and following is the JS file content for the above
jQuery("#booking-tab-contents .input-daterange").datepicker({
format: "yyyy-mm-dd",
autoclose: true,
startDate: new Date(),
show: true,
inputs: jQuery('.booking-date-fields-container')
});
$('#dp3').datepicker().on('click', function (ev) {
$('#dateArrival').val( $('#dp3').datepicker('getFormattedDate'));
});
$('#dp4').datepicker().on('click', function (ev) {
$('#dateDeparture').val( $('#dp4').datepicker('getFormattedDate'));
});
I want to make my date-picker in such a way that, when I select arrival date or check in date, the checkout date must be a day after the check-in date
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35598926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java util Timer - Thread addition Timer timer = new Timer();
// scheduling the task at interval
timer.schedule(tasknew,100, 100);
If this is added as part of a web-application at the startup, how is the task getting kicked off at the scheduled time? Is a new daemon thread process being created, solely for triggering this task?
I just want to understand if we are creating any additional thread that is responsible for this task threads?
A:
I just wanted to understand if we are creating any additional threads that is responsible for this task threads?
Yes - from the documentation:
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27278638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to disallow multiple parallel user sessions per login in ZF2? I'm currently facing the situation, that the ZendFramework2 ZFCuser-Module does not have any options to prevent a user from logging in from two devices at the same time.
We recently had a case, that two people were "account-sharing" and accidentally deleted each others data. Since I did not build the application to account for this kind of resource conflicts, I need to prevent this behaviour now.
Is there any module or easy possibility out there to prevent account-sharing in Zend Framework 2 with ZFCUser?
The docs and SO and all sorts of ZF2 blogs somehow appear to never have come across this type of problem...
Thanks in advance!
A: I was able to achieve the functionality of limiting the number of sessions for the same user.
However, my solution (code below) doesn't provide any data-protected layer in order to restrict CRUD operation performed from another session.
I think you can achieve this if you restrict operation based on user_id and session_id
DB
id
user_id
client_id
00m5nqcvpk9bhqv7rbllq5hsi4
198
14
34ssnqcvpk9xxqv7rbll4354fdf
123
42
id will be session_id (PHP SID)
Method
/**
*
* @param int $userId
* @param int $clientId
* @return type
*/
public function validateActiveSession($userId, $clientId) {
if (empty($userId)) {
$userId = $this->getResourceManager()->getIdentity()->getId();
}
if (empty($clientId)) {
$clientId = $this->getResourceManager()->getIdentity()->getClientId();
}
$sessionManager = $this->getServiceLocator()->get('Zend\Session\SessionManager');
$id = $sessionManager->getId();
$userModel = $this->getResourceManager()->getuserModel();
$sIdUserExist = $userModel->getUserActiveSession('', '', $id);
if (empty($sIdUserExist)) {
$userModel->addUserSessionBySidAndUserClientId($id, $userId, $clientId);
}
}
Repository
public function addUserSessionBySidAndUserClientId($sessionId, $userId, $clientId)
{
$em = $this->_em->getConnection();
$sql = "INSERT INTO `user_session`(`id`, `user_id`, `client_id`) VALUES (:id,:user_id,:client_id)";
$params = array('id' => $sessionId, 'user_id' => $userId, 'client_id' => $clientId);
$stmt = $em->prepare($sql);
return $stmt->execute($params);
}
public function getActiveUserSession($userId, $clientId, $sessionId)
{
$rsm = new ResultSetMapping();
$rsm->addScalarResult('id', 'id');
$rsm->addScalarResult('user_id', 'user_id');
$userIdClause = $clientIdClause = $andClause = $sessionIdClause = '';
if (!empty($userId)) {
$userIdClause = 'user_id = :user_id';
}
if (!empty($clientId)) {
$clientIdClause = ' and client_id = :client_id';
}
if (!empty($userId) && !empty($sessionId)) {
$andClause = ' and ';
}
if (!empty($sessionId)) {
$sessionIdClause = 'id = :id';
}
$query = $this->_em->createNativeQuery('SELECT id,user_id FROM user_session WHERE ' . $userIdClause . $clientIdClause . $andClause . $sessionIdClause, $rsm);
if (!empty($userId)) {
$query->setParameter('user_id', $userId);
}
if (!empty($clientId)) {
$query->setParameter('client_id', $clientId);
}
if (!empty($sessionId)) {
$query->setParameter('id', $sessionId);
}
return $query->getResult();
}
once user logged-in check for active sessions
$sameActiveUser = count($userModel->getActiveUserSession($userId, $clientId, ''));
if ($sameActiveUser == 2) { //already 2 active session than restrict 3rd
return "session already present";
} else {
$this->validateActiveSession($userId, $clientId);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30456921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I remove access to selected users from Microsoft Teams? Removing Teams licenses doesn't work In Office 365/Azure we have a set of special high privileged accounts used only for management purposes. Then normal accounts used for "office" work.
The privileged accounts are set as "unlicensed" - all app access removed. Yet, when I access Teams with any of the users, I can use it normally. Also, whenever someone performs a user search/autocomplete in Teams the privileged accounts show up. This is an issue because, for example, my name shows up 3 times causing confusion and mistakes.
What do I need to do to totally remove the users from Teams?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75308297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using floats for counters - Any problems? The code I'm looking at uses a golang float64 as a counter, does this pose a problem with loss of accuracy at some point? Specifically, are all integers represented in the range covered by float64? If not, where do I start running into problems? When do I run out of contiguous integers?
In case you're wondering, the reason for using a float64 as a counter is because it's part of a []float64 that holds many metrics that are not integers.
A: The golang specification says, "float64 is the set of all IEEE-754 64-bit floating-point numbers." which is commonly known as double precision numbers,
http://en.wikipedia.org/wiki/Double-precision_floating-point_format
You can read all of its glory details if interested, but to answer your question, quote,
"...next range, from 253 to 254, everything is multiplied by 2..."
So if you want to use it as counters, i.e. positive integers, you won't have problem until 253=9,007,199,254,740,992.
A: Yes, float64 has 52 bits to store your counter. You should be accurate until 253.
(Side note: the entire JavaScript language uses only Floating Point.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21841093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Removing From ElasticSearch by type last 7 day I have different logs in elasticsearch 2.2 separate by 'type'. How can delete all data, only one of type, older one week? thanks
Example of logs:
{
"_index": "logstash-2016.02.23",
"_type": "dns_ns",
"_id": "AVMOj--RqgDl5Axva2Nt",
"_score": 1,
"_source": {
"@version": "1",
"@timestamp": "2016-02-23T14:37:07.029Z",
"type": "dns_ns",
"host": "11.11.11.11",
"clientip": "22.22.22.22",
"queryname": "api.bing.com",
"zonetype": "Public_zones",
"querytype": "A",
"querytype2": "+ED",
"dnsip": "33.33.33.33"
},
"fields": {
"@timestamp": [
1456238227029
]
}
}
A: See here or here on how to delete by query. In Elasticsearch 2.*, you might find the Delete by Query plugin useful.
A: Deleting "types" is no longer directly supported in ES 2.x A better plan is to have rolling indexes, that way deleting indexes older than 7 days becomes very easy.
Take the example of logstash, it creates an index for every day. You can then create an alias for logstash so that it queries all indexes. And then when it comes time to delete old data you can simply remove the entire index with:
DELETE logstash-2015-12-16
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35577037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I re-layout and re-paint a field when a Manager calls setPositionChild(Field)? My class extends Manager and calls setPositionChild(Field f) to change f's position. After calling setPositionChild() method, how do I apply the position(i.e. re-layout and re-paint) so I can see the changes?
I tried to call invalidate(), which did not work.
A: invalidate() just forces a repaint, it doesn't redo the whole layout, as you noticed.
You can force a relayout by going up to the parent Screen object, and calling invalidateLayout(). Forcing the layout will almost certainly call setPositionChild() on the field you are trying to move, so you will want to make sure the new field position is preserved by the manager layout code. This may mean you need to write a custom manager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13735928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inno Setup Remove version number from "Setup has detected that ... is currently running" I've added the line AppMutex={#MyAppName} to my InnoSetup script, and #MyAppName does NOT include the version number. However, when my Setup.exe runs, it says "Your App v1.01 is already running" (or whatever) with the version number, which I don't want. Is there a way to have the message NOT show the version number?
Reason: Say I'm running v1.00 of my app, and I launch "MyApp_101_Setup.exe" (made with Inno Setup). The message shown is "Your App v1.01 is already running" which is NOT true, I'm trying to install v1.01 while v1.00 is running. This can cause confusion for my users.
Any tips? Thanks! :)
A: You are wrong.
The message is:
SetupAppRunningError=Setup has detected that %1 is currently running.%n%nPlease close all instances of it now, then click OK to continue, or Cancel to exit.
Where the %1 is replaced by value of the AppName directive:
ExpandedAppName := ExpandConst(SetupHeader.AppName);
...
{ Check if app is running }
while CheckForMutexes(ExpandedAppMutex) do
if LoggedMsgBox(FmtSetupMessage1(msgSetupAppRunningError, ExpandedAppName),
SetupMessages[msgSetupAppTitle], mbError, MB_OKCANCEL, True, IDCANCEL) <> IDOK then
Abort;
So the version is included in the message, only if you have included the version in the AppName directive. What is wrong, the directive value may not include the version, as the documentation says:
Do not include the version number, as that is defined by the AppVersion and/or AppVerName directives.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38297972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I use `Explain` with a `find_by_sql` query? User.find_by_sql("...my statement here...").explain
results in an error undefined method explain for array... which makes perfect sense to me...
I'm not using rails. I'm using sinatra although that should not matter since the commands come from the activerecord gem which I am using...
Any suggestions?
A: Error is pretty self-explanatory.
You can only run explain on ActiveRecord::Relation objects. But find_by_sql gives you an Array instead, on which explain cannot be called.
You have two ways to work around this:
*
*Convert your query with ActiveRecord methods (which return
Relation)
*Use explain inside your find_by_sql string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23692669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: laravel livewire wire:change does not fire So i have a filter with mutliple tags.
but whenever i select a 'tag' it wont fire to the function.
And it does not matter where i put the wire:change, it just does not work.
First i had a basic Select dropdown, but then i changed it so i can select multiple tags to filter on.
blade code:
<form >
<div class="multiselect" >
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect" wire:model="tag_id" wire:change="filter"></div>
</div>
<div id="checkboxes" >
@foreach($categories as $category)
<label >
<input type="checkbox" value="{{$category->id}}" /> {{ $category->name}}
</label>
@endforeach
</div>
</div>
</form>
javascript for the dropdown:
<script>
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
</script>
css for the dropdown:
<style>
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
</style>
It used to work before i altered the dropdown to multiselect
A: Your wire:model and wire:change are not on your select tag, but on the div below it. Move it to your select tag:
<select wire:model="tag_id" wire:change="filter">
<option>Select an option</option>
</select>
<div class="overSelect"></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74221978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Postfix, relay emails to next server with X port I'm working on migrating my smtp relay from sendmail to postfix. One special thing I did with sendmail was to get around ISP port 25 blocks by creating another esmtp definition in sendmail to send to another port.
In /etc/mail/sendmail.cf I added the following
Mesmtp143, P=[IPC], F=mDFMuXa, S=EnvFromSMTP/HdrFromSMTP, R=EnvToSMTP, E=\r\n, L=990,
T=DNS/RFC822/SMTP,
A=TCP $h 143
That allowed me to define an relay for a certain domain like this in /etc/mail/mailertable
domain.com esmtp143:[domain.com]
I'm looking for the equivalent in postfix. I've looked through the docs and walkthroughs, but can't seem to find this setting.
The best I can come up with is editing the /etc/postfix/transport file too have a line
domain.com smtp:[domain.com:143]
A: Answer is almost what I thought.
In /etc/postfix/transport you need to put the following to deliver to anything other than port 25
domain.com smtp:domain.com:143
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40250671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to read a JSON file using Nix? How can I read a JSON file that exists in the filesystem with Nix? Is this natively supported?
A: If we have a file example.json like:
{
"rev": "fcc9a7714053acb1aaf6913b99b6f49e0d13b1b7"
}
We can use the following where fromJSON will return an attribute set:
nix-repl> v = builtins.fromJSON (builtins.readFile "/path/to/example.json")
nix-repl> v.rev
"fcc9a7714053acb1aaf6913b99b6f49e0d13b1b7"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69887992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to load @Configuration classes from separate Jars I have a SpringBoot main application, as well as a separate Maven module project that compiles as a separate Jar. The module has a Spring config class annotated with @Configuration, which I want to get loaded, when the main app loads.
Apparently, this does not happen out of the box (by just including the module to the main app). What else do I need to do, to get the module configuration class also get loaded by the main app?
A: @ComponentScan annotation will scan all classes with @Compoment or @Configuration annotation.
Then spring ioc will add them all to spring controlled beans.
If you want to only add specific configurations, you can use @import annotation.
example:
@Configuration
@Import(NameOfTheConfigurationYouWantToImport.class)
public class Config {
}
@Import Annotation Doc
A: The easiest way is to scan the package that the @Configuration class is in.
@ComponentScan("com.acme.otherJar.config")
or to just load it as a spring bean:
@Bean
public MyConfig myConfig() {
MyConfig myConfig = new MyConfig ();
return myConfig;
}
Where MyConfig is something like:
@Configuration
public class MyConfig {
// various @Bean definitions ...
}
See docs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30272999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Cached plan must not change result type Our service team is getting the error Cached plan must not change result type sometimes when I modify the length of a column or add a new column in the table.
I tried solutions mentioned on Stack Overflow like Postgres: "ERROR: cached plan must not change result type"
I have tried autosave=conservative to resolve this issue but still, I am able to reproduce this issue. I used below JDBC connection string
jdbc-url: jdbc:postgresql://172.16.244.10:5432/testdb?autosave=conservative
why is this property not working in my case?
Also, I tested with prepareThreshold=0 and its working fine. But I think it will impact performance because it will never use client-side prepared statements.
I just want to know the best solution to avoid this error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50328177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does Tensorflow support Python 3.8.5? I was just looking into Tensorflow for Python, and they say they support python version 3.5-3.8. What I can't understand is, does "3.8" mean strictly 3.8.0 OR 3.8.x(so 3.8.5 works)?
I know it can vary for different software.
I just want to make sure that IF 3.8.5 is supported, that I use that since it's a newer version.
Thanks in advance!
A: Yes, it does. I'm on Python 3.8.5 and using tensorflow==2.3.0.
Usually when a version is given as "3.5-3.8", it includes the patch versions as well. (Sometimes there could be issues that pop up but it's intended to include all patch version of the 'from' & 'to', inclusive.)
A: I would think it works in 3.8.5, but it would be safer to use 3.8.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63712637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ERROR 1349 (HY000): View's SELECT contains a subquery in the FROM clause I do not want to create two separate views.
create view fg_voted as (
select *
from (select f1.foto, count(f1.vote) stars,f1.vote, f1.voted
from fg_foto_bewertung f1
where f1.vote >= 3 group by f1.foto, f1.vote) vi_foto
where stars > 3);
How can I write it in a single query to create view?
A: How about this instead?
create view fg_voted as (
SELECT f1.foto,
count(f1.vote) stars,
f1.vote,
f1.voted
FROM fg_foto_bewertung f1
WHERE f1.vote >= 3
GROUP BY f1.foto,
f1.vote,
f1.voted
HAVING count(f1.vote) > 3
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5416809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React Native build release apk have issue " Process 'command 'npx'' finished with non-zero exit value 1 " My project use react native. When I build release apk my app on Android Studio 3.5.2, I sometime have an issue:
Process 'command 'npx'' finished with non-zero exit value 1
and here version react-native and node
System:
OS: macOS 10.15.2
CPU: (4) x64 Intel(R) Core(TM) i7-5557U CPU @ 3.10GHz
Memory: 1.91 GB / 16.00 GB
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 12.13.0 - /usr/local/bin/node
Yarn: 1.19.1 - /usr/local/bin/yarn
npm: 6.12.0 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
IDEs:
Xcode: 11.3/11C29 - /usr/bin/xcodebuild
npmPackages:
react: 16.9.0 => 16.9.0
react-native: 0.61.5 => 0.61.5
npmGlobalPackages:
react-native-cli: 2.0.1
i don't know why? Please Help me!!! thanks you.
A: error's screenshot
In my case, it happened after installing react-native-gifted-chat, so link to the instructions:
*
*go to node_modules/react-native-parsed-text/babel.config.js
*coomment second line // api.cache(true);
*close Metro Bundler run yarn run ios,
*you may need to run it twice // "ios": "react-native run-ios"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59551109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get column collation without flags CI, CS, AI, AS Is it possible get the column collation string without flags CI, CS, AI, AS?
For example:
If we have "Latin1_General_100_CS_AS" I need "Latin1_General_100" without "_CS_AS".
Thanks.
A: CS = Case Sensitive CI= Case Insensitive you need to have one or the other.
AS = Accent sensitive, AI = Accent Insensitive.
These codes specify how to sort. You need to select CI or CS and AS or AI
https://msdn.microsoft.com/en-us/library/ms143726.aspx
A: You can use the SQL replace function to remove instances of '_CI' in your query.
For example, the code below will remove _CI and _AI from collation names. You can use similar logic to remove the other characters you don't want.
SELECT name, REPLACE(REPLACE(name, '_CI',''), '_AI','') description FROM sys.fn_helpcollations();
A: Here you are a customable solution to exlude any falg you want from a table of names (for example collation names). If you want you can prepare a procedure or function to do it easier in your batches.
-- declaration of the input table
declare @input as table (name varchar(max));
-- declaration of the output table
declare @output as table (name varchar(max));
-- declaration of the table with flags you want to exclude from names
declare @exclude as table (flag varchar(max));
-- put flags you want to exclude into array
insert into @exclude (flag)
values ('CI'), ('CS'), ('AI'), ('AS');
-- put some collations into input table (as example for testing)
insert into @input
select distinct name
from sys.fn_helpcollations();
-- now we need to loop over all value in exclude table
declare @excludeCursor as cursor;
declare @flag as varchar(max);
set @excludeCursor = cursor for
select flag
from @exclude;
open @excludeCursor;
fetch next from @excludeCursor INTO @flag;
while @@FETCH_STATUS = 0
begin
update @input
set name = replace(name, concat('_', @flag), '')
where name like concat('%_', @flag)
or name like concat('%_', @flag, '_%')
-- The where clause above ensure that you replace exactly the flag added to your exclude table.
-- Without this caluse if you want to excldue for example a BIN flag and you have a BIN and BIN2 flags in your names
-- then the '2' character from the BIN2 will stay as a part of your collation name.
fetch next from @excludeCursor INTO @flag;
end
close @excludeCursor;
deallocate @excludeCursor;
-- prepare the output table with distinct values
insert into @output
select distinct name
from @input;
-- print the output
select *
from @output
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38108914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Syncing between Spreadsheets Currently have a working script for syncing cell format and values to another spreadsheet. I know it is very rough and ready, but it works!! I don't like that there are numbers in the For loop to achieve the correct cell numbers ... But this is needed to go from a single row by 9 columns, to the destination spreadsheet which is 9 rows by 1 column.
After talking to a colleague, the feedback is this will run quite slowly. I have rewritten this as 9 If statements but the problem is when dragging cells across it only updates the first cell, not the range.
There is the copyTo function, unfortunately, this only works inside a single spreadsheet.
The overall speed doesn't really matter, is there an alternative?
// for loop to populate all cells
for (let i = 21; i < 30; i++){ // starts at volumn V (22) for 9 columns (21 to 30)
var activeCell = registerSheet.getRange(activeRow, i + 1, 1, 1); // Register column, i + 1 so it increases
var registerValue = activeCell.getValue(); // get cell value
var registerFormat = activeCell.getBackground(); // get cell format
var i2 = 'C' + (33 + i) // this increases the target cell range from C54 to C62 using the loop. 54 (start row on form) - 21 (start i value) = 33
var range = form.getRange(i2); // designate target cell
range.setValue(registerValue); // set target cell value
range.setBackground(registerFormat); // set target cell format
}
}
A: Explanation:
*
*Your code is indeed inefficient because you are calling setValue()
and setBackground() 9 times each when you can simply use
setValues() and setBackgrounds() instead once. It will get even more inefficient for a larger number of iterations.
*There is a little trick you need to do and that is to convert the data (nrows,ncolumns) returned by getRange(activeRow,22,1,9).getValues() with a shape of (1,9) to a shape of (9,1) and do the same for the background colors as well:
var rowValues=registerSheet.getRange(activeRow,22,1,9).getValues().flat().map(r=>[r]); // V:AD
var rowBackcolors = registerSheet.getRange(activeRow,22,1,9).getBackgrounds().flat().map(r=>[r]); // V:AD
*After that you can simply set the data directly to the destination sheet:
var range = form.getRange('C54:C62'); // C54:C63
range.setValues(rowValues);
range.setBackgrounds(rowBackcolors);
Solution:
Replace the for loop with this:
var rowValues=registerSheet.getRange(activeRow,22,1,9).getValues().flat().map(r=>[r]); // V:AD
var rowBackcolors = registerSheet.getRange(activeRow,22,1,9).getBackgrounds().flat().map(r=>[r]); // V:AD
var range = form.getRange('C54:C62'); // C54:C63
range.setValues(rowValues);
range.setBackgrounds(rowBackcolors);
Related article:
What does the range method getValues() return and setValues() accept?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64443191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can place marker on an image using JavaScript that doesn't change after zooming this is our code but this code is give me the coordinates according to the body relative but when i change the zoom then its gives me different values i want to get coordinates and save in my backend that cannot be change this is my code
function FindPosition(oElement) {
console.log(oElement);
console.log(oElement.pageX);
if (typeof (oElement.offsetParent) != "undefined") {
for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
}
return [posX, posY];
}
else {
return [oElement.x, oElement.y];
}
}
function GetCoordinates(e) {
var PosX = 0;
var PosY = 0;
var ImgPos;
ImgPos = FindPosition(myImg.current);
// console.log(document.documentElement.scrollTop);
console.log(myImg);
if (!e) {
var e = window.event
};
if (e.pageX || e.pageY) {
PosX = e.pageX;
PosY = e.pageY;
}
else if (e.clientX || e.clientY) {
PosX = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
PosY = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
PosX = PosX - ImgPos[0];
PosY = PosY - ImgPos[1];
}
here is jsx which is written in react js
<div className="map" ref={"Here is map image"} onMouseDown={GetCoordinates}>
<img className='mapImage' src={map} alt="" />
<RoomIcon className="markerIcon" />
</div>
this is the css code
.map {
/* height: 100px; */
text-align: center;
margin: auto;
/* overflow: scroll; */
margin-top: 18px;
position: relative;
}
.mapForm .map img {
margin-top: 18px;
/* width: ; */
/* width: 1900px; */
/* zoom: 150%; */
}
.mapImage {
width: 600px;
/* zoom: 600%; */
}
.markerIcon {
z-index: 5;
position: absolute;
color: #e24e40;
left: 30px;
top: 30px;
}
A: You should save the relative (i.e. in percent) position of the marker on the image.
You can use getBoundingClientRect to simplify calculations:
const imgRect = myImg.current.getBoundingClientRect(); // imgRect is relative to viewport
const {clientX, clientY} = e; // clientX and clientY are relative to viewport
// since both are relative to viewport, it's useless to try to get their absolute position to the document. Simply compute their pos differences
const posXpct = (clientX - imgRect.x)*100 / imgRect.width;
const posYpct = (clientY - imgRect.y)*100 / imgRect.height;
Then you store posXpct and posYpct. And to position your marker from the previously saved values:
marker.style.position.left = posXpct+'%';
marker.style.position.top = posYpct+'%';
The additional advantage is that your marker will stay in place even if you resize physically the map (for instance on responsive devices with a width in %).
Don't forget to place the marker tip on this exact position, with something like (assuming your "tip" is at the bottom-center of the marker):
.marker {
transform: translate(-50%, -100%);
}
A: by using leaflet library you can change the address by the image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70972343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does python subprocess zip fail but running at shell works? I'm on Mac OS X using Python 2.7; using subprocess.call with zip fails yet running the same command at the shell succeeds. Here's a copy of my terminal:
$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call(['zip', 'example.zip', 'example/*'])
zip warning: name not matched: example/*
zip error: Nothing to do! (example.zip)
12
>>> quit()
$ zip example.zip example/*
adding: example/file.gz (deflated 0%)
I've also tried with full paths and had the same result.
A: Martijn's advice to use glob.glob is good for general shell wildcards, but in this case it looks as if you want to add all files in a directory to the ZIP archive. If that's right, you might be able to use the -r option to zip:
directory = 'example'
subprocess.call(['zip', '-r', 'example.zip', directory])
A: Because running a command in the shell is not the same thing as running it with subprocess.call(); the shell expanded the example/* wildcard.
Either expand the list of files with os.listdir() or the glob module yourself, or run the command through the shell from Python; with the shell=True argument to subprocess.call() (but make the first argument a whitespace-separated string).
Using glob.glob() is probably the best option here:
import glob
import subprocess
subprocess.call(['zip', 'example.zip'] + glob.glob('example/*'))
A: Try shell=True. subprocess.call('zip example.zip example/*', shell=True) would work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19585305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why is my label cutting off on the middle? WPF C# .NET So just recently when i started messing around with that blue bar thing (demo in the picture)
It started cutting off the labels for some weird reason.
In this picture you can see that it says OS: Win Available RAM etc but it should say Windows 8.1 and Available ram "And the exact number"
I DO NOT have any stack panels or anything covering it im suspecting that it has something to do with the blue bar (Picture 2)
im new to WPF.
PICTURE 2 ^
As you can see there is a blue bar next to the labels and Im starting to suspect hat it tis the one messing things up.
What is causing my labels to cut off?
<Page x:Class="TestApplication.systemPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestApplication"
mc:Ignorable="d"
Background="White"
d:DesignHeight="350" d:DesignWidth="525"
Title="systemPage">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="0*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<StackPanel Name="Stacky" Background="#03a3d2" HorizontalAlignment="Left" Height="350" VerticalAlignment="Top" Width="119" Margin="-262,-59,0,-59" Grid.RowSpan="3"/>
<Image x:Name="image" HorizontalAlignment="Left" Height="84" Margin="160,13,-260,-97" VerticalAlignment="Top" Width="100" Source="Images/Logo.png" Grid.ColumnSpan="2" Grid.Row="1"/>
<Label x:Name="osInfo" Content="OS:" HorizontalAlignment="Left" Margin="19,-42,-47,0" VerticalAlignment="Top" Height="26" Width="28" Grid.ColumnSpan="2"/>
<Label x:Name="ramInfo" Content="Available RAM:" HorizontalAlignment="Left" Margin="19,-21,-108,0" VerticalAlignment="Top" Height="26" Width="89" Grid.ColumnSpan="2"/>
<Label x:Name="systemHealth" Content="System Diagnose:" HorizontalAlignment="Left" Margin="19,72,-123,0" VerticalAlignment="Top" Height="26" Width="104" Grid.ColumnSpan="2"/>
<Label x:Name="cpuInfo" Content="CPU:" HorizontalAlignment="Left" Margin="19,0,-54,0" VerticalAlignment="Top" Height="26" Width="35" Grid.ColumnSpan="2"/>
<Label x:Name="CPUUsage" Content="N/A" HorizontalAlignment="Left" Margin="54,0,-85,0" VerticalAlignment="Top" Height="26" Width="31" Grid.ColumnSpan="2"/>
<Label x:Name="RAMUsage" Content="N/A" HorizontalAlignment="Left" Margin="108,-21,-139,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Height="26" Width="31"/>
<Label x:Name="osInfoLabel" Content="N/A" HorizontalAlignment="Left" Margin="47,-42,-78,0" VerticalAlignment="Top" Height="26" Width="31" Grid.ColumnSpan="2"/>
<Button x:Name="startScanButton" Click="startScanButton_Click" Background="Transparent" BorderThickness="0" Content="Start Diagnose" HorizontalAlignment="Left" Margin="-143,29,0,-61" VerticalAlignment="Top" Width="137" Height="32" Grid.Row="1"/>
<Label x:Name="connectionStateLabel" Content="N/A" HorizontalAlignment="Left" Margin="77,22,-108,0" VerticalAlignment="Top" Height="26" Width="31" Grid.ColumnSpan="2"/>
<Label x:Name="networkLabel" Content="Network:" HorizontalAlignment="Left" Margin="19,22,-77,0" VerticalAlignment="Top" Height="26" Width="58" Grid.ColumnSpan="2"/>
<Label x:Name="diagnoseResultLabel" Content="N/A" HorizontalAlignment="Left" Margin="123,72,-154,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Height="26" Width="31"/>
</Grid>
</Page>
A: It's getting cut off because you dragged and dropped controls onto the form rather then hand coded the XAML. If you want it dynamic, you need to hand craft the XAML with the proper layout panels (Grid, StackPanel, etc) using proper layout techniques. The designer produced code is not dynamic at all. It's very strict.
A: It is getting cut off because you have fixed width on most of the controls. for example,
<Label x:Name="diagnoseResultLabel" Content="N/A" HorizontalAlignment="Left" Margin="123,72,-154,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Height="26" Width="31"/>
Get rid of Width property (or make it Auto) and it would work. At the same time as @SledgeHammer pointed out, please craft the XAML with with some layouts.
A: What worked for me
I deleted this part from my XAMl
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="0*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
Not sure what it did but im assuming it deleted some transparent wall that was infront of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39277835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Parsing XML with unknown structure in Snowflake I have a bunch of XML files that define tree hierarchies (relations between ID:s) via nested tags. I want to parse it to tabular format using Snowflake's SQL syntax for semi-structured data. For XML files with known structure, I know how to do it. But for these trees, the structure is unknown at parsing time, in which case I don't know how to solve it. The generic pattern that repeats is
<Nodes>
<Node>
...
</Node>
</Nodes>
See below for example data and desired output.
Is there a way to accomplish this using Snowflake's SQL syntax?
Example data:
<Nodes>
<Node Id="1">
<Nodes>
<Node Id="2">
</Node>
<Node Id="3">
<Nodes>
<Node Id="4">
</Node>
<Node Id="5">
<Nodes>
<Node Id="6">
</Node>
</Nodes>
</Node>
<Node Id="7">
</Node>
</Nodes>
</Node>
<Node Id="8">
</Node>
</Nodes>
</Node>
<Node Id="9">
<Nodes>
<Node Id="10">
</Node>
</Nodes>
</Node>
</Nodes>
Desired tabular output is:
|-----------|---------|
| parent_id | node_id |
|-----------|---------|
| null | 1 |
| 1 | 2 |
| 1 | 3 |
| 3 | 4 |
| 3 | 5 |
| 5 | 6 |
| 3 | 7 |
| 1 | 8 |
| null | 9 |
| 9 | 10 |
|-----------|---------|
A: So RECURSIVE is the property on FLATTEN you want to use here:
with data as (
select parse_xml('<Nodes>
<Node Id="1">
<Nodes>
<Node Id="2">
</Node>
<Node Id="3">
<Nodes>
<Node Id="4">
</Node>
<Node Id="5">
<Nodes>
<Node Id="6">
</Node>
</Nodes>
</Node>
<Node Id="7">
</Node>
</Nodes>
</Node>
<Node Id="8">
</Node>
</Nodes>
</Node>
<Node Id="9">
<Nodes>
<Node Id="10">
</Node>
</Nodes>
</Node>
</Nodes>') as xml
)
select
GET(f.value, '@Id') as id
,f.path as path
,len(path) as p_len
from data,
TABLE(FLATTEN(INPUT=>get(xml,'$'), recursive=>true)) f
where get(f.value, '@') = 'Node'
;
gives:
ID PATH P_LEN
1 [0] 3
2 [0]['$']['$'][0] 16
3 [0]['$']['$'][1] 16
4 [0]['$']['$'][1]['$']['$'][0] 29
5 [0]['$']['$'][1]['$']['$'][1] 29
6 [0]['$']['$'][1]['$']['$'][1]['$']['$'] 39
7 [0]['$']['$'][1]['$']['$'][2] 29
8 [0]['$']['$'][2] 16
9 [1] 3
10 [1]['$']['$'] 13
from this you can now rebuild the hierarchy by find all the matches of path and taking the longest match.
OR
you can do a double nested loop like:
select
GET(f1.value, '@Id') as id
,GET(f2.value, '@Id') as id
,f1.value
,f2.*
, get(f2.value, '@')
from data,
TABLE(FLATTEN(INPUT=>get(xml,'$'), recursive=>true)) f1,
TABLE(FLATTEN(INPUT=>GET(xmlget(f1.value,'Nodes'), '$'))) f2
where get(f1.value, '@') = 'Node'
;
BUT it doesn't give you the first row, and snowflake behaves differently with expanding the nodes
<node>
<nodes>
<node></node>
</nodes>
<node>
and
<node>
<nodes>
<node></node>
<node></node>
</nodes>
<node>
which means you have to try handle both which is really gross.
EDIT:
So you can get closer but noting that if the second sub-case happens you can get node name get(f2.value, '@') = 'Node' thus we have something we can stuff into IFF and in the first case, the value of the flatten is 'Node' thus we can hard code fetch the parents -> nodes -> node, thus:
select
GET(f1.value, '@Id') as parent_id
,iff(get(f2.value, '@') = 'Node', GET(f2.value, '@Id'), GET(xmlget(xmlget(f1.value,'Nodes'),'Node'), '@Id')) as child_id
from data,
TABLE(FLATTEN(INPUT=>get(xml,'$'), recursive=>true)) f1,
TABLE(FLATTEN(INPUT=>GET(xmlget(f1.value,'Nodes'), '$'))) f2
where get(f1.value, '@') = 'Node'
and (get(f2.value, '@') = 'Node' OR f2.value = 'Node')
;
gives you:
PARENT_ID CHILD_ID
1 2
1 3
1 8
3 4
3 5
3 7
5 6
9 10
which is only missing the NULL, 1 and NULL, 9 rows that you wanted.
EDIT 2
So going back to my original suggestion, pulling the node id's and the paths out and then doing a LEFT JOIN on the nodes with a QUALIFY to keep the longest match can be done like so, and gives the desired output:
with data as (
select parse_xml('<Nodes>
<Node Id="1">
<Nodes>
<Node Id="2">
</Node>
<Node Id="3">
<Nodes>
<Node Id="4">
</Node>
<Node Id="5">
<Nodes>
<Node Id="6">
</Node>
</Nodes>
</Node>
<Node Id="7">
</Node>
</Nodes>
</Node>
<Node Id="8">
</Node>
</Nodes>
</Node>
<Node Id="9">
<Nodes>
<Node Id="10">
</Node>
</Nodes>
</Node>
</Nodes>') as xml
), nodes AS (
select
GET(f1.value, '@Id') as id
,f1.path as path
,len(path) as l_path
from data,
TABLE(FLATTEN(INPUT=>get(xml,'$'), recursive=>true)) f1
where get(f1.value, '@') = 'Node'
)
SELECT p.id as parent_id
,c.id as child_id
FROM nodes c
LEFT JOIN nodes p
ON LEFT(c.path,p.l_path) = p.path AND c.id <> p.id
QUALIFY row_number() over (partition by c.id order by p.l_path desc ) = 1
;
gives:
PARENT_ID CHILD_ID
null 1
1 2
1 3
3 4
3 5
5 6
3 7
1 8
null 9
9 10
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67283821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: nth-child not rendering in Dreamweaver So I have a newsBox with float left that contains a picture, title and small text that contains small segments of news. I have 2 news boxes in every row, and I want every 1st newsBox to have an extra margin-right with 20px.
I have used .newsBox:nth-child(odd) { margin-right:20px; } in the css, and it works fine in Chrome but doesn't render in Dreamweaver CS6.
Is this not an officially supported rule? Or there is another more "clean" way to do this?
Thanks in advance!
A: The Dreamweaver design view sucks, it usually never gives an accurate representation of how things look in a real browser.
As an alternative and a helpful answer to your issues you can try the live view from dreamweaver that was implemented after CS5.
Here is a video explaining how to set it up.
http://tv.adobe.com/watch/creating-time/dreamweavers-live-view-helps-you-save-time/
As a final note, try not to use the design view and tey to get more into the code... once you get used to it you can read the code and visualize almost exactly (usually always better than design view) how things look. So please do not trust design view in dreamweaver for development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17897565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Create event on Facebook I am trying to create an event using graph API with following code:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"venue name",@"name",
@"2012-01-13T17:00:00+0000",@"start_time",
@"2012-01-16T01:30:00+0000",@"end_time",@"location",@"location name ch",@"1234567890",@"id", nil];
[self.facebook requestWithGraphPath:@"me/events"
andParams:params
andHttpMethod:@"POST"
andDelegate:self];
but when I am trying to create the event, an alert comes with "Facebook Fail bad URL". Can any one suggest what I am doing wrong or what I am missing in parameters or anywhere or is there any other method?
-Thanx in advance
A: Maybe because there is no param id.
If you want to set venue location, use location_id.
A: Try doing the same thing with the same parameters here: https://developers.facebook.com/tools/explorer and see what the error message is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8905371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RDWeb Error 403 by choosing other Physical Path of Default Site the last days I tried to set up a Windows Server 2012 R2 IIS 8 Web-Server with the Laravel Framework and RDWeb.
RDWeb worked perfectly, until I tried to use Laravel.
The Problem is that I need to change the physical path of the Default Web Site form C:\inetpub\snx
to C:\inetpub\snx\public
and everytime I try this RDWeb write Error 403, if I want to open an rdp session by clicking on an item.
RDWeb Page if it does not work:
So the Error occurs every time I change the physical path to a "deeper" physical path.
Can you help me please?
Thank you
SUT_2
Here is the F12 Screenshot.
Something is forbidden - but I don't know how to solve the problem.
A: I have solved the problem - I just delted the web.config File in laravels /public-Folder.
Now, Laravel and RDWeb works - I hope I don't have further problems.
Thank you for your answers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41020412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Constraining types in Scala's generics to accept any kind of Int I want to write a function vaguely like:
def doubleit[A](a: A): A = {a + a}
But I want 'A' to mean any kind of Int, but not anything. Is there a way to give Scala a clue about what I want 'A' to mean?
def doubleit[A <: Int](a: A): A = {a + a}
is rejected by the compiler.
A: In plain Scala you can use type class Integral:
scala> def doubleit[A : Integral](a: A): A = implicitly[Integral[A]].plus(a, a)
doubleit: [A](a: A)(implicit evidence$1: Integral[A])A
scala> doubleit(2)
res0: Int = 4
scala> doubleit(BigInt(4))
res1: scala.math.BigInt = 8
Another possible syntax:
def doubleit[A](a: A)(implicit ev: Integral[A]): A = ev.plus(a, a)
ev is a commonly used name for those implicit parameters.
It is also possible to use normal operations like +, -, etc. instead of plus and minus:
def doubleit[A](a: A)(implicit ev: Integral[A]): A = {
import ev._
a + a
}
Or as per suggestion by @KChaloux, import from Integral.Implicits beforehand:
import Integral.Implicits._
def doubleit[A : Integral](a: A): A = a + a
If you want the function to support not only integers, but also Doubles, BigDecimals, etc. you can use Numeric instead of Integral:
import Numeric.Implcits._
def doubleit[A : Numeric](a: A): A = a + a
Explanation:
Writing [A : Integral] makes the function receive an implicit parameter of type Integral[A]. The implicits for all basic integral types are already defined in Scala, so you can use it with Int or BigInt straightaway. It is also possible to define new Integral types by defining a new implicit variable of type Integral[NewIntegralType] and implementing all the necessary methods.
The call to implicitly[Integral[A]] returns this implicit instance of Integral[A] which has method plus for addition, and other methods for performing other operations on integrals.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28093316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can you import exe4j script/project into install4j? Is it possible to import exe4j project into install4j? I have some legacy exe4j projects which I would like to import into install4j project.
A: Not directly, but you can do the following:
In your install4j project add a launcher (with arbitrary configuration) and open the project file in a text editor. Locate the launcher element and swap it out with the contents of your exe4j file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19001078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java Initialize String array Can I initialize string array like this
String arr=new String[];/* initialize the array */
A: No, because you need to tell the compiler how big you want the array to be. Remember that arrays have a fixed size after creation. So any of these are okay, to create an empty array:
String[] array = {};
String[] array = new String[0];
String[] array = new String[] {};
Admittedly an empty array is rarely useful. In many cases you'd be better off using an ArrayList<String> instead. Of course sometimes you have to use an array - in order to return a value from a method, for example.
If you want to create an array of a specific length and then initialize it later, you can specify the length:
String[] array = new String[5];
for (int i = 0; i < 5; i++) {
array[i] = String.valueOf(i); // Or whatever
}
One nice feature of empty arrays is that they're immutable - you can't change the length, and because then length is 0 there are no elements to mutate. So if you are going to regularly use an empty array of a particular type, you can just create it once:
private static final String[] EMPTY_STRING_ARRAY = {};
... and reuse that everywhere.
A: No you can't do that. It will produce compile error
you shoud write
String[] arr=new String[4]; //you should declared it sized
or
String[] arr={"asgk"};
or
String[] arr=new String[]{};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14620332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: ComputedFactors.profitPercentage -> detectionData.aggFields.profitPrecent What is the meaning of -> in the case of SCALA code?
ComputedFactors.profitPercentage -> detectionData.aggFields.profitPrecent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72258234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Infinite scroll : Sequencing post with Ajax and php I'm trying to infinite scroll my page using ajax php and jquery.
I have pasted the jquery code doe reference. I'm trying to get post in sequence using jquery and php. My jquery code sends the counta to the php script. php script then returns the result according to the number it receives. I'm trying to get the post in sequence so that they don't repeat. I get the post when the user reaches the bottom of the page.
Any other answers then this are also welcomed. But I just want to use the core of jquery meaning without inclusion of any external library.
var counta = 0;
$(document).ready(function(){
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 2000) {
// console.log("Here");
$.ajax({
type: 'post',
url: 'extendost.php',
data: '&articles='+counta,
success: function (data) {
alert(counta);
$("#morepost").append(data);
counta++;
},
error: function (data) {
alert(data);
},
});
}
});
A: This is what I would do:
<div id="start">0</div>
<div class="post_content"></div>
$(window).data('ajaxready', true).scroll(function(e) {
var postHeight = $('#post_content').height();
if ($(window).data('ajaxready') == false) return;
var start = parseInt($('#start').text());
var limit = 30; // return 30 posts each
if ($(window).scrollTop() >= postHeight - $(window).height() - 400) {
var height = $(window).scrollTop();
$(window).data('ajaxready', false);
if (start > 0) {
var new_start = start + limit;
var dataString = {articles : start, limit : limit};
$.ajax({
cache: false,
url: 'extendost.php',
type: 'POST',
data: dataString,
success: function(data) {
if ($.trim(data).indexOf('NO POST') > -1) {
/* stop infinite scroll when no more data */
$('#start').text(0);
} else {
$('#post_content').append(data);
$('#start').text(new_start);
}
$(window).data('ajaxready', true);
}
});
}
}
});
This way your #start value will change as it scroll and ready for the next scroll value
Then base on the $start (offset) and $limit, make your query like
$query = "SELECT * FROM articles LIMIT {$limit} OFFSET {$start}";
if (!$result = mysqli_query($con, $query) {
echo 'NO POST';
} else {
// fetch and echo your result;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46016001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does my Path.expanduser keep getting this following error message? ['str' object has no attribute '_drv'] I am trying to use Path.expanduser() to extract the base directory of all of my web app users. I intend to use the base directory to locate the Downloads folder and direct all of my web app exports into their respective Downloads folder. But when I implement this function and try to test it out by checking directory it returns me, I only get the error message of ['str' object has no attribute '_drv'] instead of the base directory.
Imported pathlib into my app.py
snippet of my app.py
from flask import Flask, flash, redirect, render_template, request, session, abort, jsonify, url_for, Markup
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField, SelectField, SelectMultipleField
from werkzeug import secure_filename
from pprint import pprint
from pathlib import Path
@app.route('/process_pt', methods = ['GET', 'POST'])
def process_pt():
if request.method == 'POST':
colSelection = request.form.get('selectedCol')
cols = colSelection.split(",")
valSelection = request.form.get('selectedVal')
global filtered_df
filtered_df = pd.pivot_table(filtered_df, values=[valSelection], index=cols, aggfunc=np.sum)
filtered_df.reset_index()
dl_path = Path.expanduser('~\\Users')
print(str(dl_path))
return render_template(
'summarized_df.html',
data = filtered_df.to_html()
)
Expected: dl_path to return the base directory
Actual: Error Message 'str' object has no attribute '_drv'
A: You should be using os.path.expanduser for working with strings.
pathlib.Path.expanduser is a method of pathlib.Path objects. You could convert your string to such an object and do what you want with Path('~\\Users').expanduser().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56289823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Select2 not removing id from token list I am using Select2 to assign content to other users (multiple tags). It all works great except I can not find out how to remove assignees once added.
Once I have added a user to the list of assignees in my modal, after I click the cross with class select2-search-choice-close, the corresponding list item with class select2-search-choice is deleted from the input field, but the id is not removed from assignee tokens (and is thus passed to the controller when I submit the form).
What am I missing?
NOTE: I am not 100% sure whether this is related, but I noticed that the assignee_ids passed when I submit the form sometimes contain the same id several times (e.g: assignee_ids => "12,1,4,4").
This is how I initialize the input:
$('#assignable_item_assignment_assignee_ids').select2({
minimumInputLength: 2
tags: true
tokenSeparators:[',', ' ']
createSearchChoice: (term, data) ->
{id: term, new_choice: true}
multiple: true
ajax:
url: url
dataType: 'json'
quietMillis: 150
data: (term, page) ->
query: term
results: (data, page) ->
return {results: data}
formatResult: userFormatResult
formatSelection: userFormatSelection
formatInputTooShort: (term, minLength) ->
"Search existing users or assign by email"
dropdownCssClass: 'select2'
})
And this is the form I am using:
<%= form_for AssignableItemAssignment.new, url: assignable_items_assignments_path, html: { class: "form-horizontal", id: "new-assignment" } do |f| -%>
<fieldset>
<div class="control-group">
<%= f.label :to %>
<div class="with-spinner">
<%= f.text_field :assignee_ids, placeholder: "Search users by name or email", class: 'select2' %>
</div>
</div>
<div class="control-group">
<%= f.label :add_a_message %>
<%= f.text_area :message, rows: 3, placeholder: "Add a message for your recipients (optional)" %>
</div>
<%= f.button "Submit", disable_with: 'Submiting' %>
</fieldset>
<% end %>
A: I had a similar problem, which is fixed after installing latest release (3.3.2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15584301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: If else condition in RecyclerView onBindViewHolder I'm trying to set up a if else statement on my onBindViewHolder() such that it checks for status, then sets text and text color depending on the status found.
I've tried but it just gives me the results of the first condition on every item in the RecyclerView.
Here is my code for the Adapter:
public class PreviousSettingsAdapter extends RecyclerView.Adapter<PreviousSettingsAdapter.PreviousSettingsViewHolder> {
private List<Setting> SettingsModelList;
private Context context;
public PreviousSettingsAdapter(Context context, List<Setting> SettingsModelList) {
this.SettingsModelList = SettingsModelList;
this.context = context;
}
public class PreviousSettingsViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.date)
TextView date;
@BindView(R.id.Setting_id)
TextView SettingId;
@BindView(R.id.status)
TextView status;
public PreviousSettingsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
@NonNull
@Override
public PreviousSettingsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.placed_Setting_items, parent, false);
return new PreviousSettingsViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull PreviousSettingsViewHolder holder, int position) {
Setting singleSetting = SettingsModelList.get(position);
holder.date.setText(singleSetting.getCreatedAt());
holder.SettingId.setText("Setting Id: " + String.valueOf(singleSetting.getId()));
boolean paymentStatus = singleSetting.getConfirmed();
boolean fulfilledStatus = singleSetting.getProcessed();
if (paymentStatus && !fulfilledStatus ) {
holder.status.setText(R.string.processed);
holder.status.getResources().getColor(R.color.colorOrange);
} else
if (!paymentStatus && !fulfilledStatus) {
holder.status.setText(R.string.unchanged);
holder.status.getResources().getColor(R.color.colorRed);
} else if(paymentStatus && fulfilledStatus){
holder.status.setText(R.string.delivered);
holder.status.getResources().getColor(R.color.colorGreen);
}else{
holder.status.setText(" ");
}
}
@Override
public int getItemCount () {
return SettingsModelList.size();
}
}
A: Debug and kindly see that the paymentStatus and fulfilledStatus values.As you said, it might be going into the if loop with those conditions satisfying.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54017247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How show version number in title of installation in WIX? I need to display the version number in the title along with the application name.
Currently, it looks like
Here is my wix snippet:
<Product Id="$(var.ProductId)" Name="Test Application" Language="1033" Version="$(var.ProductVersion)" Manufacturer="Test1111 Inc"
UpgradeCode="C9BC6B42-FCAF-4E96-8F8F-E9D0AC4F393B">
If I change it (append version number in the Name attribute) as below, it will display the version number in all the places Title, Welcome text/description but I just want to change in Title.
<Product Id="$(var.ProductId)" Name="Test Application $(var.ProductVersion)" Language="1033" Version="$(var.ProductVersion)" Manufacturer="Test1111 Inc"
UpgradeCode="C9BC6B42-FCAF-4E96-8F8F-E9D0AC4F393B">
How we can accomplish this in Wix?
A: Localization Override: You can try to add a localization file and then override the WelcomeDlgTitle string (the WiX GUI string list / list of string identifiers can be found here (for English):
*
*Note that this assumes the Mondo dialog set:
*
*Add to WiX markup: <UIRef Id="WixUI_Mondo" />
*Add reference to %ProgramFiles(x86)%\WiX Toolset v3.11\bin\WixUIExtension.dll
*WiX Hello World Sample in Visual Studio (WiX markup with comments towards bottom is usually enough for developers to get the gist of things)
*Right click your WiX project in Visual Studio => Add => New Item...
*Select WiX v3 in the left menu. Double click Localization file (very common to add a WiX v4 file instead, double check please)
*Add the string below to the localization file:
<?xml version="1.0" encoding="utf-8"?>
<WixLocalization Culture="en-us" xmlns="http://schemas.microsoft.com/wix/2006/localization">
<String Id="WelcomeDlgTitle">{\WixUI_Font_Bigger}Welcome to the [ProductName] [ProductVersion] Setup Wizard</String>
</WixLocalization>
*Compile and test
Sample Dialog:
WiX GUI: I am quite confused myself with WiX GUI, hence I wrote this little overview and "check list" to remember better (uses a similar approach to change the style of a dialog entry): Changing text color to Wix dialogs.
Links:
*
*WiX UI Sources: (languages strings and dialog sources)
*
*https://github.com/wixtoolset/wix3/tree/develop/src/ext/UIExtension/wixlib
*WiX UI English Strings:
*
*https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/WixUI_en-us.wxl
*WiX UI Norwegian Strings:
*
*https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/WixUI_nb-NO.wxl
*There are many such language files, use above link for full list
A: WiX UI extension doesn't allow this type of customization. Your two chances would be
1) define Name="Test Application $(var.ProductVersion)" (Side effect. version listed in programs and features twice
2) Stop using the WiXUI extension and instead clone all the code from https://github.com/wixtoolset/wix3/tree/develop/src/ext/UIExtension/wixlib into your project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55221550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using 'this' in javascript function attached to object property Edit:
The question referred to as the duplicate doesn't really answer why arrow functions shouldn't be used to access a non-lexical this. It just answers that arrow functions automatically bind this. My situation is that using an arrow function rather than a normal function cause me to lose the correct reference of this. If you need this outside of the current scope, use a normal function.
I've searched around for a solution to my problem with no luck. Even if I was pointed in the right direction as to what I needed to do would be awesome! My problem essentially is that this.Favkey is undefined here:
const setFavorite = val => {
console.log(this);
this.Favorite = val;
AsyncStorage.setItem(this.Favkey, JSON.stringify(val));
};
This function is getting assigned to a particular object like so:
for (const obj of objArray) {
obj.Favkey = `c${obj['-id=']}`;
obj.Favorite = await getFavorite(obj.Favkey);
obj.SetFavorite = setFavorite;
}
And then I am calling this later on a button:
onPress={val => props.myObj.SetFavorite(val)}
In the first block of code, I want this to be the specific obj that I am attempting to enclose the function on. But this.Favkey in setFavorite is undefined. What is printed out instead on console.log(this) is what I think is the whole prototype of Object. So I'm not quite sure what I'm doing wrong here.
A: Don't use an arrow function - it loses the binding to this which is what you're trying to access. Just use a normal function:
const setFavorite = function(val) {...};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56783350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to determine if a File has finished downloading I download GB's of stuff every day. And I get all OCD and organize files and folders so many times during the day and it's driving me nuts.
So I plan on writing an app that detects when a file has finished downloading (to the Windows Downloads folder), and then places it in its relevant categorized folder.
E.g.:
I download an app. When the app detects that the file has finished downloading, it places it into Sub-folder Applciations. Or, when I finish downloading a Document, the document is then placed inside the Documents sub-folder of the Downloads folder.
The problem I have here is that I don't want to do this unless there is a definitive way to tell whether a file has finished downloading.
Things I have thought of:
*
*I have thought about implementing FileSystemWatcher on the Downloads folder, and when a new file is created there, it gets added to a list. And when FileSystemWatcher detects that the file size has changed, or has been modified, it will start a timer; the purpose of this timer is to determine after x amount of seconds whether the download is complete. It does this by assuming (wrongly) that if a file's size has not increased in a specified period of time, the download is complete.
That's all I can think of. Any ideas on how this kind of thing can be accomplished?
A: File is blocked when it is accessed. Not every file. But you could check whether the file is open by another application. If the file is not open - this should tell you, that it has downloaded completely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13325715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generating new column of data by aggregating specific columns of dataset My dataset has a few interesting columns that I want to aggregate, and hence create a metric that I can use to do some more analysis.
The algorithm I wrote takes around ~3 seconds to finish, so I was wondering if there is a more efficient way to do this.
def financial_score_calculation(df, dictionary_of_parameters):
for parameter in dictionary_of_parameters:
for i in dictionary_of_parameters[parameter]['target']:
index = df.loc[df[parameter] == i].index
for i in index:
old_score = df.at[i, 'financialliteracyscore']
new_score = old_score + dictionary_of_parameters[parameter]['score']
df.at[i, 'financialliteracyscore'] = new_score
for i in df.index:
old_score = df.at[i, 'financialliteracyscore']
new_score = (old_score/27.0)*100 #converting score to percent value
df.at[i, 'financialliteracyscore'] = new_score
return df
Here is a truncated version of the dictionary_of_parameters:
dictionary_of_parameters = {
# money management parameters
"SatisfactionLevelCurrentFinances": {'target': [8, 9, 10], 'score': 1},
"WillingnessFinancialRisk": {'target': [8, 9, 10], 'score': 1},
"ConfidenceLevelToEarn2000WithinMonth": {'target': [1], 'score': 1},
"DegreeOfWorryAboutRetirement": {'target': [1], 'score': 1},
"GoodWithYourMoney?": {'target': [7], 'score': 1}
}
EDIT: generating toy data for df
df = pd.DataFrame(columns = dictionary_of_parameters.keys())
df['financialliteracyscore'] = 0
for i in range(10):
df.loc[i] = dict(zip(df.columns,2*i*np.ones(6)))
A: Note that in Pandas you can index in ways other than elementwisely with at. In the four-liner below, index is a list which can then be used for indexing with loc.
for parameter in dictionary_of_parameters:
index = df[df[parameter].isin(dictionary_of_parameters[parameter]['target'])].index
df.loc[index,'financialliteracyscore'] += dictionary_of_parameters[parameter]['score']
df['financialliteracyscore'] = df['financialliteracyscore'] /27.0*100
Here's a reference although I personally never found it useful in my earlier days of programming... https://pandas.pydata.org/pandas-docs/stable/indexing.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51429286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Better way to check bounds I am checking to see in an object is outside the bounds of a box. If it is outside the bounds of the box, then I put it back in.
if position.left < dot_radius
dot.css 'left', dot_radius
if position.left > display_width - dot_radius
dot.css 'left', display_width - dot_radius
if position.top < dot_radius
dot.css 'top', dot_radius
if position.top > display_height - dot_radius
dot.css 'top', display_height - dot_radius
The code is a little verbose. Is there a better way to write it?
A: You could make a simple function:
bounds = (prop, min, max) ->
val = position[prop];
if (val < min)
dot.css prop, min
if (var > max)
dot.css prop, max
bounds 'left', dot_radius, display_width - dot_radius
bounds 'top', dot_radius, display_height - dot_radius
You even might put the dot_radius inside the function, though it gets less reusable then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17605202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how Apollo client optimisticResponse working http://dev.apollodata.com/react/mutations.html
I am trying out with optimisticResponse, but i am confused... and couldn't get it working on my local.
My questions are:
*
*will optimisticResponse update the props and hence the re-render? how important is __typename: 'Mutation' can you leave it?
*updateQueries is for new record appear? is this function trigger automatically or you need to invoke it?
is there any full example of out there which include the apollo server side?
A: Solution found:
const networkInterface = createNetworkInterface('http://localhost:8080/graphql');
this.client = new ApolloClient({
networkInterface,
dataIdFromObject: r => r.id
}
);
dataIdFromObject is the one thing i am missing during the Apolloclient initiation
dataIdFromObject (Object) => string
A function that returns a object identifier given a particular result object.
it will give unique ID for all result object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40687823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use slack auth running in docker from within a private IP addressed enterprise network We are deploying our application in docker within our enterprise. The host machine has an RFC1918 space in the 10/8 network and the docker containers are on 172.21/16 space.
I'm trying to use slack authentication to authenticate our node/react application which works locally in development mode, but I believe the second layer of private address space may be throwing a wrench into the communications. The redirect url for the node/react app is using the IP of the host machine, which is what you are hitting when you attempt to login to the server via the web interface. I've tried many combinations but basically you navigate to 10.1.1.4:3000 which is configured in the Slack API as our redirect URL and is also configured in the .env file for our node app. Once you click continue on the slack auth page the page doesn't load but just hangs.
I've changed the redirect URL to localhost, the gateway IP of the docker network, and the IP address of the host machine the docker container is running on, which I think is the way to go, but nothing lets me hit my app.
A: If you're using Linux docker hosts, you could try using the host network mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56066939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert Doc,Docx to TIFF with delphi Hi
How can i convert doc,docx to TIFF whith delphi?
A: In short, you can't.
Doc and TIFF are two completely different things. It's not like converting from BMP to TIFF (two image formats), or WAV to MP3 (two audio formats). For very limited Word documents, I suppose you could run Word through OLE automation (or maybe even embed Word in your application for better control), then take a screenshot, but I think your problems runs deeper than that. Maybe you could provide some more info about what you try to achieve?
A: I've done it from within Word, however the code is long lost I'm sorry.
I created an Office plugin using the Add-in Express Component.
I used Word automation to convert the current document to RTF, used WP-Tools to render, which gave me the bitmap for each page. Finally I used GDI+ to create the multi-page TIFF.
A: The standard trick is like with word to pdf: find a virtual printer that outputs tiffs, and instrument word over OLE to print to the virtual printer.
If I put "tiff printer virtual" in google, I see quite some hits. (not all free though, and of course it complicates installation to use two programs (word+printer) to do this)
A: Word is not able to save its documents to TIFF format. Your best options are to use third party software which can do that. Just google for Doc to Tiff.
A: When looking for tools to do this, you should also be aware that not all TIFF files are faxable. TIFF files can contain a whole range of image formats and sizes. You need to find a tool which can convert your document to monochrome bitmaps 1728 pixels wide, with the page images each in a single strip and with a compression method supported by your fax software.
A: A good fax software usually comes with a fax printer driver, check with the maker of your fax software if they have one. With a driver you can simply use OLE Automation to make Word print the document to this driver. The fax software we use expects the fax number and other parameters embedded in the text like this: @@NUMBER12345678@@
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3912379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the use case of Firebase Queue? I am doing some experiments on Firebase realtime database. Though I came across firebase-queue. This is what docs says https://github.com/firebase/firebase-queue.
A fault-tolerant, multi-worker, multi-stage job pipeline built on the Firebase Realtime Database.
What does it mean ?
A: firebase-queue lets you use Realtime Database to submit jobs to a backend server you control. Clients write into the database, and that data is received by firebase-queue, where you can do whatever you want with it.
If you have interest in running backend code that reacts to changes in your Firebase project, you are much better off looking into Cloud Functions for Firebase, because you won't have to manage a backend server at all. You just write and deploy code to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43275602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I get how many computers I have delivered per date in SQL Server? I have a table with the following columns:
Inventory
ID,
SerialComputer,
RegistrationDate,
Deadline
I want to make a query in which the first column shows me all the dates on which computers have been delivered, and next to the amount of computers that were delivered on that date, how can I make that possible in SQL Server?
I know I get the dates this way:
SELECT DISTINCT Deadline
FROM Inventory
ORDER BY Deadline
How do I add the COUNT () with the SerialComputer column?
A: Do aggregation using GROUP BY clause :
SELECT Deadline, COUNT(*) AS [# computers delivered]
FROM Inventory
GROUP BY Deadline;
DISTINCT will remove duplicate values so, that will not help you.
A: Presumably, deadline is the delivery date. If so, you want aggregation:
SELECT Deadline, COUNT(*)
FROM Inventory
GROUP BY Deadline
ORDER BY Deadline
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59053945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parallel checkout of different branches of the same repository I am trying to figure out if is possible to have on the server cloned more that one branches from the same repository. Those branches are cloned into different folders through ssh.
Let's say:
feature/feature1 -> C:\feature1 (user1)
feature/feature2 -> C:\feature2 (user2)
feature/feature3 -> C:\feature3 (user3)
feature/feature4 -> C:\feature4 (user4)
The goal is to access every folder by different user at the same time (more different checkouts at the same time are needed). Pulls, pushes, commits are in parallel proces ...
Does this solution make sense? We need to work on server as our system has access just there. There is not access to our local PCs.
A: The git worktree method described in comments will work on a Unix/Linux system, but probably not on Windows if your different users have different accounts (which they should, for sanity if nothing else). It has some drawbacks: in particular, while each working tree gets its own index, all the working trees share one single underlying repository, which means that Git commands that must write to the repository have to wait while someone else has the repository databases busy. How disruptive this might be in practice depends on how your users would use this.
It's usually a much better idea to give each user their own full clone, even on a shared server, and even if it's a Unix/Linux system. They can then push to, and fetch from, one more clone on that shared server, that you designate as the "source of truth". There is only one drawback to this method of sharing, which is that each clone occupies its own extra disk space. However, this tends to be minor: when cloning a local repository locally, using file-oriented "URLs":
git clone /path/to/source-of-truth.git work/my-clone
Git will, to the extent possible, use "hard links" to files to save space. These hard links work quite well, although the links "break apart" over time (as files get updated) and gradually the clones wind up taking more and more space. This means that every once in a while—say, once a month or once a year or so, depending on activity—it may be helpful for space purposes to have your users-on-the-shared-server delete their clones and re-clone at a time that's convenient for them. This will re-establish complete sharing.
(Of course, disk space is cheap these days, and the right way to handle this on a modern Linux server is probably to set up a ZFS pool with, say, a bunch of 8 or 12TB drives in a RAIDZ1 or RAIDZ2 configuration to get many terabytes of usable storage at around $30 per terabyte, even counting overhead and the cost of cabling and so on. You'll probably pay more for some high end Intel CPU than you do for all the drives put together.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69433476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using the ROLLUP function in CASE Statement I have a query where I need to dynamically change the column I perform the ROLLUPon.
So here is the sample data:
+-----------+---------+-------+--------+-------+----------------------------+
|Location_ID|PLANT | ... |COUNT_IO|TIME_IO|TIME_TARGET_OEE_100_FILTERED|
+-----------+---------+-------+--------+-------+----------------------------+
|01105123000|1 | ... |10 |50 |75 |
+-----------+---------+-------+--------+-------+----------------------------+
|01105123001|1 | ... |13 |65 |75 |
+-----------+---------+-------+--------+-------+----------------------------+
|01105123002|1 | ... |15 |75 |65 |
+-----------+---------+-------+--------+-------+----------------------------+
|01105123003|1 | ... |13 |65 |75 |
+-----------+---------+-------+--------+-------+----------------------------+
|01101113001|2 | ... |40 |200 |400 |
+-----------+---------+-------+--------+-------+----------------------------+
|01101113002|2 | ... |20 |100 |400 |
+-----------+---------+-------+--------+-------+----------------------------+
desired output (ROLLUP on LOCATION_ID):
+-----------+---------+-------+--------+-------+
|Location_ID|PLANT | ... |COUNT_IO|OEE |
+-----------+---------+-------+--------+-------+
|01105123000|1 | ... |10 |66,66 |
+-----------+---------+-------+--------+-------+
|01105123001|1 | ... |13 |86,66 |
+-----------+---------+-------+--------+-------+
|01105123002|1 | ... |15 |115,38 |
+-----------+---------+-------+--------+-------+
|01105123003|1 | ... |13 |86,66 |
+-----------+---------+-------+--------+-------+
|NULL |1 | ... |51 |87,93 |
+-----------+---------+-------+--------+-------+
desired output (ROLLUP on PLANT):
+-----------+---------+-------+--------+-------+
|Location_ID|PLANT | ... |COUNT_IO|OEE |
+-----------+---------+-------+--------+-------+
|01105123000|1 | ... |51 |87,93 |
+-----------+---------+-------+--------+-------+
|01105123001|1 | ... |51 |87,93 |
+-----------+---------+-------+--------+-------+
|01105123002|1 | ... |51 |87,93 |
+-----------+---------+-------+--------+-------+
|01105123003|1 | ... |51 |87,93 |
+-----------+---------+-------+--------+-------+
|01101113001|2 | ... |60 |37,5 |
+-----------+---------+-------+--------+-------+
|01101113002|2 | ... |60 |37,5 |
+-----------+---------+-------+--------+-------+
|... |NULL | ... |111 |50,92 |
+-----------+---------+-------+--------+-------+
sample code:
SELECT
--Dimensions:
--VALUES_FOR_TABLEAU_METADATA:
DISTINCT LOCATION_ID,
CONTINENT,
COUNTRY,
PLANT,
BUSINESS_UNIT,
PRODUCT,
--Measures (KPI's):
--Count:
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN SUM(COUNT_IO) OVER (PARTITION BY BUSINESS_UNIT)
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN SUM(COUNT_IO) OVER (PARTITION BY PLANT)
ELSE SUM(COUNT_IO) OVER (PARTITION BY LOCATION_ID)
END AS "COUNT_IO",
--OEE:
CASE
WHEN TIME_IO = 0 OR TIME_TARGET_OEE_100 = 0
THEN 0
ELSE
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN SUM(TIME_IO) OVER (PARTITION BY BUSINESS_UNIT) *100/SUM(TIME_TARGET_OEE_100_FILTERED) OVER (PARTITION BY BUSINESS_UNIT)
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN SUM(TIME_IO) OVER (PARTITION BY PLANT) *100/SUM(TIME_TARGET_OEE_100_FILTERED) OVER (PARTITION BY PLANT)
ELSE SUM(TIME_IO) OVER (PARTITION BY LOCATION_ID) *100/SUM(TIME_TARGET_OEE_100_FILTERED) OVER (PARTITION BY LOCATION_ID)
END
END AS "OEE"
FROM VALUES_FOR_TABLEAU_METADATA
WHERE
COUNT_TARGET_OEE != 0 AND PLANT LIKE <Parameters.Plant> AND BUSINESS_UNIT LIKE <Parameters.BU> AND LOCATION_ID LIKE <Parameters.LocationID> AND WORKING_DAY BETWEEN <Parameters.WorkingDay_Start> AND <Parameters.WorkingDay_End>
GROUP BY
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN LOCATION_ID
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN LOCATION_ID
ELSE ROLLUP(LOCATION_ID)
END,
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN PLANT
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN ROLLUP(PLANT)
ELSE PLANT
END,
CASE
WHEN <Parameters.BU> = '%' AND <Parameters.Plant> = '%' THEN ROLLUP(BUSINESS_UNIT)
WHEN <Parameters.BU> != '%' AND <Parameters.Plant> = '%' THEN BUSINESS_UNIT
ELSE BUSINESS_UNIT
END,
CONTINENT, COUNTRY, PRODUCT, COUNT_IO, COUNT_TARGET_OEE, TIME_IO, TIME_TARGET_OEE_100, TIME_TARGET_OEE_100_FILTERED
I guess that the problem is caused by the ROLLUP in the CASE statement, since the code up to the GROUP BY is working fine. Also I am not quite sure if the usage of my CASE statement is used properly.
The Parameters may look quite weird, but they are for use in Tableau and work fine.
The error I get is:
ORA-00904: "ROLLUP": invalid identifier
A: The best and easiest way to work with Tableau is to let it generate optimized SQL based on what you express in Tableau. Don't use custom SQL with Tableau except in rare situations. You get a lot more flexibility and performance that way.
In this case, I recommend just connecting to VALUES_FOR_TABLEAU_METADATA from Tableau.
*
*Define a string valued parameter to allow the user to choose the dimension for his "rollup", say called Dimension_For_Rollup with a list of two possible values: "Location" and "Plant".
*Define a calculated field called Selected_Dimension defined as if [Dimension_For_Rollup] = "Location" then [Location Id] else [Plant] end
*Use Selected_Dimension on your viz as desired.
*Show the parameter control for Dimension_For_Rollup
So the user can toggle between Dimensions for Rollup as he wishes, and Tableau will generate optimized SQL, cache the query as needed.
Your Count_IO or Time_IO stats can be expressed in different ways in Tableau, possible needing Tableau's level of detail (LOD) calcs, but again -- your Tableau experience will be better if you don't try to hard code everything in SQL in advance. You can use Tableau that way, but you're making life hard on yourself and giving up a good part of the benefit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48681985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Miniforge Conda "PackagesNotFoundError" on ARM processor for PyTorch I am unable to install any packages with miniforge 3 (conda 4.11.0).
I am attempting this on a Jetson Nano Developer Kit running Jetpack. Initially it had conda installed but it seems to have gone missing, so I decided to reinstall conda. It looks like the base version of anaconda/miniconda is having issues running on ARM processors, and so I downloaded miniforge which apparently is working.
I have set up an environment successfully, but attempting to download pytorch gives the following error:
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
PackagesNotFoundError: The following packages are not available from current channels:
- pytorch
Current channels:
- https://conda.anaconda.org/pytorch/linux-aarch64
- https://conda.anaconda.org/pytorch/noarch
- https://conda.anaconda.org/abinit/linux-aarch64
- https://conda.anaconda.org/abinit/noarch
- https://conda.anaconda.org/matsci/linux-aarch64
- https://conda.anaconda.org/matsci/noarch
- https://conda.anaconda.org/conda-forge/linux-aarch64
- https://conda.anaconda.org/conda-forge/noarch
To search for alternate channels that may provide the conda package you're
looking for, navigate to
https://anaconda.org
and use the search bar at the top of the page.
This is for Python 3.7.12. It seems this issue persists no matter what version of pytorch I try to install.
I am however able to install some other packages, as I was able to install beautifulsoup4.
A: There is no linux-aarch64 version of pytorch on the default conda channel, see here
This is of course package specific. E.g. there is a linux-aarch64 version of beautifulsoup4 which is why you wre able to install it without an issue.
You can try to install from a different channel that claims to provide a pytorch for aarch64, e.g.
conda install -c kumatea pytorch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70954061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Styling a Div Class within Div ID I have a page that has the following div element:
<div id="name" class="class_name">
Which of the following should I use to style the class?
#name .class_name
name .class_name
#name class_name
A: Just #name would be enough to apply the style only to that specific element:
#name {
// your styles here
}
If you want to apply the style to all the elements using the class_name class, then you can use:
.class_name {
// your styles here
}
A: #name .class_name will apply to the children elements of your div with the .class_name class.
There must not be any spaces between.
You should use: #name.class_name because it is the correct syntax.
But, when working with identifiers, it should be enough to use it alone.
#name {
// some properties
}
But let's say you have a unique block, which inherits some generic styles, then you could use #idenifier.class to mix styles.
#comments {
width: 453px;
}
#comments.links
{
border: 0 none;
}
A: If I got your question right you use
#name .class_name
as in
#name .class_name {
color:#000;
}
But actually you don't need to do that.
If #name and .class_name are oly used in that div you can just drop the .class_name. Otherwise, if you use multiple stuff with .class_name that don't share the same properties as div #name, you should separate them.
.class_name {
color:#000;
}
#name {
width:600px;
}
A: ID's should be unique, so there isn't much point in styling both the id of the div and the class_name.
Just using the ID of the div is fine if that's your goal.
#name
{
//styles
}
If you want to style every div that has that class name, then just use
.class_name
{
//styles
}
A: You can read about CSS selectors here:
http://reference.sitepoint.com/css/selectorref
In the CSS you can reference it by class:
.class_name { color: green; }
or by id using #id
#name { color: green; }
or by element type
div { color: green; }
//or by combinations of the above
div.class_name { color: green; }
div#name { color: green; }
A: If you already have #name and .class_name styled, but for some reason you want to style
<div id="name" class="class_name"></div>
(that is, a specific style to the element with an id of "name" AND a class of "class_name"), you can use
#name.class_name {
/* note the absence of space between the id and class selector */
...
}
Bear in mind that this selector is not supported by Internet Explorer 6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2556701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: OrderBy List by another collection Have some problem.
Need to sort the list by another collection:
List<Books> b = new List<Books>();
Class Books:
public partial class Books
{
public Books()
{
this.BookAuthors = new HashSet<BookAuthors>();
}
public int BookID { get; set; }
public string BookName { get; set; }
public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}
Class BookAuthors:
public partial class BookAuthors
{
public int Id { get; set; }
public int AuthorID { get; set; }
public int BookID { get; set; }
public virtual Books Books { get; set; }
public virtual Authors Authors { get; set; }
}
Class Authors:
public partial class Authors
{
public Authors()
{
this.BookAuthors = new HashSet<BookAuthors>();
}
public int AuthorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}
How i can sort b by authors last name?
A: Something like this, though with mutiple authors it remains a question which author you order by:
var sorted =
from book in b
let firstAuthor = book.BookAuthors.First()
let lastName = firstAuthor.LastName
order book by lastName
select book
Alternatively you could apply some logic (if you had it)...
var sorted =
from book in b
let author = book.BookAuthors.FirstOrDefault(a=>a.Primary) ??
book.BookAuthors.FirstOrDefault(a=>a.Editor) ??
book.BookAuthors.First()
let lastName = author.LastName
order book by lastName
select book
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27102465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unreachable statment error call an activity I'm developping an android application so I'm trying to call activity1 "myown" in another activity2 "MainActivity" but I just keep getting an error "Unreachable statement" over this line of code
Intent launchActivity2 = new Intent(MainActivity.this, myown.class);
MainActivity.this.startActivity(launchActivity2);
Could you explain to me what may went wrong an tell me how to fix it?
i would be really grateful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25755221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL to LINQ semi-complex query projecting to ViewModel I know sql well enough to get by professionally, but i'm still new to linq concepts and even less familiar with lambda syntax. below is my sql query... I successfully join 2 tables on matching id's and filter my results by a certain status and select only the newest entry based on date.
select ma.* , mnh.note
from MerchApps ma
join MerchNoteHist mnh on mnh.appid = ma.id
where ma.[Status] != 6 and mnh.CreatedDate = (select max(CreatedDate) from
MerchantNoteHistories where appid = ma.Id)
The ultimate goal is to project this query to my viewmodel.
public class ViewModelListItem
{
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public ApplicationStatus Status { get; set; }
public string RecentNote { get; set; }
... //other things that aren't related to the question
}
Issue is: find the correct max usage.
My best attempt at LINQ lambda syntax, what I've been able to piece together after doing research:
_db.MerchApps
.Join(_db.MerchNoteHist,
ma => ma.Id,
note => note.AppId,
(ma, note) => new { MA = ma, Note = note })
.Include(x => x.MA.User)
.Where(x => x.MA.Status != ApplicationStatus.Approved)
.Include(x => x.Note.Note)
.Where(x => x.Note.CreatedDate == Max(x.Note.CreatedDate) //<--Issue is here, because I can't find the correct max usage.
.ProjectTo<ViewModelListItem>(_mapperConfig)
.OrderBy(x => x.Status).ThenBy(x => x.CreatedDate).ToListAsync();
The final step is to lay it all out in a view from a foreach loop that uses the above viewmodel.
After research and trial-and-error and working through lunch to try to figure this out... I'm a solid 7 hours into this and at my wits end. Any help at all would be appreciated.
A: You should use a GroupJoin instead of Join, this will yield a set of MerchNoteHist (I'm assuming this is the same table as MerchantNoteHistories here) that match the AppId.
Then, you can use an aggregate (Max) in the resultSelector of the function.
Here's roughly what your code should look like:
_db.MerchApps
.Where(ma => ma.User.Status != ApplicationStatus.Approved)
.GroupJoin(
_db.MerchNoteHist,
ma => ma.Id,
noteList => note.AppId,
(ma, noteList) => new
{
MA = ma,
Note = noteList.OrderByDescending(n=>n.CreatedDate).First()
})
//rest of your logic here
A: Alternatively you could put this in as the second Where clause:
.Where(x => x.Note.CreatedDate== _db.MerchNoteHist
.Where(y => y.AppId == x.Note.AppId).OrderByDescending(y => y.CreatedDate)
.First().CreatedDate)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48270598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AWS: Permissions for exporting logs from Cloudwatch to Amazon S3 I am trying to export logs from one of my CloudWatch log groups into Amazon S3, using AWS console.
I followed the guide from AWS documentation but with little success. My organization does not allow me to manage IAM roles/policies, however I was able to find out that my role is allowed all log-related operations (logs:* on all resources within the account).
Currently, I am stuck on the following error message:
Could not create export task. PutObject call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.
My bucket policy is set in the following way:
{
[
...
{
"Sid": "Cloudwatch Log Export 1",
"Effect": "Allow",
"Principal": {
"Service": "logs.eu-central-1.amazonaws.com"
},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::my-bucket"
},
{
"Sid": "Cloudwatch Log Export 2",
"Effect": "Allow",
"Principal": {
"Service": "logs.eu-central-1.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-bucket/*"
}
]
}
Prior to editing bucket policy, my error message had been
Could not create export task. GetBucketAcl call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.
but editing the bucket policy fixed that. I would expect allowing PutObject to do the same, but this has not been the case.
Thank you for help.
A: Please check this guide Export log data to Amazon S3 using the AWS CLI
Policy's looks like the document that you share but slight different.
Assuming that you are doing this in same account and same region, please check that you are placing the right region ( in this example is us-east-2)
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "s3:GetBucketAcl",
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-exported-logs",
"Principal": { "Service": "logs.us-east-2.amazonaws.com" }
},
{
"Action": "s3:PutObject" ,
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-exported-logs/*",
"Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
"Principal": { "Service": "logs.us-east-2.amazonaws.com" }
}
]
}
I think that bucket owner full control is not the problem here, the only chance is the region.
Anyway, take a look to the other two examples in case that you were in different accounts/ using role instead user.
This solved my issue, that was the same that you mention.
A: Ensure when exporting the data you configure the following aptly
S3 bucket prefix - optional This would be the object name you want to use to store the logs.
While creating the policy for PutBucket, you must ensure the object/prefix is captured adequately. See the diff for the PutBucket statement Resource:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "s3:GetBucketAcl",
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-exported-logs",
"Principal": { "Service": "logs.us-east-2.amazonaws.com" }
},
{
"Action": "s3:PutObject" ,
"Effect": "Allow",
- "Resource": "arn:aws:s3:::my-exported-logs/*",
+ "Resource": "arn:aws:s3:::my-exported-logs/**_where_i_want_to_store_my_logs_***",
"Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
"Principal": { "Service": "logs.us-east-2.amazonaws.com" }
}
]
}
A: One thing to check is your encryption settings. According to https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3ExportTasksConsole.html
Exporting log data to Amazon S3 buckets that are encrypted by AWS KMS is not supported.
Amazon S3-managed keys (SSE-S3) bucket encryption might solve your problem. If you use SSE-KMS, Cloudwatch can't access your encryption key in order to properly encrypt the objects as they are put into the bucket.
A: I had the same situation and what worked for me is to add the bucket name itself as a resource in the Allow PutObject Sid, like:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowLogsExportGetBucketAcl",
"Effect": "Allow",
"Principal": {
"Service": "logs.eu-west-1.amazonaws.com"
},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::my-bucket"
},
{
"Sid": "AllowLogsExportPutObject",
"Effect": "Allow",
"Principal": {
"Service": "logs.eu-west-1.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": [
"my-bucket",
"my-bucket/*"
]
}
]
}
I also believe that all the other answers are relevant, especially using the time in milliseconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69015426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: C# Expression tree for string interpolation I have a program that reads a json file with some property names of a certain class. The values of the configured property names should compose up a key.
Lets take an example:
Class:
class SomeClass
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public string PropertyThree { get; set; }
public string PropertyFour { get; set; }
}
var someClass = new SomeClass
{
PropertyOne = "Value1",
PropertyTwo = "Value2",
PropertyThree = "Value3",
PropertyFour = "Value4",
};
Configuration file:
{
"Properties": ["PropertyOne", "PropertyTwo"]
}
If I knew the properties at compile time I would have create a lambda like:
Func<SomeClass, string> keyFactory = x => $"{x.PropertyOne}|{x.PropertoTwo}"
Is there a way to compile such a lambda using expressions? Or any other suggestions maybe?
A: In Expression Tree, string interpolation is converted to string.Format. Analogue of your sample will be:
Func<SomeClass, string> keyFactory =
x => string.Format("{0}|{1}", x.PropertyOne, x.PropertoTwo);
The following function created such delegate dynamically:
private static MethodInfo _fromatMethodInfo = typeof(string).GetMethod(nameof(string.Format), new Type[] { typeof(string), typeof(object[]) });
public static Func<T, string> GenerateKeyFactory<T>(IEnumerable<string> propertyNames)
{
var entityParam = Expression.Parameter(typeof(T), "e");
var args = propertyNames.Select(p => (Expression)Expression.PropertyOrField(entityParam, p))
.ToList();
var formatStr = string.Join('|', args.Select((_, idx) => $"{{{idx}}}"));
var argsParam = Expression.NewArrayInit(typeof(object), args);
var body = Expression.Call(_fromatMethodInfo, Expression.Constant(formatStr), argsParam);
var lambda = Expression.Lambda<Func<T, string>>(body, entityParam);
var compiled = lambda.Compile();
return compiled;
}
Usage:
var keyFactory = GenerateKeyFactory<SomeClass>(new[] { "PropertyOne", "PropertyTwo", "PropertyThree" });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73634606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending Multipart data using Retrofit Interface
public interface iUpload{
@Multipart
@POST("/uploadmultiplepropimages/")
SamplePojoClass getUploadData(
@Part("prop_id") RequestBody prop_id,
@Part("type") RequestBody type,
@Part("prop_photos") TypedFile prop_photos
);
}
I'm sending like this. I cant send request body text like this.
@Override
protected Void doInBackground(String... params) {
String s = params[0];
File photoFile = new File(s);
System.out.println("file path:"+photoFile);
TypedFile photoTypedFile = new TypedFile("image/png", photoFile);
RequestBody idd = RequestBody.create(MediaType.parse("text/plain"), "");
RequestBody type = RequestBody.create(MediaType.parse("text/plain"), "single");
try {
//uploadImageResponse = RequestResponse.getUploadData(AccountUtils.getProfileId(),photoTypedFile);
uploadImageResponse = RequestResponse.getUploadData(idd,type,photoTypedFile);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}`
It says error:
Cannot access ByteString class file.
A: I hope you have added okio dependency in your gradle file. This will resolve Cannot access ByteString class file error.
compile 'com.squareup.okio:okio:1.13.0'
Then Edit your iUpload interface file like:
public interface iUpload{
@Multipart
@POST("/uploadmultiplepropimages/")
SamplePojoClass getUploadData(
@Part MultipartBody.Part file
@Part MultipartBody.Part prop_id,
@Part MultipartBody.Part type
);
}
Then write MultipartBody.Part like this:
RequestBody lRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), pFile);
MultipartBody.Part lFile = MultipartBody.Part.createFormData("file", pFile.getName(), lRequestBody);
MultipartBody.Part id = MultipartBody.Part.createFormData("prop_id", "WRITE_ID_HERE");
MultipartBody.Part type = MultipartBody.Part.createFormData("type", "WRITE TYPE HERE");
and finally pass these parameters to your api like this:
uploadImageResponse = RequestResponse.getUploadData(lFile,id,type);
I hope it will resolve your problem.
Note: Here pFile is instance of File. To get file from dicrectory you can write code like:
File pFile = new File("PATH_OF_FILE");
A: I have done Multipart upload in okhttp. I hope this will help.
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
multipartBuilder.addFormDataPart("prop_photos", photoFile, RequestBody.create(MEDIA_TYPE_PNG, file));
multipartBuilder
.addFormDataPart("type", type)
.addFormDataPart("prop_id", prop_id);
RequestBody requestBody = multipartBuilder.build();
Request request1 = new Request.Builder().url(urlString).post(requestBody).build();
A: Use the following fuction for your problem
public static RegisterResponse Uploadimage(String id, String photo,String proof) {
File file1 = null, file2 = null;
try {
if (photo.trim() != null && !photo.trim().equals("")) {
file1 = new File(photo);
}
if (proof.trim() != null && !proof.trim().equals("")) {
file2 = new File(proof);
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(WEB_SERVICE + "protoupload.php?");
MultipartEntity reqEntity = new MultipartEntity();
// reqEntity.addPart("studentid", new StringBody(
// Global.profileDetail.id));
reqEntity.addPart("id", new StringBody(id));
if (file1 == null) {
reqEntity.addPart("photo", new StringBody(""));
} else {
FileBody bin1 = new FileBody(file1);
reqEntity.addPart("photo", bin1);
}
if (file2 == null) {
reqEntity.addPart("proof", new StringBody(""));
} else {
FileBody bin2 = new FileBody(file2);
reqEntity.addPart("proof", bin2);
}
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
String inputStreamString = EntityUtils.toString(resEntity);
if (inputStreamString.contains("result")) {
return new Gson().fromJson(inputStreamString,
RegisterResponse.class);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return new RegisterResponse();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45413327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unimplemented Javascript primitive caml_pure_js_expr I want to write and compile cubes.ml such that 1) it wraps an OCaml function to make a JS function that can be called in web; 2) the OCaml function and the bytecode can still be tested in a command line under Linux.
cubes.ml is as follows:
let () =
let oneArgument (a: int) = a + 100 in
Js.Unsafe.global##.jsOneArgument := Js.wrap_callback oneArgument;
print_string "hello\n";
exit 0
The following 2 commands generate a bytecode T, and translates T to cubes.js:
ocamlfind ocamlc -package js_of_ocaml.ppx -linkpkg cubes.ml -o T
js_of_ocaml T -o cubes.js
I have tested that the function jsOneArgument of cubes.js can well be called by other JS or HTML files. So my 1) goal is satisfied.
However, my 2) goal cannot be satisfied: ./T returns an error:
:testweb $ ./T
Unimplemented Javascript primitive caml_pure_js_expr!
Although node cubes.js returns hello, I do need to be able to test ./T directly, because when there is an error, it would show well the error position, whereas the information shown by node cubes.js is not readable...
So does anyone know how to solve that?
PS: node --version gives v6.1.0; npm --version gives 3.8.6; ocaml -version gives The OCaml toplevel, version 4.02.3.
js_of_ocaml --version gives 2.7.
A: I don't see anyway to avoid the use of node but you can improve the information returned by it by
*
*compiling the OCaml with the debug info (add -g option to ocamlc)
*add the options --debuginfo --sourcemap --pretty to the invocation of js_of_ocaml
In your example, you'd have to do
ocamlfind ocamlc -g -package js_of_ocaml.ppx -linkpkg cubes.ml -o T
js_of_ocaml --debuginfo --sourcemap --pretty T -o cubes.js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37320532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: High accuracy but bad predictions on Keras Tensorflow I have a 9 class dataset with 7000 images, I use MobilenetV2 for training my set and ImageGenerator, resulting in 82% percent val accuracy. But when i predict my test images, it always predicts a false class. I have no idea what is wrong with it.Here is my code;
My ImageGenerator:
image_gen = ImageDataGenerator(rotation_range = 20,
width_shift_range=0.12,
height_shift_range=0.12,
shear_range=0.1,
zoom_range = 0.06,
horizontal_flip=True,
fill_mode='nearest',
rescale=1./255)
My model:
Model = Sequential()
Model.add(Conv2D(filters=32,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))
Model.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))
Model.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))
Model.add(Conv2D(filters=64,kernel_size=(3,3),input_shape=image_shape,activation='relu'))
Model.add(MaxPool2D(pool_size=(2,2)))
Model.add(Flatten())
Model.add(Dense(256,activation='relu'))
Model.add(Dense(9,activation='softmax'))
MobilenetV2:
height=224
width=224
img_shape=(height, width, 3)
dropout=.3
lr=.001
class_count=9 # number of classes
img_shape=(height, width, 3)
base_model=tf.keras.applications.MobileNetV2( include_top=False, input_shape=img_shape, pooling='max', weights='imagenet')
x=base_model.output
x=keras.layers.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001 )(x)
x = Dense(512, kernel_regularizer = regularizers.l2(l = 0.016),activity_regularizer=regularizers.l1(0.006),
bias_regularizer=regularizers.l1(0.006) ,activation='relu', kernel_initializer= tf.keras.initializers.GlorotUniform(seed=123))(x)
x=Dropout(rate=dropout, seed=123)(x)
output=Dense(class_count, activation='softmax',kernel_initializer=tf.keras.initializers.GlorotUniform(seed=123))(x)
Model = keras.models.Model(inputs=base_model.input, outputs=output)
Model.compile( loss='categorical_crossentropy', metrics=['accuracy'],optimizer='Adamax')
My Rlronp:
rlronp=tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=1, verbose=1, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)
My train_image_gen:
train_image_gen = image_gen.flow_from_directory(train_path,
target_size=image_shape[:2],
color_mode='rgb',
batch_size=batch_size,
class_mode='categorical')
My test_image_gen:
test_image_gen = image_gen.flow_from_directory(test_path,
target_size=image_shape[:2],
color_mode='rgb',
batch_size=batch_size,
class_mode='categorical',shuffle=False)
My earlystop:
early_stop = EarlyStopping(monitor='val_loss',patience=4)
My Model fit:
results = Model.fit(train_image_gen,epochs=20,
validation_data=test_image_gen,callbacks=[rlronp,early_stop],class_weight=class_weight
)
Training and accuracy:
Epoch 20/20 200/200 [==============================] - 529s 3s/step -
loss: 0.3995 - accuracy: 0.9925 - val_loss: 0.8637 - val_accuracy: 0.8258
My problem is when i predict an image from test set, it predicts the false class, 90% of time.
For example here, it has to be 3rd class, but max is on 2nd class.
array([[0.08064549, 0.04599327, 0.27055973, 0.05219262, 0.055945 ,
0.25723988, 0.07608379, 0.10404343, 0.05729679]], dtype=float32)
I tried collecting my own dataset with 156 class and 2.5k images, but it was even worse.
My loss on 20 epochs:
A: accuracy: 0.9925; val_accuracy: 0.8258
Clearly the model is overfitted,
*
*Try using regularization techniques such as L2,L1 or Dropout, they will work.
*Try to Collect More data(Or use data augumentation)
*Or search for other Neural Network Architectures
*The best method is plot val_loss v/s loss
r = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=15)
import matplotlib.pyplot as plt
plt.plot(r.history['loss'], label='loss')
plt.plot(r.history['val_loss'], label='val_loss')
plt.legend()
and check the point where loss and val_loss meet each other and then at the point of intersection see the number of epochs (say x) and train the model for x epochs only.
Hope you will find this useful.
A: Model is overfitted...use dropout layer.. I think it will help
Model.add(Dropout(0.2))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67064566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Replacing Golang standard package and calling the original within Assume that there is a special hardware that can make
certain standard library functionality faster.
Hardware might be present or not.
I can write a package that would utilize this hardware with the same
function signatures as in the standard one, but it will force all the applications and other packages to decide which package to import based on the availability of the hardware on the specific target. At build time and with code modifications in all the applications and packages.
Ideally, I would prefer to make the decision of which package to use at runtime and without requiring applications to change their imports.
The package would check for the availability of the hardware and would either use it or execute standard functionality instead.
Is there any way to achieve it?
Any other ways to "intercept" the calls to the standard package functions?
A: It sounds like you're talking about a library that will be used by other applications. You can't (thankfully!) modify the standard library this way - otherwise just importing a package could have incredibly broad and potentially disastrous side-effects. If you want to apply some special hardware-specific optimizations to the standard library, for use by other people in a broad range of projects, your best bet is to make your changes to the standard library and submit a patch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44959262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Prologue -Webframework - How to set thread-local variables for logging when compiling with `--threads:on` flag? I am writing a web-application in nim, using the web-framework prologue and the ORM norm. I've found that the log-messages of prologue and norm that normally appear in the terminal when starting up the application disappear, when you compile with the --threads:on flag.
That is because log-message-handlers and log levels are set as thread-local variables, so when a new thread is created the log-level must be set for that thread again etc.
However, prologue is the one instantiating the threads, so how do I properly set this up for every thread that prologue creates?
A: I found the answer thanks to the help of prologue's creator: xflywind.
The answer is prologue-events.
When prologue creates a thread, it triggers a list of procs, so called events, that are registered on startup. All you need to do is define an event that sets the log-level and provides a handler.
proc setLoggingLevel() =
addHandler(newConsoleLogger())
logging.setLogFilter(lvlDebug)
let
event = initEvent(setLoggingLevel)
var
app = newApp(settings = settings, startup = @[event])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71545667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Automation Script vs Export Template I'm puzzled with the "automation script" vs "export template" in the Resource manager blade. So many sources are mixing those two things, my understanding is that "automation script" was introduced later, but I'm might be wrong.
When I switched the language (English to German) it's saying actually "automation script", so I'm not sure if that's really an UI issue, and why so many different sources have sometimes "automation script" (which I'm getting only in German) or sometimes "export templates"?
https://pasteboard.co/I75s2jJ.png
A: those are 2 different names for the same thing. its actually an api call you can perform without the portal as well. just an inconsistency within UI.
Api call: https://learn.microsoft.com/en-us/rest/api/resources/resourcegroups/exporttemplate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55343905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Insert blank rows based on column condition I have to have atlest 4 rows for each manager (mgr col) and so that HR can assign task to each of them. HR will add values in new col, they can assign task up to 4 based. I am thinking to create a macro that can check minimum 4 lines for each manager if less than 4 add it and if more then no need to add.
For example:
Dep Mgr Task
1 jerry cheese
1 jerry bread
2 tom milk
Expected output:
Dep Mgr Task HRtask
1 jerry cheese ---
1 jerry bread ---
1 jerry --- ---
1 jerry --- ---
2 tom milk ---
2 tom --- ---
2 tom --- ---
2 tom --- ---
--- is blank here.
what I found on internet
Sub Insert4RowsWithCondition()
' here starting with A3 cell but need to set on unique value in that mgr col automatically
Range("A3").Select
Do Until ActiveCell.Value =""
Selection.EntireRow.Insert
Selection.EntireRow.Insert
ActiveCell.Offset(3,0).Select
Loop
error
It is adding 2 new blank rows after each line which is not useful in my case.
A: Try this... A bit lengthy though... I added the rows depending on Dep count instead of Mgr name, as there can be more than one mgr with same name... So Assuming Dep is some sort of Mgr's ID...
Sub Macro1()
' Get count of Dep
Columns("A:B").Select
Selection.Copy
Range("F1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range("$F:$G").RemoveDuplicates Columns:=Array(1, 2), Header _
:=xlYes
Range("H2").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(C1,RC[-2])"
Range("H2").Select
Selection.Copy
lRow = Cells(Rows.Count, 6).End(xlUp).Row
Range("H2:H" & lRow).Select
ActiveSheet.Paste
Application.CutCopyMode = False
' Number of rows to add
lRow = Cells(Rows.Count, 6).End(xlUp).Row
For i = 2 To lRow
num = Cells(i, 8).Value
If num < 4 Then
Range("F" & i & ":" & "G" & i).Copy
Range("A1").Select
Selection.End(xlDown).Select
For j = 1 To 4 - num
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next
End If
Next
' Sorting Data
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("A:A") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A:D")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("F:H").ClearContents
Range("A1").Select
End Sub
Hope this Helps...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73821564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flatpickr - Limit the amount of dates that can be selected I am using 'flatpickr' as a datetime picker on my app. This date picker allows for multiple dates to be selected but after reading the docs I can't find any way to limit the maximum amount of selected dates.
Jquery:
$('#gig_date_multi').flatpickr({
"mode": "multiple",
"locale": "<%= I18n.locale %>",
minDate: new Date(),
enableTime: true,
time_24hr: true,
minuteIncrement: 15,
onChange: function(selectedDates, dateStr, instance) {
var array = selectedDates;
if (array.length >= 3) {
console.log("YOU HAVE REACHED YOUR LIMIT")
} else {
console.log("YOU CAN STILL SELECT MORE DATES")
}
var newHTML = [];
$.each(array, function(index, value) {
var formatted = moment(value).format("HH:mm - dddd Do MMMM YYYY");
newHTML.push('<span>' + formatted + '</span>');
});
$(".multi-dates").html(newHTML.join(""));
}
});
Here when 3 dates are selected the console outputs "YOU HAVE REACHED YOUR LIMIT" and I was thinking maybe I could disable all dates (apart from previously selected ones) when this occurs.
Flatpickr has a disable and enable function but I am unsure how I can integrate this into the code... I am a jquery beginner.
The docs show these two methods;
{
"disable": [
function(date) {
// return true to disable
return (date.getDay() === 5 || date.getDay() === 6);
}
],
"locale": {
"firstDayOfWeek": 1 // start week on Monday
}
}
and
{
enable: ["2017-03-30", "2017-05-21", "2017-06-08", new Date(2017, 8, 9) ]
}
A: You can use:
set(option, value): Sets a config option optionto value, redrawing the calendar and updating the current view, if necessary
In order to disable all dates except the 3 selected you can write:
instance.set('enable', selectedDates);
and, in order to reset you can:
instance.set('enable', []);
A different approach can be based on Enabling dates by a function:
instance.set('enable', [function(date) {
if (selectedDates.length >= 3) {
var currDateStr = FlatpickrInstance.prototype.formatDate(date, "d/m/Y")
var x = selectedDatesStr.indexOf(currDateStr);
return x != -1;
} else {
return true;
}
}]);
The snippet:
$('#gig_date_multi').flatpickr({
"mode": "multiple",
"locale": 'en',
minDate: new Date(),
enableTime: true,
time_24hr: true,
minuteIncrement: 15,
onChange: function(selectedDates, dateStr, instance) {
var selectedDatesStr = selectedDates.reduce(function(acc, ele) {
var str = instance.formatDate(ele, "d/m/Y");
acc = (acc == '') ? str : acc + ';' + str;
return acc;
}, '');
instance.set('enable', [function(date) {
if (selectedDates.length >= 3) {
var currDateStr = instance.formatDate(date, "d/m/Y")
var x = selectedDatesStr.indexOf(currDateStr);
return x != -1;
} else {
return true;
}
}]);
}
});
input[type="text"] {
width: 100%;
box-sizing: border-box;
-webkit-box-sizing:border-box;
-moz-box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/flatpickr/dist/flatpickr.min.css">
<script src="https://unpkg.com/flatpickr"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input type="text" id="gig_date_multi">
A: On a side note, if anyone wants to disable past date as well as time selection in Flatpickr, use Date().getTime() like this:
$("input.picker-datetime").flatpickr({
enableTime: true,
dateFormat: "Y-m-d H:i",
time_24hr: true,
minDate: new Date().getTime()
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45391963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Enable squid proxy blocking https I'm trying to block some sites like gmail and outlook from my squid proxy server.
My squid.conf is:
acl blacklist dstdomain "/etc/squid/blacklist.acl"
http_access deny blacklist
And blacklist.acl is:
.atlassian.net
.accounts.google.com
.mail.google.com
.gmail.com
.gmail.google.com
This only seems to work for sites using http (ie. they successfully get blocked)
https sites still are able to get through ?
I'm running squid 4.10 on Ubuntu-20.04
Does anyone know how to achieve this ?
Thanks in advance!
A: this is probably because you haven't enabled SSL bumping, i.e. your http_port directive is set to the default http_port 3128.
I've written about both Squid's SSL setup and blocking websites
*
*configure squid with ICAP & SSL
*block and allow websites with squid
A: When the site is encrypted squid can validate only the Domain but not the entire URL path or keywords in the URL. To block https sites using urlpath_regex we need to setup Squid proxy using SSLbump. It is tricky and a long process , need to carefully configure the SSL bump settings by generating certificates.. but it is possible . I have succeeded in blocking the websites using urlpathregex over https sites...
For more detailed explanation:
Squid.conf file should have the below to achieve block websites using Keywords or Path ie..urlpath_regex
http_port 3128 ssl-bump cert=/usr/local/squid/certificate.pem generate-host-certificates=on dynamic_cert_mem_cache_size=4MB
acl BlockedKeywords url_regex -i "/etc/squid/.."
acl BlockedURLpath urlpath_regex -i "/etc/squid/..."
acl BlockedFIles urlpath_regex -i "/etc/squid3/...."
http_access deny BlockedKeywords
http_access deny BlockedFIles
http_access deny BlockedURLpath
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71655960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Does ArrayList.clear() also delete all contained objecs? Assuming I have an ArrayList of ArrayLists created in this manner:
ArrayList< ArrayList<String> > listOfListsOfStrings =
new ArrayList< ArrayList<String> >();
If I call:
listOfListsOfStrings.clear();
Will an attempt to later access any of the Strings inside listOfListsOfStrings always result in a java.lang.NullPointerException?
A: No, just the references will be cleared. If no reference to an object exists anymore it might be garbage collected, but you'd get no NPE, since you then have no way to get a new reference to that object anyway.
A: No, it will not delete objects in the ArrayList if you still have external references to them. ArrayList.clear() does nothing to the objects being referred to unless they are orphaned, in which case you won't be referring to them later on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5669223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Elixir program, what does this program do? this is one of the practice questions from the upcoming exam, and I have no idea what should be written for init() in order for the output to run.
If someone could help me out, that would be awsome
output: This is what I would run
p1=Pawn.new(),
Obj.call(p1,{:goto, 1, 2}),
1=Obj.call(p1, :x),
2=Obj.call(p1, :y),
Obj.call(p1,{:moveDelta , 3, 1}),
4=Obj.call(p1, :x ) ,
3=Obj.call(p1 ,:y ).
Add the necessary code to the following to support the API used above for the object pawn:
function: I need to fill out the init() function here.
defmodule Obj do
def call(obj,msg) do
send obj,{self(), msg}
receive do
Response -> Response
end
end
end
defmodule Pawn do
def new(), do: spawn(__MODULE__,:init, [] ).
def init() do: // fill this out
Thank you for your time
A: I'm reluctant to do all your homework for you. However, given that the code you were given is not valid Elixir, I'll provide you a partial solution. I've implemented the :goto and :x handlers. You should be able to figure out how to write the :moveDelta and :y handlers.
defmodule Obj do
def call(obj, msg) do
send obj, { self(), msg }
receive do
response -> response
end
end
end
defmodule Pawn do
def new(), do: spawn(__MODULE__,:init, [] )
def init(), do: loop({0,0})
def loop({x, y} = state) do
receive do
{pid, {:goto, new_x, new_y}} ->
send pid, {new_x, new_y}
{new_x, new_y}
{pid, {:moveDelta, dx, dy}} ->
state = {x + dx, y + dy}
send pid, state
state
{pid, :x} ->
send pid, x
state
{pid, :y} ->
send pid, y
state
end
|> loop
end
end
p1=Pawn.new()
Obj.call(p1,{:goto, 1, 2})
1=Obj.call(p1, :x)
2=Obj.call(p1, :y)
Obj.call(p1,{:moveDelta , 3, 1})
4=Obj.call(p1, :x )
3=Obj.call(p1 ,:y )
The code runs. Here is the output of the test cases you provided (after I fixed the syntax issues:
iex(5)> p1=Pawn.new()
#PID<0.350.0>
iex(6)> Obj.call(p1,{:goto, 1, 2})
{1, 2}
iex(7)> 1=Obj.call(p1, :x)
1
iex(8)> 2=Obj.call(p1, :y)
2
iex(9)> Obj.call(p1,{:moveDelta , 3, 1})
{4, 3}
iex(10)> 4=Obj.call(p1, :x )
4
iex(11)> 3=Obj.call(p1 ,:y )
3
iex(12)>
Also, I fixed syntax issues in the given problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43430811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django Error While Submitting Forms Performing system checks...
Unhandled exception in thread started by .wrapper at 0x75abfcd8> Traceback (most recent call last): File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 673, in exec_module File "", line 222, in _call_with_frames_removed File "/home/pi/tango_with_django_project/tango_with_django_project/urls.py", line 25, in url(r'^rango/', include('rango.urls')), File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 673, in exec_module File "", line 222, in _call_with_frames_removed File "/home/pi/tango_with_django_project/rango/urls.py", line 2, in from rango import views File "/home/pi/tango_with_django_project/rango/views.py", line 5, in from rango.forms import CategoryForm File "/home/pi/tango_with_django_project/rango/forms.py", line 4, in class CategoryForm(forms.ModelForm): File "/home/pi/.venv/lib/python3.5/site-packages/django/forms/models.py", line 243, in new "needs updating." % name django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form CategoryForm needs updating.
Here is my forms.py
from django import forms from rango.models import Page, Category
class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Category
class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of the page.") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Page
fields = ('title', 'url', 'views')
here is my views.py
from django.template import RequestContext from django.shortcuts import render_to_response from rango.models import Category from rango.models import Page from rango.forms import CategoryForm
def index(request): context = RequestContext(request) category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories': category_list} for category in category_list: category.url = category.name.replace(' ', '_') return render_to_response('rango/index.html', context_dict, context)
def about(request): context = RequestContext(request) context_dict = {'boldmessage': "I am bold font from the context"} return render_to_response('rango/about.html', context_dict, context)
def category(request, category_name_url): context = RequestContext(request) category_name = category_name_url.replace('_', ' ') context_dict = {'category_name': category_name} try: category = Category.objects.get(name=category_name) pages = Page.objects.filter(category=category) context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: pass return render_to_response('rango/category.html', context_dict, context)
def add_category(request): context = RequestContext(request)
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print (form.errors)
else:
form = CategoryForm()
return render_to_response('rango/add_category.html', {'form': form}, context)
A: You need to add a fields or exclude attribute to the form class
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['name']
Seems like you don't have a model named Category in that case you should inherit from forms.Form
class CategoryForm(forms.Form):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49239346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Javascript matching objects of an array I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.
Any way to do this with map? And present in a list?
I've come this far:
const allaOrter = orter.map((allOrt) =>
<li>{allOrt.url}</li>
)
What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)
orter.json
[{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}]
A: Use array.prototype.filter method then map the returned array
const arr = [{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}]
let filtered = (a) => a.url.includes("/blekinge")
console.log(arr.filter(filtered))
then map the result
A: You should first try to narrow down by matching the object which contains the url /blekinge using the filter method. Once you have filtered, the resulting array can be used to present a list.
To keep things simple, I implemented an unordered list to present the result, but the core of what you need is in the resulting filtered array.
let listElement = document.getElementById('name-list');
let data = [
{
"id": "2",
"name": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"name": "Karlshamn",
"url": "/blekinge/karlshamn"
},
{
"id": "24",
"name": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"name": "Olofström",
"url": "/blekinge/olofstrom"
},
{
"id": "26",
"name": "Ronneby",
"url": "/test/ronneby"
}
];
let updateList = (list, content) => {
let li = document.createElement("li");
li.innerHTML = content;
list.appendChild(li);
};
let filteredData = data.filter(elem => elem.url.indexOf('/blekinge') !== -1);
filteredData.map(elem => updateList(listElement, elem.name));
<label for="name-list">Matching names</label>
<ul id="name-list">
<ul>
A: Working Demo :
const data = [{
"id": "2",
"namn": "Blekinge",
"url": "/blekinge"
},
{
"id": "23",
"namn": "Karlshamn",
"url": "/alpha/beta"
},
{
"id": "24",
"namn": "Karlskrona",
"url": "/blekinge/karlskrona"
},
{
"id": "25",
"namn": "Olofström",
"url": "/abc/def"
},
{
"id": "26",
"namn": "Ronneby",
"url": "/blekinge/ronneby"
}];
const res = data.filter((obj) => obj.url.indexOf('/blekinge') !== -1);
console.log(res);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71082280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: i can't pass and get the variable in scalate template As suggested I'm asking new question in new topic.
I have a problem with passing an argument to my scalate template (.ssp)
Below my controller and my template
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
User user = new User("Dawid", "Pacholczyk");
ModelAndView template = new ModelAndView("defaultTemplate");
template.addObject("user", user);
return template;
}
<%@ val bar: String = "this is the default value" %>
<% attributes("title") = "This is the custom title" %>
<%@ var user: User %>
<p>Hi ${user.name},</p>
#do(layout("layouts/default.ssp"))
this is some template output...
<br />
${bar}
#end
Now I get exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.fusesource.scalate.CompilerException: Compilation failed:
/WEB-INF/scalate/defaultTemplate.ssp:3.13 error: not found: type User
^
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Now I don't know what to do. I'll add that when I delete <%@ var user: User %> everything works great
What to do ?
A: You need to import user before you can use it.
<% import somePackage.User %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9753017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Caching a list from a service call in android I'm using retrofit2 to make a service call. One thing that I display is a list. I have no problem displaying the list even in a case where I have 242 items. The problem I have is when I select an item from the list to show in a detailed view, a separate activity.
I get this crash in the log
RuntimeException: android.os.TransactionTooLargeException: data parcel size 873448 bytes
If limited the size of the list to 20 items and I no longer get the crash.
What options do I have for caching this list and not pulling out too many to where I get the crash? I don't want to cache the whole response, just the list and pull out say 20 at a time.
Also, if I end up loading all of them into the list, won't I run into the same problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45723331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to correctly define (function || function) inside a Javascript object? This works:
<div id="result"></div>
<script type="text/javascript">
var Base64Encode = window.btoa || CryptoJS.enc.Base64.stringify;
document.getElementById('result').innerHTML = Base64Encode("Please work.");
</script>
However, this:
<div id="result"></div>
<script type="text/javascript">
var Test = {
Base64Encode: window.btoa || CryptoJS.enc.Base64.stringify
};
document.getElementById('result').innerHTML = Test.Base64Encode("Please work.");
</script>
Generates an error of "TypeError: 'btoa' called on an object that does not implement interface Window."
Fiddle:
http://jsfiddle.net/kAGU2/
Why does the first example work but the second one emit that error? What's the correct way to fix this particular error?
A:
Why does the first example work but the second one emit that error?
When the function is called as Base64Encode(), the this context is implicitly set to window. However, when you call it as a method on Test.Base64Encode(), this will refer to Test and btoa grumps about that.
What's the correct way to fix this particular error?
You will need to bind it to the expected context:
Base64Encode = window.btoa
? window.btoa.bind(window)
: CryptoJS.enc.Base64.stringify;
A: Use .bind():
var Test = {
Base64Encode: function() {
if (window.btoa)
return window.btoa.bind(window);
return CryptoJS.enc.Base64.stringify;
}()
};
You got the error because you invoked the function via that object property reference. When you do that, the value of this is set to a reference to the object involved. The btoa() function doesn't like that (for who knows what reason), but .bind() creates a wrapper function for you that ensures the proper this.
A: It appears as that btoa function is a member function of Window class. And so it has to be called with this set to window.
In order it to work in your setup you should call it this way:
Test.Base64Encode.call(window,"Please work.");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22117094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: java.lang.IllegalArgumentException: Not supported: indent-number public String filter(String message) {
if (message == null) {
return null;
}
// Remove formatting, transformer fails to handle wrong indentation correctly.
message = message.replaceAll(">\\s*[\\r\\n]+\\s*", ">");
message = message.replaceAll("\\s*[\\r\\n]+\\s*", " "); // for wrapped attribute lists
Source xmlInput = new StreamSource(new StringReader(message));
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", INDENT); // for Java 6
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", INDENT.toString()); // Java 1.5
transformer.transform(xmlInput, new StreamResult(stringWriter));
String pretty = stringWriter.toString();
pretty = pretty.replace("\r\n", "\n");
return pretty;
} catch (TransformerException e) {
if (e.getCause() != null && e.getCause() instanceof SAXParseException) {
return message;
}
throw new RuntimeException(e);
}
}
but i get exception here:
transformerFactory.setAttribute("indent-number", INDENT); // for Java 6
java.lang.IllegalArgumentException: Not supported: indent-number
my java:
java version "1.6.0_33"
why i get this error?
A: Instead of
TransformerFactory transformerFactory = TransformerFactory.newInstance();
you should write
TransformerFactory transformerFactory = new TransformerFactoryImpl();
because not all implementations of TransformerFactory have this field: indent-number.
A: I fixed that exception by commenting this line:
transformerFactory.setAttribute("indent-number", indent);
and adding this line:
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
The exception is gone even though the indetation that appears in the browser is incorrect.
A: Likely because Xalan (as packaged in JDK1.6/1.7) support "indent-number", yet others don't and have their own way of specifying the size of indent. So you have to put in the string appropriate for the XSLT provider. Work out which you're using and see its docs
Aren't standards that don't specify such things great?
A: You should use the predefined constant OutputKeys.INDENT, or if you really insist on hardcoding the value, it should be 'indent', not 'indent-number'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15134861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: iOS6: MFMailComposeViewController slow to load and flashes black screen; MailCompositionS begins hogging memory On iOS 6, after sending a few email messages (by using MFMailComposeViewController), the email screens become very slow to open- at first opening with none of the fields populated (no Subject, no body, etc.) for a few seconds, and eventually (after sending about 8 messages), a black screen is displayed to the user for a few seconds before the email view controller is properly displayed.
The log spits out the following line before each black screen is displayed:
[MFMailComposeRemoteViewController: ....] timed out waiting for fence
barrier from com.apple.MailCompositionService
Also, using MFMailComposeViewController on iOS6 causes the MailCompositionS process to start hogging memory (it's going all the way up to roughly 260MB on my iPhone). I'm assuming this is the reason for the MFMailComposeViewController display issues.
Everything runs fine on iOS 5. This issue only occurs on iOS 6.
Has anyone found a way to resolve this issue?
Thanks!
The code is standard, but I'll include it anyway:
-(IBAction)doEmailLog:(id)sender
{
if( [self canSendMail] )
{
// create the compose message view controller
MFMailComposeViewController* mailComposer = [[MFMailComposeViewController alloc] init];
// this class will handle the cancel / send results
mailComposer.mailComposeDelegate = self;
// fill in the header and body
[mailComposer setSubject:@"My Subject"];
[mailComposer setMessageBody:@"My message body" isHTML:NO];
// attach log file
if ([[NSFileManager defaultManager] fileExistsAtPath:filename])
{
NSData *data = [NSData dataWithContentsOfFile:filename];
[mailComposer addAttachmentData:data mimeType:@"text/plain" fileName:filename];
}
// show the view controller
[self presentViewController:mailComposer animated:YES completion:^{LogTrace(@"Presented mail view controller");}];
}
else
{
...
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
...
// dismiss the compose message view controller
[self dismissViewControllerAnimated:YES completion:^{LogTrace(@"Finished dismissing mail controller");}];
}
A: on ios 6 the mail composer is its own app (inside yours)
:: http://oleb.net/blog/2012/10/remote-view-controllers-in-ios-6/
the code looks good to me if you are using ARC else it leaks and on ios6 that might result in x XPC remotes
if all is good there, Id blame it on a bug in apple's new handling of XPC
A: there's another possible solution:
Remove custom fonts from the appearance methods, if you have any
https://stackoverflow.com/a/19910337/104170
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13298448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How to download nested json data, convert to excel format in angular 10? employees = [
{
SNO : 1,
name : "HARIPRASATH",
SALARY : [
{
SNO: 1,
MONTH : 'APRIL',
DATE : '01-04-2022',
TIME : '10.AM',
AMOUNT : 15000
},
{
SNO: 2,
MONTH : 'MAY',
DATE : '01-05-2022',
TIME : '10.AM',
AMOUNT : 15000
},
{
SNO: 3,
MONTH : 'JUNE',
DATE : '01-06-2022',
TIME : '10.AM',
AMOUNT : 15000
}
]
},
{
SNO : 2,
name : "SINDHUJA",
SALARY : [
{
SNO: 1,
MONTH : 'APRIL',
DATE : '01-04-2022',
TIME : '10.AM',
AMOUNT : 18000
},
{
SNO: 2,
MONTH : 'MAY',
DATE : '01-05-2022',
TIME : '10.AM',
AMOUNT : 18000
},
{
SNO: 3,
MONTH : 'JUNE',
DATE : '01-06-2022',
TIME : '10.AM',
AMOUNT : 18000
}
]
}
I need to convert this table type to excel format like this:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73329529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.