text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Convert time data into human readable time using PHP I have a time value in the following data format:
"2020-08-05T11:45:10.3159677Z"
How do I convert it to something human readable, like as follows, using PHP?
Wednesday, August 5, 2020, 11:45 AM
A: Try this:
echo date("H:i A, F jS, Y", strtotime("2020-08-05T11:45:10.3159677Z"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63271755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spinner with on Click Listener I am using spinner that shows error when i am trying to extract the item id of the selected spinner item.
My Code goes here:
public void dispspi()
{
spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter <String> adap= new ArrayAdapter(this, android.R.layout.simple_spinner_item, level);
spinner.setAdapter(adap);
spinner.setOnItemClickListener(new OnItemClickListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
int item = spinner.getSelectedItemPosition();
p=item;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
How to get the item id of the spinner? Any help is appreciated..Thanks in advance
A: private String selecteditem;
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
selecteditem = adapter.getItemAtPosition(i).toString();
//or this can be also right: selecteditem = level[i];
}
@Override
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
A: IIRC, you should be using a selected listener, not click:
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
Then you can add the override tag to your selected method.
A: spinner3.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
// TODO Auto-generated method stub
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
Toast.makeText(getBaseContext(),
"You have selected 222 : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
A: Yes you can use some OnItemSelectedListener for work with selected item. But sometimes we would like to handle exactly click for spinner. For example hide keyboard or send some analytics etc. In this case we should use TouchListener because OnClickListener doesn't work properly with Spinner and you can get error. So I suggest to use TouchListener like:
someSpinner.setOnTouchListener { _, event -> onTouchSomeSpinner(event)}
fun onTouchSomeSpinner(event: MotionEvent): Boolean {
if(event.action == MotionEvent.ACTION_UP) {
view.hideKeyBoard()
...
}
return false
}
A: you should have this in the listener(OnItemSelectedListener)
public void onNothingSelected(AdapterView<?> arg0) {
}
It might works without it but put it to be consistent
but there might be other errors also, can you provide the error log ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7402818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Order by data as per supplied Id in sql Query:
SELECT *
FROM [MemberBackup].[dbo].[OriginalBackup]
where ration_card_id in
(
1247881,174772,
808454,2326154
)
Right now the data is ordered by the auto id or whatever clause I'm passing in order by.
But I want the data to come in sequential format as per id's I have passed
Expected Output:
All Data for 1247881
All Data for 174772
All Data for 808454
All Data for 2326154
Note:
Number of Id's to be passed will 300 000
A: One option would be to create a CTE containing the ration_card_id values and the orders which you are imposing, and the join to this table:
WITH cte AS (
SELECT 1247881 AS ration_card_id, 1 AS position
UNION ALL
SELECT 174772, 2
UNION ALL
SELECT 808454, 3
UNION ALL
SELECT 2326154, 4
)
SELECT t1.*
FROM [MemberBackup].[dbo].[OriginalBackup] t1
INNER JOIN cte t2
ON t1.ration_card_id = t2.ration_card_id
ORDER BY t2.position DESC
Edit:
If you have many IDs, then neither the answer above nor the answer given using a CASE expression will suffice. In this case, your best bet would be to load the list of IDs into a table, containing an auto increment ID column. Then, each number would be labelled with a position as its record is being loaded into your database. After this, you can join as I have done above.
A: If the desired order does not reflect a sequential ordering of some preexisting data, you will have to specify the ordering yourself. One way to do this is with a case statement:
SELECT *
FROM [MemberBackup].[dbo].[OriginalBackup]
where ration_card_id in
(
1247881,174772,
808454,2326154
)
ORDER BY CASE ration_card_id
WHEN 1247881 THEN 0
WHEN 174772 THEN 1
WHEN 808454 THEN 2
WHEN 2326154 THEN 3
END
Stating the obvious but note that this ordering most likely is not represented by any indexes, and will therefore not be indexed.
A: Insert your ration_card_id's in #temp table with one identity column.
Re-write your sql query as:
SELECT a.*
FROM [MemberBackup].[dbo].[OriginalBackup] a
JOIN #temps b
on a.ration_card_id = b.ration_card_id
order by b.id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41799973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting error while POST request with JSON This is my server.js file code . I am trying to push the JSON content in the user object , but i am getting following error. Please tell me where i am going wrong.
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const bodyParser = require('body-parser')
app.use(express.json())
const users = []
app.get('/users', (req, res) => {
JSON.stringify(users)
res.json(users)
})
app.post('/users', (req, res) => {
const user = {
name: req.body.name,
password: req.body.password
}
users.push(user)
res.status(201).send()
})
app.listen(3000, console.log("server started"));
I used an extension in VS code called REST client.
GET http: //localhost:3000/users
#####
POST http: //localhost:3000/users
Content-Type: application/json
{
"name": "Tanay",
"password": "password"
}
When I'm firing POST request it shows the error - SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at parse (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\body-parser\lib\types\json.js:89:19)
at C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:224:16)
at done (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\TANAY RAJ\Desktop\nodePassport\Wsimplified\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
A: Can be something wrong with the user variable. Can you check this:
const user={'name':req.body.name,'password':req.body.password}
Update
I tried out:
var data = [];
const user={'name':"Deshan",'password':"password"}
data.push(user);
console.log(data);
And the result was as follow:
[ { name: 'Deshan', password: 'password' } ]
So it maybe a problem with the request data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61974192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the mantissa of an 80-bit long double as an int on x86-64 frexpl won't work because it keeps the mantissa as part of a long double. Can I use type punning, or would that be dangerous? Is there another way?
A: x86's float and integer endianness is little-endian, so the significand (aka mantissa) is the low 64 bits of an 80-bit x87 long double.
In assembly, you just load the normal way, like mov rax, [rdi].
Unlike IEEE binary32 (float) or binary64 (double), 80-bit long double stores the leading 1 in the significand explicitly. (Or 0 for subnormal). https://en.wikipedia.org/wiki/Extended_precision#x86_extended_precision_format
So the unsigned integer value (magnitude) of the true significand is the same as what's actually stored in the object-representation.
If you want signed int, too bad; including the sign bit it would be 65 bits but int is only 32-bit on any x86 C implementation.
If you want int64_t, you could maybe right shift by 1 to discard the low bit, making room for a sign bit. Then do 2's complement negation if the sign bit was set, leaving you with a signed 2's complement representation of the significand value divided by 2. (IEEE FP uses sign/magnitude with a sign bit at the top of the bit-pattern)
In C/C++, yes you need to type-pun, e.g. with a union or memcpy. All C implementations on x86 / x86-64 that expose 80-bit floating point at all use a 12 or 16-byte type with the 10-byte value at the bottom.
Beware that MSVC uses long double = double, a 64-bit float, so check LDBL_MANT_DIG from float.h, or sizeof(long double). All 3 static_assert() statements trigger on MSVC, so they all did their job and saved us from copying a whole binary64 double (sign/exp/mantissa) into our uint64_t.
// valid C11 and C++11
#include <float.h> // float numeric-limit macros
#include <stdint.h>
#include <assert.h> // C11 static assert
#include <string.h> // memcpy
// inline
uint64_t ldbl_mant(long double x)
{
// we can assume CHAR_BIT = 8 when targeting x86, unless you care about DeathStation 9000 implementations.
static_assert( sizeof(long double) >= 10, "x87 long double must be >= 10 bytes" );
static_assert( LDBL_MANT_DIG == 64, "x87 long double significand must be 64 bits" );
uint64_t retval;
memcpy(&retval, &x, sizeof(retval));
static_assert( sizeof(retval) < sizeof(x), "uint64_t should be strictly smaller than long double" ); // sanity check for wrong types
return retval;
}
This compiles efficiently on gcc/clang/ICC (on Godbolt) to just one instruction as a stand-alone function (because the calling convention passes long double in memory). After inlining into code with a long double in an x87 register, it will presumably compile to a TBYTE x87 store and an integer reload.
## gcc/clang/ICC -O3 for x86-64
ldbl_mant:
mov rax, QWORD PTR [rsp+8]
ret
For 32-bit, gcc has a weird redundant-copy missed-optimization bug which ICC and clang don't have; they just do the 2 loads from the function arg without copying first.
# GCC -m32 -O3 copies for no reason
ldbl_mant:
sub esp, 28
fld TBYTE PTR [esp+32] # load the stack arg
fstp TBYTE PTR [esp] # store a local
mov eax, DWORD PTR [esp]
mov edx, DWORD PTR [esp+4] # return uint64_t in edx:eax
add esp, 28
ret
C99 makes union type-punning well-defined behaviour, and so does GNU C++. I think MSVC defines it too.
But memcpy is always portable so that might be an even better choice, and it's easier to read in this case where we just want one element.
If you also want the exponent and sign bit, a union between a struct and long double might be good, except that padding for alignment at the end of the struct will make it bigger. It's unlikely that there'd be padding after a uint64_t member before a uint16_t member, though. But I'd worry about :1 and :15 bitfields, because IIRC it's implementation-defined which order the members of a bitfield are stored in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57499986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Draw with canvas Javascript Maybe you can advice me, I need to draw with canvas using the coordinates of images as vertex, but I have the images into a table(html table) so I don't know how to do that, how to do the draw inside the table or over the table. For example you have an image on coordinates(60,90) another on (79,45) and other on (70,64), i need to make a triangle with that coordinates, but the images are into a table(each image in different cells.
This is my draw code:
function draw(elem) { //elem is the image
var image= elem;
var position = image.getBoundingClientRect();
//alert(posicion.top+" "+ posicion.right+" "+posicion.bottom+" "+posicion.left);
var canvas = document.getElementById('myCanvas');
var contexto = canvas.getContext('2d');
contexto.beginPath();
contexto.moveTo(position.top,50);
contexto.lineTo(position.top,150);
contexto.lineTo(position.top+100,150);
contexto.fill();
}
and this is my canvas:
<canvas id="myCanvas" width="700" height="700">Your browse don't support canvas</canvas>
I put it under the table code and I call the function in other function. If you could help me it would be great.
Thanks!
A: I hope I understand your question correctly: you have images in an actual Table element (<table></table>) and images in some cells. You have a canvas placed below it which you want to draw lines on to connect the images in the table.
To do this just subtract the canvas element's absolute position from the image's absolute position. This will make the image's position relative to the canvas.
For example
var canvas = document.getElementById('myCanvas');
var canvasPos = canvas.getBoundingClientRect();
var position = image.getBoundingClientRect();
var x = position.left - canvasPos.left;
var y = position.top - canvasPos.top;
var contexto = canvas.getContext('2d');
contexto.beginPath();
contexto.moveTo(x, y);
... next image
A: jsBin demo
Let's say you have a table and canvas inside a parent like:
<div id="wrapper">
<canvas id="lines"></canvas>
<table id="table">
<!-- 7*7 -->
</table>
</div>
#wrapper{
position:relative;
margin:0 auto;
width: 700px;
height:700px;
}
#wrapper canvas{
display:block;
position:absolute;
}
#wrapper table{
position: absolute;
}
#wrapper table td{
background: rgba(0,0,0,0.1);
width: 100px;
height: 100px;
vertical-align: middle;
}
#wrapper table td img{
display: block;
opacity:0.4;
}
You need to connect your images using lines,
you're probably interested for the image center but you need also to account the parent offset, so you need to subtract that position from the brc (getBoundingClientRect) of each image and it's td parentNode height/width:
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
var canvas = document.getElementById("lines");
var ctx = canvas.getContext("2d");
var x, y; // Remember coordinates
canvas.width = table.offsetWidth;
canvas.height = table.offsetHeight;
function connect( image ) {
var im = new Image();
im.onload = function(){ // make sure image is loaded
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
ctx.beginPath();
ctx.moveTo(x, y);
x = imgBcr.left + (image.parentNode.offsetWidth / 2) - tabBcr.left;
y = imgBcr.top + (image.parentNode.offsetHeight / 2) - tabBcr.top;
ctx.lineTo(x, y);
ctx.stroke();
};
im.src = images[i].src;
}
for(var i=0; i<images.length; i++){
connect( images[i] );
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30016224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Install self signed Certificates via ADB I'm trying to install self-signed Certificates(created by Charles) via ADB
I've pushed it to /sdcard/xxx.pem , And then failed to open it with Browsers that I could find, And Since the device removes the Setting Application, I could not install cert under the Setting App.
Then I searched And try
am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert file:///sdcard/test.cer
But just shown
01-07 17:47:56.442 12889-12889/com.android.certinstaller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.certinstaller, PID: 12889
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.certinstaller/com.android.certinstaller.CertInstallerMain}: java.lang.NullPointerException: uri
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5418)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:731)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:621)
Caused by: java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
at com.android.certinstaller.CertInstallerMain.startInstallActivity(CertInstallerMain.java:139)
at com.android.certinstaller.CertInstallerMain.onCreate(CertInstallerMain.java:119)
at android.app.Activity.performCreate(Activity.java:6270)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1115)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5418)
at java.lang.reflect.Method.invoke(Native Method)
I'm not familiar with this com.android.certinstaller app, Is there any reference How I could use it to install a cert?
A: Please try below:
adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///sdcard/test.cer
if throw
com.android.certinstaller E/CertInstaller: Failed to read certificate: java.io.FileNotFoundException: /sdcard/cer (Permission denied)
please root your devices and push cer to /system/etc/
adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///system/etc/test.cer
A: You need to make sure the file is readable if you are getting "Permission denied" or "Cloud not find the file" toast.
chmod o+r /sdcard/test.cer
and then
adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///sdcard/test.cer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59626101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: New custom action in Alfresco I want to do a custom action associated to rule.
I have used a guide http://wiki.alfresco.com/wiki/Custom_Action_UI but I don't get I need. I'm really newby using Alfresco...
My problem:
I have created my custom action. I select it in Alfresco UI and when I press the button "Set Values and Add" the application doesn't show any window to add any value to parameter that I have defined in method addParameterDefinitions:
protected void addParameterDefinitions(List<ParameterDefinition> paramList) {
paramList.add(new ParameterDefinitionImpl(PARAM_CUSTOM_URL, DataTypeDefinition.TEXT, true, getParamDisplayLabel(PARAM_CUSTOM_URL)));
}
I'm not sure if I need a jsp, all I want is a text box to type a parameter.
I have created a jsp and its ActionHandler, defining it in the web-client-config-custom.xml file, but Alfresco don't recognise the jsp. I don't know the location where I have to put the jsp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8093154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get data from many tables I am building a patient profile that has many tables such as medicines, treatments, x-ray, patient info, etc. all of them shared a patient ID, but I feel like it will have a big load on the service and take time, I searched a lot but I don't know if this approach is good or it could be better. here is an example of my eloquent code.
$patient = Patient::with(['country' => function ($q) {
$q->select('id', 'name');}])
->with(['city' => function ($q) {
$q->select('id', 'name');}])
->with(['recourse' => function ($q) {
$q->select('id', 'name');}])
->find($id);
$appointments = Appointment::where('patient_id', $id)
->with(['branch' => function ($q) {
$q->select('id', 'name');}])
->with(['doctor' => function ($q) {
$q->select('id', 'first_name');}])
->with(['service_cat' => function ($q) {
$q->select('id', 'name');}])
->orderBy('id', 'ASC')
->get();
$invoices = Invoice::select('id', 'creditor_cat_id', 'final_price', 'status')->where('patient_id', $id)
->with(['service_cat' => function ($q) {
$q->select('id', 'name');}])
->get();
$medicine = Medicine::select('id', 'medicines_cats', 'start', 'end', 'status')->where('patient_id', $id)
->with(['medicinescats' => function ($q) {
$q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();
$medicine_cat = Medicine_cat::all();
$disease = Disease::select('id', 'disease_cats', 'start', 'end', 'status')->where('patient_id', $id)
->with(['diseasecats' => function ($q) {
$q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();
$disease_cat = Disease_cat::all();
$treatment = Treatment::select('id', 'treatment_cat_id', 'sessions', 'sessions_done', 'start', 'end', 'status')->where('patient_id', $id)
->with(['treatment_cat' => function ($q) {
$q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();
$treatment_cat = Treatment_cat::all();
$session_pat = Session_pat::select('id', 'services_cat_id', 'treatment_id', 'invoice_id', 'status')->where('patient_id', $id)
->with(['service_cat' => function ($q) {
$q->select('id', 'name');}])
->with(['treatment' => function ($q) {
$q->select('id', 'sessions');}])
->with(['invoice' => function ($q) {
$q->select('id', 'code', 'status');}])
->orderBy('status', 'ASC')
->get();
$service_cat_treat = Service_cat::where('type', 2)->get();
edited: in case I used hasMany, these tables have other tables connected as shown, so I did not know how to make it, for example, the patient table has treatment table, treatment table has 2 tables connected which are invoice and treatment category, and I did what is above to get all data from these connected tables
A: So you have a few options to choose from:
*
*Combine all your queries into a single query (Make a larger query, which will join together all the tables you need in your example)
*Create a view (Create a view of these tables within the database, then query using the view)
*Create a materialized view (Creating a materialized view has it's benefits, though the upkeep of it is a bit tougher. Since materialized views actually hold real data, it means they need to be synced with the tables. They are only intended to be used when you need data fast and the data does not change often. In your case it could actually work, if you sync the materialized view every 5 min.) - Warning: MySQL does not directly support materialized views.
If you are trying to go for speed, then cache your results and only retrieve what was inserted after it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69748213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: Fix DecodeError when receiving data I've searched other post but from what I can tell they all have control of the data being sent to them. In this case I have no control over the data being sent to me. I'm receiving data from an IRC server that I cannot encode specifically to UTF-8 before it is sent. I was wondering if there is anyway to avoid UTF-8 decode errors when receiving data from the socket connected to the IRC channel.
I'm using python and the line of code I use for receiving is:
data = socket.recv(2048).decode('UTF-8')
Any help is appreciated: Thank You
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43867445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clojure Spec on a vararg function I am trying to write a spec for a merge function which takes a function and maps as an input and uses function to resolve the conflicts. However the spec i wrote for the function fails. I am trying to figure out how to write spec for such functions.
Below is the code snippet.
(require '[clojure.spec.test :as stest])
(require '[clojure.spec :as spec])
(defn deep-merge-with [func & maps]
(let [par-func (partial deep-merge-with func)]
(if (every? map? maps)
(apply merge-with par-func maps)
(apply func maps))))
(spec/fdef deep-merge-with
:args (spec/cat :func (spec/fspec :args (spec/cat :maps (spec/* map?))
:ret map?)
:maps (spec/cat :maps (spec/* map?)))
:ret map?)
(stest/instrument `deep-merge-with)
(deep-merge-with (fn [f s] s) {:a 1} {:a 2})
The spec error i am getting is:
clojure.lang.ExceptionInfo: Call to #'boot.user/deep-merge-with did not conform to spec:
In: [0] val: () fails at: [:args :func] predicate: (apply fn), Wrong number of args (0) passed to: user/eval22001/fn--22002
:clojure.spec/args (#function[boot.user/eval22001/fn--22002] {:a 1} {:a 2})
A: In your [:args :func] spec:
(spec/fspec :args (spec/cat :maps (spec/* map?)) :ret map?)
You're saying that the function must accept as arguments any number of maps and return a map. But the function you pass to deep-merge-with does not conform to that spec:
(fn [f s] s)
This function takes exactly two arguments, not an arbitrary number of maps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38253196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Issue with chromedriver in RobotFramework I started with python and Robot Framework.
I'm having this strange exception while trying to run a test case in Robot Framework.
WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: -1073741819
I tried changing the chromedriver versions, also checked the chrome browser it was updated to the last version.
I'm sure it's in it's place "Python27\Scripts" which is added to the environment variables as well.
Has anyone else had this issue, or know how to solve it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51925243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass Object from one Aspx to another from Javascript Correct me if I am doing wrong.
I have a Login page which uses a Webservice to process login. In my Login page I use Jquery with JSon to consume the webservice.
After the login is processed I recieve an object and I want to redirect the recieved object to home page.
Let me know how.
Thanks
Samuel
A: POST redirect the received JSON to server, and deserialize the JSON to your typed object. You can consider keeping the object in your SESSION and access it when required.
UPDATE
put a hidden field in your aspx/ascx page
Once you receive your JSON Data from your service. Just put your response to the hidden field. (USE JQUERY)
$("input[id$=jsonResponse]").val(responseFromService);
On your Page_Load method on your home.aspx
Use JavaScriptSerializer to deserialize your JSON data
JavaScriptSerializer serializer = new JavaScriptSerializer();
LoginData loginDataObject = serializer.Deserialize<LoginData>(jsonResponse.Value);
Now you can consider putting your loginDataObject to SESSION and access through out your application scope
// to store in session
Request.Session["loginData"] = loginDataObject;
// to retrieve from session
LoginData loginDataObject = (LoginData) Request.Session["loginData"];
A: You could store the object in a cookie and change the url with location.href or something similar?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8340774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to create Up and Down Methods using migrations? I am new to Code first, can you tell me how i can have all Up and Down methods for all tables in the database like below(given for one table)
public partial class abc: DbMigration
{
public override void Up()
{
AddColumn("dbo.UserTasks", "ServiceTechReason", c => c.Long());
}
public override void Down()
{
DropColumn("dbo.UserTasks", "ServiceTechReason");
}
}
i want all three types for a table viz .cs , .Designer.cs , .resx.
2) Can you explain the above example, i pick it from somewhere on internet i was searching for this but found nothing. is abc is my table name in database?
Provide me link if it is already answered.
EDIT
As mentioned by @scheien i already tried those commands they do not automatically override up and down methods for a table
A: Creating migrations is done by running the command Add-Migration AddedServiceTechReason.
This assumes that you have already enabled migrations using the Enable-Migrations command.
To apply the current migration to the database, you'd run the Update-Database. This command will apply all pending migrations.
The point of Code-First migrations is that you make the changes you want to your Entity(ies), and then add a new migration using the Add-Migration command. It will then create a class that inherits DbMigration, with the Up() and Down() methods filled with the changes you have made to your entity/entities.
As per @SteveGreenes comment: It does pick up all changes to your entities, so you don't need to run it once per table/entity.
If you want to customize the generated migration files, look under the section "Customizing Migrations" in the article listed.
All these commands are run in the package manager console.
View -> Other windows -> Package Manager Console.
Here's a great article from blogs.msdn.com that explains it in detail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33430217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way of reading/writing structured binary data in C# Like in C we could use structure pointers to read or write structured binary data like file headers etc, is there a similar way to do this in C#?
A: Using BinaryReader and BinaryWriter over a MemoryStream tends to be the best way in my opinion.
Parsing binary data:
byte[] buf = f // some data from somewhere
using (var ms = new MemoryStream(buf, false)) { // Read-only
var br = new BinaryReader(ms);
UInt32 len = br.ReadUInt32();
// ...
}
Generating binary data:
byte[] result;
using (var ms = new MemoryStream()) { // Expandable
var bw = new BinaryWriter(ms);
UInt32 len = 0x1337;
bw.Write(len);
// ...
result = ms.GetBuffer(); // Get the underlying byte array you've created.
}
They allow you to read and write all of the primitive types you'd need for most file headers, etc. such as (U)Int16, 32, 64, Single, Double, as well as byte, char and arrays of those. There is direct support for strings, however only if
The string is prefixed with the length, encoded as an integer seven bits at a time.
This only seems useful to me if you wrote the string in this way from BinaryWriter in this way. It's easy enough however, say your string is prefixed by a DWord length, followed by that many ASCII characters:
int len = (int)br.ReadUInt32();
string s = Encoding.ASCII.GetString(br.ReadBytes(len));
Note that I do not have the BinaryReader and BinaryWriter objects wrapped in a using() block. This is because, although they are IDisposable, all their Dispose() does is call Dispose() on the underlying stream (in these examples, the MemoryStream).
Since all the BinaryReader/BinaryWriter are is a set of Read()/Write() wrappers around the underlying streams, I don't see why they're IDisposable anyway. It's just confusing when you try to do The Right Thing and call Dispose() on all your IDisposables, and suddenly your stream is disposed.
A: To read arbitrarily-structured data (a struct) from a binary file, you first need this:
public static T ToStructure<T>(byte[] data)
{
unsafe
{
fixed (byte* p = &data[0])
{
return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
}
};
}
You can then:
public static T Read<T>(BinaryReader reader) where T: new()
{
T instance = new T();
return ToStructure<T>(reader.ReadBytes(Marshal.SizeOf(instance)));
}
To write, convert the struct object to a byte array:
public static byte[] ToByteArray(object obj)
{
int len = Marshal.SizeOf(obj);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
...and then just write the resulting byte array to a file using a BinaryWriter.
A: Here is an simple example showing how to read and write data in Binary format to and from a file.
using System;
using System.IO;
namespace myFileRead
{
class Program
{
static void Main(string[] args)
{
// Let's create new data file.
string myFileName = @"C:\Integers.dat";
//check if already exists
if (File.Exists(myFileName))
{
Console.WriteLine(myFileName + " already exists in the selected directory.");
return;
}
FileStream fs = new FileStream(myFileName, FileMode.CreateNew);
// Instantialte a Binary writer to write data
BinaryWriter bw = new BinaryWriter(fs);
// write some data with bw
for (int i = 0; i < 100; i++)
{
bw.Write((int)i);
}
bw.Close();
fs.Close();
// Instantiate a reader to read content from file
fs = new FileStream(myFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
// Read data from the file
for (int i = 0; i < 100; i++)
{
//read data as Int32
Console.WriteLine(br.ReadInt32());
}
//close the file
br.Close();
fs.Close();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13963508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I skip methods using @AfterMethod in TestNG I have a set of tests as follows.
@Test
public void testX(){
}
@Test
public void testY(){
}
@Test
public void testZ(){
}
I have another test which I should run after each of the test is executed.
I hope I could do that with
@AfterMethod
public void testA(){
}
Now I need to skip testA for testX. Which means I don't need testA to run after testX. How do I do it? Also how to specify multiple test cases to skip in the above manner?
A: One way to do that would be to add to the same group every method you want testA to execute.
In the following example, testY and testZ are added to the "myGroup" group so the testA after method, which also belongs to this group, will only be executed for those tests.
@Test
public void testX(){
}
@Test(groups = { "myGroup" })
public void testY(){
}
@Test(groups = { "myGroup" })
public void testZ(){
}
@AfterMethod(groups = { "myGroup" })
public void testA(){
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33431870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get two item from a List<> in every get request in ASP.NET Core MVC How can I get two value per get request from a List<>, For example,
I have a Person List<> with six Person Ordered by ID in that List<> now in every get request using JQuery ajax() I want to get only two item from the list<>, first request will return Person with ID 1 & 2, second request will return Person with ID 3 & 4, and so forth.
I've tried
public IEnumerable<PersonViewModel> GetAllStudents()
{
IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Take(2);
List<PersonViewModel> persons = new List<PersonViewModel>();
foreach(var p in dbPersons)
{
persons.Add(MapDbPieToPersonViewModel(p));
}
return persons;
}
But this only return first two item.
A: You should use Enumerable.Skip(Int32)
public IEnumerable<PersonViewModel> GetAllStudents(int page)
{
const int PageSize = 2;
IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Skip(page * PageSize).Take(PageSize);
List<PersonViewModel> persons = new List<PersonViewModel>();
foreach(var p in dbPersons)
{
persons.Add(MapDbPieToPersonViewModel(p));
}
return persons;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47821238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can a NSDictionary take in NSSet as key? I know you can use any object as key for NSDictionary but the problem is will it be able to retrieve the correct value? Support I have an entry where the key = {1,3,5} and value = { @"hello" }. Will I be able to retrieve from this dictionary entry by passing in the set {3,5,1}?
In order words, is the key matched based on the pointer or does it actually compare the contents of the set? (And if it is the former, how can I overcome this?)
A: The equality of keys is done using isEqual on the keys in question. Thus, the comparison of {1,3,5} and {3,5,1} (assuming that the numbers are represented by NSNUmber instances) will be YES.
A: Yep it seems to work nicely (not sure if there are any gotchas).
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
NSSet * set;
set = [NSSet setWithObjects:@"a", @"b", @"c", @"d", nil];
[dict setObject:@"1" forKey:set];
set = [NSSet setWithObjects:@"b", @"c", @"d", @"e", nil];
[dict setObject:@"2" forKey:set];
id key;
NSEnumerator * enumerator = [dict keyEnumerator];
while ((key = [enumerator nextObject]))
NSLog(@"%@ : %@", key, [dict objectForKey:key]);
set = [NSSet setWithObjects:@"c", @"b", @"e", @"d", nil];
NSString * value = [dict objectForKey:set];
NSLog(@"set: %@ : key: %@", set, value);
Outputs:
2009-12-08 15:42:17.885 x[4989] (d, e, b, c) : 2
2009-12-08 15:42:17.887 x[4989] (d, a, b, c) : 1
2009-12-08 15:42:17.887 x[4989] set: (d, e, b, c) : key: 2
A: Yes (since a set conforms to NSCopying and implements isEqual:), with one catch: Do not use a mutable set, or any other mutable object, as a key. You will mutate it, whereupon you will break your ability to look up its value in the dictionary.
A: Yes.
Try this in irb:
require 'osx/cocoa'
abc=OSX::NSSet.setWithArray([1,2,3])
cba=OSX::NSSet.setWithArray([3,2,1])
dict=OSX::NSMutableDictionary.dictionary
dict[abc] = 'hello'
puts dict[cba]
(it works, because isEqual: for NSSet is true when you'd expect it to be and NSDictionary bases its actions on that)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1863061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to return var parameter in Delphi ASM I'm far from having knowledge about ASM, so forgive me if this is a stupid question.
I have this function:
function SwapDWord(const AValue: DWORD): DWORD;
asm
BSWAP EAX
end;
How would I convert it to a procedure in ASM:
procedure SwapDWordVar(var AValue: DWORD);
asm
// ???
end;
I do not want to use AValue := SwapDWord(AValue); which I could. I want to do this in ASM.
I tried many silly things by looking at system.pas and tried to understand which register(s) to use. but nothing worked. It always return back the original AValue.
A: Possible variant:
procedure SwapDWordVar(var AValue: DWORD);
asm
mov edx, [eax]
bswap edx
mov [eax], edx
end;
You might find useful Guido Gybels articles
A: Just try
procedure SwapDWordVar(var AValue: DWORD);
asm
mov edx, dword ptr [AValue]
bswap edx
mov dword ptr [AValue], edx
end;
Note that this version will compile and work for both Win32 and Win64.
But note that it won't be faster than AValue := SWapDWord(AValue) since most of the time will be spent calling the function, not accessing the memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47748565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to run custom mysql script for Laravel app in test pipeline in CodeShip Basic? Relative newbie to PhpUnit and testing in general. We do not use migrations in our project, but have a couple of scripts that I need to run in order to set up the database for testing. How can I run mysql scripts from the project in the test pipeline? I also need to create a new database with a specific name before running those scripts.
Thanks!
A: The commands that you use on your local machine are the same commands you can run in CodeShip Basic. CodeShip Basic is just a build machine with Ubuntu Bionic and it will run through the setup, test, and deploy commands as if you were entering each line into your CLI. :)
We also have some documentation about mysql: https://documentation.codeship.com/basic/databases/mysql/
A: OK, after some digging I found out how to do all this. Below is the script I used for testing with a new mysql schema created with specific user from a sql script. Hope this helps someone in the future.
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE USER 'myuser'@'%' IDENTIFIED BY 'testpassword';"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE SCHEMA myschemaname;"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'testpassword';"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/1of2-schema.sql
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/2of2-seed.sql
php artisan passport:install
./vendor/bin/phpunit
$MYSQL_USER and $MYSQL_PASSWORD are replaced by Codeship - these are the env variables for the user and password for the mysql that exists in the build container.
the -e switch on the mysql call runs the script given and exits. Had to do it this way since I couldn't interact with the mysql client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57261297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: replace 0 into dash in Fast Report Is it Possible to replace 0 value and turn it into dash in fast report?
like:
No. turns to
1 1
2 2
0 -
3 3
0 -
0 -
A: Yes.
Use a built-in script engine.
Assuming you have a dataset DS and a field FIELD_NAME then instead of [DS."FIELD_NAME"] you should write [IIF(<DS."FIELD_NAME"> = 0, '-', <DS."FIELD_NAME">)] as your frxMemoView text.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26030030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: databricks init script to mount dbfs on adls I am using a python notebook to mount dbfs on adls , now I want to add this to the init scrip so this can be done during the job cluster start
this is the python code I am using how to make this run as the init script please:
environment = "development"
scopeCredentials = "test-" + environment
# Secrets
# ADLS
app_id = dbutils.secrets.get(scope=scopeCredentials, key="app_id")
key = dbutils.secrets.get(scope=scopeCredentials, key="key")
adls_name = dbutils.secrets.get(scope=scopeCredentials, key="adls-name")
# Configs
# ADLS
adls_configs = {
"dfs.adls.oauth2.access.token.provider.type": "ClientCredential",
"dfs.adls.oauth2.client.id": app_id, #id is the AppId of the service principal
"dfs.adls.oauth2.credential": key,
"dfs.adls.oauth2.refresh.url": "url"
}
mount_point="mount_point"
if any(mount.mountPoint == mount_point for mount in dbutils.fs.mounts()):
print("Storage: " + mount_point + " already mounted")
else:
try:
dbutils.fs.mount(
source = "source",
mount_point = "mount_point",
extra_configs = adls_configs)
print("Storage: " + mount_point + " successfully mounted")
except:
print("Storage: " + mount_point + " not mounted")
pass
any idea how to change this to make it as a bash init script ?
A: Mounting of the storage needs to be done once, or when you change credentials of the service principal. Unmount & mount during the execution may lead to a problems when somebody else is using that mount from another cluster.
If you really want to access storage only from that cluster, then you need to configure that properties in the cluster's Spark Conf, and access data directly using abfss://... URIs (see docs for details). Mounting the storage just for time of execution of the cluster doesn't make sense from the security perspective, because during that time, anyone in workspace can access mounted data, as mount is global, not local to a cluster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72029642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Spring Reactive MVC vs @EnableAsync I'm a newbie to Spring Reactive Modules. What I got is basically, at its core it enable reactive programming and we can develop end to end reactive service.
But, suppose I just want to make my controller as Async, so that I can do work on multiple threads and send a reply like "Task Started" (not particularly this) and have my work going on and close the HTTP link.
I also got to know about @EnableAsync and @Async to make a method Async.
What if I just use @Async above my controller method that I want to make async. It worked but, is this a good practice? And can we use this in production codes?
A: I do not see any problem using @Asyncas this will release the request thread. But this is a simple approach and it has a lot of limitations. Note that if you want to deal with reactive streams, you do not have an API capable of that. For instance, if an @Async method calls another, the second will not be async.
The Webflux instead will bring the most complete API (in Java) to deal with things the reactive way. What you cannot do with only @Async. With Flux, for instance, you can process or access with multiple layers reactively and this you cannot reach the way you doing.
Nevertheless, it will bring a new universe for you, so if you just want to release the thread of the request, your approach is just fine, but if you need more you will have to deal with it in a more complex way.
Now, if you want to answer the HTTP request and then do the work asyncly, this is not what you want. I recommend that you have a JMS provider (like ActiveMQ), where your controller sends the message to be processed by a job and answers the request.
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48107287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why search in .Net Dictionary is slower than in .Net List I tried to solve this task:
We have an array, eg. [1, 1, 2, 3, 5, 2, 7, 8, 1], find and output duplicates. For this array the result is
1, 2.
I wrote code to try "slow" and "fast" solutions.
"Slow" solution with inner loop and searching via list
public uint[] InnerLoops(uint[] arr)
{
var timer = new Stopwatch();
timer.Start();
var result = new List<uint>();
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] == arr[j] && result.All(a => a != arr[j]))
result.Add(arr[j]);
}
}
timer.Stop();
Console.WriteLine($"Seconds: {timer.Elapsed}");
return result.ToArray();
}
I would estimate the solutions as O(n^2) and O(n) inside each inner loop. Sorry, I am not good at estimating complexity. Anyway, I thought, the following solution would be better
public uint[] OneLoopDictionary(uint[] arr)
{
var timer = new Stopwatch();
timer.Start();
var dictionary = new Dictionary<uint, bool>();
for (int i = 0; i < arr.Length; i++)
{
// Key - number, value - true if duplicates
if (dictionary.ContainsKey(arr[i]))
{
dictionary[arr[i]] = true;
}
else
{
dictionary[arr[i]] = false;
}
}
var result = new List<uint>();
foreach (var item in dictionary)
{
if (item.Value)
result.Add(item.Key);
}
timer.Stop();
Console.WriteLine($"Seconds: {timer.Elapsed}");
return result.ToArray();
}
The complexity is O(2n) - one loop and loop via dictionary.
I was surprised that the fist solution with loop was faster that the second one. Could anyone explain me why?
A: Thanks to all! Espesially to who gave an advice to try with bigger array. I tryied with 100, 1000 and 100000 and I was surprised, that the dictionary was faster. Of course, previously, I tryied not just with array from my first post, bur with array of about 50 numbers, but the dictionary was slower.
With aaray of 100 or more numbers the dictuinary is much more faster. The result for 100000 items is:
list - 31 seconds,
dicionary - 0.008 seconds
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64368414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: angularJs directive to format date I want to have a functionality in angular which help to enter date and show it in proper format and don't allow invalid values in it. also able to show server returned '20140314T00:00:00Z' json string for date.
Can anyone help me ?
A: Angular.js already have date filter {{20140314 | date}} // Jan 1, 1970 9:35:40 AM
Angular Date Docs
A: This works for me,
.directive('myDate', ['$timeout', '$filter', function ($timeout, $filter)
{
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, $ctrl)
{
var dateFormat = 'mm/dd/yyyy';
$ctrl.$parsers.push(function (viewValue)
{
//convert string input into moment data model
var pDate = Date.parse(viewValue);
if (isNaN(pDate) === false) {
return new Date(pDate);
}
return undefined;
});
$ctrl.$formatters.push(function (modelValue)
{
var pDate = Date.parse(modelValue);
if (isNaN(pDate) === false) {
return $filter('date')(new Date(pDate), dateFormat);
}
return undefined;
});
$element.on('blur', function ()
{
var pDate = Date.parse($ctrl.$modelValue);
if (isNaN(pDate) === true) {
$ctrl.$setViewValue(null);
$ctrl.$render();
} else {
if ($element.val() !== $filter('date')(new Date(pDate), dateFormat)) {
$ctrl.$setViewValue($filter('date')(new Date(pDate), dateFormat));
$ctrl.$render();
}
}
});
$timeout(function ()
{
$element.kendoDatePicker({
format: dateFormat
});
});
}
};
}])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22414788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I solve my foreign key constraint error when I know I created the relationships right?
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema BrendasDMS
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `BrendasDMS` ;
-- -----------------------------------------------------
-- Schema BrendasDMS
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `BrendasDMS` DEFAULT CHARACTER SET utf8 ;
SHOW WARNINGS;
USE `BrendasDMS` ;
-- -----------------------------------------------------
-- Table `Customers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Customers` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Customers` (
`Customer_ID` INT NOT NULL AUTO_INCREMENT,
` FirstName` VARCHAR(45) NOT NULL,
`LastName` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`Phone` VARCHAR(45) NOT NULL,
PRIMARY KEY (`Customer_ID`),
UNIQUE INDEX `CustomerID_UNIQUE` (`Customer_ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Employees`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Employees` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Employees` (
`Employee_ID` INT NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(45) NOT NULL,
`LastName` VARCHAR(45) NOT NULL,
`Address` VARCHAR(45) NOT NULL,
`City` VARCHAR(45) NOT NULL,
`State` VARCHAR(45) NOT NULL,
`Zip` VARCHAR(45) NOT NULL,
`County` VARCHAR(45) NOT NULL,
`PhoneNumber` VARCHAR(45) NOT NULL,
`BirthDate` DATE NOT NULL,
`SSN` VARCHAR(45) NOT NULL,
PRIMARY KEY (`Employee_ID`),
UNIQUE INDEX `FirstName_UNIQUE` (`FirstName` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Shops`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Shops` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Shops` (
`Shop_ID` INT NOT NULL AUTO_INCREMENT,
`Address` VARCHAR(45) NOT NULL,
`County` VARCHAR(45) NOT NULL,
`Zip` VARCHAR(45) NOT NULL,
`Phone Number` VARCHAR(45) NOT NULL,
PRIMARY KEY (`Shop_ID`),
UNIQUE INDEX `ID_UNIQUE` (`Shop_ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Sales`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Sales` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Sales` (
`Sale_ID` INT NOT NULL AUTO_INCREMENT,
`SaleDate` DATE NOT NULL,
`Employee_ID` INT NOT NULL,
`Customer_ID` INT NOT NULL,
`Shop_ID` INT NOT NULL,
`Quantity` INT NOT NULL,
`Price` DECIMAL NOT NULL,
`UnitOfMeasure` VARCHAR(45) NOT NULL,
PRIMARY KEY (`Sale_ID`, `Customer_ID`, `Employee_ID`, `Shop_ID`),
INDEX `fk_Sale_Employee1_idx` (`Employee_ID` ASC),
INDEX `fk_Sale_Customer1_idx` (`Customer_ID` ASC),
INDEX `fk_Sale_Shops1_idx` (`Shop_ID` ASC),
CONSTRAINT `fk_Sale_Employee1`
FOREIGN KEY (`Employee_ID`)
REFERENCES `Employees` (`Employee_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Sale_Customer1`
FOREIGN KEY (`Customer_ID`)
REFERENCES `Customers` (`Customer_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Sale_Shops1`
FOREIGN KEY (`Shop_ID`)
REFERENCES `Shops` (`Shop_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Products`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Products` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Products` (
`Product_ID` INT NOT NULL AUTO_INCREMENT,
`ProductName` VARCHAR(45) NOT NULL,
`UnitOfMeasure` VARCHAR(45) NOT NULL,
`Price` DECIMAL NOT NULL,
`Quantity` INT NOT NULL,
PRIMARY KEY (`Product_ID`),
UNIQUE INDEX `RecipeID_UNIQUE` (`Product_ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `SaleLineItems`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `SaleLineItems` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `SaleLineItems` (
`Sale_ID` INT NOT NULL,
`Quantity` INT NOT NULL,
`Product_ID` INT NOT NULL,
PRIMARY KEY (`Sale_ID`, `Product_ID`),
INDEX `fk_Sale_has_Product_Sale1_idx` (`Sale_ID` ASC),
INDEX `fk_SaleLineItem_Product1_idx` (`Product_ID` ASC),
CONSTRAINT `fk_Sale_has_Product_Sale1`
FOREIGN KEY (`Sale_ID`)
REFERENCES `Sales` (`Sale_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_SaleLineItem_Product1`
FOREIGN KEY (`Product_ID`)
REFERENCES `Products` (`Product_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Vendors`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Vendors` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Vendors` (
`Vendor_ID` INT NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(45) NOT NULL,
`LastName` VARCHAR(45) NOT NULL,
`VendorType` VARCHAR(45) NOT NULL,
`Address` VARCHAR(45) NOT NULL,
`Zip` VARCHAR(45) NOT NULL,
`PhoneNumber` VARCHAR(45) NOT NULL,
PRIMARY KEY (`Vendor_ID`),
UNIQUE INDEX `ID_UNIQUE` (`Vendor_ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Orders`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Orders` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Orders` (
`Order_ID` INT NOT NULL AUTO_INCREMENT,
`Date` DATE NOT NULL,
`Vendor_ID` INT NOT NULL,
`Quantity` INT NOT NULL,
`UnitOfMeasure` VARCHAR(45) NOT NULL,
`Price` DECIMAL NOT NULL,
PRIMARY KEY (`Order_ID`, `Vendor_ID`),
UNIQUE INDEX `ID_UNIQUE` (`Order_ID` ASC),
INDEX `fk_Orders_Vendor1_idx` (`Vendor_ID` ASC),
CONSTRAINT `fk_Orders_Vendor1`
FOREIGN KEY (`Vendor_ID`)
REFERENCES `Vendors` (`Vendor_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `EmployeeShop`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `EmployeeShop` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `EmployeeShop` (
`Shop_ID` INT NOT NULL,
`Employee_ID` INT NOT NULL,
PRIMARY KEY (`Shop_ID`, `Employee_ID`),
INDEX `fk_Shop_has_Employee_Employee1_idx` (`Employee_ID` ASC),
INDEX `fk_Shop_has_Employee_Shop1_idx` (`Shop_ID` ASC),
CONSTRAINT `fk_Shop_has_Employee_Shop1`
FOREIGN KEY (`Shop_ID`)
REFERENCES `Shops` (`Shop_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Shop_has_Employee_Employee1`
FOREIGN KEY (`Employee_ID`)
REFERENCES `Employees` (`Employee_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Ingredients`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Ingredients` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Ingredients` (
`Ingredient_ID` INT NOT NULL,
`IngredientName` VARCHAR(45) NOT NULL,
`UnitOfMeasure` VARCHAR(45) NOT NULL,
`Quantity` INT NOT NULL,
`Price` DECIMAL NOT NULL,
PRIMARY KEY (`Ingredient_ID`))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `OrderLineItems`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `OrderLineItems` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `OrderLineItems` (
`Quantity` INT NOT NULL,
`Order_ID` INT NOT NULL,
`Ingredient_ID` INT NOT NULL,
PRIMARY KEY (`Order_ID`, `Ingredient_ID`),
INDEX `fk_OrderLineItems_Orders1_idx` (`Order_ID` ASC),
INDEX `fk_OrderLineItems_Ingredients1_idx` (`Ingredient_ID` ASC),
CONSTRAINT `fk_OrderLineItems_Orders1`
FOREIGN KEY (`Order_ID`)
REFERENCES `Orders` (`Order_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_OrderLineItems_Ingredients1`
FOREIGN KEY (`Ingredient_ID`)
REFERENCES `Ingredients` (`Ingredient_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = ndbcluster;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `Recipes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Recipes` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Recipes` (
`Recipe_ID` INT NOT NULL,
`Directions` VARCHAR(45) NOT NULL,
`Product_ID` INT NOT NULL,
PRIMARY KEY (`Recipe_ID`, `Product_ID`),
UNIQUE INDEX `Recipe_ID_UNIQUE` (`Recipe_ID` ASC),
INDEX `fk_Recipes_Products1_idx` (`Product_ID` ASC),
CONSTRAINT `fk_Recipes_Products1`
FOREIGN KEY (`Product_ID`)
REFERENCES `Products` (`Product_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `RecipeIngredients`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `RecipeIngredients` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `RecipeIngredients` (
`Quantity` INT NOT NULL,
`Ingredient_ID` INT NOT NULL,
`UnitOfMeasure` VARCHAR(45) NOT NULL,
`Price` DECIMAL NOT NULL,
`Recipe_ID` INT NOT NULL,
PRIMARY KEY (`Ingredient_ID`, `Recipe_ID`),
INDEX `fk_RecipeIngredients_Ingredients2_idx` (`Ingredient_ID` ASC),
INDEX `fk_RecipeIngredients_Recipes1_idx` (`Recipe_ID` ASC),
CONSTRAINT `fk_RecipeIngredients_Ingredients2`
FOREIGN KEY (`Ingredient_ID`)
REFERENCES `Ingredients` (`Ingredient_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_RecipeIngredients_Recipes1`
FOREIGN KEY (`Recipe_ID`)
REFERENCES `Recipes` (`Recipe_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
I have created a lot of tables and I am now trying to forward engineer my logical model into a physical database, but I am having trouble when it keeps saying "Can't add a foreign key constraint".
However, I know that the error is related to the Products referencing the Recipe_ID, but when I click on the relationship line from Recipes table to RecipeIngredients table, I see that the FK Recipe_ID IS REFERENCING the Recipe_ID primary key column in the Recipes table, not the Product table.
If that is the case, why is problem occurring? Any suggestions except recreating all of the tables again. Here is my picture model and picture of my problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43190655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Swagger-play2 - hiding internal parameters I have configured swagger-play2 library version 1.7.1 (for play framework version 2.7) and have it up and running successfully. Our controller methods have an additional input: Http.Request request which is passed across the application for some logging and monitoring purposes. I need to hide this from the swagger specs, tried using @ApiParam(hidden = true) but it still shows up in specs. Is this flag not working as expected? how do I hide the input in this case? I'd like to know whether @ApiParam(hidden = true) has worked for anyone with swagger-play2 plugin, not with Spring.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56661513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Flutter - AndroidManifest.xml corrupted after Flutter Upgrade I've just upgraded to Flutter 2 and upgraded an application along with it. I followed all the steps to upgrade the application, but now I can't seem to run the app because my AndroidManifest.xml file seems corrupted.
Here is the xml file (I've also added comments where the errors are appearing).
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.finances_management">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:name="io.flutter.app.FlutterApplication" <-- Unresolved class 'FlutterApplication'
android:label="finances_management"
android:icon="@mipmap/ic_launcher"> <-- Cannot resolve symbol '@mipmap/ic_launcher'
<activity
android:name=".MainActivity" <-- Unresolved class 'MainActivity'
android:launchMode="singleTop"
android:theme="@style/LaunchTheme" <-- Cannot resolve symbol '@style/LaunchTheme'
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" <-- Cannot resolve symbol '@style/NormalTheme'
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background" <-- Cannot resolve symbol '@drawable/launch_background'
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
I've seen elsewhere that people are just completely rebuilding their projects (as in completely generating a new project, stripping business logic from their Flutter 1.x app and copying it across to a Flutter 2.x app). Does anyone know what's happened to my XML file?
A: The best solution is to downgrade the Flutter . after that update AndroidManifest file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67221631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regarding GetProcAddress I have got MyDll.dll and its function defined as below
void pascal Myfunction(BOOL);
when I'm trying to use the function in another project i am unable get the address of the function with GetProcAddress(). Here is my code:
void callMyDll()
{
HINSTANCE hDll;
hDll=LoadLibrary(_T("MyDll.dll");
if(hDll!=NULL)
{
cout<<"\n DLL Loaded \n";
}
else
cout<<"\n DLL Not loaded\n"
typedef void (__stdcall *MyFunction)(bool)
Myfunction mf1 = (MyFunction) GetProcAddress(hDll, "MyFunction");
if (mf1!=NULL)
cout<<"\n Function Loaded Successfully \n";
else
cout<<"\n Function not loaded \n";
FreeLibrary(hDll);
}
I'm getting output as:
DLL Loaded
Function not loaded
But when I'm trying with known DLLs like glut32.dll and its functions it is working fine.
I think it may be problem with its function like
void pascal MyFunction(BOOL);
Can anybody help me in this regard?
A: You need to use extern "C" to prevent name mangling and ensure the function is exported:
extern "C" __declspec(dllexport) void Myfunction(BOOL);
To view the exports from your DLL you can use dumpbin.exe utility that is shipped with Visual Studio:
dumpbin.exe /EXPORTS MyDll.dll
This will list the names of all exported symbols.
In addition to this do not have either of the following compiler switches specified:
Gz __stdcall calling convention: "Myfunction" would be exported as Myfunction@4
Gr __fastcall caling convention: "Myfunction" would be exported as @Myfunction@4
Note: I think last symbol is dependent on compiler version but is still not just "Myfunction".
A: The DLL export process is subject to name mangling and decoration. The long obsolete 16 bit pascal calling convention is equivalent to stdcall on 32 bit platforms.
First of all you should use extern "C" to specify C linkage and disable name mangling.
However, your function will still be subject to name decoration. If you export it with __declspec(dllexport) then it will in fact be exported with the name _Myfunction@4. If you wish to export it by its true name then you need to use a .def file.
However, the possibility still remains that you did not export the function from the DLL at all. Use Dependency Walker to check whether it was exported, and if so by what name.
A: Why are you using the pascal calling-convention? Perhaps that alters the names of symbols, and if so you might need to take that into account.
A: The symbol is going to be decorated, so it will never be called MyFunction, its more likely _MyFunction@4. you can quickly check this using something like dumpbin.
You can read up more on mangling here, if you want to avoid mangling, you need to use a def file to specify symbol names (or ordinals).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9001619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: i am dumping a piped data , but when i try to read using pickle.loads i get an error this code works fine thats piping out
allWriteNodes=nuke.allNodes("Write")
test = nuke.allNodes()
for index,each in enumerate(test):
wrtNodelst.insert(index,each.name())
print index, each.name()
sys.stdout.write(pickle.dumps(wrtNodelst))
quit()
except RuntimeError:
sys.stderr.write('could not find %s\n' % target_file)
raise
but this line that is going to read in different file causes error:
print pickle.loads(process.stdout.read())
giving IndexError : list index out of range... any idea what might be causing it and out to read pickled stdout data ?
The Traceback error
Traceback (most recent call last):
File "\RenderUI.py", line 384, in execApp
print pickle.loads(process.stdout.read())
File "D:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "D:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "D:\Python26\lib\pickle.py", line 1203, in load_setitems
mark = self.marker()
File "D:\Python26\lib\pickle.py", line 874, in marker
while stack[k] is not mark: k = k-1
IndexError: list index out of range
A: use
print pickle.load(process.stdout)
does this work?
read may not return the whole string.
A: This line:
print index, each.name()
Causes issues, as it is sending debug output to stdout before the pickle is sent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13838903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Decimal/double to integer - round up (not just to nearest) How would you round up a decimal or float to an integer. For instance...
0.0 => 0
0.1 => 1
1.1 => 2
1.7 => 2
2.1 => 3
Etc.
A: Simple, use Math.Ceiling:
var wholeNumber = (int)Math.Ceiling(fractionalNumber);
A: Something like this?
int myInt = (int)Math.Ceiling(myDecimal);
A: Before saying it does not work, you have to check that ALL VALUES in the operation are double type.
Here is an example in C#:
int speed= Convert.ToInt32(Math.Ceiling((double)distance/ (double)time));
A: Math.Ceiling not working for me, I use this code and this work :)
int MyRoundedNumber= (int) MyDecimalNumber;
if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
MyRoundedNumber++;
and if you want to round negative number to down for example round -1.1 to -2 use this
int MyRoundedNumber= (int) MyDecimalNumber;
if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
if(MyRoundedNumber>=0)
MyRoundedNumber++;
else
MyRoundedNumber--;
A: var d = 1.5m;
var i = (int)Math.Ceiling(d);
Console.Write(i);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8666069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Node.js bindings for a Digital Asset Ledger Project I am working through Digital Asset Getting Started with Node.js bindings.
Running
npm install @da/daml-ledger
causes the following error message
npm ERR! code E401
npm ERR! 401 Unauthorized: @da/daml-ledger@latest
npm ERR! A complete log of this run can be found in:
npm ERR! /...../.npm/_logs/2019-02-22T17_48_44_560Z-debug.log
here are the contents of that log file:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/node',
1 verbose cli '/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/npm',
1 verbose cli 'install',
1 verbose cli '@da/daml-ledger' ]
2 info using [email protected]
3 info using [email protected]
4 verbose npm-session 99e5e60df68735cb
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 401 https://api.bintray.com/npm/digitalassetsdk/npm/@da%2fdaml-ledger 411ms
8 silly fetchPackageMetaData error for @da/daml-ledger@latest 401 Unauthorized: @da/daml-ledger@latest
9 timing stage:rollbackFailedOptional Completed in 4ms
10 timing stage:runTopLevelLifecycles Completed in 515ms
11 verbose stack Error: 401 Unauthorized: @da/daml-ledger@latest
11 verbose stack at fetch.then.res (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.j
s:42:19)
11 verbose stack at tryCatcher (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
11 verbose stack at Promise._settlePromiseFromHandler (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/relea
se/promise.js:512:31)
11 verbose stack at Promise._settlePromise (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise.
js:569:18)
11 verbose stack at Promise._settlePromise0 (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise
.js:614:10)
11 verbose stack at Promise._settlePromises (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise
.js:693:18)
11 verbose stack at Async._drainQueue (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:
16)
11 verbose stack at Async._drainQueues (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143
:10)
11 verbose stack at Immediate.Async.drainQueues [as _onImmediate] (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/blueb
ird/js/release/async.js:17:14)
11 verbose stack at runCallback (timers.js:705:18)
11 verbose stack at tryOnImmediate (timers.js:676:5)
11 verbose stack at processImmediate (timers.js:658:5)
12 verbose cwd /home/vantage/DAnodeBindings
13 verbose Linux 4.15.0-45-generic
14 verbose argv "/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/node" "/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/npm" "install" "@da/daml-ledger"
15 verbose node v10.15.1
16 verbose npm v6.4.1
17 error code E401
18 error 401 Unauthorized: @da/daml-ledger@latest
19 verbose exit [ 1, true ]
I followed the instructions in step 1 and step 2. my .npmrc is updated with the response I received from entering
curl -umehul@digitalassetsdk:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da
and I entered the command
npm config set @da:registry https://api.bintray.com/npm/digitalassetsdk/npm
What is causing the error?
A: From the comments it appears you missed a step of the setup, namely as the instructions tell you to paste the response of curl to ~/.npmrc.
The response should be pasted in the ~/.npmrc (in Windows %USERPROFILE%/.npmrc) file.
As an alternative, on Linux and MacOS you can just pipe the output of curl to ~/.npmrc as follows:
curl -u<USERNAME>:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da >> ~/.npmrc
Using the >> operator will preserve the current content of ~/.npmrc and append the output of curl to the file (or create it if it's not there yet). If you want to overwrite the current ~/.npmrc file, just use the > operator instead.
A: The Bintary 'Set Me Up' Instructions (referenced in step 1.3 of https://docs.daml.com/app-dev/bindings-js/getting-started.html) say to run a curl command and the to run
npm config set @<SCOPE>:registry https://api.bintray.com/npm/digitalassetsdk/npm
When I skip the npm config step I have no problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54832864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vue.js - Is there any way to render elements in two different divs using one v-for loop? The goal is to make the output look like this:
<div id="tabs">
<div id="first">
<a>tab 1</a>
<a>tab 2</a>
</div>
<div id="second">
<a>tab 3</a>
</div>
</div>
Currently I'm using this solution (using two v-for loops):
tabs.js (current)
export default {
data() {
return {
tabs: {
first: [{ name: 'tab1' }, { name: 'tab2' }],
second: [{ name: 'tab3' }],
}
}
}
template: `
<div id="tabs">
<div id="first">
<a v-for="tab in tabs.first">{{ tab.name }}</a>
</div>
<div id="second">
<a v-for="tab in tabs.second">{{ tab.name }}</a>
</div>
</div>
`
}
I had an idea to do something like this but it performs more iterations than in the case with two loops:
tabs.js (idea)
export default {
data() {
return {
tabs: {
test: [
{ name: 'tab1', category: 'first' },
{ name: 'tab2', category: 'first' },
{ name: 'tab3', category: 'second' }
]
}
}
}
template: `
<div id="tabs">
<div v-for='category in ["first", "second"]' :id='category' :key='category'>
<template v-for="tab in tabs.test">
<a v-if="tab.category === category">{{ tab.name }}</a>
</template>
</div>
</div>
`
}
I read this topic but it contains slightly different solutions, which unfortunately didn't work in this case.
A: I did not see any harm in using two v-for (one for the object keys and another for the array elements) as far as it is all dynamic. You can give a try to this solution by using of Object.keys() :
new Vue({
el: '#app',
data: {
tabs: {
first: [{ name: 'tab1' }, { name: 'tab2' }],
second: [{ name: 'tab3' }],
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div id="tabs">
<div v-for="tab in Object.keys(tabs)" :key="tab" :id="tab">
<a v-for="tab in tabs[tab]">{{ tab.name }}</a>
</div>
</div>
</div>
A: There's no problem using more than one v-for loops. And there's no problem using nested v-for loops.
The problem I see with your current code is that it's not scalable. You're hard-coding the exact values of your tabs in <template />(e.g: first, second).
The main idea here is to loop through tabs and, inside each tab, to loop through each contents, without the <template> needing to know what the tab is or how many there are.
So that when you change your tabs to, say...
{
tab1: [{ name: 'intro'}],
tab2: [{ name: 'tab2-1' }, { name: 'tab2-2' }],
tab3: [{ name: 'tab3' }]
}
template still works, without needing any change.
To achieve this type of flexibility, you need to use a nested v-for loop:
<div id="tabs">
<div v-for="(items, name) in tabs" :key="name" :id="name">
<a v-for="(item, key) in items" :key="key" v-text="item.name"></a>
</div>
</div>
Demo:
new Vue({
el: '#app',
data: () => ({
tabs: {
tab1: [{
name: 'intro'
}],
tab2: [{
name: 'tab2-1'
}, {
name: 'tab2-2'
}],
tab3: [{
name: 'tab3'
}]
}
})
})
#tabs a { padding: 3px 7px }
<script src="https://v2.vuejs.org/js/vue.min.js"></script>
<div id="app">
<div id="tabs">
<div v-for="(links, name) in tabs" :key="name" :id="name">
<a v-for="(link, key) in links"
:key="key"
:href="`#${link.name}`"
v-text="link.name"></a>
</div>
</div>
</div>
But I'd take it one step further and change the tabs to be an array:
data: () => ({
tabs: [
[{ name: 'intro'}],
[{ name: 'tab1' }, { name: 'tab2' }],
[{ name: 'tab3' }]
]
})
And use :id="'tab-' + name" on tab divs if you really need those unique ids. (Hint: you don't).
It makes more sense to me.
A: You could add a computed property being the .concat from both and loop for it
export default {
data() {
tabs: {
first: [{ name: 'tab1' }, { name: 'tab2' }],
second: [{ name: 'tab3' }],
}
},
computed: {
tabsCombined () {
return this.tabs.first.concat(this.tabs.second)
}
},
template: `
<div id="tabs">
<div v-for='category in tabsCombined' :id='category' :key='category'>
<template v-for="tab in tabs.test">
<a v-if='tab.category === category>{{ tab.name }}</a>
</template>
</div>
</div>
`
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72913124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing Activity to Fragment with sqlite db I have recently tried to change a working sqlite populated listview activity into a fragment. I have made the changes needed but I continue to get errors that i dont understand. If any of you could help it would relieve serious frustration.
Here is my main activity
public class FoursFragment extends Fragment {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.display_activity, container, false);
userList = (ListView) view.findViewById(R.id.List);
mHelper = new DbHelper(getActivity());
//add new record
getView().findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
build = new AlertDialog.Builder(getActivity());
build.setTitle("Delete " + user_fName.get(arg2) + " "
+ user_lName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(
getActivity(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
return view;
}
@Override
public void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Here is adapter that is called.
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
}
}
And here is the DBhelper.
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
The error i receive is as follows
03-20 13:15:50.108: E/AndroidRuntime(795): FATAL EXCEPTION: main
03-20 13:15:50.108: E/AndroidRuntime(795): java.lang.NullPointerException
03-20 13:15:50.108: E/AndroidRuntime(795): atapp.norman.tennis.FoursFragment.onCreateView(FoursFragment.java:52)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.app.BackStackRecord.run(BackStackRecord.java:622)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.os.Handler.handleCallback(Handler.java:605)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.os.Looper.loop(Looper.java:137)
03-20 13:15:50.108: E/AndroidRuntime(795): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-20 13:15:50.108: E/AndroidRuntime(795): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 13:15:50.108: E/AndroidRuntime(795): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 13:15:50.108: E/AndroidRuntime(795): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-20 13:15:50.108: E/AndroidRuntime(795): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-20 13:15:50.108: E/AndroidRuntime(795): at dalvik.system.NativeStart.main(Native Method)
I really don't mind if it is something stupid but really cant figure out what is going on! Thankyou!
A: Replace
//add new record
getView().findViewById(...
with
//add new record
view.findViewById(...
getView() in onCreateView() is too early - you haven't yet returned the view to the framework for getView() to return.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22535619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rollback not happening for ForEach container in SSIS I have the following use case:
I am trying to move the files in one folder to another folder. If any file is corrupt then whole process should be rolled back and no files should be moved.
For achieving this I am making use of one data flow task and one file system task. Data flow task would check for the integrity of the file and file system task would then move the file. These two tasks are in foreach container.
The transaction property of foreach is set to required and for the two tasks inside it, i am keeping it as supported.
Issue: There are 6 files in one folder which are to be moved. The file # 4 is corrupt. I want the whole task to rollback when system detects the corrupt file. However, this is not happening and files uptil file no 3 get moved.
Screen shot attached.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27773823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check type a variable I'm making a call to os/Create function and want to make sure in one of my test cases that the response is indeed of type *os.File.
Below is my code snippet. Though I made a lot of iterations but the motivation for these lines was this post.
//somevar -- gets *os.File from a function
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(reflect.TypeOf(somevar).Implements(tpe)) // I expect a true or false
When I run this code I get a panic:
panic: reflect: non-interface type passed to Type.Implements [recovered]
panic: reflect: non-interface type passed to Type.Implements
Please suggest what wrong I'm doing. All I want to check for is - some variable is of type *os.File - yes or no.
A: I think you may just be looking for
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(tpe == reflect.TypeOf(somevar).Elem())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64093530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python django ORM error/bug?: ...Cannot resolve keyword 'id' into field. Choices are: id, i found the answer! this happened if i named a script exactly like the app name!
this is a corrected (simplified) version of the post.
i'm trying to run this standalone script (or even located in the app directory):
#!/usr/local/bin/python -W ignore
# coding: utf-8
import sys, os
sys.path.append('/usr/home/code')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tuppy.settings'
from tuppy.tup.models import *
some_dict={}
print UserProfile.objects.filter(id=1)
print 'lallala'
print some_dict['unexisting_key']
and get the following error. mind that the script first prints the correct request result to UserProfile, and only facing another error prints incorrect error description:
# ./tup.py
[<UserProfile: 115>]
lallala
Traceback (most recent call last):
File "./tup.py", line 10, in <module>
p = UserProfile.objects.filter(id=1)
File "/usr/local/lib/python2.6/site-packages/django/db/models/manager.py", line 141, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/django/db/models/query.py", line 556, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/django/db/models/query.py", line 574, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1152, in add_q
can_reuse=used_aliases)
File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1045, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1215, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
django.core.exceptions.FieldError: Cannot resolve keyword 'id' into field. Choices are: credit_limit, id, insured_order_limit, mob_tel, resale_limit, sec_tel, status, user, voice_psw
#
A: I had the same issue on trying to get the first group from auth_group (Django v. 1.3.5)
Group.objects.get(name='First Group')
gave the same FeildError.
Stangerly this worked:
try:
Group.objects.get(name="Active Rater") #crazily not working
except django.core.exceptions.FieldError as e:
group = Group.objects.get(name="Active Rater") #crazily works
I have not yet dug into the django code to figure out why.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5771965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: visual c++ 2005 dll project and prerequisites needs to be installed on target machine i wrote a simple dll and i included below header files:
#include <windows.h>
#include <sddl.h>
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
#include <mprapi.h>
#include <raserror.h>
#include <mprerror.h>
#include <strsafe.h>
so my dll works fine in my computer but in another computer not working. i installed vcredist_x86 on target machine but nothing changed. i also used setup deploy wizard and nothing happend. but when i installed visual studio 2005 on target machine my dll works perfectly.
so here is the question, how can i retrieve which prerequisites needs to be installed on target machine?
also i must mention that i compiled my code as c code "Compile as C Code (/TC)".
sorry for my poor english and thanks for your helps in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15203463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to ensure that gid in /etc/passwd also exist in /etc/group Background: The Unclassified RHEL 6 Security Technical Implementation Guide (STIG), a DoD guide, specifies in (STID-ID) RHEL-06-000294 that all user primary GIDs appearing in /etc/passwd must exist in /etc/group.
Instead of running the recommended 'pwck -rq' command and piping to a log then forcing the admin to manually remediate, it makes more sense to programmatically check if the users GID exists and, if not, simply set it to something which does exist such as "users" or "nobody"
I've been beating my head against this and can't quite get it. I've failed at sed, awk, and some piping of grep into sed or awk. The problem seems to be when I attempt to nest commands. I learned the hard way that awk won't nest in one-liners (or possibly at all).
The pseudo-code for a more traditional loop looks something like:
# do while not EOF /etc/passwd
# GIDREF = get 4th entry, sepparator ":" from line
# USERNAMEFOUND = get first entry, separator ":" from line
# grep ":$GIDREF:" /etc/group
# if not found then
# set GID for USERNAMEFOUND to "users"
# fi
# end-do.
This seems like it should be quite simple but I'm apparently missing something.
Thanks for the help.
-Kirk
A: List all GIDs from /etc/passwd that don't exist in /etc/group:
comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \
<(awk -F: '{print $3}' /etc/group | sort -u)
Fix them:
nogroup=$(awk -F: '($1=="nobody") {print $3}' /etc/group)
for gid in $(
comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \
<(awk -F: '{print $3}' /etc/group | sort -u)); do
awk -v gid="$gid" -F: '($4==gid) {print $1}' /etc/passwd |
xargs -n 1 usermod -g "$nogroup"
done
A: I'm thinking along these lines:
if ! grep "^$(groups $USERNAME | cut -d\ -f 1):" /etc/group > /dev/null; then
usermod -g users $USERNAME
fi
Where
groups $USERNAME | cut -d\ -f 1
gives the primary group of $USERNAME by splitting the output of groups $USERNAME at the first space (before the :) and
grep ^foo: /etc/group
checks if group foo exists.
EDIT: Fix in the code: quoting and splitting at space instead of colon to allow the appended colon in the grep pattern (otherwise, grep ^foo would have also said that group foo existed if there was a group foobar).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27237269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access object in Typescript/Javascript class ResistorColor {
private colors: string[]
public colorValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
constructor(colors: string[]) {
if( colors.length > 2)
{
for( key in this.colorValues)
{
if (this.colorValues[key].indexOf(colors[0]) !== -1)
{
return key;
}
}
}
this.colors = colors
}
}
Idea is to find whether the color that has been input by the user is present in the object colorValues or not.
I referred to this: Find a value in a JavaScript object
I am getting the error of cannot find name key. I am using a Typescript, online editor.
Please explain to me what am I doing wrong here.
A: Look at @Owl 's answer, it fixes the other problems in your code too.
In your loop the variable key is not defined. You'd have to write it like this:
for (const key in this.colorValues) {
...
}
Although I wouldn't use a for-in loop, since objects have their own prototype properties, which you would also receive in a for-in loop. A better solution would be this:
for (const key of Object.keys(this.colorValues) {
...
}
But since you don't need the keys and just use them to retreive the values in the colorValues object, you could also use this:
for (const color of Object.values(this.colorValues) {
...
}
A: The cannot find name key error is answered by @MrCodingB
A nicer way to write this:
class ResistorColor {
private colors: string[]
public colorValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
constructor(colors: string[]) {
const colorValues = Object.keys(this.colorValues);
// colorValues is ["black", "brown", "red", ...]
const isValid = colors.every(c => colorValues.includes(c));
// `every` is used to tests whether all elements in the array pass the test implemented by the provided function,
// in this case, we check whether each value exists in `colorValues`
if (isValid) {
this.colors = colors
} else {
throw new Error("Invalid Color(s)");
}
}
}
const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");
const resistorColor2 = new ResistorColor(["black", "brown", "gold"]); // throws error
console.log("resistorColor2 has correct color");
Typescript playground
It's also possible to print out the incorrect colors value by using .filter()
class ResistorColor {
private colors: string[]
public colorValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
constructor(colors: string[]) {
const colorValues = Object.keys(this.colorValues);
const invalidColors = colors.filter(c => !colorValues.includes(c));
if (invalidColors.length === 0) {
this.colors = colors
} else {
throw new Error(`Invalid Color -> ${invalidColors.join(", ")}`);
}
}
}
const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");
const resistorColor2 = new ResistorColor(["black", "brown", "gold", "foo"]); // throws error "Invalid Color -> gold, foo"
Typescript playground
A: Some of the errors that you are trying to prevent at run-time can be avoided at compile-time with stricter types. You can create a type that only allows specific string literal color names and you can also enforce a minimum length on the colors array using tuple types.
It looks like this.colorValues might just be an enum?
enum COLOR_VALUES {
black = 0,
brown = 1,
red = 2,
orange = 3,
yellow = 4,
green = 5,
blue = 6,
violet = 7,
grey = 8,
white = 9
}
type ColorNames = keyof typeof COLOR_VALUES;
class ResistorColor {
// can have two or more colors
constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
}
}
Now you can only call the constructor with valid arguments.
const a = new ResistorColor(["black", "blue"]); // ok
const b = new ResistorColor(["black", "blue", "red"]); // ok
const c = new ResistorColor(["black"]); // error: Source has 1 element(s) but target requires 2.
const d = new ResistorColor(["white", "cyan"]); // error: Type '"cyan"' is not assignable to type
Typescript Playground Link
If this.colorValues is an instance variable I would create the initial value outside of the class so that we can use typeof.
const initialValues = {
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
type ColorNames = keyof typeof initialValues;
class ResistorColor {
public colorValues = initialValues;
// can have two or more colors
constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
}
}
Typescript Playground Link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66758615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS Keychain data after renewing distribution certificate My distribution certificate is about to expire & I am planning to submit a new update of app to AppStore. My question is what happens to my app's keychain data after updating the distribution certificate ?
I have read this questionwhich describes that
On iPhone, Keychain rights depend on the provisioning profile used to sign your application. Be sure to consistently use the same provisioning profile across different versions of your application.
But as I am not updating my provisioning profiles but distribution certificate , can anybody tell me what happens after updating distribution certificate ?
Any kind of information will be very helpful. Thanks in advance
A: Apple removed this sentence from the docs, because it's not true. Team ID and keychain-access-groups are the most important things that should match.
Check the github link below a code example of two apps reading and writing the same keychain item:
https://github.com/evgenyneu/keychain-swift/issues/103#issuecomment-491986324
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26136021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: loosing pointers on vector of struct instances, with pointers in the struct Not sure if the title is right or not, but here it goes:
If I have for example the following structure:
struct strA{
int x;
strA(int x);
}
strA::strA(int x){
this->x = x;
}
And another structure that uses a pointer to the previous one:
#include strA
struct strB{
int y;
strA *var_strA;
strB(int y);
~strB(){
delete var_strA;
}
};
strB::strB(int y){
this->y = y;
var_strA = new strA(123);
}
Then if I do from the main aplication a vector of strB items:
std::vector<strB> vectB;
main(){
strB *itemB = new strB(456);
vectB.push_back(*itemB);
delete itemB;
//more code
}
If I try to access the var_strA on the item in the vector, is empty. And also, I get an error when by deleting the item on the vector, since the destructor tries to delete var_strA again.
Comming from Java... I'm really getting lost with the damn pointers.
thanks in advance
A: You need a copy constructor and a copy assignment operator on that pointer-holding type, i.e. follow the rule of three. Here's a great resource here on SO: What is The Rule of Three?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6105057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: performSelector unable to run while UITableView is dragged? I have a UITableViewController with its default UITableView. I begin slowly dragging the table with my finger to scroll, i.e. not flicking it with my finger. Every time the table moves on-screen the scrollViewDidScroll method of the controller is called; when some conditions I've specified are met, one of these calls to scrollViewDidScroll uses performSelector:withObject:afterDelay to schedule some action at a later time.
However, I'm finding that the action will not execute until I release my finger. For example, if I set the afterDelay parameter to 2 seconds, but hold my finger for 5 seconds, when I release my finger and the action executes it's 3 seconds too late. Is there any way to allow the action (which is to update the UI and so must run in the main thread) to execute while the finger is still against the screen?
Thanks!
A: This is because when a UIScrollView (UITableView's superclass) is scrolling, it changes its runloop in order to prioritize the scrollView over whatever the application was doing. This is happening to make sure scrolling is as smooth as it can be.
try using this version of delayed method:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;
for the modes, I'd suggest starting with an array that contains the following:
[[NSRunloop currentRunLoop] currentMode],
NSDefaultRunLoopMode
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4230361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java get each digit from 2 strings and calculate it The task is asking me to insert 2 strings of a very huge number and sum them from right to left like the way we studied in primary school like:
23 + 28 =
(2 + 2 + <1> (this is the left 1 >>> keep reading ))(3 + 8 (give the left <1> from 11 sum with the two front numbers)) =
51.
The algorithm is ok but when I try to do like (just default that the 2 number has the same length so I get lenA and not greater than 10 to make easier):
int len = a.length();
String result="";
for(int i = len; i>0 ; i--) { //<- We only need it to loop how many times
result = Integer.valueOf( a.charAt(len-1) ) + Integer.valueOf( b.charAt(len-1) ) + "" + result;//<<<because we sum them from right to left
lenA--; lenB--;
}
and that (<<<) line always give me the error.
This is just one of a many ways I tried if it's wrong and you have a solution, please just guide me, sometimes i think too much and forgot a lot of small details :))
So the question here is how can i change it from a digit of String to Integer, calculate it and print out String again. But after I read the .charAt() info it said: "Returns the char value at the specified index." so the question maybe confuse between the first question and Convert from a digit from String use charAt -> become Char then convert Char to Integer to calculate and finally convert back to String so that I can + with String result.
I tried a lot of way but still can't solve it.
A: int lena = a.length();
int lenb = b.length();
int inta[] = new int[lena];
int intb[] = new int[lenb];
int result[];
int carry = 0, maxLen = 0, tempResult;
if(lena >lenb)
maxLen = lena + 1;
else
maxLen = lenb + 1;
result = new int[maxLen];
for(int i = lena - 1; i>=0 ; i--) {
inta[i] = Integer.valueOf( a.charAt(i) );
}
for(int i = lenb - 1; i>0 ; i--) {
intb[i] = Integer.valueOf( b.charAt(i) );
}
for(int i = maxLen - 1; i >= 0; i--) {
result[i] = 0;
}
for(int i = 1; i < maxLen - 1; i++) {
tempResult = 0;
if(lena > i)
tempResult += inta[lena - i];
if(lenb > i)
tempResult += intb[lenb - i];
result[maxSize - i] += tempResult % 10;
result[maxSize - i - 1] = tempResult / 10;
}
String res = "";
for(int i = 0; i < maxLen; i++) {
res += result[i];
}
System.out.println(res);
I think that would do what you want and will avoid most simple mistakes (couldn't try it, no acces to an IDE).
I actually separate the two string into their inside number and then add them into the result tab.
Then I put the result tab into a string that I print.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49571219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Deserialize ISO 8601 date time string to C# DateTime I'm trying to use:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )
But it gives me a FormatException: Input string was not in a correct format.
What am I doing wrong?
A: If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:
DateTime value = DateTime.ParseExact(text, "o", null);
The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.
I haven't specified a format provider, as it doesn't matter:
The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.
If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.
Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17301229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: jquery ajax return value and done function I found this little example on jquery documentation page. I always tried returning value from ajax function and I was always told that there is some problem of sync and async thing and I can't return value out of $.ajax function without making it async.
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
In the example above, on what this done function is applied(whats being used as $(this) in example).
one more thing, as the ajax function can't set global variables, can't the be set in this done too? cant I return value out of done function either?
A:
what this done function is applied
$.ajax returns a jqXHR object (see first section after the configuration parameter description) wich implements the promise interface and allows you to add callbacks and get notified of changes of the Ajax call.
whats being used as $(this) in example
Inside the callbacks for $.ajax, this refers to the object context refers to in the configuration or the jqXHR instance if context was not set. In this case it refers to document.body:
context: This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).
This and more is all explained in the documentation: http://api.jquery.com/jQuery.ajax/
as the ajax function can't set global variables
That is not correct, any function can set global variables. The problem with asynchronous functions is that you are likely accessing the variable before it was set.
can't the be set in this done too
See above
cant I return value out of done function either
You can return a value (as in putting a return statement inside the callback), but you cannot return it to your code, since jQuery is calling the callback internally and just ignoring the return value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12869127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Making Python Logging work async with Celery I have logging setup. In particular, I have SMTPHandler. I would like to have it happen async. I'd like to use celery to make that happen. Is that possible?
import logging
logger = logging.getLogger("logger")
mail_handler = STMPHandler(...)
mail_handler.setLevel(logging.ERROR)
...
logger.addHandler(mail_handler)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12718840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Record Screen's Happenings(Audio+Video) i am new baby in WebRTC and want to implement system like video conferencing , live streaming or you can skype using WebRTC and NodeJS.
i am confused with one thing , as its our one of client's requirement , suppose on page whatever is happening it may be video conferencing say one moderator answering to many audiences one by one , so there should be one video created , which continuously recording all this stuff together and sending live stream to server to save in our database.
is this kind of stuff implementable or not?
any help please.
A: You can capture video through grabbing Jpeg images from a canvas element. You could also capture the entire page(if numerous videos in the same page) through grabbing the page itself through chrome.
For audio, recording remote audio with the Audio API is still an issue but locally grabbed audio is not an issue.
*
*RecordRTC and my Modified Version for recording streams either to file or through websockets respectively.
*Capture a page to a stream on how to record or screenShare an entire page of Chrome.
If you have multiple different videos not all in the same page but want to combine them all, I would suggest recording them as above and then combining and syncing them up server side(not in javascript but probably in C or C++).
If you MUST record remote audio, then I would suggest that you have those particular pages send their audio data over websockets themselves so that you can sync them up with their video and with the other sessions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24037528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with CKEditor inside a ColorBox modal popup Please can anyone help me out. I have an html page in which I have added a modal popup from ColorBox. In the ColorBox popup, I have added a CKEditor. The problem is as follows:
In IE, the CKEditor works fine, but in FF & Chrome, I get the CKEditor like in readonly mode (I can't type anything in it).
If i put the CKEditor directly into the page (and not in the modal popup), it works fine in all browsers.
I think this might be a problem with the z-index on one of the elements generated by CKEditor. But I don't know which one exactly?
I would really appreciate some help plz, thanks in advance!
A: We got around our problem by switching lightboxes, rather than use ColorBox, use Simple Modal. I have a funny feeling it will work for you. Good luck!
A: <script>
$(document).ready(function() {
initCKEditor(); //function ckeditor.
$("#id_textarea").val(CKEDITOR.instances.id_textarea.getData());
});
</script>
A: Render/create ckeditor on colorbox "onComplete" callback.
See callbacks here : http://www.jacklmoore.com/colorbox
A: After some debugging I found that it is because of a CSS rule.
In the skin named kama you need to change the following CSS rule in mainui.css from:
.cke_skin_kama .cke_browser_ie.cke_browser_quirks .cke_contents iframe
{
position: absolute;
top: 0;
}
To:
.cke_skin_kama .cke_browser_ie.cke_browser_quirks .cke_contents iframe
{
top: 0;
}
Depending on your setup, you might need to change it in skins/kama/editor.css
I however recommend upgrading to a newer version of ckeditor. I found this issue on version 3.6.2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5376836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: JPA: relation manyToMany on the same entity I have an Entity that has two relation manyToMany with itself and I don't want to use Cascade.MERGE because I need to do some data checks to validate the data:
@Entity("device")
public class Device {
...
@ManyToMany(mappedBy = "parents", targetEntity = Device.class, fetch = FetchType.LAZY)
public Set<Device> getChildren() {
return this.children;
}
@Override
@ManyToMany(targetEntity = Device.class, fetch = FetchType.LAZY)
@JoinTable(name = "dem_hierarchy", joinColumns = {
@JoinColumn(name = "CHILDREN_UUID", referencedColumnName = "UUID")},
inverseJoinColumns = {
@JoinColumn(name = "DEM_DEVICE_UUID", referencedColumnName = "UUID")})
public Set<Device> getParents() {
return parents;
}
...
}
When I save a tree like this:
Device grandGrandPa = new Device();
grandGrandPa.setName("TEST" + counter + "_grandGrandPa");
Device grandPa = new Device();
grandPa.setName("TEST" + counter + "_grandPa");
grandGrandPa.addChild(grandPa);
Device daddy = new Device();
daddy.setName("TEST" + counter + "_daddy");
grandPa.addChild(daddy);
Device son = new Device();
son.setName("TEST" + counter + "_son");
daddy.addChild(son);
grandGrandPa = deviceService.register(grandGrandPa);
The register method is recursive and it descends the tree using the children column. When its the turn of the "grandPa" to be saved the weblogic return an exception:
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
I cannot understand why this happens. It gives me this error when in code there are some queries on parent Device: first turn it is empty, second turn it has one value.
I'm using weblogic 12.1.3 and hibernate 4.0.0, as database Oracle 11g.
A:
It gives me this error when in code there are some queries on parent Device
By default, Hibernate will flush pending changes to the database before attempting to execute a query. At that stage, all entities referenced in all relationships should have been persisted, or else an exception will be thrown.
Also, since mappedBy is declared on the children end, the parents is the owning side of the relationship. Because of that, Hibernate will ignore children completely at persist time and look for transient entities in parents instead. Your persisting logic should therefore be reversed - save parents first, children last (alternatively, you could simply declare children the owning side).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41225598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Google.GoogleApiException 'File not found: [404]' when trying to list files in a non-root Google Drive folder I'm trying to access files in Google Drive. I picked up code to create a Google Drive service from the Google docs...
private static DriveService GetDriveService() {
UserCredential credential;
using (FileStream stream = new("credentials_desktop.json", FileMode.Open, FileAccess.Read)) {
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore("token.json", true)).Result;
}
DriveService service = new(new BaseClientService.Initializer {
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
Using code found in this blog post, I can make a call to the Google Drive API and see all the files in the root folder...
private static void ListFiles() {
DriveService service = GetDriveService();
FilesResource.ListRequest fileList = service.Files.List();
fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'root' in parents";
fileList.Fields = "nextPageToken, files(id, name, size, mimeType)";
List<File> files = new();
string pageToken = null;
do {
fileList.PageToken = pageToken;
FileList filesResult = fileList.Execute();
IList<File> pageFiles = filesResult.Files;
pageToken = filesResult.NextPageToken;
files.AddRange(pageFiles);
} while (pageToken != null);
// dump files to console...
}
That works fine, but if I try to list the files in a folder...
fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents";
...then when it tries to make the call to fileList.Execute() I get the following exception...
Google.GoogleApiException
HResult=0x80131500
Message=Google.Apis.Requests.RequestError
File not found: . [404]
Errors [
Message[File not found: .] Location[fileId - parameter] Reason[notFound] Domain[global]
]
Source=Google.Apis
StackTrace:
at Google.Apis.Requests.ClientServiceRequest`1.<ParseResponse>d__35.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
at GoogleDrivePlay.Program.ListFiles2() in d:\GoogleDrivePlay\GoogleDrivePlay\Program.cs:line 59
at GoogleDrivePlay.Program.Main(String[] args) in d:\GoogleDrivePlay\GoogleDrivePlay\Program.cs:line 23
As you can see, the Admin folder does exist...
Anyone any idea how I can list the contents of other folders? Thanks
A: fileList.Q = "mimeType != 'application/vnd.google-apps.folder' and 'Admin' in parents";
The issue you are having is that you are using the name of the directory 'Admin' you need to use the file id of the Admin directory.
Do a file.list and search for the admin directory get its file id then pass it to that instead.
fileList.Q = "name ='Admin' and mimeType != 'application/vnd.google-apps.folder'";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69903008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get values from NSDictionaries I have the following code:
NSDictionary *dict = @[@{@"Country" : @"Afghanistan", @"Capital" : @"Kabul"},
@{@"Country" : @"Albania", @"Capital" : @"Tirana"}];
I want to list many countries and capitals, and then randomize i.e a country and put it on the screen, then the user should be able to pick the correct capital..
*
*How to I put the Country? Like dict.Country[0] or something like that?
*What is wrong with the code? I get the error "Initializer element is not a compile-time constant" and the warning "Incompatible pointer types initializing 'NSDictionary *_strong' with an expression of type 'NSArray *'.
*Can I make a third String in the Dictionary, containing a flag file.. for example
@"Flagfile" : @"Albania.png"
and later put it in a image view?
I want like a loop with a random number I (for example) and put like (I know this is not right, but I hope you get the point)
loop..
....
text= dict.Country[I];
button.text= dict.Capital[I];
Imageview=dict.Flagfile[I];
.....
....
A: Your top level element is an NSArray (@[], with square brackets, makes an array) of two NSDictionary's. To access an attribute in one of the dictionaries, you would do array[index][key], e.g. array[0][@"Country"] would give you @"Afghanistan". If you did NSArray *array = ... instead of NSDictionary *dict = ...
If you want to pick a country at random, you can get a random number, get it mod 2 (someInteger % 2) and use that as your index, e.g. array[randomNumber % 2][@"Country"] will give you a random country name from your array of dictionaries.
If you store an image name in the dictionaries, you can load an image of that name using UIImage's +imageNamed: method.
A: Here's more complete instruction on mbuc91's correct idea.
1) create a country
// Country.h
@interface Country : NSObject
@property(strong,nonatomic) NSString *name;
@property(strong,nonatomic) NSString *capital;
@property(strong,nonatomic) NSString *flagUrl;
@property(strong,nonatomic) UIImage *flag;
// this is the only interesting part of this class, so try it out...
// asynchronously fetch the flag from a web url. the url must point to an image
- (void)flagWithCompletion:(void (^)(UIImage *))completion;
@end
// Country.m
#import "Country.h"
@implementation Country
- (id)initWithName:(NSString *)name capital:(NSString *)capital flagUrl:(NSString *)flagUrl {
self = [self init];
if (self) {
_name = name;
_capital = capital;
_flagUrl = flagUrl;
}
return self;
}
- (void)flagWithCompletion:(void (^)(UIImage *))completion {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.flagUrl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
UIImage *image = [UIImage imageWithData:data];
completion(image);
} else {
completion(nil);
}
}];
}
@end
2) Now, in some other class, use the Country
#import "Country.h"
- (NSArray *)countries {
NSMutableArray *answer = [NSMutableArray array];
[answer addObject:[[Country alloc]
initWithName:@"Afghanistan" capital:@"Kabul" flagUrl:@"http://www.flags.com/afgan.jpg"]];
[answer addObject:[[Country alloc]
initWithName:@"Albania" capital:@"Tirana" flagUrl:@"http://www.flags.com/albania.jpg"]];
return [NSArray arrayWithArray:answer];
}
- (id)randomElementIn:(NSArray *)array {
NSUInteger index = arc4random() % array.count;
return [array objectAtIndex:index];
}
-(void)someMethod {
NSArray *countries = [self countries];
Country *randomCountry = [self randomElementIn:countries];
[randomCountry flagWithCompletion:^(UIImage *flagImage) {
// update UI, like this ...
// self.flagImageView.image = flagImage;
}];
}
A: You cannot initialize an NSDictionary in that way. An NSDictionary is an unsorted set of key-object pairs - its order is not static, and so you cannot address it as you would an array. In your case, you probably want an NSMutableDictionary since you will be modifying its contents (see Apple's NSMutableDictionary Class Reference for more info).
You could implement your code in a few ways. Using NSDictionaries you would do something similar to the following:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]
initWithObjectsAndKeys:@"Afghanistan", @"Country",
@"Kabul", @"Capital", nil];
You would then have an array of dictionaries, with each dictionary holding the details of one country.
Another option would be to create a simple model class for each country and have an array of those. For example, you could create a Class named Country, with Country.h as:
#import <Foundation/Foundation.h>
@interface Country : NSObject
@property (nonatomic, retain) NSString *Name;
@property (nonatomic, retain) NSString *Capital;
//etc...
@end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14740911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net Razor v3 jquery ajax post returns 404 not found I recently started a Asp.net Razor v3 project. It's the first time I use this (before I only used MVC and Web Forms)
I am struggling to get a code behind that gets called by a jquery ajax function to work. When debugging on Chrome I see that the script returns POST 404 (Not Found)
$.ajax({
type: "POST",
url: "../App_Code/GlobalSitesController/GetSiteTable",
data: "{'siteName': 'Some Site' , 'daysDiff': '0'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
document.getElementById("siteTable").innerHTML = response.responseText;
},
failure: function (response) {
document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
},
error: function (response) {
document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
}
});
public class GlobalSitesController : Controller
{
[HttpPost]
public string GetSiteTable(string siteName, int daysDiff)
{
return "some string";
}
}
First I noticed that my project didn't include System.Web.Mvc so I added Microsoft.AspNet.Mvc via Nugget
The full Chrome error is jquery-1.10.2.min.js:23 POST http://localhost:9997/App_Code/GlobalSitesController/GetSiteTable 404 (Not Found). This is the correct URL and should be working
A: It turns out the url bit needs to be in the following form
url: '@url.Action("GetSiteTable", "GlobalSitesController")',
(url needs to be initialised as in below)
System.Web.Mvc.UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47753186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python 3 hex conversion I'm trying to convert some code from 2 to 3. I have
val = str(''.join(map(chr, list(range(0, 256, 8)))))
and I need to translate
x = str(val).encode('hex')
and
x.decode('hex')
Thanks
A: In python2, your code produces:
In [4]: val = str(''.join(map(chr, list(range(0, 256, 8))))) ; val
Out[4]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [5]: x = str(val).encode('hex') ; x
Out[5]: '0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [6]: x.decode('hex')
Out[6]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
To get the similar output in python3:
In [19]: import codecs
In [20]: val = ''.join(map(chr, range(0, 256, 8))) ; val
Out[20]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0¨°¸ÀÈÐØàèðø'
In [21]: x = codecs.encode(val.encode('latin-1'), 'hex_codec') ; x
Out[21]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [22]: codecs.decode(x, 'hex_codec')
Out[22]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
Notes:
*
*The python3 version of x above is a byte-string. Since it is entirely ASCII, it can be converted to unicode simply via x.decode().
*The display of val toward the end of the string in the python3 code above does not match the python2 version. For a method of creating val which does match, see the next section.
Alternatives
Use bytes to create the string. Use binascii.hexlify to convert it to hex:
In [15]: val = bytes(range(0, 256, 8))
In [16]: val
Out[16]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [17]: binascii.hexlify(val)
Out[17]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
More on unicode and character 0xf8
You wanted ø to be 0xf8. Here is how to make that work:
>>> s = chr( int('f8', 16) )
>>> s
'ø'
And, to convert s back to a hex number:
>>> hex(ord(s))
'0xf8'
Note that 0xf8' is the unicode code point of 'ø' and that that is not the same as the byte string representing the unicode character 'ø' which is:
>>> s.encode('utf8')
b'\xc3\xb8'
So, 'ø' is the 248th (0xf8) character in the unicode set and its byte-string representation is b'\xc3\xb8'.
A: Your Python 2 code:
val = str(''.join(map(chr, list(range(0, 256, 8)))))
x = str(val).encode('hex')
x.decode('hex')
Let's make version that works on both Python 2 and 3:
import binascii
val = bytearray(range(0, 0x100, 8))
x = binascii.hexlify(val)
binascii.unhexlify(x)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22419361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MonoDevelop and XCode I'm using MonoDevelop 2.8.5 and XCode 4.2.1.
Every time I'm switching to monodevelop window from anything else, it starts to update XCode project file and pops XCode window.
More over, when I switch from XCode back to monotouch, it updates the project and switches back to XCode.
Thats's really annoying. How do I disable this "feature"?
A: Problem was fixed by downloading new Monodevelop: 2.8.6 beta
A: This behavior cannot be disabled, since there is no other way that MonoDevelop can use to communicate with xcode 4. This is because MonoDevelop creates an Xcode project on the fly (when you dbl clic any xib file within MD) and then MD launches xcode with the generated xcode project.
when you do all necessary changes in xcode and you switch back to MD the OnFocus event of MD (i don't really know if thats the event's name btw) process the changes you have done on the xcode project and modifies it in order to maintain both projects (xcode and MD) on sync
My suggestion is just make all necessary changes on xcode save them and then close it, then work on MD as usual and if you need to reopen xcode again work on it, Xcode won't bother you as long as you don't focus the MD window
I hope this helps.
Alex
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8826835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I cannot seem to run this properly... It stucks and does not display an output Here's my script:
while [[ $startTime -le $endTime ]]
do
thisfile=$(find * -type f | xargs grep -l $startDate | xargs grep -l $startTime)
fordestination=`cut -d$ -f2 $thisfile | xargs cut -d ~ -f4`
echo $fordestination
startTime=$(( $startTime + 1 ))
done
A: I think your cut and grep commands could get stuck. You probably should make sure that their parameters aren't empty, by using the [ -n "$string" ] command to see if $string isn't empty. In your case, if it were empty, it wouldn't add any files to the command that would use it afterwards, meaning that the command would probably wait for input from the command line (ex: if $string is empty and you do grep regex $string, grep wouldn't receive input files from $string and would instead wait for input from the command line). Here's a "complex" version that tries to show where things could go wrong:
while [[ $startTime -le $endTime ]]
do
thisfile=$(find * -type f)
if [ -n "$thisfile" ]; then
thisfile=$(grep -l $startDate $thisfile)
if [ -n "$thisfile" ]; then
thisfile=$(grep -l $startTime $thisfile)
if [ -n "$thisfile" ]; then
thisfile=`cut -d$ -f2 $thisfile`
if [ -n "$thisfile" ]; then
forDestination=`cut -d ~ -f4 $thisfile`
echo $fordestination
fi
fi
fi
fi
startTime=$(( $startTime + 1 ))
done
And here's a simpler version:
while [[ $startTime -le $endTime ]]
do
thisfile=$(grep -Rl $startDate *)
[ -n "$thisfile" ] && thisfile=$(grep -l $startTime $thisfile)
[ -n "$thisfile" ] && thisfile=`cut -d$ -f2 $thisfile`
[ -n "$thisfile" ] && cut -d ~ -f4 $thisfile
startTime=$(( $startTime + 1 ))
done
The "-R" tells grep to search files recursively, and the && tells bash to only execute the command that follows it if the command before it succeeded, and the command before the && is the test command (used in ifs).
Hope this helps =)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12658050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to set a threshold value from signal to be processed in wavelet thresholding in python I'm trying to denoise my signal using discrete wavelet transform in python using pywt package. But i cannot define what is threshold value that i should set in pywt.threshold() function
I have no idea what the best threshold value that should be set in order to reconstruct a signal with minimal noise
I used ordinary code:
pywt.threshold(mysignal, threshold, 'soft')
yes i am intended to do soft thresholding
I want to know if the threshold value could be determined by looking to my signal or from the other way
A: There are some helpful graphics on pywt webpage that help visualize what these thresholds are and what they do.
The threshold applies to the coefficients as opposed to your raw signal. So for denoising, this will typically be the last couple of entries returned by pywt.wavedec that will need to be zeroed/thresholded.
I could initial guess is the 0.5*np.std of each coefficeint level you want to threshold.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58725295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Convert c# date to Javascript This is how I convert .Net Datetime to Javascript. I found the code somewhere a long time ago and use it for Highcharts. Now the chart sometimes looks strange with the lines messed up. I suspect it has to do with the date.
Datetime curDate = "11/14/2013";
string jsDate = "Date.UTC(" + curDate.Year + "," + (curDate.Month - 1) + "," + curDate.Day;
if (curDate.Millisecond > 0)
{
jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second + "," + curDate.Millisecond;
return jsDate += ")";
}
if (curDate.Second > 0)
{
jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second;
return jsDate += ")";
}
if (curDate.Minute > 0)
{
jsDate += "," + curDate.Hour + "," + curDate.Minute;
return jsDate += ")";
}
if (curDate.Hour > 0)
{
jsDate += "," + curDate.Hour;
return jsDate += ")";
}
jsDate += ")";
Is this a correct way to convert .Net date to javascript?
Thank you!
A: The easiest way to convert between the two is to convert the .NET time to a timespan in milliseconds from the UNIX epoch time:
public static long ToEpochDate(this DateTime dt)
{
var epoch = new DateTime(1970, 1, 1);
return dt.Subtract(epoch).Ticks;
}
You can then use that to generate your JS string:
DateTime current = DateTime.Now;
var jsDate = string.Format("Date.UTC({0})", current.ToEpochDate());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19985581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: two forms conflict with each other I have placed two forms on one page. Bothe forms work fine separately but when they are placed on one page at the same time they conflict with each other. Here are both forms:
Contact Form:
<form name="contactform" id="contactform" method="post" action="#targetAnchorPage2">
<table>
<?php
if (isset($_POST["name"])){
?>
<tr>
<td colspan="2" class="error">
<?php
require_once("contact_send.php");
?>
</td>
</tr>
<?php
}
?>
<tr><td><label for="name" class="<?=$name_class?>">name:</label></td><td><input type="text" name="name" maxlength="50" value="<?=$name?>"></td></tr>
<tr><td><label for="email" class="<?=$emailaddress_class?>">email:</label></td><td><input type="text" name="email" maxlength="80" value="<?=$emailaddress?>"></td></tr>
<tr><td colspan="2"><label id="tworows" for="message" class="<?=$message_class?>">your message:</label></td></tr><tr><td colspan="2"><textarea name="message" cols="22" rows="6" value="<?=$message_class?>"></textarea>
</td></tr>
<tr>
<td colspan="2" style="text-align:center"><br /><input class="button" type="submit" value="">
</td>
</tr>
</table>
</form>
Subscribe Form:
<form name="subscribeform" id="subscribeform" method="post" action="#targetAnchorPage3">
<table>
<?php
if (isset($_POST["name"])){
?>
<tr>
<td colspan="2" class="error">
<?php
require_once("subscribe_send.php");
?>
</td>
</tr>
<?php
}
?>
<tr><td><label for="name" class="<?=$name_class?>">name:</label></td><td><input type="text" name="name" maxlength="50" value="<?=$name?>"></td></tr>
<tr><td><label for="email" class="<?=$emailaddress_class?>">email:</label></td><td><input type="text" name="email" maxlength="80" value="<?=$emailaddress?>"></td></tr>
<tr>
<td colspan="2" style="text-align:center"><br /><input class="button" type="submit" value="">
</td>
</tr>
</table>
</form>
How can this be solved? Is it caused by the "required_once" command?
A: I am guessing that since you are showing the required files based on the same criteria isset($_POST['name']) and since both forms have the name field you end up showing the code in both requires regardless of which form is submitted. You should simply change the form field names on on of the forms such that they are different.
A: Both forms have the same action attribute, they both point back to the same page (note that the hash is not sent to the server). As they both have a field called name and you are checking for that, both actions get executed regardless of which form was sent in.
You can do either:
*
*use different scripts / form processors (don't post back to the same page)
*use a different check for each form, for example by adding a hidden input that will allow you to distinguish between the forms.
A: Add
formaction="Your_URL"
Attribut in Button
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14341904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading a whole mySQL table into a PHP array I have a table with 4 columns and 23 rows. I need all 92 values in the the table as PHP variables (whether that be one array, 4 arrays, 92 individual variables, or whatever).
The rows are:
ID
Category
Summary
Text
I need to build a series of select boxes where the items are grouped by the category, the options available are the summaries, and the resulting text is passed on for processing.
I've been searching, but all the examples I can find are about printing the table out, and I need to continue working with the variables.
I really appreciate any help!
Billy
A: Just a SELECT * FROM table_name will select all the columns and rows.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
$num = mysql_num_rows($results);
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
// You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
}
}
A: OK, I found my answer with better search terms. I'm still new here, so let me know if this is not a fair way to handle the situation. I upvoted @Indranil since he or she spent so much time trying to help me.
Anyway...
$content = array();
while($row = mysql_fetch_assoc($result)) {
$content[$row['id']] = $row;
}
Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code. And it even names the first level of the array by the ID (which is the unique identifier).
Thank you to those that tried to help me!
Billy
A: $pdo = new PDO(
'mysql:host=hostname;dbname=database;charset=utf-8',
'username',
'password'
);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table');
if ( $stmt !== false )
{
$data = $stmt->fetchAll( PDO::FETCH_ASSOC );
}
In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters.
Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8570059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: trouble scraping data from an html table I'm trying to scrape data, in the form of a table, and the hrefs from within that table from a town assessor website using the R package rvest. Despite having luck scraping tables from other websites (e.g. wikipedia), I'm unable to get anything from the town assessor.
I am using RStudio v1.1.442 and R v3.5.0.
sessioninfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] rvest_0.3.3 xml2_1.2.0 V8_2.2
loaded via a namespace (and not attached):
[1] httr_1.4.0 compiler_3.5.0 selectr_0.4-1 magrittr_1.5 R6_2.4.0 tools_3.5.0 yaml_2.2.0
[8] curl_3.3 Rcpp_1.0.1 stringi_1.4.3 stringr_1.4.0 jsonlite_1.6
I have tried to follow a few examples. First, the wikipedia state population example, which works fine.
url <- "https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States_by_population"
population <- url %>%
read_html() %>%
html_nodes("#mw-content-text > div > table:nth-child(11)") %>%
html_table()
population <- population[[1]]
I've also been able to scrape data from yelp without issue. This, for example, gives me the names of the restaurants.
url <- "https://www.yelp.com/search?find_loc=New+York,+NY,+USA"
heading <- url %>%
read_html() %>%
html_nodes(".alternate__373c0__1uacp .link-size--inherit__373c0__2JXk5") %>%
html_text()
The website I'm having trouble with is like this one, which is the output of a search for properties on a specific street.
url <- "https://imo.ulstercountyny.gov/viewlist.aspx?sort=printkey&swis=all&streetname=Lake+Shore+Dr"
helpme <- url %>%
read_html() %>%
html_nodes("#tblList > tbody") %>%
html_table()
I would also like to be able to pull out the hrefs using something like this
helpme <- url %>%
read_html() %>%
html_nodes("#tblList > tbody") %>%
html_attr('href') %>%
html_text()
Unfortunately, my attempts to scrape the table and the href are empty.
Is there something strange about this website. I've used the chrome browser inspector and SelectorGadget to help find the right copy selectors. I've also tried it with the xpath. The result is the same either way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56160153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hibernate EntityManager is getting closed, in wildfly 10 I use container managed JPA where inject the EntityManager instance. With the injected entitymanager instance, when I use find() method it says entity manager is closed.
I use wildfly 10.
How can I overcome this issue? What I do wrong here?
I create entity manager like this;
@PersistenceContext
protected EntityManager em;
@Stateless
public class CustomerService CrudService<Customer> {
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void update(Customer entity) {
Customer item = em.find(Customer.class,entity.getId()); //ISSUE
if (entity.getParentId()!=null) {
item.setParent(em.find(CRMEntity.class , entity.getParentId()));
item.setParentId(entity.getParentId());
}
....
super.update(item);
}
public abstract class CrudService<T extends BaseEntity> {
public void update(T entity) {
Session session = null;
try {
session = getSession();
session.update(entity);
session.flush();
} catch (HibernateException ex) {
log.error("Error when update." + entity.getCode(), ex);
if (session != null) {
session.cancelQuery();
}
} finally {
if (session != null && session.isOpen()) {
session.clear();
session.close();
}
}
}
public Session getSession() {
if (session == null || !session.isOpen()) {
session = getEntityManager().unwrap(Session.class);
}
return session;
}
}
I get issue at this line;
Customer item = em.find(Customer.class,entity.getId());
Error
Caused by: java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:326)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:126)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3312)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3297)
at org.jboss.as.jpa.container.AbstractEntityManager.find(AbstractEntityManager.java:213)
at com.leightonobrien.lob2.service.autogen.CustomerService.update(CustomerService.java:412)
at sun.reflect.GeneratedMethodAccessor249.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
A: Issue here is I closed the session. After removing it, everything works fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40274703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Allow only numeric value in textbox using Javascript I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user.
Any suggestion for optimized and short javascript code?
A: function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
from here
A: use following code
function numericFilter(txb) {
txb.value = txb.value.replace(/[^\0-9]/ig, "");
}
call it in on key up
<input type="text" onKeyUp="numericFilter(this);" />
A: Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};
A: Please note that, you should allow "system" key as well
$(element).keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which), value;
if (isSysKey(code) || code === 8 || code === 46) {
return true;
}
if (e.shiftKey || e.altKey || e.ctrlKey) {
return ;
}
if (code >= 48 && code <= 57) {
return true;
}
if (code >= 96 && code <= 105) {
return true;
}
return false;
});
function isSysKey(code) {
if (code === 40 || code === 38 ||
code === 13 || code === 39 || code === 27 ||
code === 35 ||
code === 36 || code === 37 || code === 38 ||
code === 16 || code === 17 || code === 18 ||
code === 20 || code === 37 || code === 9 ||
(code >= 112 && code <= 123)) {
return true;
}
return false;
}
A: // Solution to enter only numeric value in text box
$('#num_of_emp').keyup(function () {
this.value = this.value.replace(/[^0-9.]/g,'');
});
for an input box such as :
<input type='text' name='number_of_employee' id='num_of_emp' />
A: @Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.
For safer side, use this:
$("#testInput").keypress(function(event){
instead of:
$("#testInput").keyup(function(event){
I hope this will help for someone.
A: or
function isNumber(n){
return (parseFloat(n) == n);
}
http://jsfiddle.net/Vj2Kk/2/
A: This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.
HTML:
<form>
<input type="text" id="txt" />
</form>
JS:
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
For a result: http://jsfiddle.net/uUc22/
Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.
A: Javascript For only numeric value in textbox ::
<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" />
<!--Only Numeric value in Textbox Script -->
<script type="text/javascript">
function onlyNos(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
catch (err) {
alert(err.Description);
}
}
</script>
<!--Only Numeric value in Textbox Script -->
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7454591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spring Data JPA Self Join with Nullable foreign key I have problem with Spring Data JPA. I want to create a category that have parent category with the same table. Some categories don't need to have parent category, so parent category can be null. but when I do that, and save it, it shown error as below:
org.hibernate.TransientPropertyValueException: object references an unsaved
transient instance - save the transient instance before flushing :
com.ltech.solutions.ecom.models.category.Category.parent ->
com.ltech.solutions.ecom.models.category.Category
Here is my model:
@Entity
@Table(name = "tb_category")
public class Category extends BaseEntity {
@Column(name = "name", nullable = false)
private String name;
@JsonIgnore
@ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id", referencedColumnName = "id")
private Category parent;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
@JsonProperty(value = "sub_categories")
private Set<Category> subCategories;
@Column(name = "is_visible", insertable = false, columnDefinition =
"BOOLEAN DEFAULT TRUE")
@JsonProperty(value = "is_visible")
private Boolean isVisible;
@Column(name = "is_enable", insertable = false, columnDefinition = "BOOLEAN
DEFAULT TRUE")
@JsonProperty(value = "is_enable")
private Boolean isEnable;
@Column(name = "desc_attribute")
private String descAttribute;
}
*
*When saving object, I use save method of CRUDRepsoitory.
Here is my view:
<form th:object="${createCategoryForm}" th:action="@{/category/save}"
method="post">
<fieldset>
<legend>Create Category</legend>
<div class="form-group">
<label>Name</label>
<input class="form-control" th:field="*{name}" />
</div>
<div class="form-group">
<label>Code</label>
<input class="form-control" th:field="*{code}" />
</div>
<div class="form-group">
<label>Description (English)</label>
<input class="form-control" th:field="*{descEn}" />
</div>
<div class="form-group">
<label>Description (Khmer)</label>
<input class="form-control" th:field="*{descKh}" />
</div>
<div class="form-group">
<label>Attribute</label>cs
<input class="form-control" th:field="*{descAttribute}" />
</div>
<div class="form-group">
<label>Parent of</label>
<select class="form-control" th:field="*{parent.id}">
<option value="">None</option>
<option th:each="parent : ${parentCategories}" th:value="${parent.id}" th:text="${parent.name}"></option>
</select>
</div>
<input type="submit" />
</fieldset>
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51362944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to import one column to a new worksheet? I have a workbook which has individual worksheets detailing client stock trading data, and a master worksheet which has month to date and week to date totals for the clients.
I would like to set up a new worksheet titled week to date which will import the week to date column from the master worksheet and save it.
Additionally, I would like it to update every time I run the macro so it has an up to date record of the week to date figures.
My current code provides sum totals for specified columns on each worksheet, and embeds the contents of the active worksheet into the body of an outlook email.
Sub AutoSum()
Dim wscount As Long
wscount = ActiveWorkbook.Worksheets.Count
Dim i As Long
For i = 1 To wscount
Sheets(i).Select
Range("K3").Select
Selection.End(xlDown).Select
ActiveCell.Offset(2, 0).Select
Dim cel1 As String, cel2 As String
cel1 = ActiveCell.Offset(-2, 0).End(xlUp).Address
cel2 = ActiveCell.Offset(-1).Address
ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"
Next i
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
'Only the visible cells in the selection
Set rng = Selection.SpecialCells(xlCellTypeVisible)
'You can also use a fixed range if you want
'Set rng = Sheets("YourSheet").Range("D4:D12").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "[email protected]"
.CC = ""
.BCC = ""
.Subject = "Today's Trades" & Date
.HTMLBody = RangetoHTML(rng)
.Send 'or use .Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
A: It sounds like you're just asking how to cut a column across into another worksheet. This will move everything in the K column in the master sheet and copy it to the A column in wtd. Obviously this can be changed to any column you want.
Sheets("wtd").Range("A:A").Value = Sheets("master").Range("K:K").Value
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53009916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Overloading functions not compiling I am following the book C++ Cookbook from O'Reilly and I try one of the examples, here is the code:
#include <string>
#include <iostream>
#include <cctype>
#include <cwctype>
using namespace std;
template<typename T, typename F>
void rtrimws(basic_string<T>& s, F f){
if(s.empty())
return;
typename basic_string<T>::iterator p;
for(p = s.end(); p != s.begin() && f(*--p););
if(!f(*p))
p++;
s.erase(p, s.end());
}
void rtrimws(string& ws){
rtrimws(ws, isspace);
}
void rtrimws(wstring& ws){
rtrimws(ws, iswspace);
}
int main(){
string s = "zing ";
wstring ws = L"zonh ";
rtrimws(s);
rtrimws(ws);
cout << s << "|\n";
wcout << ws << "|\n";
}
When I try to compile it, I get the following error
trim.cpp: In function ‘void rtrimws(std::string&)’:
trim.cpp:22: error: too many arguments to function ‘void rtrimws(std::string&)’
trim.cpp:23: error: at this point in file
and I don't understand what's wrong. If I don't use the char version (string) but the wchar_t version only, everything runs smooth.
By the way, I am using g++ 4.4.3 in an ubuntu machine 64 bits
A: isspace is also a template in C++ which accepts a templated character and also a locale with which it uses the facet std::ctype<T> to classify the given character (so it can't make up its mind what version to take, and as such ignores the template).
Try specifying that you mean the C compatibility version: static_cast<int(*)(int)>(isspace). The differences between the compilers could come from the inconsistent handling of deduction from an overloaded function name among the compilers - see this clang PR. See the second case in Faisal's first set of testcases for an analogous case.
Someone pointed out on IRC that this code would call isspace using a char - but isspace takes int and requires the value given to be in the range of unsigned char values or EOF. Now in case that char is signed on your PC and stores a negative non-EOF value, this will yield to undefined behavior.
I recommend to do it like @Kirill says in a comment and just use the templated std::isspace - then you can get rid of the function object argument too.
A: Try rtrimws(ws, ::isspace);.
Also, just as a note, you should be using the reverse iterator.
A: That's because isspace is a template function in c++. It cannot deduce F. If you want to use C variant of isspace you could fully qualify its name as follows:
void rtrimws(string& ws){
rtrimws(ws, ::isspace); // this will use isspace from global namespace
// C++ version belongs to the namespace `std`
}
This is one more good sample why you shouldn't use using namespace std.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3679801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to remove child(html elements) of div Id using jQuery I have
<div id="myId">
<div>aa</div>
<h3>hellow</h3>
<a href="#"></a>
</div>
So how to remove all content of Id "myId" Using jQuery?
The result must be this:
<div id="myId"></div>
A: *
*Use .empty()
Description: Remove all child nodes of the set of matched elements from the DOM.
$("#myId").empty()
console.log($("#myId").get(0).outerHTML)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myId"><div>aa</div><h3>hellow</h3><a href="#"></a></div>
A: You could use different ways:
// ref: https://api.jquery.com/empty/
$("#myId").empty()
// ref: https://api.jquery.com/html/
$("#myId").html('')
A: you can use remove() method. .empty()
$( "#myId" ).empty()
A: In order to remove or empty all the elements of a container div in this case, you can:
$("#myId").empty();
OR
$("#myId").html('');
Reference link to empty()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45561971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: jQuery status indication by file on web server I have a web server. On the web server there is a process running that is doing something. While the process (or program) is running it will post updates on the status of the task it is doing that should indicate more or less when it will be finished. (Like a status bar indicator for example with percentage number)
The process (or program) will write to a file called busy.html - Inside busy.html the following will be written by the process: Processing: 50%
busy.html is located at: http://www.somewhere.com/temp/busy.html for example.
The process on the web server will intermittently write to busy.html while it is working until 100% is reached. When 100% is reached busy.html will be removed.
On a web page I would like to have jQuery code that displays the contents of busy.html to indicate the status or progress of the process the web server is busy with.
So in other words, Jquery should poll and display the contents of busy.html inside an existing web page until busy.html does not exist anymore.
How would the Jquery code for this look like? Perhaps there is a much easier way of passing on the progress status to jQuery instead of using a file to indicate the existing status like explained here.
Update to my question:
Also, would this be the proper way (using jQuery) to indicate the status of a process running on the server? I would like to enter a URL that is password protected and the web page that loads should tell me the status of the process running on the server. The tech that is running the process is a Perl script or program that is busy indexing the contents of files into a database.
A: You can use this code:
var place = $('#foo');
var delay = 3 * 1000; // 3 seconds
var url = 'http://www.somewhere.com/temp/busy.html';
(function recur() {
$.ajax({url: url, success: function(page) {
place.html(page);
setTimeout(function() {
recur();
}, delay);
}, error: function() {
place.hide();
}});
})();
A: Here are the steps you need.
*
*Read JQuery post or get method and see simple example.
*Inside document ready call a post or get request (get would do with your scenario) and url will point to busy.html
*In response you will get data that is your html or text written inside busy.html
*You can then use the last three letters of that text to fetch percentage and show a chart, guage or simple text as you wish.
Its not complicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39705831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Use Regular Expressions to find a date in a String I am trying to use regular Expressions to extract the dates from a string using VBA in Excel.
The string is:
Previous Month: 9/1/2015 - 9/30/2015
Or it can be :
Custom: 9/1/2015 - 9/30/2015
Do you have any idea how can I achieve that? I have never used Regular Expressions before.
A: RegEx is a poor choice for dates. You could look for : and examine the remaining tokens:
Sub Foo()
Dim result() As Variant
result = GetDates("Previous Month: 9/1/2015 - 9/30/2015")
If UBound(result) Then
Debug.Print result(0)
Debug.Print result(1)
End If
End Sub
Function GetDates(str As String) As Variant()
Dim tokens() As String
tokens = Split(Mid$(str, InStr(str & ": ", ":")), " ")
If (UBound(tokens) = 3) Then
If IsDate(tokens(1)) And IsDate(tokens(3)) Then
GetDates = Array(CDate(tokens(1)), CDate(tokens(3)))
Exit Function
End If
End If
ReDim GetDates(0)
End Function
A: Try this:
([1-9]|1[012])[/]([1-9]|[1-2][0-9]|3[01])[/](19|20)[0-9]{2}
A: search a commandtext string for dates and then replace them with a new date
dim regex as object
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "\d{1,2}[-/]\d{1,2}[-/]\d{2,4}"
regex.Global = True
Set regexMatches = regex.Execute(CommandText)
for i=0 to regexMatches.Count()
date1 = regexMatches(i)
next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33277932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Image create using gd I am creating image using GD library all the functions are working fine. But the main problem where i stucked that i want to merge png image over an other image but after overlapping it cannot merge properly and looking like jpg or other instead of png. I cannot upload my image here due to low reputation so click on these links below to see the image.
The image which i want to merge is this
Png image
The image where i merge above image is:
My code is here:
<?php
$im = imagecreate(288,288);
$background_color = imagecolorallocate($im, 230, 248, 248);
$file = 'images/smiley/smile'.$_POST['smiley'].'.png';
$bg = imagecreatefrompng($file);
imagealphablending($im, true);
imagesavealpha($bg, true);
imagecopyresampled($im, $bg, 80, 80, 0, 0, 50, 50, 185, 185);
header("Content-Type: image/png");
$filename = $_SESSION['rand'].'.png';
imagepng($im,$filename);
echo '<img src="'.$filename.'" alt="" />';
?>
A: Your background image doesn't have an alpha channel. This makes the PHP GD library do all of it's copying operations without using an alpha channel, instead just setting each pixel to be fully opaque or transparent, which is not what you want.
The simplest solution to this is to create a new image of the same size as the background that has an alpha channel, and then copy both the background and face into that one.
$baseImage = imagecreatefrompng("../../var/tmp/background.png");
$topImage = imagecreatefrompng("../../var/tmp/face.png");
// Get image dimensions
$baseWidth = imagesx($baseImage);
$baseHeight = imagesy($baseImage);
$topWidth = imagesx($topImage);
$topHeight = imagesy($topImage);
//Create a new image
$imageOut = imagecreatetruecolor($baseWidth, $baseHeight);
//Make the new image definitely have an alpha channel
$backgroundColor = imagecolorallocatealpha($imageOut, 0, 0, 0, 127);
imagefill($imageOut, 0, 0, $backgroundColor);
imagecopy($imageOut, $baseImage, 0, 0, 0, 0, $baseWidth, $baseHeight); //have to play with these
imagecopy($imageOut, $topImage, 0, 0, 0, 0, $topWidth, $topHeight); //have to play with these
//header('Content-Type: image/png');
imagePng($imageOut, "../../var/tmp/output.png");
That code produces this image:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16979100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 404 Response with Retrofit POST request with Headers parameters I am new to Retrofit Library. When I sending post request with headers parameters using hashMap using @HeaderMap annotation.
Below is my code
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest(@HeaderMap Map <String, String>id);
I am sending the headers using HashMap here like this.
HashMap<String, String> headers = new HashMap<>();
headers.put("eventId", String.valueOf(1));
I am getting 404 error response. Please some one help me.
I have reviewed some Stack Overflow links, but again I am getting this error.
A: Try this:
@FormUrlEncoded
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest(@FieldMap Map <String, String>id);
A: add headers in your interface class:
@Headers({"Content-Type: application/json",
"eventId: 1"})
@POST(Constants.UrlPath.POST_CLOSE_EVENT)
Call<ResponseBody> callDeleteEventRequest();
A: check your path Constants.UrlPath.POST_CLOSE_EVENT is right or not.
try to call using postman if it is working fine in that or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56269368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Harmonic Average Yields incorrect Result As a homework assignment we are required to calculate the harmonic mean using an assembly program being driven by a C program.
We are using 64-bit linux machines and are required to use 64-bit floating point numbers.
I am new to Assembly. I apologize for any bad coding practices or if my code is just flat out wrong.
The problem with the code is the result returns only the last number entered in floating-point format. I do not know where the error occurs, although I believe it to lie in the addDen function.
As an example: If you were to enter the numbers 5, 6, 7, 8 the result would return 8.0000.
Here is my code for the assembly program:
;Assembly function that computs the harmonic mean
;of an array of 64-bit floating-point numbers.
;Retrieves input using a C program.
;
;Harmonic mean is defined as Sum(n/((1/x1) + (1/x2) + ... + (1/xn)))
;
; expects:
; RDI - address of array
; RSI - length of the array
; returns
; XMMO - the harmonic average of array's values
global harmonicMean
section .data
Zero dd 0.0
One dd 1.0
section .text
harmonicMean:
push rbp
mov rbp, rsp ;C prologue
movss xmm10, [Zero] ;Holds tally of denominator
cvtsi2ss xmm0, rsi ;Take length and put it into xmm0 register
.whileLoop:
cmp rsi, 0 ;Is the length of array 0?
je .endwhile
call addDen ;Compute a denominator value and add it to sum
add rdi, 4 ;Add size of float to address
dec rsi ;Decrease the length
jmp .whileLoop
.endwhile:
divss xmm0, xmm10
leave
ret
;Calculates a number in the denominator
addDen:
push rdi
movss xmm8, [One]
movss xmm9, [rdi]
divss xmm8, xmm9
addss xmm10, xmm8
pop rdi
ret
In order to recreate the logic error, i will also include my driver program:
/*
* Harmonic Mean Driver
* Tyler Weaver
* 03-12-2014
*/
#include<stdio.h>
#define ARRAYSIZE 4
double harmonicMean(double *, unsigned);
int main(int argc, char **argv) {
int i;
double ary[ARRAYSIZE];
double hm;
printf("Enter %d f.p. values: ", ARRAYSIZE);
for (i = 0; i < ARRAYSIZE; i++) {
scanf(" %lf", &ary[i]);
}
hm = harmonicMean(ary, ARRAYSIZE);
printf("asm: harmonic mean is %lf\n", hm);
return 0;
}
Any help will be much appreciated!
A: Yes there seems to be float vs double confusion. You pass in a double array, but pretty much all of the asm code expects floats: you use the ss instructions and you assume size 4 and you return a float too.
– Jester
There was an issue with floats and doubles! I really appreciate both of your responses. I was confused because the instructor had told us to use floats in our assembly program he had used doubles in an example driver. I spoke with the instructor and he had fixed his instructions. I thank you again! – Tyler Weaver
A: here is the algorithm, is a mix between C and pseudo code
My suggestion is to write this program in C.
Then have the compiler output the related asm language
then use that asm output as a guide in writing your own program
! ----------------------------------------------------------
! This program reads a series of input data values and
! computes their arithmetic, geometric and harmonic means.
! Since geometric mean requires taking n-th root, all input
! data item must be all positive (a special requirement of
! this program , although it is not absolutely necessary).
! If an input item is not positive, it should be ignored.
! Since some data items may be ignored, this program also
! checks to see if no data items remain!
! ----------------------------------------------------------
PROGRAM ComputingMeans
IMPLICIT NONE
REAL :: X
REAL :: Sum, Product, InverseSum
REAL :: Arithmetic, Geometric, Harmonic
INTEGER :: Count, TotalNumber, TotalValid
Sum = 0.0 ! for the sum
Product = 1.0 ! for the product
InverseSum = 0.0 ! for the sum of 1/x
TotalValid = 0 ! # of valid items
READ(*,*) TotalNumber ! read in # of items
DO Count = 1, TotalNumber ! for each item ...
READ(*,*) X ! read it in
WRITE(*,*) 'Input item ', Count, ' --> ', X
IF (X <= 0.0) THEN ! if it is non-positive
WRITE(*,*) 'Input <= 0. Ignored' ! ignore it
ELSE ! otherwise,
TotalValid = TotalValid + 1 ! count it in
Sum = Sum + X ! compute the sum,
Product = Product * X ! the product
InverseSum = InverseSum + 1.0/X ! and the sum of 1/x
END IF
END DO
IF (TotalValid > 0) THEN ! are there valid items?
Arithmetic = Sum / TotalValid ! yes, compute means
Geometric = Product**(1.0/TotalValid)
Harmonic = TotalValid / InverseSum
WRITE(*,*) 'No. of valid items --> ', TotalValid
WRITE(*,*) 'Arithmetic mean --> ', Arithmetic
WRITE(*,*) 'Geometric mean --> ', Geometric
WRITE(*,*) 'Harmonic mean --> ', Harmonic
ELSE ! no, display a message
WRITE(*,*) 'ERROR: none of the input is positive'
END IF
END PROGRAM ComputingMeans
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27282898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to call d3 pie chart on button click in angularjs? I am trying to display pie chart using d3.js charts in angularjs . As far as the examples i have seen so far implements pie chart on load . But here i want to display pie chart based on the response from service which is called on a button click . Need some guidance to start
my user.html
<h1>Group by users</h1><br>
<select name="users" id="search" ng-model="searchItem">
<option value="">Search By</option>
<option value="admin">admin</option>
<option value="superAdmin">superAdmin</option>
</select>
<button ng-click="search()">Search</button>
<div pie-chart="" style="width:100%;height:460px;" data="data"></div>
my user.js
'use strict';
angular.module('myApp.employee',['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/employee', {
templateUrl: 'employee/employee.html',
controller: 'EmployeeCtrl'
});
}])
.controller('EmployeeCtrl', ['$scope','$http',function($scope,$http) {
$scope.search = function(){
var search=angular.element(document.getElementById("search"));
//var data ;
$scope.searchItem =search.val();
console.log($scope.searchItem);
$http.get("/assets/empDetails.json").then(function(response){
// $scope.empDetail=response.data
console.log(response.data);
console.log();
// function groupBy(arr, prop) {
// const map = new Map(Array.from(arr, obj => [obj[prop], []]));
// arr.forEach(obj => map.get(obj[prop]).push(obj));
// return Array.from(map.values());
// }
// console.log(groupBy(response.data,$scope.searchItem ));
var rows = response.data;
var keyName =$scope.searchItem;
groupBy(keyName);
function groupBy(keyName) {
console.log("Group By :: ", keyName)
var occurences = rows.reduce(function (r, row) {
r[row[keyName]] = ++r[row[keyName]] || 1;
return r;
}, {});
var result = Object.keys(occurences).map(function (key) {
return { key: key, value: occurences[key] };
});
console.log(result);
//data = result ;
$scope.data = [
{
name : "Blue",
value : 10,
color : "#4a87ee"
},
{
name : "Green",
value : 40,
color : "#66cc33"
},
{
name : "Orange",
value : 70,
color : "#f0b840"
},
{
name : "Red",
value : 2,
color : "#ef4e3a"
}
];
}
})
}
}])
.directive ("pieChart", function () {
return {
restrict : "A",
scope : {
data : "="
},
link : function (scope, element) {
var width,
height,
radius,
pie,
arc,
svg,
path;
width = element[0].clientWidth;
height = element[0].clientHeight;
radius = Math.min (width, height) / 2;
pie = d3.layout.pie ()
.value (function (d) {return d.value;})
.sort (null);
arc = d3.svg.arc ()
.outerRadius (radius - 20)
.innerRadius (radius - 80);
svg = d3.select (element[0])
.append ("svg")
.attr ({width : width, height : height})
.append ("g")
.attr ("transform", "translate(" + width * 0.5 + "," + height * 0.5 + ")");
path = svg.datum (scope.data)
.selectAll ("path")
.data (pie)
.enter ()
.append ("path")
.attr ({
fill : function (d, i) {return scope.data [i].color;},
d : arc
});
scope.$watch (
"data",
function () {
pie.value (function (d) {return d.value;});
path = path.data(pie);
path.attr("d", arc);
},
true
);
}
};
})
i have used this https://embed.plnkr.co/plunk/jDvdSh as reference . All i want to implement is on search i want perform the service call and then manipulate the response and render it as a pie chart.or someone please explain how the pie chart directive is called in the above plnkr reference that would be more helpful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58526693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Finding 2D points reachable with short intermediate hops I have a list allNodes of around 60,000 nodes that correspond to 2D points. I'm constructing an adjacency list like
for(i in allNodes)
for(j in allNodes)
if(distance(i, j) <= 10) addEdge between i and j
and then performing a depth-first search from a set of sourceNodes to find the set of nodes reachable from sourceNodes. How can I make this faster than quadratic? I'm using C++.
A: The easy approach is to divide the plane into d-by-d where d > 10 bins and put each point in the bin indexed by floor(x/d), floor(y/d). Then, instead of iterating over all pairs of points,
for bin1 in bins:
for i in bin1:
for bin2 in bins neighboring bin in nine directions (including bin):
for j in bin2:
if(distance(i, j) <= 10) addEdge between i and j
This will make things faster if the points are well spread, but the worst case is still quadratic.
For a guaranteed O(n log n)-time algorithm, compute the Delaunay triangulation and throw away the edges longer than 10. This may remove some direct connections between nodes at distance less than or equal to 10, but they will still be connected indirectly.
A: The binning approach suggested by David Eisenstat's answer works if you expect points to be homogeneously distributed, which is not a property you specified about your data. Additionally, as noted, the Delaunay triangulation still requires local search on the induced graph to ensure that all nodes within the specified distance are found.
One way to get guaranteed performance is with a kd-tree. You can build one in O(2n log n) time (or faster if you don't care as much about guarantees and use randomization) and use it for performing range searches with a total time of O(2n√n).
It's unclear to me whether the Delaunay triangulation or the kd-tree would be faster in practice, but it seems to me that finding and using an appropriate kd-tree library would be a fast and simple solution, if you are worried about development time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42121913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java auto-update jar files- Eclipse I have designed a Desktop based GUI on Eclipse using Windows Builder and I have added few external jar files.
Now, I am looking to implement a mechanism which checks the updated version of those external jar files and download automatically. Replacement of these .jar files will be done manually.
Can anyone give me an advice which technique will be suitable ?
Your advice will be highly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64205857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DNA micro satelite counter I wrote a code to run over the letters in a variable fragile_x_test
and count the number of "CGG". as long as the while loop encounter "CGG" it will add it into the counter variable repeat, otherwise, it will break from the while loop and go for the "if" loop below.
After the if loop, I want the code to go back to the while loop and continue running over the letters. But I don't want it to go back to the for loop at the beginning because it will reset the i.
Does anyone have a clue how to do that? many thanks!
this is the code:
fragile_x_test = "CGGCGGCGGCGGCGGACTTCACGGCGGCGGCGGCGGCGGCGG"
for i in range(0,len(fragile_x_test)):
repeat = 0
tandem = 0
while fragile_x_test[i:i+3] == "CGG":
repeat += 1
i = i+3
if repeat >= 5:
tandem +=1
i = i+3
A: 1st method :
With .split(), you can directly get the number of 'CGG' in your string.
len(fragile_x_test.split('CGG'))-1
It should also be easier to calculate the tandem variable with it.
2nd method :
If you don't need to work on the non 'CGG' part of the string, you can use .count()
fragile_x_test.count('CGG')
3rd method :
This method only counts 1 occurrence for each one or more "CGG" in a row and will add one to tandem variable each time there is more than 5 "CGG" in a row.
example="|CGGCGGCGGCGGCGG|ACTACT|CGGCGGCGGCGGCGGCGGCGG|"
count , repeat , tandem = 0 , 0 , 0
for element in example.split('CGG')[1:-1]:
if element == '':
count+=1
if count==4: tandem+=1
else:
count=0
if count==1:
repeat+=1
print("Number of CGG in a row : ",repeat)
print("Number of CGG tandems : ",tandem)
It will print repeat=2 and tandem=2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63834469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automatically Update Work Item Status within Visual Studio (From 'New' to 'Active') Is there a way to automatically update the status of a Work Item within Azure DevOps from 'New' to 'Active' when the item is added to my 'In Progress Work' from within the 'Available Work Items' section of Visual Studio?
Brief context: I'm using the Kanban board within Azure DevOps and I'd like to move work items along the columns / stages in as automated a way as possible via Visual Studio.
This synchronisation seems to be working fine for items going from 'Active' to 'Resolved', e.g. when I add items to my 'In Progress', amend some code, and perform a check in, I can visually see the item move over to the next column of my Kanban board - it's also changing it's status from 'Active' to 'Resolved'.
A:
Is there a way to automatically update the status of a Work Item
within Azure DevOps from 'New' to 'Active' when the item is added to
my 'In Progress Work' from within the 'Available Work Items' section
of Visual Studio?
The status of the work items in Azure DevOps is not a one-to-one relationship with the work item status of My work in Visual Studio.
The status of work item in Visual Studio is used to classify the work items not change the status of the work item, so that we can more clearly distinguish which work items are being processed.
You can view the description of In Progress Work in Visual Studio is:
drag a work item here to get started
This looks more like a swim lanes, giving developers a clearer idea of which workitems are associated with development.
Besides, when we commit the code and status of work items, there is option which we could select only with Associate and Resolve:
Only if we confirm that the currently associated work item is completed, we will choose the option to Resolve, otherwise it will be Associate.
On the other hand, we could add a custom status of work item on the Azure DevOps. Obviously, we could not match our new custom state to the status of work item in Visual Studio.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56201813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Replace Quoted Values In External SQL Query I use the simple query below to select from a table based on the date:
select * from tbl where date = '2019-10-01'
The simple query is part of a much larger query that extracts information from many tables on the same server. I don't have execute access on the server, so I can't install a stored procedure to make my life easier. Instead, I read the query into Python and try to replace certain values inside single quote strings, such as:
select * from tbl where date = '<InForceDate>'
I use a simple Python function (below) to replace with another value like 2019-10-01, but the str.replace() function isn't replacing when I look at the output. However, I tried this with a value like that wasn't in quotes and it worked. I'm sure I'm missing something fundamental, but haven't uncovered why it works without quotes and fails with quotes.
Python:
def generate_sql(sql_path, inforce_date):
with open(pd_sql_path, 'r') as sql_file:
sql_string = sql_file.read()
sql_final = str.replace(sql_string, r'<InForceDate>', inforce_date)
return(sql_final)
Can anyone point me in the right direction?
A: Nevermind folks -- problem solved, but haven't quite figured out why. File encoding is my guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58714891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom tabs with duplicate tab label name not getting filled in According to: Custom tag in documents uploaded using API, multiple tabs with the same tab label should all be getting filled in with the same value, however, for me, only the first instance is getting that value. I have multiple text tabs with the same tab label, and am creating the envelope with: "text" + "tabLabel" + kvp.Key + "tabLabel" + "value" + kvp.Value + "value" + "text" , yet only the first occurrence of that tab label gets the value. Any suggestions ?
A: In your API request, try prefacing the tabLabel with \\*. For example, if multiple text tabs have the label "address", the portion of the API request to populate those tabs (each with the value '123 Main Street') would look like this:
"tabs":{
"textTabs":[
{
"tabLabel":"\\*address",
"value":"123 Main Street"
},
],
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25789380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PhpMyAdmin Create Database No Privileges issue on Mac I have just installed the PhpMyAdmin on my Mac (Yosomite 10.10.5), Everything looks fine, But when I log in to PhoMyAdmin as root and try to create a new database, It shows No Privileges
Screenshot here: https://i.stack.imgur.com/YNfSs.png
Thanks in Advance
A: Log in via phpMyAdmin with a MySQL account that has sufficient privileges (like root). If you don't have such account, ask this MySQL server's manager about it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44306838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use EF4 as a DAL I am currently using EF 4 with my ASP.NET Website to access a MySql database. This works fine. However I now want another Web Site project to access the same entities. How do I set this up?
I can't just reference the original website as it's a Web Site, not a Web Application. So presumably, I need to put the Entity Data Model in its own project and compile to a DLL. But...
*
*Which project type?
*Do I just cut and paste the DataModel.edmx and DataModel.Designer.cs, compile and add a reference in both websites? What about namespaces?
*Where do I put the connection string? At the moment it's in my project's Web.config.
I really have no idea where to begin - I've just followed tutorials to get EF working up to now! I'd really appreciate step-by-step instructions if anyone has time. Thanks.
A: The model should be placed in a new class library project. My preference would be to recreate the model at this point based on the existing model. For the namespace I like to use {CompanyName}.DataAccess. Remove the old model from your web site project, add a reference to the new class library project and build the web site project. The website project will break in many places, but it should be a simple matter of changing the namespace to the new data access assembly. I prefer this method as to cut/paste because now you have nice clean namespaces. Be careful of any places you may have strings with entity names in them, like if you were using Include (if you are using EF 4 and lazy loading, this should not be a problem). Leave the connection string in web.config for both of the web site projects. When you create the model in the class library, it will add a connection string in app.config. That is OK, it is just there so the model knows how to connect to the database when you refresh it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5662104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Store app submission is non-compliant (not accepting applications submitted through the DreamSpark developer program) I submitted my app updates for certification, but the certification process failed:
Thanks for your interest in Windows Store. Unfortunately, at this
time, we are not accepting applications submitted through the
DreamSpark developer program. We apologize for any inconvenience this
may cause. We also encourage you to read a recent blog on how to make
your app more visible in the Store
(https://blogs.windows.com/buildingapps/2016/01/15/give-your-apps-more-visibility-six-recommendations-for-2016)
to build quality apps that customers want. Please reach out to
Developer Support if you have any questions.
Locations: Metadata
DreamSpark developers won't be able to submit apps to windows store?
PS: many people have the same problem - https://social.msdn.microsoft.com/Forums/en-US/3f90fbf2-42a3-4c85-8fc3-6ac8bb06c173/is-app-submission-from-dreamspark-developers-postponed
A: The message received is correct. There have been issues with misuse of Dreamspark accounts that were causing severe issues with the Store. However, we realize that many of you are not part of this activity and as such we can help you by contacting Developer Support. Please contact them directly so that they have your account information and can get your apps set up for success!
Thanks
Jo
Windows App and Catalog Operations
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35382208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring Doc: swagger-ui.html giving Whitelabel Error Page 404 I am using springdoc-open api for swagger integration in my springboot project.
I have added below property in application.yml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_mathcher
and added below dependency in build.gralde file
implementation "org.springdoc:springdoc-openapi-ui:1.6.9"
I am able to access /v3/api-docs , but /swagger-ui/index.html and /swagger-ui.html giving 404 Whitelabel Error Page
A: After googling so many thins, I found a solution to this issue. I had to add an additional configuration class that is OpenApiConfig.java to make it work.
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"org.springdoc"})
@Import({org.springdoc.core.SpringDocConfiguration.class,
org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class,
org.springdoc.webmvc.ui.SwaggerConfig.class,
org.springdoc.core.SwaggerUiConfigProperties.class,
org.springdoc.core.SwaggerOAuthProperties.class,
org.springframework.autoconfigure.jackson.JacksonAutoConfiguration.class})
class OpenApiConfig implements WebMvcConfigurer {
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72885697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to update(refresh) JTable with data from a database I'm trying to update a JTable after I add or remove a record from the database (MS Access), but it doesn't seem to work. Also, I don't understand why my column names do not show up. Here's my code:
package Administrator13_03_13;
public class Arsti2 {
JFrame main = new JFrame("Ārst");
JPanel tP = new JPanel();
JPanel bP = new JPanel();
JButton one = new JButton("Test");
JTable table = new JTable();
DefaultTableModel model;
Vector columnNames = new Vector();
Vector data = new Vector();
Arsti2() {
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(840,300);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
Connection con = DriverManager.getConnection(Base,"","");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM Arsti");
ResultSetMetaData rsmd = res.getMetaData();
int column = rsmd.getColumnCount();
columnNames.addElement("ID");
columnNames.addElement("Vards");
columnNames.addElement("Uzvards");
columnNames.addElement("Dzimums");
columnNames.addElement("Personas kods");
columnNames.addElement("Telefona numurs");
columnNames.addElement("Nodalas ID");
columnNames.addElement("Amata ID");
while(res.next()) {
Vector row = new Vector(column);
for(int i=1; i<=column; i++) {
row.addElement(res.getObject(i));
}
data.addElement(row);
}
model = new DefaultTableModel(data,columnNames);
table.setModel(model);
//model.fireTableDataChanged();
tP.add(table);
bP.add(one);
main.add(tP,BorderLayout.NORTH);
main.add(bP,BorderLayout.SOUTH);
} catch(Exception e) {
e.printStackTrace();
}
main.setVisible(true);
one.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt1) {
model.fireTableDataChanged();
}
});
}
public static void main(String[] args) {
new Arsti2();
}
}
A:
also I don't understand why doesn't my column names show up
Column names won't show up unless you add a container (like a JScrollPane) to it.
add(new JScrollPane(table));
should be enough.
A: Just model.fireTableDataChanged();wont work you have to reload your model from database
This should work:
public class Arsti2 {
JFrame main = new JFrame("Ārst");
JPanel tP = new JPanel();
JPanel bP = new JPanel();
JButton one = new JButton("Test");
JTable table = new JTable();
DefaultTableModel model;
Vector columnNames = new Vector();
Vector data = new Vector();
Arsti2() {
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(840,300);
try {
reloadData();
model = new DefaultTableModel(data,columnNames);
table.setModel(model);
//model.fireTableDataChanged();
tP.add(table);
bP.add(one);
main.add(tP,BorderLayout.NORTH);
main.add(bP,BorderLayout.SOUTH);
} catch(Exception e) {
e.printStackTrace();
}
main.setVisible(true);
one.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt1) {
try {
reloadData();
model.fireTableDataChanged();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void reloadData() throws ClassNotFoundException, SQLException {
columnNames.clear();
data.clear();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
Connection con = DriverManager.getConnection(Base,"","");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM Arsti");
ResultSetMetaData rsmd = res.getMetaData();
int column = rsmd.getColumnCount();
columnNames.addElement("ID");
columnNames.addElement("Vards");
columnNames.addElement("Uzvards");
columnNames.addElement("Dzimums");
columnNames.addElement("Personas kods");
columnNames.addElement("Telefona numurs");
columnNames.addElement("Nodalas ID");
columnNames.addElement("Amata ID");
while(res.next()) {
Vector row = new Vector(column);
for(int i=1; i<=column; i++) {
row.addElement(res.getObject(i));
}
data.addElement(row);
}
}
public static void main(String[] args) {
new Arsti2();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15459823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How To Create JPanels at runtime and show its name when user click on it I am creating Chess game , for this i am creating 64 JPanels using Loop. and changing background color, here is the example code that i am using to create panel and changing its background color.
for(int i=0;i<8;i++)
{
for( int j=0;j<8;j++)
{
jp[i][j]=new JPanel();
p.add(jp[i][j]);
this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel
if(j%2==0&&i%2==0)// code to change background color of panels for chess board
{
jp[i][j].setBackground(Color.DARK_GRAY);
}
if(j%2!=0&&i%2!=0)
{
jp[i][j].setBackground(Color.DARK_GRAY);
}
}
}
i need code to get name of the JPanel when user click on it in chess board
A: extend JPanel and add a name property that you want to save and read
class MyPanel extends JPanel {
public final int i;
public final int j;
public MyPanel(int i,int j){
super();
this.i = i;
this.j = j;
}
}
and
for(int i=0;i<8;i++)
{
for( int j=0;j<8;j++)
{
jp[i][j]=new MyJPanel(i,j);
p.add(jp[i][j]);
jp[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
MyPanel p = (MyPanel)e.getSource();
// p.i p.j
}
});
this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel
if(j%2==0&&i%2==0)// code to change background color of panels for chess board
{
jp[i][j].setBackground(Color.DARK_GRAY);
}
if(j%2!=0&&i%2!=0)
{
jp[i][j].setBackground(Color.DARK_GRAY);
}
}
}
and on click listener, cast panel to MyPanel
MyPanel p = (MyPanel)object;
String name = p.name;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27172668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inserting a string between certain characters in another string Say I have a string, say String stringy = "<Monkey><Banana><Raffle/>"
and another string String stringier = <Cool stuff to add/>
How can I insert stringier between the closing > of <Banana> and the opening < of <Raffle/>? I can't use the index of the string either, because stringy could have more or less characters before the <Raffle/> and will likely never be the same thing. Any ideas?
A: Are you just looking for a find and replace? If not, can you expand on your question?
stringy = stringy.replace("<Banana><Raffle/>", "<Banana>"+ stringier +"<Raffle/>")
A: This can be another option:
stringy = stringy.substring(0, stringy.indexOf("<Banana>") + "<Banana>".length())
+ stringier
+ stringy.substring(stringy.indexOf("<Banana>") + "<Banana>".length());
A: You can use String.indexOf to find an occurrence of a string within another string. So, maybe it would look something like this.
String stringy = "<Monkey><Banana><Raffle/>";
String stringier = "<Cool stuff to add/>";
String placeToAdd = "<Banana><Raffle/>";
String addAfter = "<Banana>";
int temp;
temp = stringy.indexOf(placeToAdd);
if(temp != -1){
temp = temp+addAfter.length();
stringy = stringy.substring(0, temp) + stringier + stringy.substring(temp+1, stringy.length());
System.out.println(stringy);
} else {
System.out.println("Stringier \'" + stringier+"\" not found");
}
After looking at other answers, replace is probably a better option than the substring stuff.
A: Java strings are immutable, but StringBuilder is not.
public class StringyThingy {
public static void main(String[] args) {
StringBuilder stringy = new StringBuilder("<Monkey><Banana><Raffle/>");
System.out.println(stringy);
// there has to be a more elegant way to find the index, but I'm busy.
stringy.insert(stringy.indexOf("Banana")+"Banana".length()+1,"<Cool stuff to add/>");
System.out.println(stringy);
}
}
// output
<Monkey><Banana><Raffle/>
<Monkey><Banana><Cool stuff to add/><Raffle/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17370055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pandas Create Percentages from Category Sums I have a dataset of website traffic, for about 2000 websites over a period of a month, tabulated by the type of device from which the traffic originated:
In [12]: df.sample(10)
Out[12]:
date device nb_uniq_visitors site_id
11 2017-10-31 Tv 0.0 3331.0
6 2017-10-22 Car browser 0.0 503.0
7 2017-10-22 Camera 0.0 3259.0
7 2017-10-08 Car browser 0.0 630.0
3 2017-10-23 Camera 0.0 118.0
0 2017-10-12 Desktop 1.0 4769.0
11 2017-10-31 Tv 0.0 361.0
5 2017-10-12 Phablet 0.0 2999.0
9 2017-10-17 Portable media player 0.0 1725.0
0 2017-10-13 Desktop 2410.0 1004.0
4 2017-10-13 all 900.0 1271.0
Note that the all category of the device column represents the total of all devices, therefore it could serve as the denominator of the percentage calculation.
I want to see the percentages of device types for each website, I'm imagining the output looking like this (I manually calculated the below for example):
nb_uniq_visitors
site_id device
74.0 Camera 0.00
Car browser 0.00
Console 0.00
Desktop 0.56
Feature phone 0.00
Phablet 0.01
Portable media player 0.00
Smart display 0.00
Smartphone 0.37
Tablet 0.05
Tv 0.00
Unknown 0.00
all 1.00
96.0 Camera 0.00
Car browser 0.00
Console 0.00
Desktop 0.64
Feature phone 0.00
Phablet 0.01
Portable media player 0.00
Smart display 0.00
Smartphone 0.29
Tablet 0.06
Tv 0.00
Unknown 0.01
all 1.00
I used groupby to group by site_id and device:
In [23]: sl = df.groupby(['site_id', 'device']).sum()
In [24]: sl.head(25)
Out[24]:
nb_uniq_visitors
site_id device
74.0 Camera 0.0
Car browser 0.0
Console 1.0
Desktop 10534.0
Feature phone 0.0
Phablet 178.0
Portable media player 4.0
Smart display 0.0
Smartphone 6955.0
Tablet 1022.0
Tv 1.0
Unknown 62.0
all 18757.0
96.0 Camera 0.0
Car browser 2.0
Console 6.0
Desktop 118157.0
Feature phone 0.0
Phablet 1061.0
Portable media player 73.0
Smart display 0.0
Smartphone 53292.0
Tablet 11060.0
Tv 2.0
Unknown 1717.0
all 185370.0
How do I translate the above from aggregate values to percentages? Or is there a better way entirely?
A: Use DataFrame.xs for select all rows with dividing by DataFrame.div:
sl = df.groupby(['site_id', 'device']).sum()
a = sl.div(sl.xs('all', level=1))
print (a)
nb_uniq_visitors
site_id device
74.0 Camera 0.000000
Car browser 0.000000
Console 0.000053
Desktop 0.561604
Feature phone 0.000000
Phablet 0.009490
Portable media player 0.000213
Smart display 0.000000
Smartphone 0.370795
Tablet 0.054486
Tv 0.000053
Unknown 0.003305
all 1.000000
96.0 Camera 0.000000
Car browser 0.000011
Console 0.000032
Desktop 0.637412
Feature phone 0.000000
Phablet 0.005724
Portable media player 0.000394
Smart display 0.000000
Smartphone 0.287490
Tablet 0.059664
Tv 0.000011
Unknown 0.009263
all 1.000000
Detail:
print (sl.xs('all', level=1))
nb_uniq_visitors
site_id
74.0 18757.0
96.0 185370.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47205492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Array item completion in a UITextView I'm trying to accomplish an autocomplete of my own for matching array items while typing. So, I already have the logic done for matching what's being typed with what's in the array, but my question is related to displaying the proposed correction in the UITextView like this screenshot
I was trying by splitting the text in the textview and replacing the last word into attributed strings, but that makes the proposed correction part of the actual contents. Any ideas of how this is accomplished in this app?
A: What you currently do is good , when you set the text of the textView to attributed string make bool flag say it's name is textEdited = true with a string part that the user types say it's name userStr , when textView change method is triggered check that bool and according to it make the search if it's true proceed search with userStr if it's not proceed search with whole textView text , don't forget to make textEdited= false after every zero suggested result
Edit: regarding the cursor put a label under the textfield with the same font as the textView and make it's background darkGray , also make background of the textview transparent and every attributed string assign it to the label so plus part of the label will be shown and cursor will be as it is in the textView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48370339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: String Replacement Combinations So I have a string '1xxx1' and I want to replace a certain number (maybe all maybe none) of x's with a character, let's say '5'. I want all possible combinations (...maybe permutations) of the string where x is either substituted or left as x. I would like those results stored in a list.
So the desired result would be
>>> myList = GenerateCombinations('1xxx1', '5')
>>> print myList
['1xxx1','15xx1','155x1','15551','1x5x1','1x551','1xx51']
Obviously I'd like it to be able to handle strings of any length with any amount of x's as well as being able to substitute any number. I've tried using loops and recursion to figure this out to no avail. Any help would be appreciated.
A: How about:
from itertools import product
def filler(word, from_char, to_char):
options = [(c,) if c != from_char else (from_char, to_char) for c in word]
return (''.join(o) for o in product(*options))
which gives
>>> filler("1xxx1", "x", "5")
<generator object <genexpr> at 0x8fa798c>
>>> list(filler("1xxx1", "x", "5"))
['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']
(Note that you seem to be missing 15x51.)
Basically, first we make a list of every possible target for each letter in the source word:
>>> word = '1xxx1'
>>> from_char = 'x'
>>> to_char = '5'
>>> [(c,) if c != from_char else (from_char, to_char) for c in word]
[('1',), ('x', '5'), ('x', '5'), ('x', '5'), ('1',)]
And then we use itertools.product to get the Cartesian product of these possibilities and join the results together.
For bonus points, modify to accept a dictionary of replacements. :^)
A: Generate the candidate values for each possible position - even if there is only one candidate for most positions - then create a Cartesian product of those values.
In the OP's example, the candidates are ['x', '5'] for any position where an 'x' appears in the input; for each other position, the candidates are a list with a single possibility (the original letter). Thus:
def candidates(letter):
return ['x', '5'] if letter == 'x' else [letter]
Then we can produce the patterns by producing a list of candidates for positions, using itertools.product, and combining them:
from itertools import product
def combine(candidate_list):
return ''.join(candidate_list)
def patterns(data):
all_candidates = [candidates(element) for element in data]
for result in product(*all_candidates):
yield combine(result)
Let's test it:
>>> list(patterns('1xxx1'))
['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']
Notice that the algorithm in the generator is fully general; all that varies is the detail of how to generate candidates and how to process results. For example, suppose we want to replace "placeholders" within a string - then we need to split the string into placeholders and non-placeholders, and have a candidates function that generates all the possible replacements for placeholders, and the literal string for non-placeholders.
For example, with this setup:
keywords = {'wouldyou': ["can you", "would you", "please"], 'please': ["please", "ASAP"]}
template = '((wouldyou)) give me something ((please))'
First we would split the template, for example with a regular expression:
import re
def tokenize(t):
return re.split(r'(\(\(.*?\)\))', t)
This tokenizer will give empty strings before and after the placeholders, but this doesn't cause a problem:
>>> tokenize(template)
['', '((wouldyou))', ' give me something ', '((please))', '']
To generate replacements, we can use something like:
def candidates(part):
if part.startswith('((') and part.endswith('))'):
return keywords.get(part[2:-2], [part[2:-2]])
else:
return [part]
That is: placeholder-parts are identified by the parentheses, stripped of those parentheses, and looked up in the dictionary.
Trying it with the other existing definitions:
>>> list(patterns(tokenize(template)))
['can you give me something please', 'can you give me something ASAP', 'would you give me something please', 'would you give me something ASAP', 'please give me something please', 'please give me something ASAP']
To generalize patterns properly, rather than depending on other global functions combine and candidates, we should use dependency injection - by simply passing those as parameters which are higher-order functions. Thus:
from itertools import product
def patterns(data, candidates, combine):
all_candidates = [candidates(element) for element in data]
for result in product(*all_candidates):
yield combine(result)
Now the same core code solves whatever problem. Examples might look like:
def euler_51(s):
for pattern in patterns(
s,
lambda letter: ['x', '5'] if letter == 'x' else [letter],
''.join
):
print(pattern)
euler_51('1xxx1')
or
def replace_in_template(template, replacement_lookup):
tokens = re.split(r'(\(\(.*?\)\))', template)
return list(patterns(
tokens,
lambda part: (
keywords.get(part[2:-2], [part[2:-2]])
if part.startswith('((') and part.endswith('))')
else [part]
),
''.join
))
replace_in_template(
'((wouldyou)) give me something ((please))',
{
'wouldyou': ["can you", "would you", "please"],
'please': ["please", "ASAP"]
}
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14841652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Firestore returns empty list I have 3 entries in my firestore database. I need to query the data and fetch it, then input it into an ArrayList. The problem is my query is always returning empty hence the list does not get populated. I have tried pointer debugging this but to no avail. The following is the code in my .kt file
class Users : AppCompatActivity() {
private val db = Firebase.firestore
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_users)
val userList = ArrayList<User>()
db.collection("Users").get()
.addOnCompleteListener(OnCompleteListener<QuerySnapshot?> { task ->
if (task.isSuccessful) {
for (document in task.result) {
val user = User(document.data["name"] as String, document.data["email"] as String)
userList.add(user)
}
Log.d(TAG, userList.toString())
} else {
Log.d(TAG, "Error getting documents: ", task.exception)
}
})
recyclerView = findViewById<RecyclerView>(R.id.rv)
val adapter = UsersAdapter(userList)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
}
}
A: First of all, what if Firebase.firestore? Are you checking if that variable is returning an app or an instance? Or, you just debug it using for example: Log.e("TAG", "$db") or using the Android debugger.
To debug inside of the lambda I recommend you to use the following code:
db.collection("Users").get()
.addOnCompleteListener(object : OnCompleteListener<QuerySnapshot?> {
override fun onComplete(task: Task<QuerySnapshot?>) {
if (task.isSuccessful) {
for (document in task.result!!) {
val user = User(document.data["name"] as String, document.data["email"] as String)
userList.add(user)
}
Log.d(TAG, userList.toString())
} else {
Log.d(TAG, "Error getting documents: ", task.exception)
}
}
})
In that block you can use the Android Debugger because it's not a lambda function, so, when you figured out the null data and fixed it you can switch the object function to a lambda.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72221768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I send nested json POST request in java using jersey? I am using a document converter api called cloudconvert. They don't have an official java library, but a third party java option. I needed a little customization so I cloned the github project and added it to my project. I am sending cloudconvert a .epub file and getting a .pdf file in return. If I use the default settings it works without issue and properly converts my .epub to a .pdf. Here is the code that makes it happen.
Here is what triggers the conversion:
// Create service object
CloudConvertService service = new CloudConvertService("api-key");
// Create conversion process
ConvertProcess process = service.startProcess(convertFrom, convertTo);
// Perform conversion
//convertFromFile is a File object with a .epub extension
process.startConversion(convertFromFile);
// Wait for result
ProcessStatus status;
waitLoop:
while (true) {
status = process.getStatus();
switch (status.step) {
case FINISHED:
break waitLoop;
case ERROR:
throw new RuntimeException(status.message);
}
// Be gentle
Thread.sleep(200);
}
//Download result
service.download(status.output.url, convertToFile);
//lean up
process.delete();
startConversion() calls:
public void startConversion(File file) throws ParseException, FileNotFoundException, IOException {
if (!file.exists()) {
throw new FileNotFoundException("File not found: " + file);
}
startConversion(new FileDataBodyPart("file", file));
}
Which calls this to actually send the POST request using jersey:
private void startConversion(BodyPart bodyPart) {
if (args == null) {
throw new IllegalStateException("No conversion arguments set.");
}
MultiPart multipart = new FormDataMultiPart()
.field("input", "upload")
.field("outputformat", args.outputformat)
.bodyPart(bodyPart);
//root is a class level WebTarget object
root.request(MediaType.APPLICATION_JSON).post(Entity.entity(multipart, multipart.getMediaType()));
}
Up to this point everything is working. My problem is that the when the conversion happens the .pdf that returns has very small margins. cloudconvert provides a way to change those margins. You can send in an optional json param converteroptions and set the margins manually. I have tested this out using postman and it works without issue, I was able to get a properly formatted margin document. So know this is possible. Here is the POSTMAN info I used:
@POST : https://host123d1qo.cloudconvert.com/process/WDK9Yq0z1xso6ETgvpVQ
Headers: 'Content-Type' : 'application/json'
Body:
{
"input": "base64",
"file": "0AwAAIhMAAAAA", //base64 file string that is much longer than this
"outputformat": "pdf",
"converteroptions": {
"margin_bottom": 75,
"margin_top": 75,
"margin_right": 50,
"margin_left": 50
}
}
Here are my attempts at getting the POST request formatted properly, I'm just not very experienced with jersey and the couple of answers I did find on stackoverflow didn't work for me.
Attempt 1, I tried adding the json string as a Multipart.field. It didn't give me any errors and still returned a converted .pdf file, but the margins didn't get changed so I must not be sending it back right.
private void startConversion(BodyPart bodyPart) {
String jsonString = "{\"margin_bottom\":75,\"margin_top\":75,\"margin_right\":50,\"margin_left\":50}";
MultiPart multipart = new FormDataMultiPart()
.field("input", "upload")
.field("outputformat", args.outputformat)
.field("converteroptions", jsonString)
.bodyPart(bodyPart);
root.request(MediaType.APPLICATION_JSON).post(Entity.entity(multipart, multipart.getMediaType()));
}
Attempt 2, when I had it working in POSTMAN it was using the 'input' type as 'base64' so I tried changing it to that but it this time it doesn't return anything at all, no request errors, just a timeout error at the 5 minute mark.
//I pass in a File object rather than the bodypart object.
private void startConversion(File file) {
byte[] encoded1 = Base64.getEncoder().encode(FileUtils.readFileToByteArray(file));
String encoded64 = new String(encoded1, StandardCharsets.US_ASCII);
String jsonString = "{\"margin_bottom\":75,\"margin_top\":75,\"margin_right\":50,\"margin_left\":50}";
MultiPart multipart = new FormDataMultiPart()
.field("input", "base64")
.field("outputformat", args.outputformat)
.field("file", encoded64)
.field("converteroptions", jsonString);
root.request(MediaType.APPLICATION_JSON).post(Entity.entity(multipart, multipart.getMediaType()));
}
Attempt 3, after some googling on how to properly send jersey json post requests I changed the format. This time it returned a 400 bad request error.
private void startConversionPDF(File file) throws IOException {
byte[] encoded1 = Base64.getEncoder().encode(FileUtils.readFileToByteArray(file));
String encoded64 = new String(encoded1, StandardCharsets.US_ASCII);
String jsonString = "{\"input\":\"base64\",\"file\":\"" + encoded64 + "\",\"outputformat\":\"pdf\",\"converteroptions\":{\"margin_bottom\":75,\"margin_top\":75,\"margin_right\":50,\"margin_left\":50}}";
root.request(MediaType.APPLICATION_JSON).post(Entity.json(jsonString));
}
Attempt 4, Someone said you don't need to manually use a jsonString you should use serializable java beans. So I created the corresponding classes and made the request like shown below. Same 400 bad request error.
@XmlRootElement
public class PDFConvert implements Serializable {
private String input;
private String file;
private String outputformat;
private ConverterOptions converteroptions;
//with the a default constructor and getters/setters for all
}
@XmlRootElement
public class ConverterOptions implements Serializable {
private int margin_bottom;
private int margin_top;
private int margin_left;
private int margin_right;
//with the a default constructor and getters/setters for all
}
private void startConversionPDF(File file) throws IOException {
byte[] encoded1 = Base64.getEncoder().encode(FileUtils.readFileToByteArray(file));
String encoded64 = new String(encoded1, StandardCharsets.US_ASCII);
PDFConvert data = new PDFConvert();
data.setInput("base64");
data.setFile(encoded64);
data.setOutputformat("pdf");
ConverterOptions converteroptions = new ConverterOptions();
converteroptions.setMargin_top(75);
converteroptions.setMargin_bottom(75);
converteroptions.setMargin_left(50);
converteroptions.setMargin_right(50);
data.setConverteroptions(converteroptions);
root.request(MediaType.APPLICATION_JSON).post(Entity.json(data));
}
I know this is quite the wall of text, but I wanted to show all the different things I tried so that I wouldn't waste anyone's time. Thank you for any help or ideas you might have to make this work. I really want to make it work with jersey because I have several other conversions I do that work perfectly, they just don't need any converteroptions. Also I know its possible because it works when manually running the process through POSTMAN.
Cloudconvert api documentation for starting a conversion
Github repo with the recommended 3rd party java library I am using/modifying
A: I finally figured it out. Hours of trial and error. Here is the code that did it:
private void startConversionPDF(File file) throws IOException {
if (args == null) {
throw new IllegalStateException("No conversion arguments set.");
}
PDFConvert data = new PDFConvert();
data.setInput("upload");
data.setOutputformat("pdf");
ConverterOptions converteroptions = new ConverterOptions();
converteroptions.setMargin_top(60);
converteroptions.setMargin_bottom(60);
converteroptions.setMargin_left(30);
converteroptions.setMargin_right(30);
data.setConverteroptions(converteroptions);
MultiPart multipart = new FormDataMultiPart()
.bodyPart(new FormDataBodyPart("json", data, MediaType.APPLICATION_JSON_TYPE))
.bodyPart(new FileDataBodyPart("file", file));
root.request(MediaType.APPLICATION_JSON).post(Entity.entity(multipart, multipart.getMediaType()));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43856634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stack-Based Buffer Overflow Vulnerabilities I am reading a book titled Hacking: The Art of Exploitation, and I have a problem with the section Stack-Based Buffer Overflow Vulnerabilities.
I am following the instructions given by the author, but I don't get the expected results.
First, here is the program auth_overflow2.c, copied from the book:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check_authentication(char *password) {
char password_buffer[16];
int auth_flag = 0;
strcpy(password_buffer, password);
if(strcmp(password_buffer, "brillig") == 0)
auth_flag = 1;
if(strcmp(password_buffer, "outgrabe") == 0)
auth_flag = 1;
return auth_flag;
}
int main(int argc, char *argv[]) {
if(argc < 2) {
printf("Usage: %s <password>\n", argv[0]);
exit(0);
}
if(check_authentication(argv[1])) {
printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
printf(" Access Granted.\n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
} else {
printf("\nAccess Denied.\n");
}
}
This is a copy of my Ubuntu terminal:
(gdb) break 19
Breakpoint 1 at 0x40077b: file auth_overflow.c, line 19.
(gdb) break 7
Breakpoint 2 at 0x4006df: file auth_overflow.c, line 7.
(gdb) break 12
Breakpoint 3 at 0x40072a: file auth_overflow.c, line 12.
(gdb) run AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Starting program: /home/test/a.out AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Breakpoint 1, main (argc=2, argv=0x7fffffffdf08) at auth_overflow.c:19
19 if(check_authentication(argv[1])) {
(gdb) i r esp
esp 0xffffde10 -8688
(gdb) x/32xw $esp
0xffffffffffffde10: Cannot access memory at address 0xffffffffffffde10
(gdb) c
Continuing.
Breakpoint 2, check_authentication (password=0x7fffffffe2cc 'A' <repeats 30 times>) at auth_overflow.c:7
7 strcpy(password_buffer, password);
(gdb) i r esp
esp 0xffffddc0 -8768
(gdb) x/32xw $esp
0xffffffffffffddc0: Cannot access memory at address 0xffffffffffffddc0
(gdb) p 0xffffde10 - 0xffffddc0
$1 = 80
(gdb) x/s password_buffer
0x7fffffffdde0: "\001"
(gdb) x/x &auth_flag
0x7fffffffdddc: 0x00
(gdb)
When i try x/32xw $esp i get:
0xffffffffffffde10: cannot access memory at address 0xffffffffffffde10
Same thing happens when i continue to the second break point.
When author types x/s password_buffer the output is:
0xbffff7c0: "?o??\200????????o???G??\020\205\004\b?????\204\004\b????\020\205\004\bH???????\002"
but my output looks like this:
0x7fffffffdde0: "\001"
My i r esp result is also different from the book.
in the book there are two hexadecimal numbers:
esp 0xbffff7e0 0xbffff7e0
I am using Ubuntu and GCC and GDB.
A: I think I might have the answer - your argv[ 1 ] is pointing to the 30 'A's - and you have a password buffer of 16. The strcpy() will just fill the buffer and beyond.
I would increase the buffer size to a larger size (say 255 bytes).
In practise, you should review your code, even examples, and make them more robust (example: allowing for larger passwords then 16 )
A: Please less the number of As try A(17) times it will work
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31320531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Multiple login prompts from azure application gateway V2 I have configured an application behind my application gateway V2 and it is providing multiple logins prompts. I Have enabled cookie-based affinity on my HTTP settings as outlined in the Azure Application Gateway Documentation, Application Gateway supports cookie-based affinity enabling which it can direct subsequent traffic from a user session to the same server for processing. Also I have moved out 1 server from the backend pool leaving only 1 server behind. We are still facing same issues.
A: Please use Application Gateway V1. I have seen this issue where the server sends negotiate and NTLM and with AppGW V2 the auth fallsback to NTLM where it promts for login for each and every request(CSS file loading).
A: NTLM / Kerberos is not supported on V2 gateways. No idea why.
https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-faq#does-application-gateway-v2-support-proxying-requests-with-ntlm-authentication
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60900680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Initialize variables in one line? Is it possible do the following initializations in one line? As I am quite curious whether a shorter code is possible.
X = []
Y = []
A: You can initialize them using sequence unpacking (tuple unpacking in this case)
X, Y = [], []
because it's equivalent to
(X, Y) = ([], [])
You can also use a semicolon to join lines in your example:
X = []; Y = []
A: You can use tuple unpacking (or multiple assignment):
X, Y = [], []
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26282217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ajax uploadProgress function not working I have this ajax code for uploading an image. Everything is working fine but the uploadProgress: function is not working.
$('#imageuploadform').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: 'tools/image',
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
//console.log("success");
console.log(data);
//alert(data);
},
uploadProgress: function(event, position, total, percentComplete) {
console.log(position);
},
error: function(data){
//alert('error');
//console.log("error");
console.log(data);
}
});
}));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23025327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting rows with similar column value depending on max value of other column I have data set like following
FC RC aa
F93 GT 16
F92 GT 1
F90 OT 48
F94 AP 2
F93 EU 2
F90 NA 13
F92 OT 1
F92 SA 1
I would like the result to be:
FC RC aa
F93 GT 16
F90 OT 48
F94 AP 2
F93 EU 2
F90 NA 13
F92 SA 1
How I can achieve this?
I am using Oracle 11g database.
A: SQL Fiddle Demo
SELECT FC, MAX(RC) RC, aa
FROM YourTable
GROUP BY FC, aa
OUTPUT
| FC | RC | aa |
|-----|----|----|
| F90 | NA | 13 |
| F90 | OT | 48 |
| F92 | SA | 1 |
| F93 | EU | 2 |
| F93 | GT | 16 |
| F94 | AP | 2 |
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37756077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why typedef doesn't work with pthread? I'm trying to send a typedef through a function. However, it seems I can't.
#define MAX 2
typedef struct
{
unsigned long myPid;
unsigned long parentPid;
unsigned long myTid;
} myProperties;
void* funcproperties(void* arg);
void createthread(myProperties (*properties)[MAX]);
So this is how my typedef is defined.
void* funcproperties(void* arg)
{
myProperties *properties=(myProperties*) arg;
properties->myPid=getpid();
properties->parentPid=getppid();
properties->myTid=syscall(SYS_gettid);
return NULL;
}
If I give values to properties[0].myPid=getpid(), I won't have problems. However, when I send the address of the position where the typedef will start (0 or 1), it doesn't. I wonder why? Maybe pthread doesn't support it?
void createthread(myProperties (*properties)[MAX])
{
pthread_t tids[MAX];
for (int i = 0; i < MAX; i++) {
if ((errno = pthread_create(&tids[i], NULL, funcproperties, properties[i])) != 0)
ERROR(C_ERRO_PTHREAD_CREATE, "pthread_create() failed!");
}
for (int i = 0; i < MAX; i++)
printf("\n PID:%lu DAD: %lu TID: %lu", properties[i]->myPid, properties[i]->parentPid ,properties[i]->myTid);
}
This is the result I'm getting (I force pid to define. However, if I'm not mistaken, I'm getting random values).
PID:0 DAD: 3076323888 TID: 134519979
PID:612976384 DAD: 3077911516 TID: 3220212208
PID:0 DAD: 3076323888 TID: 134519979
PID:612976384 DAD: 3077911516 TID: 3220212208
PID:0 DAD: 3076323888 TID: 134519979
PID:612976384 DAD: 3077911516 TID: 3220212208
I 9292 did my job now make yourself served
PS: I'm also using processes.
A: You must ensure that it is impossible for one thread to access an object while another thread might be modifying it. You have not done this, so the results are unpredictable.
One solution would be to call pthread_join on all the threads before looking at the values they are setting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40065627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Position middle container right after the one before, but docked to bottom I have a web page that consists of a header, slider menu content and footer.
I need the content to start from the menu (menu size and location is based on the elements above that depends on device), and it should always be 25px from the bottom overlapping the footer.
If I try to make it relative, it hangs to the middle and doesn't reach the end, if I make it absolute, I have to specify the value it should be started from which is dynamic.
Is there an efficient way to do this?
UPDATE
I don't mind doing it with jQuery as long as the top of the content is dynamic and depends on the previous element no matter what it is.
UPDATE
Here's an abstract example to what I need.
The footer should always be anchored to the bottom (later I'll apply sticky footer technique, here my issue is the content), the header, slider and menu are anchored to element above, the content should be anchored to the element above and to the footer.
A: your not very clear with what you want exactly. so I've made some assumptions.
(all of those assumptions can be corrected if I assumed wrong).
Assumptions:
*
*Header should scroll with the content. (that behavior can be changed if you want)
*the scroll should be applied on the 'Content Zone' only. (that behavior can be changed if you want)
*the content wrapper should always span to the end of the page, even if the physical content is smaller then that. and should have a scrolling only when the physical content is larger than the available space. (that behavior can be changed if you want)
[as you can see, all of those behaviors can be changed with the correct CSS]
Here is a Working Fiddle
*
*this is a pure CSS solution. (I always avoid scripts if I can)
*cross browser (Tested on: IE10, IE9, IE8, Chrome, FF)
HTML: (I've added a wrapper for the scroll-able content)
<div class="scollableContent">
<div class="header">
<h1>header</h1>
</div>
<div class="main">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque lacinia tempus diam in malesuada. Aliquam id enim nisl. Integer hendrerit adipiscing quam, fermentum pellentesque nisl. Integer consectetur hendrerit sapien nec vestibulum. Vestibulum ac diam in arcu feugiat fermentum nec id nibh. Proin id laoreet dui, quis accumsan nisi. Quisque eget sem ut arcu faucibus convallis. Sed sed nisl commodo, faucibus leo sed, egestas est. Cras at nibh et erat ullamcorper sollicitudin vitae non nibh.</h1>
</div>
</div>
<div class="footer">
<h2>footer</h2>
</div>
CSS:
*
{
padding: 0;
margin: 0;
}
.scollableContent
{
position: absolute;
top: 0;
bottom: 25px; /*.footer height*/
overflow: auto;
}
.scollableContent:before
{
content: '';
height: 100%;
float: left;
}
.header
{
/*Addition*/
background-color: red;
}
.main
{
/*Addition*/
background-color: yellow;
}
.main:after
{
content: '';
display: block;
clear: both;
}
.footer
{
position: fixed;
width: 100%;
bottom: 0px;
height: 25px;
/*Addition*/
color: white;
background-color: blue;
}
Explanation:
The .footer is fixed to the view port bottom, with a fix height. and spans the whole view port width.
the .scollableContent is absolutely positioned to span exactly all the space between the top of the view port, and the top of the footer. with automatic overflow that allow scrolling if the content is bigger than the available space.
inside the .scollableContent we have a simple block element for the header, that will span his content height. after him we have another block element for the content itself.
now we want the content to always stretch to the end of the container, regardless of the header height (so we can't apply it with a fixed height).
we achieve this using floating & clearing techniques.
we create a floating element before the .scollableContent, with no content (so it's invisible and doesn't really take any place at all) but with 100% height.
and at the end of the content div, we create a block with clear instruction.
now: this new block cannot be position in the same line with the floating element. so he has to be moved down, dragging the content div along with him.
Et voilà!
EDIT:
you're probably going to use this solution inside some existing Container in your website. (and not as the whole website layout).
I've updated the fiddle so that the content is enclosed within a container. that way it will be easier for you to port this solution to your working website.
here is the Updated Fiddle
A: <style>
div {
border: 3px solid black;
height: 300px;
width: 100%;
position: absolute;
bottom: 25px;
}
</style>
<div></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18820949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails4 Youtube uploader 401 error i'am developing a rails4 application that uploads videos to youtube using the user's Google account credentials. I succeeded contacting the YoutubeDataApi to check user's credentials but when i try to push the Video to youtube servers it respond to with a 401 error : Token Invalid.
Started POST "/videos/get_upload_token" for 127.0.0.1 at 2015-04-04 18:21:00 +0200
Processing by VideosController#get_upload_token as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qisidAqdL5CjdfHbk20B6bS3DNYa1yjXn17Eos86TTVHAsP5j2WoR/FI08ptp04vGdWw3DLn/3HY6xt/Um2ztg==", "title"=>"sqdqs", "description"=>"dsqf"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Rendered text template (0.0ms)
Completed 500 Internal Server Error in 210ms
OAuth2::Error (<HTML>
<HEAD>
<TITLE>Token invalid</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Token invalid</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
):
app/controllers/videos_controller.rb:24:in `get_upload_token'
I'am using Youtube_it gem and oAuth2 to contact google.
Here is the GitHub link to my project : https://github.com/GhostGumm/Bubblz101
Any help or direction will be much appreciated, thank you :).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29448850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XPATH expression with negating condition in SAP PI XSLT Mapping I have to maintain conditions in Interface Determination of ICO in SAP PI. I have several invoice types like L1, S1, G1, F1, etc. I have two separate mappings as per requirement.
When the Invoice type is L1, S1 or G1, and LAND1 = IND, PARW= W and QUALF=015, I want to pick 1st mapping and for remaining invoice types I want to pick 2nd mapping.
The XPath expressions in the Condition Editor for the two mappings are:
1)
(/ZEINV_INVOIC02/IDOC/E1EDKA1[PARVW = 'W' and LAND1 = 'IND']) EX AND
(/ZEINV_INVOIC02/IDOC/E1EDK14[QUALF = 015 and ORGID = 'L1']) EX OR
(/ZEINV_INVOIC02/IDOC/E1EDKA1[PARVW = 'W' and LAND1 = 'IND']) EX AND
(/ZEINV_INVOIC02/IDOC/E1EDK14[QUALF = 015 and ORGID = 'G1']) EX OR
(/ZEINV_INVOIC02/IDOC/E1EDKA1[PARVW = 'W' and LAND1 = 'IND']) EX AND
(/ZEINV_INVOIC02/IDOC/E1EDK14[QUALF = 015 and ORGID = 'S1']) EX
2) (I have an issue with the second line about ORGID expression)
(/ZEINV_INVOIC02/IDOC/E1EDKA1[PARVW = 'W' and LAND1 = 'IND']) EX AND
(/ZEINV_INVOIC02/IDOC/E1EDK14[QUALF = 015 and ( ORGID ≠ 'L1' or ORGID ≠ 'G1' or ORGID ≠ 'S1' )]) EX
The issue is that when the ICO is run, it is picking both mappings, satisfying both conditions with these values:
ORGID = 'L1'
QALF = 015
PARW = 'W'
LAND1 = 'IND'
What is the XPath expression for the second condition when we have ORGID values other than L1, G1 and S1?
A: Unfortunately, the expression ORGID ≠ 'L1' or ORGID ≠ 'G1' or ORGID ≠ 'S1' is a tautology, i.e. it's true if ORGID is 'L1' and true if ORGID is not L1, so the whole expression is always true whatever the value of ORGID is.
What you want is this:
not( ORGID = 'L1' or ORGID = 'G1' or ORGID = 'S1' )
Note that you may also use the equivalent expression without not, by using the De Morgan's law, here you have to switch and/or and negate the conditions:
ORGID != 'L1' and ORGID != 'G1' and ORGID != 'S1'
NB: does ≠ really work? Shouldn't you use !=?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59559238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.