id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_3800
|
Like I have a words
Computer
<input type="text" name="name" />
I need it like in different Block Like Name Speel
[C] [o] [m] [p] [u] [t] [e] [r]
Any help appreciated.
A: What you might want is the following JavaScript:
"Computer".split("")
A: I think that the main problem is this part: "select each Alphabet and use it in Different Places Like..." so the solution is to use .charAt() function.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "How are you doing today?";
var res = str.charAt(0);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
| |
doc_3801
| ||
doc_3802
|
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$obj->$key = $val;
}
$array = $obj;
}
A: If it's a one-dimensional array, a cast should work:
$obj = (object)$array;
A: Why not just cast it?
$myObj = (object) array("name" => "Jonathan");
print $myObj->name; // Jonathan
If it's multidimensional, Richard Castera provides the following solution on his blog:
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
} else {
return FALSE;
}
}
A: This works for me
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$key = str_replace("-","_",$key)
$obj->$key = $val;
}
$array = $obj;
}
make sure that str_replace is there as '-' is not allowed within variable names in php, as well as:
Naming Rules for Variables
* A variable name must start with a letter or an underscore "_"
* A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
* A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)
So, since these are permitted in arrays, if any of them comes in the $key from the array you are converting, you will have nasty errors.
| |
doc_3803
|
At first I tried to create validator by inherit by BaseValidator class, but I can not pin it to my aspx file (<%@ Register %> doesn't work)
At second I tried to use CustomValidator, but when I fix ID of my capcha control asp.net give me error "Control 'ctrlCapcha' referenced by the ControlToValidate property of 'cusValCapcha' cannot be validated." (I service event "OnServerValidate")
Could you tell me which way is better? Thank for you all suggestions :)
A: What are the fields that are inside the UserControl? I assume you want to validate one of these fields. You can add the Customvalidator to the UserControl itself and implement your ServerValidate inside the codebehind of the user control. You don’t have to set the “ControlToValidate” property. In the ServerValidate, you just add whether validation logic you want.
| |
doc_3804
|
version: '3.8'
services:
mongo-bootstrapper:
container_name: mongo-bootstrapper
image: mongo
volumes:
- ./.devcontainer/tests/init-mongo-db/entrypoint.sh:/init.sh
entrypoint: /init.sh
networks:
- mongo-net
mongo1:
image: mongo
container_name: mongo1
restart: always
ports:
- "27017:27017"
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
volumes:
- ./.devcontainer/tests/replica.key:/opt/replica.key
command:
- --replSet
- rs0
- --keyFile
- /opt/replica.key
- --port
- "27017"
networks:
- mongo-net
mongo2:
image: mongo
container_name: mongo2
restart: always
ports:
- "27027:27027"
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
volumes:
- ./.devcontainer/tests/replica.key:/opt/replica.key
command:
- --replSet
- rs0
- --keyFile
- /opt/replica.key
- --port
- "27027"
networks:
- mongo-net
mongo3:
image: mongo
container_name: mongo3
restart: always
ports:
- "27037:27037"
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
volumes:
- ./.devcontainer/tests/replica.key:/opt/replica.key
command:
- --replSet
- rs0
- --keyFile
- /opt/replica.key
- --port
- "27037"
networks:
- mongo-net
app:
platform: linux/amd64
build:
context: .
dockerfile: .devcontainer/Dockerfile
container_name: app
env_file: ./.devcontainer/.env.test
ports:
- "80:80"
volumes:
- .:/app
networks:
- mongo-net
networks:
mongo-net:
Here's the entrypoint for mongo-bootstrapper:
#!/bin/bash
echo "########### Waiting for primary ###########"
until mongosh -u root -p root --host mongo1 --eval "printjson(db.runCommand({ serverStatus: 1}).ok)"
do
echo "########### Sleeping ###########"
sleep 5
done
echo "########### Waiting for replica 01 ###########"
until mongosh -u root -p root --host mongo2 --port 27027 --eval "printjson(db.runCommand({ serverStatus: 1}).ok)"
do
echo "########### Sleeping ###########"
sleep 5
done
echo "########### Waiting for replica 02 ###########"
until mongosh -u root -p root --host mongo3 --port 27037 --eval "printjson(db.runCommand({ serverStatus: 1}).ok)"
do
echo "########### Sleeping ###########"
sleep 5
done
echo "########### All replicas are ready!!! ###########"
echo "########### Initiating replica set ###########"
mongosh -u root -p root --host mongo1 <<EOF
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1:27017" },
{ _id: 1, host: "mongo2:27027" },
{ _id: 2, host: "mongo3:27037" }
]
})
EOF
echo "########### Getting replica set status again ###########"
mongosh --host mongo1 -u root -p root <<EOF
rs.status()
EOF
echo "########### Stopping TEMP instance ###########"
mongod --shutdown
This is what gh actions logs when bootstrapping the service:
mongo-bootstrapper | MongoNetworkError: getaddrinfo ENOTFOUND mongo1
mongo-bootstrapper | ########### Sleeping ###########
mongo-bootstrapper | Current Mongosh Log ID: 63fe0727c38672c5fda58e82
mongo-bootstrapper | Connecting to: mongodb://<credentials>@mongo1:27017/?directConnection=true&appName=mongosh+1.6.2
See the github workflow:
name: CI & CD
on:
push:
branches:
- dev
- staging
- main
jobs:
cintegration:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- name: Run tests
run: ./.devcontainer/tests/runTests.sh
- name: Install dependencies
run: npm install
- name: Build the app
run: npm run build
To automate the steps, I have a runTests.sh script:
#!/bin/bash
docker-compose -f docker-compose.test.yml up -d
# Wait for the replica set to be ready
mongo_bootstrapper_running=true
until [ "$mongo_bootstrapper_running" == "false" ]; do
echo "Waiting for MongoDB replica set to be ready..."
sleep 5
mongo_bootstrapper_running=$(docker ps --filter "name=mongo-bootstrapper" -q | wc -l | grep -q "0" && echo false || echo true)
done
# MongoDB replica set is ready, run the tests
echo "MongoDB replica set is ready, run the tests"
# Push database schema
docker-compose -f ./docker-compose.test.yml run app npx prisma db push
docker-compose -f ./docker-compose.test.yml run app npm run test:ci
test_exit_code=$?
# Stop the local MongoDB replica set
echo "Stopping the local MongoDB replica set."
docker-compose -f docker-compose.test.yml down
exit $test_exit_code
Can someone explain why docker networking isn't working on github actions and is there a way to solve this?
| |
doc_3805
|
What I'm trying to do is after it unanchored it will respawn after 10 seconds and repeat the process.
A: You can throw the Baseplate into ServerStorage for it to be moved back to the Workspace.
local part = game.Workspace.Baseplate
-- Remove baseplate:
part.Parent = game.ServerStorage
-- Then to put baseplate back:
part.Parent = game.Workspace
Full code
local part = game.Workspace.Baseplate
wait(5)
for i = 0, 0.9, 0.1 do
part.Transparency = i
wait(1)
end
part.Transparency = 1
part.Parent = game.ServerStorage
wait(10)
part.Parent = game.Workspace
for i = 0.9, 0, -0.1 do
part.Transparency = i
wait(1)
end
Please note that in the statement to unanchor the part was removed; it is unnecessary and causes problems.
A: First of all let's write your code like a programmer. You don't have to hardcode those transparency values.
local part = game.Workspace.Baseplate
wait(5)
for i = 0.1, 0.9, 0,1 do
part.transparency = i
wait(1)
end
part.transparency = 1
part.Anchored = false
wait(10)
I'm no Roblox expert but spawning parts seems to be just a matter of setting a part's parent. So to respawn something it is probably sufficient to remove and set the Parent property of part and wait in between.
Try something like
Baseplate.Parent = nil
wait(1)
Baseplate.Parent = game.Workspace
| |
doc_3806
|
Pasang = [0, 4, 4, 5, 1, 7, 6, 7, 5, 7, 4, 9, 0, 10, 1, 10,...., 23, 9, 23, 7, 23]
I count item from that list:
satuan = Counter(pasang)
then I get :
Counter({5: 10, 6: 7, 0: 5, 1: 5, 7: 5, 10: 4, 11: 4, 15: 4,...,14: 1, 21: 1})
I want to get key from counter, so i do this:
satu = satuan.keys()
and I get sorted list like this:
[0, 1, 2, 4, 5,...,21, 22, 23]
but I need an output like this (not sorted):
[5, 6, 0, 1,...,14, 21]
Sorry for my bad english.
A: You probably need:
[key for key, freq in c.most_common()]
where c is the Counter instance.
most_common will return pairs of keys and frequencies, in decreasing order of frequency. Then you extract the key part using a comprehension.
A: If you want to maintain the order then have a look at the Counter object you just created, it has elements sorted w.r.t to the frequency in decreasing order and you can also achieve the same behaviour by sorting the keys on frequency and setting the reverse flag to be True
import collections
Pasang = [0, 4, 4, 5, 1, 7, 6, 7, 5, 7, 4, 9, 0, 10, 1, 10, 23, 9, 23, 7, 23]
a = collections.Counter(Pasang)
keys = sorted(a.keys(), key = lambda x:a[x], reverse = True)
print a
print keys
>>> Counter({7: 4, 4: 3, 23: 3, 0: 2, 1: 2, 5: 2, 9: 2, 10: 2, 6: 1})
>>> [7, 4, 23, 0, 1, 5, 9, 10, 6]
| |
doc_3807
|
<add assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
I assume what has happened is that installed VS2010 has updated the GAC with version 10 of this component.
Problem is, when I publish the app to the live server, the app is broken precisely because it doesn't have version 10.0.0.0.
What is the quickest way to resolve this problem? I'm thinking there must be a way to either:
1) Update the GAC on the server with the latest version of the assembly (but what might that break?)
2) 'Undo' the change to the GAC on my dev machine to use 9.0.0.0 instead.
Or is there another option? Can anyone provide some advice on how to overcome this?
A: Both version 9 and 10 work with Visual Studio 2010, so make sure your project is still referencing version 9. The only reason you'll get that error when running the app is if you're referencing v10, but still have the v9 config.
A: the problem is in reference and using correct files
Reference the file it in your project, and set properties as copy local
this should solve your problem.
ps make sure you select correct version (10/9/8)
| |
doc_3808
|
const functions = require('firebase-functions')
function buildHtml (path) {
return HTML_BODY_WITH_path_BEING_CONSIDERED
}
export const rendering = functions.https.onRequest(function(req, res) {
const path = req.path
res.send(buildHtml(path))
})
When I rewrite every source to this function, I could obtain /colletion/1 as path then render the page, when I access https://MY-PROJECT.firebaseapp.com/collection/1.
What I can't figureout is how can I obtain the MY-PROJECT.firebaseapp.com part.
I fetched req.domain but it was null.
Any idea?
A: Since HTTPS functions are served by Express (and receive an express request object as a parameter, you'll want to use the request hostname in tandem with the request protocol to build a URL that may be helpful to the caller. These are both properties on the req parameter in your given code, which is an Express Request object.
| |
doc_3809
|
I have my git history now in a branch 'intermediate'. the git log of master is simply
$ git log
commit b00e1de5676690a8b8c303cd265185578842af9d (HEAD -> master, origin/master, origin/HEAD)
Author: My Name <my.name@mydomain.com>
Date: Tue Aug 18 18:46:38 2020 +0200
Initial empty repository
but if I do now
$ git checkout intermediate
$ git rebase master
i get the following:
$ git rebase master
First, rewinding head to replay your work on top of it...
Applying: commit message 1
Applying: commit message 2
Applying: commit message 3
Applying: commit message 4
Applying: commit message 5
Applying: commit message 6
Applying: commit message 7
.git/rebase-apply/patch:101: trailing whitespace.
.git/rebase-apply/patch:326: trailing whitespace.
.git/rebase-apply/patch:328: trailing whitespace.
.git/rebase-apply/patch:332: trailing whitespace.
.git/rebase-apply/patch:335: trailing whitespace.
warning: squelched 21 whitespace errors
warning: 26 lines add whitespace errors.
Using index info to reconstruct a base tree...
M mypath/myfile.txt
Falling back to patching base and 3-way merge...
Auto-merging mypath/myfile.txt
CONFLICT (content): Merge conflict in mypath/myfile.txt
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch' to see the failed patch
Patch failed at 0007 Cleanup refactoring and resolve compilation errors.
Resolve all conflicts manually, mark them as resolved with
"git add/rm <conflicted_files>", then run "git rebase --continue".
You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".
if I understand git rebase correctly, what it does is start at the commit upon which to rebase and then apply commit by commit on top of this. But if this is an empty commit, shouldn't it be impossible to get mergeconflicts?
A: It's not really clear to me what you mean by empty commit (Git normally refuses to make something that it calls an "empty commit", but what it means is a commit that is no different than its parent: such a commit isn't actually empty, it's just identical in terms of the file snapshot). However, any rebase operation can result in merge conflicts.
if I understand git rebase correctly, what it does is start at the commit upon which to rebase and then apply commit by commit on top of this.
That is, more or less, what rebase does. But consider what happens if you have a repository in which we have these commits:
C--D
/ \
A--B G <-- branch1
\ /
E--F
H <-- branch2
where commit H has no files at all: it's a snapshot of Git's empty tree. If we now run:
git checkout branch1
git rebase branch2
Git will list out all the commits that it should copy, commit-by-commit, that are reachable from the current branch (branch1) but not from the target commit (branch2 = commit H). So this is commits A, then B, then either of C-then-D or E-then-F, then whichever two of the C-D / E-F pair it skipped earlier. Commit G, being a merge commit, gets dropped entirely.
If commit G had merge conflicts that had to be resolved, these merge conflicts will definitely occur again during the rebase operation. These could be the merge conflicts you are seeing.
Without seeing the commit graph and each commit's snapshot, it is hard to say specifically why you got the conflicts you got, but the theory of operation for Git shows that rebase can indeed have conflicts as a result purely of the source commits, without regard for the --onto target (H in this case).
| |
doc_3810
|
I have the following code that works fine in the SDK server but fails in production. Is what I am doing even correct? If yes what could be wrong, any ideas how to troubleshoot it?
# Code earlier writes the file bs_file_name. This works fine because I can see the file
# in the Cloud Console.
bk = blobstore.create_gs_key( "/gs" + bs_file_name)
assert(bk)
if not isinstance(bk,blobstore.BlobKey):
bk = blobstore.BlobKey(bk)
assert isinstance(bk,blobstore.BlobKey)
# next line fails here in production only
assert(blobstore.get(bk)) # <----------- blobstore.get(bk) returns None
A: Unfortunately, as per the documentation, you can't get a BlobInfo object for GCS files.
https://developers.google.com/appengine/docs/python/blobstore/#Python_Using_the_Blobstore_API_with_Google_Cloud_Storage
Note: Once you obtain a blobKey for the GCS object, you can pass it around, serialize it, and otherwise use it interchangeably anywhere you can use a blobKey for objects stored in Blobstore. This allows for usage where an app stores some data in blobstore and some in GCS, but treats the data otherwise identically by the rest of the app. (However, BlobInfo objects are currently not available for GCS objects.)
A: I encountered this exact same issue today and it feels very much like a bug within the blobstore api when using google cloud storage.
Rather than leveraging the blobstore api I made use of the google cloud storage client library. The library can be downloaded here: https://developers.google.com/appengine/docs/python/googlecloudstorageclient/download
To access a file on GCS:
import cloudstorage as gcs
with gcs.open(GCSFileName) as f:
blob_content = f.read()
print blob_content
A: It sucks that GAE has different behaviours when using blobInfo in local mode or the production environment, it took me a while to find out that, but a easy solution is that:
You can use a blobReader to access the data when you have the blob_key.
def getBlob(blob_key):
logging.info('getting blob('+blob_key+')')
with blobstore.BlobReader(blob_key) as f:
data_list = []
chunk = f.read(1000)
while chunk != "":
data_list.append(chunk)
chunk = f.read(1000)
data = "".join(data_list)
return data`
https://developers.google.com/appengine/docs/python/blobstore/blobreaderclass
| |
doc_3811
|
select
replace(AUDITOR_COMMENTS,char(13),'')
from csa_sli_all.T_CONV_QUOTE
When I put char(13) in quote 'char(13)' error goes but it will not do as desired.
I think I cannot include char(13) in quotes .
I am using Oracle Database 10g Release 10.2.0.1.0 - 64bit Production
A: The function isn't char it's chr try calling:
select
replace(AUDITOR_COMMENTS,chr(13),'')
from csa_sli_all.T_CONV_QUOTE
A: try chr(13) instead of char(13) and see if it works
A: replace(your_data, chr(13), '')
try this as @sebastian said
select
replace(AUDITOR_COMMENTS,chr(13),'')
from csa_sli_all.T_CONV_QUOTE
A: Try this :
REPLACE(col_name, CHR(13) + CHR(10), '')
or
REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )
| |
doc_3812
|
<script setup lang="ts">
const props = defineProps<{
items: Record<string, unknown>[],
selected: Record<string, unknown> | null
field: string
}>()
const emit = defineEmits<{
(e: 'update:selected', value: Record<string, unknown> | null): void
}>()
</script>
<template>
<div v-for="(item,idx) in items" :key="idx">
<div
@click="emit('update:selected',item)"
style="cursor: pointer">
{{ item[field] }}
</div>
</div>
</template>
Let's try to use it by passing a list of employees.
<script setup lang='ts'>
import MyList from './MyList.vue'
import {Ref, ref} from "vue";
interface Employee {
name: string;
age: number;
}
const employees: Employee[] = [
{name: 'Mike', age: 34},
{name: 'Kate', age: 19},
{name: 'Den', age: 54},
]
const selectedEmployee=ref<Employee | null>(null)
</script>
<template>
Age: {{selectedEmployee?selectedEmployee.age:'not selected'}}
<MyList :items="employees" v-model:selected="selectedEmployee" field="name"/>
</template>
Everything is working. But, if you do a build, an error occurs TS2322: “Type 'Employee' is not assignable to type 'Record<string, unknown>'".
A generic component would be the solution. But it's not there yet.
What is the best way to solve this problem?
vue playground
A: It is possible to create a method.
export const wrapSelected = <T>(value: Ref<T | null>) => {
return computed<Record<string, unknown> | null>({
get: () => value.value as unknown as (Record<string, unknown> | null),
set: (val: Record<string, unknown> | null) => {
value.value = val as unknown as T | null
}
})
}
App.vue
...
const wrapperSelected=wrapSelected(selectedEmployee)
</script>
<template>
Age: {{ selectedEmployee ? selectedEmployee?.age : 'not selected' }}
<my-list :items="wrapperItems" v-model:selected="wrapperSelected" field-name="name"/>
</template>
Though it's not very aesthetically pleasing. It's better than good old any?
A: I would use any instead of unknown. So for your MyList component:
const props = defineProps<{
items: Record<string, any>[],
selected: Record<string, any> | null
field: string
}>()
const emit = defineEmits<{
(e: 'update:selected', value: Record<string, any> | null): void
}>()
Here is a good discussion on the differences between any and unknown. Unless you need unknown for a specific reason, any might solve your problem.
'unknown' vs. 'any'
| |
doc_3813
|
A: First we have to create a requirements file and store it in directory in AzureML workspace directory.
myenv = Environment.from_pip_requirements(name="myenv", file_path="path-to-pip-requirements-file")
Then, we can use it for our experiment.
For example:
src = ScriptRunConfig(source_directory=".",
script="example.py",
compute_target="local",
environment=myenv)
run = myexp.submit(config=src)
run.wait_for_completion(show_output=True)
| |
doc_3814
|
I have tested the actual loop and obfuscate process and it works fine, I have also successfully tested the beginning of the script up to just before the loop, which creates OBFUS_TABLE and inserts the values into it. The problem comes when it tries to do the two together, failing on a "table or view does not exist" error when it attempts to execute the loop. Snippet of code below:
alter session set current_schema = SYSTEM;
DECLARE
t_count NUMBER;
t_count2 NUMBER;
p_tname VARCHAR2(100);
p_cname VARCHAR2(100);
l_datatype VARCHAR2(100);
BEGIN
SELECT COUNT(*) INTO t_count FROM all_tables WHERE table_name = 'OBFUS_TABLE';
SELECT COUNT(*) INTO t_count2 FROM all_tables WHERE table_name = 'OBFUS_LOG';
IF (t_count = 0)
THEN
EXECUTE immediate 'create table OBFUS_TABLE( TABLENAME VARCHAR2(200 BYTE), COLUMNNAME VARCHAR2(200 BYTE), DATA_TYPE VARCHAR2(20 BYTE), ACTIVE VARCHAR(1 BYTE) )';
END IF;
IF (t_count2 = 0)
THEN
EXECUTE immediate 'CREATE TABLE OBFUS_LOG (SRC_TABLENAME VARCHAR2(50 BYTE), SRC_TABLE_ROW_COUNT NUMBER, COPY_TABLENAME VARCHAR2(50 BYTE), COPY_TABLE_ROW_COUNT NUMBER, UPDATE_DATE TIMESTAMP(6) )';
END IF;
EXECUTE immediate 'INSERT INTO OBFUS_TABLE VALUES (''OB_MYTABLE1'',''SRNM'',''NAME'',''Y'')';
COMMIT;
FOR x IN (SELECT TABLENAME, COLUMNNAME, DATA_TYPE FROM OBFUS_TABLE WHERE ACTIVE='Y')
LOOP
p_tname := upper(x.TABLENAME); -- Table name
p_cname := upper(x.COLUMNNAME); -- Column name
l_datatype := upper(x.DATA_TYPE);
dbms_output.put_line('Started: '||TO_CHAR(sysdate,'YYYY/MM/DD HH24:MI:SS'));
END LOOP;
END;
NB: There are actually around 30 insert statements in exactly the same format as the one above. I removed them since they would pad out this post too much, but I have manually checked every insert statement and they're all correct.
I assume the problem is that SQL Developer does a "sanity check" on the code before running, and looks ahead to the loop and realises OBFUS_TABLE doesn't exist, but fails to understand that by the time that piece of code is executed, OBFUS_TABLE will definitely exist.
Is there a way to get around this? I thought maybe a GOTO statement might help but no luck. I would rather keep the solution as one single script rather than two seperate ones, but if the only way around this is to do so then I could do that I suppose. Any help would be much appreciated.
A: You will need to use dynamic SQL for the select like this:
declare
...
l_tname varchar2(100);
l_cname varchar2(100);
l_datatype varchar2(100);
rc sys_refcursor;
begin
...
open rc for 'SELECT TABLENAME, COLUMNNAME, DATA_TYPE
FROM OBFUS_TABLE WHERE ACTIVE=''Y''';
loop
fetch rc into l_tname, l_cname, l_datatype;
exit when rc%notfound;
dbms_output.put_line('Started: '||TO_CHAR(sysdate,'YYYY/MM/DD HH24:MI:SS'));
end loop;
close rc;
end;
| |
doc_3815
|
After closing the window, and recreating 1:1 similar window the events will not fire. The same happens if I .update() the panel and re-run my function - the events fail to fire. Why is this?
I can still see elements being found, and apparently some events must be registered, but my clicks can't be captured by the debug code, or the receiving function anymore.
addEvents: function(win) {
// The Window
var ow = win;
// Using this debug trick I can see that on the second time the events wont fire
// -- nothing gets printed to console
Ext.util.Observable.capture(ow, function(){
console.log(arguments);
});
// Will search for elements, finds elements that have class myclass
// In my case the elements are just ordinary html tags in the visible content
// area of the panel.
var elems = ow.down('panel').getEl().select(".myclass").elements;
Ext.Array.forEach(elems, function (item, index, allItems) {
// We need Ext DOM element to be able to attach stuff to it
var elem = new Ext.dom.Element(item);
elem.on ('click', function (evt, el, o) {
ow.fireEvent('myevent', ow, elem);
});
});
}
I suspected at first that I have to actually unregister the previous events and destroy the window, so I tried adding this to the close of the window:
window.down('panel').destroy();
window.destroy();
However it seems I have some other problem I really am unable to understand.
A: This is a very JQuery-ish way to add events. You are dealing with components and should add event listeners on components. If you need to delegate events down to html elements then you need to set a single event listener on the Component encapsulating the elements and add delegate config to the actual html elements.
Here are some resources:
Explain ExtJS 4 event handling
Event delegation explained:
http://www.sencha.com/blog/event-delegation-in-sencha-touch (applies to extjs just as well)
More on Listeners with extjs: https://stackoverflow.com/a/8733338/834424
| |
doc_3816
|
id
coins
value
user_id
created
UUID1
25
0
UUID42
datetime
UUID2
-25
0
UUID42
datetime
UUID3
50
599
UUID42
datetime
UUID4
25
0
UUID13
datetime
UUID5
25
399
UUID42
datetime
UUID6
100
1099
UUID42
datetime
UUID7
25
299
UUID42
datetime
Using this table, say that user UUID42 is spending 100 coins. I need to get back records UUID3, UUID5, and UUID6 because the SUM(coins) >= 100, but not record UUID7 since the other 3 already fulfill the criteria. Once I have all of those records back, I'll be able to sum the value and do other processing, but I'll need to individual records returned because I need to know their individual values since it's not a simple SUM(value).
Here's where I'm at currently (as provided by Stu, but slightly modified).
with rt as (
select *,
sum(coins) over(partition by user_id order by created) running
from t
), valid as (
select *,
case when lag(running) over(partition by user_id order by created)<running then 1 else 0 end cons
from rt
where user_id = 'UUID42' and running - 100 < 100
)
select id, coins, value
from valid
where cons = 1
The issue I'm having from this query is that if the user spends 49 coins, then only record UUID3 needs to be returned because the 50 coins in that record cover the 49 needed, but I'm getting both 3 & 5 returned. Then, if the user is only spending 1 coin, again only record UUID3 should be returned, but nothing is returned.
I'm using postgres, but if anyone knows how it can be done in another engine, I'm sure I can get it close.
EDIT: The answer @Stu gave is super close, and gives me the answer to my original question, but it turns out that it only really works for that one case. I've updated my question to better clarify what I'm looking for.
A: Here's a possible solution that should work in most databases inc Postgres. It uses a couple of consecutive CTEs to first calculate the running total and then to indicate which values are consecutive, and finally taking the overall sum of qualifying rows.
with rt as (
select *,
Sum(coins) over(partition by user_id order by id) running
from t
), valid as (
select *,
case when lag(running) over(partition by user_id order by id)<running
and lag(running) over(partition by user_id order by id)<=100
then 1 else 0 end cons
from rt
)
select Sum(value)
from valid
where cons=1
DB<>Fiddle
A: Try this:
select sum(value) from ledger
where user_id=42 and id<=
(
with temp1 AS(
select t.id, t.value, sum(t.coins) over(order by t.id) from ledger t
where t.user_id=42
),
temp2 as (
select t1.id, t1.value from temp1 t1
where t1.sum-100>0 limit 1
)
select id from temp2
)
The result:
| |
doc_3817
|
This is Attributes Model .
const mongoose = require('mongoose');
const Schema = mongoose.Schema ;
const attributeSchema = new Schema({
Name : {
type: String,
required : true
},
Type : {
type: String,
required : true
},
ItemTypes : [{
type: mongoose.Schema.Types.ObjectId, ref:'ItemTypes',
required : true
}],
Code : {
type: String,
required : true
},
isRequired : {
type: Boolean,
required : true
},
CreatedUser:{
type: mongoose.Schema.Types.ObjectId , ref:'Users',
required:true
},
UpdatedUser:{
type: mongoose.Schema.Types.ObjectId , ref:'Users',
required:true
},
CreatedOn : {
type: Date,
default: Date.now
},
UpdatedOn : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('Attributes',attributeSchema);
And This is Item Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema ;
const itemSchema = new Schema({
Name : {
type: String,
required : true
},
Code : {
type: String,
required : true
},
ItemType : {
type: mongoose.Schema.Types.ObjectId , ref : "ItemTypes",
required : true
},
Family : {
type: String,
required : true
},
Attributes : [{
type: mongoose.Schema.Types.ObjectId , ref: "Attributes",
required : true
}],
CreatedUser:{
type: mongoose.Schema.Types.ObjectId , ref:'Users',
required:true
},
UpdatedUser:{
type: mongoose.Schema.Types.ObjectId , ref:'Users',
required:true
},
CreatedOn : {
type: Date,
default: Date.now
},
UpdatedOn : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('Items',itemSchema);
And this is ItemValue Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema ;
const itemValueSchema = new Schema({
Item : {
type: mongoose.Schema.Types.ObjectId, ref:'Items',
required : true
},
Attribute : {
type: mongoose.Schema.Types.ObjectId, ref:'Attributes',
required : true
},
Value : {
type: String,
required : true
},
CreatedUser:{
type: mongoose.Schema.Types.ObjectId , ref:'Users',
required:true
},
UpdatedUser:{
type: mongoose.Schema.Types.ObjectId , ref:'Users',
required:true
},
CreatedOn : {
type: Date,
default: Date.now
},
UpdatedOn : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('ItemValues',itemValueSchema);
So I've a Get Method for Get Item . But when I get item, I want to show this item's Attributes and This Attributes Values from ItemValues table. This is my Get Method
router.get('/test2', async (req, res) => {
itemModel.aggregate(
[
{
$match: { Code: 'UmitHesapCode11223' }
},
{
$lookup:
{
from: "itemvalues",
localField: "_id",
foreignField: "Item",
as: "ItemValues"
},
},
{
$group: {
_id: "$_id"
}
}
]
)
.exec((err, result) => {
if (err) return res.status(400).send(err)
res.status(200).send(result)
})
})
When I call this method , This Response is returning =>
[
{
"_id": "631cbdd8a63c12fd5f4638be",
"Name": "UmitHesap",
"Code": "UmitHesapCode11223",
"Family": "AccountFamily",
"UpdatedUser": "631c78a8067dacf22960edff",
"CreatedOn": "2022-09-10T16:39:52.842Z",
"UpdatedOn": "2022-09-10T16:39:52.842Z",
"ItemValues": [
{
"Attribute": "631ca8dcad85970ea70869b4",
"Value": "Umit"
},
{
"Attribute": "631ca8e7ad85970ea70869b7",
"Value": "Camurcuk"
},
{
"Attribute": "631ca8f6ad85970ea70869ba",
"Value": "BOLU"
},
{
"Attribute": "631ca902ad85970ea70869bd",
"Value": "12/09/1997"
},
{
"Attribute": "631ca910ad85970ea70869c0",
"Value": "905301237997"
}
]
},
{
"_id": "631cbe0d7b97c716d5e9cdd9",
"Name": "UmitHesap",
"Code": "UmitHesapCode",
"Family": "AccountFamily",
"UpdatedUser": "631c78a8067dacf22960edff",
"CreatedOn": "2022-09-10T16:40:45.306Z",
"UpdatedOn": "2022-09-10T16:40:45.306Z",
"ItemValues": [
{
"Attribute": "631ca8dcad85970ea70869b4",
"Value": "Umit"
},
{
"Attribute": "631ca8e7ad85970ea70869b7",
"Value": "Camurcuk"
},
{
"Attribute": "631ca8f6ad85970ea70869ba",
"Value": "BOLU"
},
{
"Attribute": "631ca902ad85970ea70869bd",
"Value": "12/09/1997"
},
{
"Attribute": "631ca910ad85970ea70869c0",
"Value": "905301237997"
}
]
},
{
"_id": "6325d9ff37d2c77e60632d63",
"Name": "Product",
"Code": "umitProduct",
"Family": "testProduct",
"UpdatedUser": "631c78a8067dacf22960edff",
"CreatedOn": "2022-09-17T14:30:23.183Z",
"UpdatedOn": "2022-09-17T14:30:23.183Z",
"ItemValues": [
{
"Attribute": "631ca927ad85970ea70869c3",
"Value": "MacStand"
},
{
"Attribute": "631ca92ead85970ea70869c6",
"Value": "13323TL"
},
{
"Attribute": "631ca937ad85970ea70869c9",
"Value": "1500"
},
{
"Attribute": "631ca941ad85970ea70869cc",
"Value": "300TL"
}
]
}
]
So in This response, I want to Populate ItemValues.Attribute. Which I mean this.
how I can fix this ? I tried so much way but I can't fix it.
| |
doc_3818
|
But I am getting an error that System.Threading.Thread.CurrentThread.CurrentUICulture does not exist.
How to use CurrentUICulture?
| |
doc_3819
|
I have already figured out how to send email in perl. I just need to figure out how to read in the file and put it as the text of the email.
A: You can just slurp up the contents of the file like so and use it as you would any other string:
open my $fh, '<', 'file.txt' or die "Ouch: $!\n";
my $text = do {
local $/;
<$fh>
};
close $fh or die "Ugh: $!\n";
print $text,"\n";
A: What are you using to send the email? I use MIME::Lite. and you can use that to just attach the file.
Otherwise you'd just open the log, read it in line at a time (or use File::Slurp) and dump the contents of the file into the email.
A: I use MIME::Lite, this is the cron script I use for my nightly backups:
$msg = MIME::Lite->new(
From => 'backup-bot@mydomain.com',
To => 'test@example.com',
Bcc => 'test@example.com',
Subject => "DB.tgz Nightly MySQL backup!",
Type => "text/plain",
Data => "Your backup sir.");
$msg->attach(Type=> "application/x-tar",
Path =>"/var/some/folder/DB_Dump/DB.tgz",
Filename =>"DB.tgz");
$msg->send;
A: You can open a file in Perl in several ways.
What you need to know is described in perl -f open
Here is an example:
my $file = 'filename.txt';
open my $ifh, '<', $file
or die "Cannot open '$file' for reading: $!";
local $/ = '';
my $contents = <$ifh>;
close( $ifh );
Now just email $contents in your email.
I'm not sure how you are sending email, but the way I use frequently is as follows:
# Install these modules from CPAN:
use Mail::Sendmail;
use MIME::Base64;
sendmail(
To => 'you@your-domain.com',
From => 'Friendly Name <friendly@server.com>',
'reply-to' => 'no-reply@server.com',
Subject => 'That file you wanted',
# If you are sending an HTML file, use 'text/html' instead of 'text/plain':
'content-type' => 'text/plain',
'content-transfer-encoding' => 'base64',
Message => encode_base64( $contents ),
);
A: I think attachments are the way to go given what you described and others have already contributed about this but if you have a requirement or need to read a file and parse it into a content of email (without attachments) via Perl here is the way to do it:
#!/usr/bin/perl
# this program will read a file and parse it into an email
use Net::SMTP;
#you need to change the four below line
my $smtp = Net::SMTP->new("your_mail_server_goes_here");
my $from_email = "your_from_email";
my $to_email = "yuor_to_email";
my $file="the_full_path_to_your_file_including_file_name";
my $header = "your_subject_here";
$smtp->mail($from_email);
#Send the server the 'Mail To' address.
$smtp->to($to_email);
#Start the message.
$smtp->data();
$smtp->datasend("From: $from_email\n");
$smtp->datasend("To: $to_email\n");
$smtp->datasend("Subject: $header \n");
$smtp->datasend("\n");
#make sure file exists
if (-e $file) {
$smtp->datasend("testing \n\n");
#read the file one line at a time
open( RFILE, "<$file" )||print "could not open file";
while (my $line = <RFILE>){
$smtp->datasend("$line");
}
close(RFILE) || print "could not close file";
}
else {
print "did not find the report $file ";
exit 1;
#End the message.
$smtp->dataend();
#Close the connection to your server.
$smtp->quit();
#Send the MAIL command to the server.
$smtp->mail("$from_email");
A: We can use mail::outlook instead of mime::lite too:
#open file from local machine
open my $fh, '<', "C:\\SDB_Automation\\sdb_dump.txt" or die "Ouch: $!\n";
my $text1 = do {
local $/;
<$fh>
};
close $fh or die "Ugh: $!\n";
print $text1,"\n";
#create the object
use Mail::Outlook;
my $outlook = new Mail::Outlook();
# start with a folder
my $outlook = new Mail::Outlook('Inbox');
# use the Win32::OLE::Const definitions
use Mail::Outlook;
use Win32::OLE::Const 'Microsoft Outlook';
my $outlook = new Mail::Outlook(olInbox);
# get/set the current folder
my $folder = $outlook->folder();
my $folder = $outlook->folder('Inbox');
# get the first/last/next/previous message
my $message = $folder->first();
$message = $folder->next();
$message = $folder->last();
$message = $folder->previous();
# read the attributes of the current message
my $text = $message->From();
$text = $message->To();
$text = $message->Cc();
$text = $message->Bcc();
$text = $message->Subject();
$text = $message->Body();
my @list = $message->Attach();
# use Outlook to display the current message
$message->display;
# create a message for sending
my $message = $outlook->create();
$message->To('xyz@.com');
$message->Subject('boom boom boom');
$message->Body("$text1");
$message->Attach('C:\SDB_Automation\sdb_dump.txt');
$message->send;
| |
doc_3820
|
import time
counter = 0
def countup():
while counter < 10:
counter += 1
print counter
time.sleep (1);
countdown();
def countdown():
while counter > 0:
counter -= 1
print counter
time.sleep (1);
countup();
countup();
And the error I am getting is:
UnboundLocalError: local variable 'counter' referenced before
assignment
Does this mean that I need to define a counter variable inside each function? I have tried this, but it didn't work. I also tried a global variable at the start using: global counter = 0 but that didn't work either.
Apologies foor the noob question, I'm just a guy prodding a bit of python code.
| |
doc_3821
|
Here's an example:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Car");
query.orderByDescending(URLEncoder.encode("_created_at"));
query.whereWithinMiles("location", currentloc, 100 );
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
My request type generated looks like:
Url : http://www.myapp.com/parse/classes/car
Method : POST
Headers : {X-Parse-OS-Version=6.0, Content-Type=application/json, X-Parse-App-Build-Version=1, X-Parse-Client-Key=, X-Parse-Installation-Id=a4be05643-0289-442b-8ab8-8a1beb30d016, X-Parse-App-Display-Version=1.0, X-Parse-Client-Version=a1.13.1, Content-Length=55, User-Agent=Parse Android SDK 1.13.1 (in.athenasoft.glimpse/1) API Level 23, X-Parse-Application-Id=GlimpseAppId, X-Parse-Session-Token=r:8486b0ada48b7asdfec58dc91e002a61}
Body : { "where": "{\"UserId\":\"lFqQpYcH3X\"}", "_method": "GET" }
The above query works well for the Parse Server but not for AWS.
My log looks like this:
01-24 17:14:07.952 7740-8352/com.package.test I/ParseLogInterceptor: Request-Id : 4
01-24 17:14:07.952 7740-8352/com.package.test I/ParseLogInterceptor: Url : http://myserver.com/parse/classes/car
01-24 17:14:07.952 7740-8352/com.package.test I/ParseLogInterceptor: Method : POST
01-24 17:14:07.952 7740-8352/com.package.test I/ParseLogInterceptor: Headers : {X-Parse-OS-Version=6.0, Content-Type=application/json, X-Parse-App-Build-Version=1, X-Parse-Client-Key=, X-Parse-Installation-Id=a4be0316-0289-442b-8ab8-8a1beb30d016, X-Parse-App-Display-Version=1.0, X-Parse-Client-Version=a1.13.1, Content-Length=17, User-Agent=Parse Android SDK 1.13.1 (com.package.test/1) API Level 23, X-Parse-Application-Id=myappAppId, X-Parse-Session-Token=r:8486b0ada48b7971aec58dc91e002a61}
01-24 17:14:07.952 7740-8352/com.package.test I/ParseLogInterceptor: Body : {
"_method": "GET"
}
01-24 17:14:07.952 7740-8352/com.package.test I/ParseLogInterceptor: --------------
01-24 17:14:07.953 7740-8352/com.package.test I/System.out: [CDS][DNS] getAllByNameImpl netId = 0
01-24 17:14:07.954 7740-8352/com.package.test D/libc-netbsd: [getaddrinfo]: hostname=myserver.com; servname=(null); netid=0; mark=0
01-24 17:14:07.954 7740-8352/com.package.test D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
01-24 17:14:07.954 7740-8352/com.package.test D/libc-netbsd: [getaddrinfo]: hostname=myserver.com; servname=(null); netid=0; mark=0
01-24 17:14:07.954 7740-8352/com.package.test D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
01-24 17:14:07.959 7740-8352/com.package.test D/libc-netbsd: getaddrinfo: myserver.com get result from proxy gai_error = 0
01-24 17:14:07.960 7740-8352/com.package.test I/System.out: [CDS]rx timeout:10000
01-24 17:14:07.960 7740-8352/com.package.test I/System.out: [socket][5] connection myserver.com/35.167.7.84:80;LocalPort=48919(10000)
01-24 17:14:07.961 7740-8352/com.package.test I/System.out: [CDS]connect[myserver.com/35.167.7.84:80] tm:10
01-24 17:14:08.430 7740-8352/com.package.test I/System.out: [socket][/192.168.1.5:48919] connected
01-24 17:14:08.430 7740-8352/com.package.test I/System.out: [CDS]rx timeout:10000
01-24 17:14:08.430 7740-8352/com.package.test I/System.out: [CDS]SO_SND_TIMEOUT:0
01-24 17:14:08.431 7740-8352/com.package.test I/System.out: [OkHttp] sendRequest<<
01-24 17:14:08.947 7740-8352/com.package.test I/System.out: close [socket][/192.168.1.5:48919]
01-24 17:14:08.951 7740-7786/com.package.test E/Error: bad json response
01-24 17:14:08.951 7740-7786/com.package.test W/System.err: com.parse.ParseRequest$ParseRequestException: bad json response
01-24 17:14:08.952 7740-7786/com.package.test W/System.err: at com.parse.ParseRequest.newTemporaryException(ParseRequest.java:290)
01-24 17:14:08.954 7740-8370/com.package.test I/ParseLogInterceptor: Type : Response
01-24 17:14:08.954 7740-8370/com.package.test I/ParseLogInterceptor: Request-Id : 4
01-24 17:14:08.954 7740-8370/com.package.test I/ParseLogInterceptor: Status-Code : 200
01-24 17:14:08.954 7740-8370/com.package.test I/ParseLogInterceptor: Reason-Phrase : OK
01-24 17:14:08.955 7740-8370/com.package.test I/ParseLogInterceptor: Headers : {etag=W/"90c-jRFsH92iLnK0S38dRq90lQ", content-encoding=gzip, content-type=application/json; charset=utf-8, date=Tue, 24 Jan 2017 11:44:08 GMT, X-Android-Selected-Protocol=http/1.1, X-Android-Response-Source=NETWORK 200, connection=close, X-Android-Sent-Millis=1485258248430, vary=X-HTTP-Method-Override, Accept-Encoding, access-control-allow-headers=X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, Content-Type, transfer-encoding=chunked, access-control-allow-methods=GET,PUT,POST,DELETE,OPTIONS, x-powered-by=Express, access-control-allow-origin=*, X-Android-Received-Millis=1485258248938}
01-24 17:14:08.955 7740-8370/com.package.test I/ParseLogInterceptor: Body : { SOME HTML Returnered
}
01-24 17:14:08.955 7740-8370/com.package.test I/ParseLogInterceptor: --------------
01-24 17:14:08.952 7740-7786/com.package.test W/System.err: at com.parse.ParseRESTCommand.onResponseAsync(ParseRESTCommand.java:308)
01-24 17:14:08.956 7740-7786/com.package.test W/System.err: at com.parse.ParseRequest$3.then(ParseRequest.java:137)
01-24 17:14:08.956 7740-7786/com.package.test W/System.err: at com.parse.ParseRequest$3.then(ParseRequest.java:133)
01-24 17:14:08.956 7740-7786/com.package.test W/System.err: at bolts.Task$15.run(Task.java:917)
01-24 17:14:08.956 7740-7786/com.package.test W/System.err: at bolts.BoltsExecutors$ImmediateExecutor.execute(BoltsExecutors.java:105)
01-24 17:14:08.956 7740-7786/com.package.test W/System.err: at bolts.Task.completeAfterTask(Task.java:908)
01-24 17:14:08.956 7740-7786/com.package.test W/System.err: at bolts.Task.continueWithTask(Task.java:715)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at bolts.Task.continueWithTask(Task.java:726)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at bolts.Task$13.then(Task.java:818)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at bolts.Task$13.then(Task.java:806)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at bolts.Task$15.run(Task.java:917)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at java.lang.Thread.run(Thread.java:818)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: Caused by: org.json.JSONException: Value �������������ך�*���W�ӵ�ҋ�� of type java.lang.String cannot be converted to JSONObject
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: at com.parse.ParseRESTCommand.onResponseAsync(ParseRESTCommand.java:298)
01-24 17:14:08.957 7740-7786/com.package.test W/System.err: ... 13 more
01-24 17:14:08.976 7740-8373/com.package.test I/ParseLogInterceptor: Type : Request
01-24 17:14:08.976 7740-8373/com.package.test I/ParseLogInterceptor: Request-Id : 5
01-24 17:14:08.977 7740-8373/com.package.test I/ParseLogInterceptor: Url : http://myserver.com/parse/classes/carUsers
01-24 17:14:08.977 7740-8373/com.package.test I/ParseLogInterceptor: Method : POST
01-24 17:14:08.977 7740-8373/com.package.test I/ParseLogInterceptor: Headers : {X-Parse-OS-Version=6.0, Content-Type=application/json, X-Parse-App-Build-Version=1, X-Parse-Client-Key=, X-Parse-Installation-Id=a4be0316-0289-442b-8ab8-8a1beb30d016, X-Parse-App-Display-Version=1.0, X-Parse-Client-Version=a1.13.1, Content-Length=135, User-Agent=Parse Android SDK 1.13.1 (com.package.test/1) API Level 23, X-Parse-Application-Id=myappAppId, X-Parse-Session-Token=r:8486b0ada48b7971aec58dc91e002a61}
01-24 17:14:08.977 7740-8373/com.package.test I/ParseLogInterceptor: Body : {
"include": "carId",
"where": "{\"UserId\":{\"__type\":\"Pointer\",\"className\":\"_User\",\"objectId\":\"lFqQpYcH3X\"}}",
"_method": "GET"
}
01-24 17:14:08.977 7740-8373/com.package.test I/ParseLogInterceptor: --------------
| |
doc_3822
|
Is there a way to confirm in a script, if an option is selected or not before submitting the whole Google Form?
A: To prevent submitting the form depending on the checkbox value, you can make the selection required, or you can validate the response.
To implement the branching logic in the forms, you must use the multiple choice control.
With Apps script you have much more validation options, but only after the form has been submitted.
| |
doc_3823
|
2 - https://i.stack.imgur.com/sRfIM.jpg
1- https://i.stack.imgur.com/EIhOy.jpg
The first image is the actual error I am facing. The second image is the junit code
part and when I try to debug 'step into' code line 118 I get the error . AssertEquals(u1, u2) is the not working part.
| |
doc_3824
|
A: You should use sudo python3 spam.py instead of python3 spam.py.
You can directly install the library using pip3 install PyAutoGUI and pip3 install keyboard.
| |
doc_3825
|
Here is the Snake Game class (main Class)
import java.io.File;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
@SuppressWarnings("unused")
public class SnakeGame {
public static int counter = -1;
public static int minutes = 0;
public static int extraSpace = 120;
public static void main(String[] args) {
// TODO Auto-generated method stub
GameFrame frame = new GameFrame();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
counter++;
if(counter == 60) {
counter = 0;
minutes++;
}
if(counter >= 10) {
extraSpace = 125;
} else {
extraSpace = 120;
}
}
}, new Date(), 1000);
}
public static void PlaySound(File Sound) { // Method that plays the sound
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Sound));
clip.start();
} catch (Exception e) {
}
}
}
Here is the JFrame class (The class that builds the frame of the game
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class GameFrame extends JFrame implements ActionListener {
public JButton resetButton;
GamePanel panel = new GamePanel();
GameFrame() {
Font F1 = new Font("Monospaced", Font.PLAIN, 12);
this.add(panel);
this.setTitle("Snake Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setLocationRelativeTo(null);
resetButton = new JButton();
resetButton.setText("Click to restart the Game!");
resetButton.setFont(F1);
resetButton.setForeground(Color.WHITE);
resetButton.setBackground(Color.BLACK);
resetButton.setSize(100, 50);
resetButton.setLocation(0, 200);
resetButton.addActionListener(this);
this.add(resetButton, BorderLayout.PAGE_END);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == resetButton) {
this.remove(panel); // Closes the Game
panel = new GamePanel(); // Makes a new a Game
this.add(panel); // Opens the game
SwingUtilities.updateComponentTreeUI(this); // Automatically updates the game frame
panel.requestFocusInWindow(); // Brings back focus to the game from the reset button
SnakeGame.counter = 0; // Resets Seconds timer when game resets
SnakeGame.minutes = 0; // Resets Minutes timer when game resets
}
}
}
and here is the GamePanel Class, here is where all the background proccess work, for example it triggers game over when the snake hits itself or bumps in the border
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Random;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JPanel;
import javax.swing.Timer;
@SuppressWarnings({"unused", "serial"})
public class GamePanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 625;
static final int UNIT_SIZE = 25;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
static final int DELAY = 75;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten = 0;
public static int highScore;
int appleX;
int appleY;
int timePassed = SnakeGame.counter;
int timePauseds = 0;
int timePausedm = 0;
int timeOvers;
int timeOverm;
String GamePause = "Game Over";
char direction = 'R';
boolean running = false;
boolean paused = false;
Timer timer;
Random random;
GamePanel() {
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
start();
}
public void start() {
newApple();
running = true;
timer = new Timer(DELAY,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void gameOver(Graphics g) {
g.setColor(Color.WHITE);
g.setFont(new Font("Ink Free", Font.PLAIN , 45));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score: " + applesEaten))/2, g.getFont().getSize());
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString(GamePause, (SCREEN_WIDTH - metrics2.stringWidth(GamePause))/2, SCREEN_HEIGHT/2);
while(applesEaten > highScore) {
highScore = applesEaten;
}
if(!running && GamePause == "Game Over") {
File NBSE = new File("C:\\Users\\2010\\My Files\\Desktop\\Java Projets\\NBSE.wav");
SnakeGame.PlaySound(NBSE);
}
g.setColor(Color.WHITE);
g.setFont(new Font("Ink Free", Font.PLAIN , 25));
FontMetrics metrics3 = getFontMetrics(g.getFont());
g.drawString("HighScore: " + highScore, (SCREEN_WIDTH - metrics3.stringWidth("HighScore: " + highScore))/2, 115);
if(!running && GamePause == "Game Over") {
timeOvers = SnakeGame.counter;
timeOverm = SnakeGame.minutes;
} else {
timeOvers = 0;
timeOverm = 0;
}
g.setColor(Color.WHITE);
g.setFont(new Font("Ink Free", Font.PLAIN, 25));
FontMetrics metrics4 = getFontMetrics(g.getFont());
g.drawString("Time Passed: " + timeOverm + ":" + String.format("%02d", timeOvers), (SCREEN_WIDTH - metrics4.stringWidth("Time Passed: " + timeOverm + ":" + String.format("%02d", timeOvers)))/2, 80);
}
public void draw(Graphics g) {
if(running) {
for(int i=0; i > SCREEN_HEIGHT/UNIT_SIZE; i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
g.setColor(Color.RED);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for(int i = 0; i < bodyParts; i++) {
if(i == 0) {
g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(new Color(45, 180, 0));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
g.setColor(Color.WHITE);
g.setFont(new Font("Ink Free", Font.PLAIN, 45));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: " + applesEaten))/2, g.getFont().getSize());
g.setColor(Color.WHITE);
g.setFont(new Font("Ink Free", Font.PLAIN, 25));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Time Passed: " + SnakeGame.minutes + ":" + String.format("%02d", SnakeGame.counter), (SCREEN_WIDTH - metrics1.stringWidth("Time Passed: " + SnakeGame.minutes + ":" + String.format("%02d", SnakeGame.counter)))/2, 80);
} else {
gameOver(g);
}
}
public void newApple() {
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)((SCREEN_HEIGHT - 2)/UNIT_SIZE))*UNIT_SIZE;
}
public void move() {
for(int i = bodyParts; i > 0; i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
File APSE = new File("C:\\Users\\2010\\My Files\\Desktop\\Java Projets\\APSE.wav");
SnakeGame.PlaySound(APSE);
newApple();
}
}
public void pause() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void resume() {
timer.stop();
}
public void checkCollisions() {
// Checks for collisions
for(int i = bodyParts; i > 0; i--) {
if((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
}
}
// Checks if head touches left border
if(x[0] < 0) {
running = false;
}
// Checks if head touches right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
// Checks if head touches top border
if(y[0] < 0) {
running = false;
}
// Checks if head touches bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
case KeyEvent.VK_A:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_D:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_W:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_S:
if(direction != 'U') {
direction = 'D';
}
break;
case KeyEvent.VK_ESCAPE:
if(running) {
running = false;
GamePause = "Paused";
timePauseds = SnakeGame.counter;
timePausedm = SnakeGame.minutes;
} else if(!running) {
running = true;
GamePause = "Game Over";
SnakeGame.counter = timePauseds;
SnakeGame.minutes = timePausedm;
}
break;
}
}
}
}
I hope I explained this good enough. If I didn't here let me try again. Basically I want to add a way so I can change the volume of the sounds in the game itself not the entire computer.
A: This link provided by @DevilsHnd and @tgdavies in the comments to your question, which makes use of the FloatControl class, is the main option if you are sticking with core Java. The Java audio tutorials cover it in the section titled Processing Audio with Controls.
This will work for most situations, but has two limitations that may or may not matter. One is that functionality being relied upon is external to Java. I think most computer systems do have a working MASTER_GAIN, but I don't know for sure.
The other drawback is that volume changes are limited as to the "granularity" of when they can occur in that they only occur at buffer-length intervals. If the buffer is 1/10th of a second long, for example 4410 frames at 44100 fps, at best you can get 10 changes in a second. For longer buffers lengths, this can make it hard to smoothly fade an ongoing sound up or down, as the "stair steps" can create an unwanted "zippering" sound.
The end of the Oracle tutorial describes the possibility of "manipulating the audio directly." This is what occurs in a library I wrote, a class called AudioCue, which provides for real-time volume changes. The class functions very much like a Clip but with additional capabilities. All the functionality is executed within Java. Changes are computed at the level of individual frames, with built in smoothing. So if you have a need for real-time fading, you can either use this class, or examine the code for an example of how to manipulate the PCM data directly.
| |
doc_3826
|
It should be possible to run a query to get other group members of a given record.
My idea is to manage it in one table:
GROUPINGS
integer group
integer member_id
primary_key (group, member_id)
foreign_key (member_id)
EDIT: Beware that group is not a foreign key. It's just a unique identifier. It should be increased for every member group which is built.
Here is an example content:
GROUPINGS group | member_id
-----------------
1 | 10
1 | 11
1 | 12
2 | 20
2 | 21
3 | 10
3 | 40
This example contains three groups: (10,11,12) and (20,21) and (10,40). You see that 10 is included in two groups.
To query the "neighbors" of member 10 we can use this SQL statement:
SELECT g2.member_id
FROM groupings g1
JOIN groupings g2 ON g1.group = g2.group
AND g1.member_id != g2.member_id
WHERE g1.member_id = 10
=> 11,12,40
What do you think? Perhaps this is a known pattern - are there links to find more about this?
EDIT: Renamed table "groups" to "groupings" and renamed attribute "group_id" to "group" to make it obvious that a record in this table is not a group - it's a link between a group and a member. Group is not an entity.
A:
A: What you have outlined is a pretty standard solution, a relational table between two entities - Group and Member. I am sure there are alternatives, but this is the solution I would go with.
A: Looks fine to me - is a normal solution to end at if a member can be part of multiple groups, which presumably they can.
The only suggestion I'd make is with your SQL query - I'd use a JOIN instead, but that's nothing to do with your schema:
SELECT g2.member_id
FROM groups g1
INNER JOIN groups g2 ON g1.group_id = g2.group_id AND g1.member_id <> g2.member_id
WHERE g1.member_id = 10
| |
doc_3827
|
(module api racket
(module a racket
(module b racket
(provide hi-there)
(define hi-there "hello"))))
I use it by requiring submodules with a prefix, like this: (require (prefix-in "a:b:" (submod 'api a b)).
Now, I want to write a macro that would help me make the require statements more elegant. I came up with the following:
(require (for-syntax racket))
(require (for-syntax racket/splicing))
(require (for-syntax syntax/parse))
(define-syntax (require-api stx)
(syntax-parse stx
[(_ root:id p1:id ...)
(splicing-let ([prefix (string->symbol (string-join (map (lambda (s) (symbol->string (syntax->datum s)))
(syntax-e #'(p1 ...)))
":"
#:after-last ":"))])
#`(require (prefix-in #,prefix (submod 'root p1 ...))))]))
Even though it gives me the exact form as I were entering manually, it does not in fact work. It does not create a binding for the require'd module:
> (require-api api a b)
> a:b:hi-there
a:b:hi-there: undefined;
cannot reference an identifier before its definition
in module: top-level
[,bt for context]
> (define-syntax (show stx)
(syntax-case stx ()
[(_)
(let ([main (local-expand #'(require-api api a b)
'top-level
(list #'require))]
[goal (local-expand #'(require (prefix-in a:b: (submod 'api a b)))
'top-level
(list #'require))])
(printf "expanded: ~s\n" (syntax->datum main))
(printf "goal: ~s\n" (syntax->datum goal))
main)]))
> (show)
expanded: (require (prefix-in a:b: (submod (quote api) a b)))
goal: (require (prefix-in a:b: (submod (quote api) a b)))
> (require (prefix-in a:b: (submod (quote api) a b)))
> a:b:hi-there
"hello"
I'm clearly missing something -- but what?
A: To quote the documentation of require:
The lexical context of the module-path form determines the context of the introduced identifiers
In your macro, (submod 'root p1 ...) is the module-path. Since you construct it in the macro require-api, its lexical context belongs to the macro. But to make it import identifiers correctly, its lexical context should belong to the original macro invocation site (as if you wrote it in the original location yourself).
An easy fix is to do the following manipulation:
(datum->syntax this-syntax (syntax-e #'(submod 'root p1 ...)))
Step-by-step explanation:
*
*#'(submod 'root p1 ...) is what you want, though it has a wrong lexical context.
*(syntax-e #'(submod 'root p1 ...)) extracts the list form from the syntax list.
*(datum->syntax this-syntax (syntax-e #'(submod 'root p1 ...))) packages the list form into a syntax list again, but with this-syntax's lexical context, which belongs to the original macro invocation site.
Here's a full program:
#lang racket
(require (for-syntax racket/string
syntax/parse))
(define-syntax (require-api stx)
(syntax-parse stx
[(_ root:id p1:id ...)
#:with prefix
(string->symbol
(string-join (map (λ (s) (symbol->string (syntax-e s)))
(attribute p1))
":"
#:after-last ":"))
#:with mp
(datum->syntax this-syntax (syntax-e #'(submod 'root p1 ...)))
#'(require (prefix-in prefix mp))]))
(module api racket
(module a racket
(module b racket
(provide hi-there)
(define hi-there "hello"))))
(require-api api a b)
a:b:hi-there ;=> "hello"
| |
doc_3828
|
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->start_date = strtotime($model->start_date);
$model->start_date = date('Y-m-d',$model->start_date);
$model->end_date = strtotime($model->end_date);
$model->end_date = date('Y-m-d',$model->end_date);
$model->date_of_request = strtotime($model->date_of_request);
$model->date_of_request = date('Y-m-d',$model->date_of_request);
//$model->start_date = date_format($model->start_date,'Y-m-d');
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}else{
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
//new line
}
}
A: For updating only one field value you have to make following changes in actionUpdate()
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->recommendation = 'recommended';
if($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
| |
doc_3829
|
Bottom 0 just aligns it to the bottom of the screen but how can I get it offscreen?
A: just use margin-top: 100%;
If you put it inside body then, it will use margin-top: 100% on the body, so it all falls out of the body. If you use overflow:hidden on body then it will work out fine i guess.
So your css looks like this:
body{
overflow: hidden;
}
#otheritem{
margin-top: 100%
}
That's a lot of body-text.
It might as well be html in stead of body.
I'm not sure.
A: you can do it just hidding the element with: display: none or visibility: hidden. or, you can set bottom: -100%; inside of a element with overflow: hidden;
| |
doc_3830
|
#!/bin/bash
set -x
(some magic command here...) > /tmp/mylog
echo "test"
and get the
+ echo test
test
output in /tmp/mylog, not in stdout.
A: This is what I've just googled and I remember myself using this some time ago...
Use exec to redirect both standard output and standard error of all commands in a script:
#!/bin/bash
logfile=$$.log
exec > $logfile 2>&1
For more redirection magic check out Advanced Bash Scripting Guide - I/O Redirection.
If you also want to see the output and debug on the terminal in addition to in the log file, see redirect COPY of stdout to log file from within bash script itself.
If you want to handle the destination of the set -x trace output independently of normal STDOUT and STDERR, see bash storing the output of set -x to log file.
A: To redirect stderr and stdout:
exec &>> $LOG_FILE_NAME
If you want to append to file. To overwrite file:
exec &> $LOG_FILE_NAME
A: In my case, the script was being called multiple times from elsewhere, and I wasn't seeing everything, so I did an append instead, and it worked:
exec 1>>FILENAME 2>&1
set -x
To avoid confusion, be sure to delete FILENAME before each run.
A: the -x output goes to stderr, so to log it do:
set -x
exec 2>/tmp/mylog
| |
doc_3831
|
I use class Sound for playing sound (as in the SoundExample of AndEngine). Testing on Samsung Galaxy S2.
The problem is the program gets lagged when the sound is played. And it even affects game physics (sometimes the ball bounces higher than the highest point when disabling sound).
This is the code:
public void onUpdate(float pSecondsElapsed) {
// mSound.play();
if (this.mSprite.collidesWith(ball.getSprite())) {
if (!colliding && mSound != null){ // play sound for first collision only
mSound.play();
colliding = true;
}
}
else{
colliding = false;
}
}
If I remove mSound.play() or keep playing sound (remove comment at line 2), the program works smoothly.
Does anyone encounter the same problem? And have a solution to get rid of the lag? Many thanks!
A: as that you mentioned that it works smoothly when you keep playing the sound .. then the problem is not with the sound
the collidesWith() method is probably your culprit, remember that onUpdate gets called every frame .. maybe you'll have to redesign your code or limit the number of frames per second [change your engine options to use a FixedStepEngine to achieve that]
| |
doc_3832
|
the code is :
< font color=blue>< a href="#" onclick="IntWebIM()">click here < /a>< /font>
i would like to hit " click here " and get the window opened like popup with some fixed height&width ..
could you please help ?
thanks
A: I think you may need to provide more details of your problem - but it sounds like you need to be looking at showModalDialog or a wrapper for it.
http://msdn.microsoft.com/en-us/library/ie/ms536759(v=vs.85).aspx
| |
doc_3833
|
I want to do the same in IntelliJ.
Here are the settings for my external tool in Eclipse.
I have configured so far in IntelliJ
When I run this tool in IntelliJ. I am shown the following Error.
C:\jython2.5.2\bin\jython.bat ${workspace_loc:/jythonTest/uploadScript.py} ${workspace_loc}${selected_resource_path} 127.0.0.1 maxadmin password
IOError: [Errno 2] File not found - C:\Users\IBM_ADMIN\workspace\jythonTest\${workspace_loc:\jythonTest\uploadScript.py} (The filename, directory name, or volume label syntax is incorrect)
Can anyone suggest a fix?
Edit: I am following this blog Upload jython scripts
A: The "macros" you're using in Eclipse (${workspace_loc} and the like) to set the command line parameters are different for IDEA. Use the "Insert Macro" button on the right side to find the equivilant IDEA macro for the paths you're trying to pass to your program.
| |
doc_3834
|
function getMake(value) {
$.post("../../sql/addVehicleFind.php",{partialMake:value},function(data){
$("#results").html(data);
});
}
function getModel(value) {
$.post("../../sql/addVehicleFind2.php",{partialModel:value},function(data){
$("#results2").html(data);
});
}
<input class="rounded" type="text" name="findMake" onkeyup="getMake(this.value)" placeholder="make"
<?php if(isset($vechileMake) && $vechileMake != '') {echo 'value="'.$vechileMake.'"';} ?> />
<div id="results" style="max-height:200px; overflow:auto; padding-left:55px; text-align: left" ></div>
<input class="rounded" type="text" name="findModel" onkeyup="getModel(this.value)" placeholder="model"
<?php if(isset($vechileModel) && $vechileModel != '') {echo 'value="'.$vechileModel.'"';} ?> />
<div id="results2" style="max-height:200px; overflow:auto; padding-left:55px; text-align: left" ></div>
My problem is when I put in values into the 2nd input box for 'getModel', I get a second round of results of 'getMake' as in the image below:
I hope there's a solution to this dilemma. Any help greatly appreciated.
Thank you so much in advance
A: I am familiar with php but not with javascript. Here I show how much of a newbie I am to programming. It occurred to me today that I can filter the selections in the php code that the function calls upon.
Hope this helps someone in the same situation.
| |
doc_3835
|
proc1 >> output &
proc2 >> output &
The problem is that output may be mixed up in the final file.
For example if first process writes:
hellow
and the second process writes:
bye
the result may be something like:
hebylloe
but I expect them to be in seperate lines like (order is not important):
bye
hello
So I used flock to synchronize writing to the file with the following script:
exec 200>>output
while read line;
flock -w 2 200
do echo $line>>output
flock -u 200
done
And run the processes like:
proc1 | script &
proc2 | script &
Now the problem is that the performance is decreased significantly. without synchronization each process could write with the speed of 4MB/sec but using the synchronization script the write speed is 1MB/sec.
Can anyone help me how to merge the output from two processes and prevent mixing outputs up?
edit:
I realized that there is a relation between line length and std buffer size, if size of each line is less than std buffer size, then every thing works well, nothing is mixed (at least in my tests). so I ran each script with bufsize command:
bufsize -o10KB proc1 | script &
bufsize -o10KB proc2 | script &
Now I want to make sure that this solution is bulletproof. I can not find any relation between buffer size and what happens now!!!
A:
Now I want to make sure that this solution is bulletproof. I can not
find any relation between buffer size and what happens now!!!
For a fully buffered output stream, the buffer size determines the amount of data written with a single write(2) call. For a line buffered output stream, a line is written with a single write(2) call as long as it doesn't exceed the buffer size.
If the file was open(2)ed with
O_APPEND, the file offset is first set to the end of the file
before writing. The adjustment of the file offset and the write
operation are performed as an atomic step.
See also these answers:
*
*Atomicity of write(2) to a local filesystem
*Understanding concurrent file writes from multiple processes
| |
doc_3836
|
"Repeat Previous Run" does not do it. If I right-click the unit test in source code and create a new session, the test will pass.
JetBrains ReSharper Ultimate 2017.3.2
Visual Studio Enterprise 2017 Version 15.6.5
A: Clear Test Result menu item visible on your second screenshot does exactly that - drops saved test result for the current session.
However, could you report the issue into JetBrains bug tracker and provide a sample (together with ReSharper caches) the next time test result is stuck?
| |
doc_3837
|
Like this:A UITableViewController in a UINavigationController.
Tableview's frame is (0,0,320,480)(This frame said by NSLog), its scroll bar is always under 44px. So scroll bar will not displayed behind navigation bar.
How to archive this? Special thanks
A: You coud set scroll edge insets. For example:
UIScrollView *scrollView;
[scrollView setScrollIndicatorInsets:UIEdgeInsetsMake(44, 0, 0, 0)];
As UITableView inherits UIScrollView all this methods are available.
| |
doc_3838
|
*
*Do normal retain/release and simply remove it all later
*Use automatic garbage collection and hope the changes needed later will be minimal
Any advice appreciated!
A: The only preparation necessary is to:
*
*Write modular code (hopefully, you're doing this already).
*Ensure you're following Cocoa memory management and naming conventions.
ARC can be activated on a per compilation unit basis, and will happily interact with non-ARC code that has these properties. You can thus adopt it gradually.
There's a good video on ARC adoption in the WWDC 2011 videos, titled "Introducing Automatic Reference Counting". I can't link right to it (it's behind an access control wall, and you'll need an Apple developer account).
A: Don't do GC. It's not recommended for new apps anymore, and it's a bigger conceptual jump to ARC than manual reference counting is.
I'd just use ARC in the first place, but if you really want to write the program in something else and then convert it, use MRC. Xcode offers an automatic converter for this.
| |
doc_3839
|
*
*Amazon Linux 2 AMI (HVM), SSD Volume Type
*Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type
What is the difference?
A: The first option is your image is a more stripped down/bare bones Linux image while the second includes commonly used packages/tools that are used when creating hosted services (such as AWS command line tools and Ruby).
I have an Amazon Linux 2 AMI (HVM), SSD Volume Type and you can see that extra packages like java and ruby are not installed.
A: The primary differences between Amazon Linux 2 and Amazon Linux AMI are:
*
*Amazon Linux 2 offers long-term support until June 30, 2023.
*Amazon Linux 2 is available as virtual machine images for on-premises
development and testing.
*Amazon Linux 2 provides the systemd service and systems manager as opposed to System V init system in Amazon Linux AMI.
*Amazon Linux 2 comes with an updated Linux kernel, C library, compiler, and tools.
*Amazon Linux 2 provides the ability to
install additional software packages through the extras mechanism.
For more click here
| |
doc_3840
|
This is so that I can retrieve an accurate Print Preview for the document without essentially rebuilding PrinterJobs functions from the ground-up in a different context.
Here's the code for the print function in my program:
public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException {
deepCopyString = string;
FontMetrics metrics = graphics.getFontMetrics(font);
int lineHeight = metrics.getHeight();
arrangePage(graphics, pageFormat, metrics);
if (page > pageBreaks.length){
return NO_SUCH_PAGE;
}
Graphics2D g = (Graphics2D) graphics;
g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g.setFont(font);
int begin = (page == 0) ? 0 : pageBreaks[page-1];
int end = (page == pageBreaks.length) ? lines.length : pageBreaks[page];
int y = 0;
int x = 0;
for (int line = begin; line < end; line++){
x = 0;
y += lineHeight;
checkSyntax(line);
String l = lines[line];
for (int c = 0; c < l.length(); c++){
applySyntax(c, line);
metrics = graphics.getFontMetrics(font);
String ch = Character.toString(l.charAt(c));
g.setFont(font);
g.drawString(ch, x, y);
x += metrics.charWidth(l.charAt(c));
//System.out.println(c + "/"+l.length());
}
//g.drawString(lines[line], 0, y);
}
reset();
records.add(g);
return PAGE_EXISTS;
}
You can already see that the Graphics objects are recorded so that I can paint them in another component, but it's rather useless seeing as it will go ahead and send these to my printer before the record can be completed.
This may be a bad idea in general, and I'm pretty new to printing. If this is seriously a bad way to go about this, feel free to direct me to a source that'll explain a better way.
A: Basically, you want to create you own Graphics context to which you can paint. You also need to construct a PageFormat that can be past to the print method.
public class TestPrint implements Printable {
private BufferedImage background;
public static final float DPI = 72;
public static void main(String[] args) {
new TestPrint();
}
public TestPrint() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
try {
background = ImageIO.read(new File("C:/Users/shane/Dropbox/MegaTokyo/MgkGrl_Yuki_by_fredrin.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
float width = cmToPixel(21f, DPI);
float height = cmToPixel(29.7f, DPI);
Paper paper = new Paper();
float margin = cmToPixel(1, DPI);
paper.setImageableArea(margin, margin, width - (margin * 2), height - (margin * 2));
PageFormat pf = new PageFormat();
pf.setPaper(paper);
BufferedImage img = new BufferedImage(Math.round(width), Math.round(height), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fill(new Rectangle2D.Float(0, 0, width, height));
try {
g2d.setClip(new Rectangle2D.Double(pf.getImageableX(), pf.getImageableY(), pf.getImageableWidth(), pf.getImageableHeight()));
print(g2d, pf, 0);
} catch (PrinterException ex) {
ex.printStackTrace();
}
g2d.dispose();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public float cmToPixel(float cm, float dpi) {
return (dpi / 2.54f) * cm;
}
public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g = (Graphics2D) graphics;
g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
if (background != null) {
int x = (int)Math.round((pageFormat.getImageableWidth() - background.getWidth()) / 2f);
int y = (int)Math.round((pageFormat.getImageableHeight() - background.getHeight()) / 2f);
g.drawImage(background, x, y, null);
}
g.setColor(Color.BLACK);
g.draw(new Rectangle2D.Double(0, 0, pageFormat.getImageableWidth() - 1, pageFormat.getImageableHeight() - 1));
return PAGE_EXISTS;
}
}
Now, obviously, there are going to be difference to what is printed to the screen and what's printed to the printer, because we're not actually using the same hardware device, but the basic concept applies
| |
doc_3841
|
Date localRecvTime = new Date();
DateFormat converter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
converter.setTimeZone(TimeZone.getTimeZone("GMT"));
String ConvertedDate =converter.format(localRecvTime);
System.out.println(ConvertedDate.length());
//above statement will print 24
byte[] dateInBytes=ConvertedDate.getBytes();
System.out.println(dateInBytes.length);
//above statement will also print 24
}
The above code works fine.
But i want to limit the size of byte array(ie. byte[] dateInBytes) to 4 bytes according to my requirements.
Is it possible to do that?
A: Don't convert it into a string in the first place. You've got a Date, which is effectively a 64-bit value: the number of milliseconds since the Unix epoch of January 1st 1970 at midnight, UTC.
If you've only got 4 bytes available, you need a 32-bit value. If you divide the milliseconds by 1000, you'll get the number of seconds since the Unix epoch... and that gives you enough range to last until 2038. You could extend that range significantly further by changing the epoch, effectively. If you use an epoch of 2075, you should be able to store values from about 2010 to 2140. You'll still only be storing the value to a second granularity, of course.
Alternatively, you could stick with milliseconds as granularity, but reduce the range. Unfortunately it would reduce the range very significantly - to about 48 days. Unless you're expecting values in a very tight range, that's probably not an option for you.
Once you've worked out your 32-bit representation, there are various ways of converting that into a byte array, including using DataOutputStream. (If the goal is to write the value to a stream anyway, don't bother with the intermediate byte array.)
A: Ummm ... no, it is not possible to put 24 bytes into 4 bytes
Nor is it possible to put 24 characters into 4 bytes either (as characters always at least as large as a byte).
But I think Jon got it right: the number of seconds since 1970 will fit in 4 bytes.
| |
doc_3842
|
I made the basic servlet and intalled tomcat version 6 and even tomcat version 8.
the server starts up correctly and i am able to see the tomcat start up page on going to
http://localhost:8080
but after logging to tomcat manager when i click on my folder name it gives me an error saying
http status 404-/online/ (online is my folder created in webapps)
type Status report
message /online/
description The requested resource is not available.
here's my codes
web.xml-> (in folder online->WEB-INF)
- <web-app>
- <servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
- <servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
FirstServlet.java->
import javax.servlet.*;
import java.io.*;
class FirstServelet implements Servlet
{
public void init(ServletConfig config)
{
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
PrintWriter out;
out=response.getWriter();
out.println("hello");
out.println("<html>");
out.println("<head>");
out.println("<title>MY First Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<marquee>ban ja tar pls</marquee>");
out.println("</body>");
out.println("</html>");
}
public String getServletInfo()
{
return null;
}
public ServletConfig getServletConfig()
{
return null;
}
public void destroy ()
{
}
}
please resolve the 404 error
A: The problem is you don't welcome-file-list, I think the default page is index.html which I suppose is not there in you folder. You can provide any html or jsp file as default file but NOT a servlet as below.
<welcome-file-list>
<welcome-file>myfile.html</welcome-file>
</welcome-file-list>
You can access your servlet by hitting http://localhost:8080/online/FirstServlet URL.
You can create a default page which will redirect to FirstServlet i.e.
myfile.html
<meta http-equiv="refresh" content="0; url=http://localhost:8080/online/FirstServlet" />
And also what @Braj said in the comment extend HttpServlet instead of implement Servlet.
Edit
You have a typo in servlet name. change the servlet name to FirstServlet from FirstServelet.
| |
doc_3843
|
When ordering, you can only order 1 variation of a product at a time. You can edit the quantity of that variation in the cart but you can't add 2 variations of the same product to the same cart at the same time. If you do, it will empty the cart and replace it with the current selection. Since I'd be taking pre-orders for screen printed clothing (similar to teespring), ordering multiple variations (sizes in this instance) at one time is important. Making them make multiple orders from the same product would just drive them away.
I don't want to let customers order from multiple preorders at once since each preordered product has a different release/ship date, but I want to let them order multiple variations, i.e. a Small Tee, a Medium Tee, and a Large Tee, of a particular product since they would all ship at the same time.
I hope all of that made sense.
Here is the code that is responsible for the cart restrictions. Any help is much appreciated.
/**
* When a pre-order is added to the cart, remove any other products
*
* @since 1.0
* @param bool $valid
* @param $product_id
* @return bool
*/
public function validate_cart( $valid, $product_id ) {
global $woocommerce;
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $product_id ) ) {
// if a pre-order product is being added to cart, check if the cart already contains other products and empty it if it does
if( $woocommerce->cart->get_cart_contents_count() >= 1 ) {
$woocommerce->cart->empty_cart();
$string = __( 'Your previous cart was emptied because pre-orders must be purchased separately.', 'wc-pre-orders' );
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( $string );
} else {
$woocommerce->add_message( $string );
}
}
// return what was passed in, allowing the pre-order to be added
return $valid;
} else {
// if there's a pre-order in the cart already, prevent anything else from being added
if ( $this->cart_contains_pre_order() ) {
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
} else {
$woocommerce->add_error( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
}
$valid = false;
}
}
return $valid;
}
/**
* Add any applicable pre-order fees when calculating totals
*
* @since 1.0
*/
public function maybe_add_pre_order_fee() {
global $woocommerce;
// Only add pre-order fees if the cart contains a pre-order
if ( ! $this->cart_contains_pre_order() ) {
return;
}
// Make sure the pre-order fee hasn't already been added
if ( $this->cart_contains_pre_order_fee() ) {
return;
}
$product = self::get_pre_order_product();
// Get pre-order amount
$amount = WC_Pre_Orders_Product::get_pre_order_fee( $product );
if ( 0 >= $amount ) {
return;
}
$fee = apply_filters( 'wc_pre_orders_fee', array(
'label' => __( 'Pre-Order Fee', 'wc-pre-orders' ),
'amount' => $amount,
'tax_status' => WC_Pre_Orders_Product::get_pre_order_fee_tax_status( $product ), // pre order fee inherits tax status of product
) );
// Add fee
$woocommerce->cart->add_fee( $fee['label'], $fee['amount'], $fee['tax_status'] );
}
/**
* Checks if the current cart contains a product with pre-orders enabled
*
* @since 1.0
* @return bool true if the cart contains a pre-order, false otherwise
*/
public static function cart_contains_pre_order() {
global $woocommerce;
$contains_pre_order = false;
if ( ! empty( $woocommerce->cart->cart_contents ) ) {
foreach ( $woocommerce->cart->cart_contents as $cart_item ) {
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $cart_item['product_id'] ) ) {
$contains_pre_order = true;
break;
}
}
}
return $contains_pre_order;
}
/**
* Checks if the current cart contains a pre-order fee
*
* @since 1.0
* @return bool true if the cart contains a pre-order fee, false otherwise
*/
public static function cart_contains_pre_order_fee() {
global $woocommerce;
foreach ( $woocommerce->cart->get_fees() as $fee ) {
if ( is_object( $fee ) && 'pre-order-fee' == $fee->id )
return true;
}
return false;
}
/**
* Since a cart may only contain a single pre-ordered product, this returns the pre-ordered product object or
* null if the cart does not contain a pre-order
*
* @since 1.0
* @return object|null the pre-ordered product object, or null if the cart does not contain a pre-order
*/
public static function get_pre_order_product() {
global $woocommerce;
if ( self::cart_contains_pre_order() ) {
foreach ( $woocommerce->cart->cart_contents as $cart_item ) {
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $cart_item['product_id'] ) ) {
// return the product object
return get_product( $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'] );
}
}
} else {
// cart doesn't contain pre-order
return null;
}
}
A: I know this post is old. But come to this same problem and i have solved my problem like this.
I have changed validate_cart() function in woocommerce-pre-orders/classes/class-wc-pre-orders-cart.php
It is like this :
public function validate_cart( $valid, $product_id ) {
global $woocommerce;
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $product_id ) ) {
if( $woocommerce->cart->get_cart_contents_count() >= 1 ) {
if ( $this->cart_contains_pre_order() ) {
return $valid;
}
$string = __( 'Your cart contains items, please complete that order first and then purchase pre-order items, because pre-orders must be purchased separately.', 'wc-pre-orders' );
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( $string );
} else {
$woocommerce->add_message( $string );
}
$valid = false;
return $valid;
}
else
{
return $valid;
}
} else {
// if there's a pre-order in the cart already, prevent anything else from being added
if ( $this->cart_contains_pre_order() ) {
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
} else {
$woocommerce->add_error( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
}
$valid = false;
}
}
return $valid;
}
Note : I know this is not the right way for implementation. Because i
have edit in plugin directly. So when plugin will update, the changes are no longer there. And you can use any 'return $valid' or 'return true' or 'return false' as your choice.
Thank you.
A: I've been having the same issue and just found an answer (I hope) here:
Pre-orders can only purchase one at a time
I managed to implement hortongroup's plugin fix as described in the comments.
There was a slight error the shortcode line in the description, it should read:
echo do_shortcode('[pre_order_fix]');
It now seems to be working perfectly, I'll have wait for the next update to WooCommerce Pre Orders to see if the plugin fix still works.
Ideally by doing it this way we won't have to alter WooCommerce Pre Orders after every update.
Here's the code I used for the custom plugin:
<?php
/**
* Plugin Name: Woo Pre-Order Fix
* Plugin URI:
* Description: Fix the one item only issue with Woocommerce Pre-Orders
* Version: 1.0
* Author: hortongroup
* Author URI:
* License: GPL12
*/
function pre_order_fix_shortcode() {
if ( in_array( 'woocommerce-pre-orders/woocommerce-pre-orders.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
remove_filter( 'woocommerce_add_to_cart_validation', array( $GLOBALS['wc_pre_orders']->cart, 'validate_cart' ), 15, 2 );
}
}
add_shortcode('pre_order_fix', 'pre_order_fix_shortcode');
?>
Hopefully this will work for you too:)
Kind regards,
JP
A: I know that it's been a long time but I think this could still be useful for someone. If you have a child theme you can just add this to functions.php:
//remove pre-order limitations --> only one item per order
add_action( 'init', 'remove_validation_cart' );
function remove_validation_cart(){
remove_filter( 'woocommerce_add_to_cart_validation', array( $GLOBALS['wc_pre_orders']->cart, 'validate_cart' ), 15, 2 );
}
This avoids the need of adding a plugin
A: Since this issue still exists today and my scenario was slightly different, I've used the following filter to fix my issue.
I want pre-orders to be made but not one pre-order item per order, there could be multiple quantities and different pre-order products in one order. The only scenario I want to prevent is that regular products are being mixed with pre-orders (which shouldn't be possible).
Maybe anyone else could use this approach (going to check for something custom in the future which you can add to your child-theme) which would be better since it could now be overwritten with an update.
/**
* When a pre-order is added to the cart, remove any other products
*
* @since 1.0
* @param bool $valid
* @param $product_id
* @return bool
*/
public function validate_cart( $valid, $product_id ) {
global $woocommerce;
if ( WC_Pre_Orders_Product::product_can_be_pre_ordered( $product_id ) ) {
// if a pre-order product is being added to cart, check if the cart already contains other products and empty it if it does
if( $woocommerce->cart->get_cart_contents_count() >= 1 ) {
// count the amount of regular items in the cart
$regularCount = 0;
foreach ($woocommerce->cart->get_cart() as $item) {
// continue of the product is a pre-order product...
if (WC_Pre_Orders_Product::product_can_be_pre_ordered( $item['product_id'] )) {
continue;
}
$regularCount++;
}
// only clear the cart if the current items in it are having regular products...
if ($regularCount > 0) {
$woocommerce->cart->empty_cart();
$string = __( 'Your previous cart was emptied because pre-orders must be purchased separately.', 'wc-pre-orders' );
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( $string );
} else {
$woocommerce->add_message( $string );
}
}
}
// return what was passed in, allowing the pre-order to be added
return $valid;
} else {
// if there's a pre-order in the cart already, prevent anything else from being added
if ( $this->cart_contains_pre_order() ) {
// Backwards compatible (pre 2.1) for outputting notice
if ( function_exists( 'wc_add_notice' ) ) {
wc_add_notice( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
} else {
$woocommerce->add_error( __( 'This product cannot be added to your cart because it already contains a pre-order, which must be purchased separately.', 'wc-pre-orders' ) );
}
$valid = false;
}
}
return $valid;
}
| |
doc_3844
|
Issue is - there's no SFTP log of the transfer so I don't know what happenned. redirecting within -ArgumentList doesn't produce any results. Is there another way of achieving the same results e.g. kill the process within 2 minutes and have full log in a PowerShell? Many thanks!
$logfile = Get-Date -UFormat "%Y-%m-%d"
Start-Transcript -Append -Path C:\Scripts\FTPs-PS\FTP-PS_logs\FTP-$logfile.txt
$process = Start-Process "C:\Program Files (x86)\PuTTY\psftp.exe" -ArgumentList "username@localhost -pw StrongPassword -batch -b C:\Scripts\sft.txt" -NoNewWindow -PassThru -Verbose
do {
start-sleep 5
if (-Not (Get-Process -Id ($process.Id))) {break}
$date = $process.StartTime | Out-String
$total = New-TimeSpan -Start $date -End (Get-Date)
} while ($total.TotalSeconds -lt 120)
if ((Get-Process -Id ($process.Id))) {Stop-Process -id ($process.Id)}
Stop-Transcript
| |
doc_3845
|
I'm unable to perform fetch on the AWS EC2 domain from the iOS Simulator. I can access the URL through Postman and simulator's browser.
When I use fetch from the iOS Simulator, I'm getting a
TypeError: Network Request Failed
I have added the following to my info.plist.
<key>{domainName}.amazonaws.com</key>
<dict>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<key>NSTemporaryExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
| |
doc_3846
|
For example, when we have a task map in the dashboard the name is MAP, how can I change it to add a specific name?
Thanks a lot.
A: Operators can be named using the name() method as shown in the following example:
DataStream<X> stream2 = stream
.map(new MyMapper()).name("MyMapFunction")
.map(new MyMapper2()).name("MyOtherMapper");
| |
doc_3847
|
Its currently all working as expected except when I click load more it loads the next page posts twice e.g:
Load more >
Post 4,
Post 5,
Post 6,
Post 4,
Post 5,
Post 6
FYI my 'posts' are @links:
links_controller.erb
def index
@links = Link.order('created_at DESC').paginate(:page => params[:page], :per_page => 3)
respond_to do |format|
format.html
format.js
end
end
views/links/index.html.erb
<div class="link-wrap">
<%= render @links %>
</div>
<% if @links.next_page %>
<div class="link more">
<%= link_to 'Load More', links_path(:page => @links.next_page), :class => 'next_page', :remote => true if @links.next_page %>
</div>
<% end %>
pagination.js.coffee
$ ->
$('.next_page').on 'click', (e) ->
e.preventDefault()
url = $(this).attr('href')
$.getScript(url)
index.js.erb
$('.link-wrap').append('<%= j render(@links) %>');
<% if @links.next_page %>
$('.next_page').attr('href','<%= links_path(:page => @links.next_page) %>');
<% else %>
$('.more').remove();
<% end %>
For the life of me I can't figure out why it would be rendering the links twice when 'load more' is clicked. This seems like a really simple thing but I'm struggling.
A: So it was a stupid error of course.
Remove the line on index.html.erb:
:remote => true if @links.next_page
So now it looks like this:
<div class="link-wrap">
<%= render @links %>
</div>
<% if @links.next_page %>
<div class="link more">
<%= link_to 'Load More', links_path(:page => @links.next_page), :class => 'next_page' %>
</div>
<% end %>
All works fine now!
A: If you check the server console, you can actually see two requests coming in, one triggered by your :remote => true enabled link and other from your custom ajax. Actually you don't need any js to make this work. Just remove that click function from your pagination.js.coffee or remove :remote => true from the link. After all both are doing the same thing. Hope this will help.
| |
doc_3848
|
I created a button_rounded_corners_gradient.xml file in my drawable folder. this file contains the code which makes my button round corner and in a rectangular shape with round corners. then i am using this file in the android:background attribute of my buttons code in xml.
activity_mainn.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anonymous.fyplogin.MainActivity">
<Button
android:id="@+id/fbbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Login with Facebook "
android:background="@drawable/button_rounded_corners_gradient"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/phbutton"
app:layout_constraintVertical_bias="0.919" />
<Button
android:id="@+id/phbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Login with Phone "
android:background="@drawable/button_rounded_corners_gradient"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="71dp" />
</android.support.constraint.ConstraintLayout>
button_rounded_corners_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<!--make a gradient background-->
<gradient
android:type="linear"
android:startColor="#003333"
android:endColor="#003333"
android:centerColor="#003333"
android:angle="90"
android:gradientRadius="90"
/>
<!--apply a border around button-->
<stroke android:color="#ff0000" android:width="2dp" />
<!-- make the button corners rounded-->
<corners android:radius="25dp"/>
</shape>
</item>
</selector>
A: Use foreground attribute:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_rounded_corners_gradient"
android:foreground="?android:selectableItemBackground" />
A: You can add a android:state to your button_rounded_corners_gradient.xml
from:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<!--make a gradient background-->
<gradient
android:type="linear"
android:startColor="#003333"
android:endColor="#003333"
android:centerColor="#003333"
android:angle="90"
android:gradientRadius="90"
/>
<!--apply a border around button-->
<stroke android:color="#ff0000" android:width="2dp" />
<!-- make the button corners rounded-->
<corners android:radius="25dp"/>
</shape>
</item>
</selector>
to:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The normal state of the button -->
<item android:state_pressed="false">
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent" />
<stroke android:color="#ff0000" android:width="1dp" />
<!-- make the button corners rounded-->
<corners android:radius="25dp"/>
</shape>
</item>
<!-- The state when the button is being pressed or clicked. -->
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@android:color/holo_red_dark"/>
<!--apply a border around button-->
<stroke android:color="#ff0000" android:width="1dp" />
<!-- make the button corners rounded-->
<corners android:radius="25dp"/>
</shape>
</item>
</selector>
to give a vibration effect to your button when clicked. add this
<uses-permission android:name="android.permission.VIBRATE"/>
permission to your AndroidManifest.xml
and do this to your activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Button button = findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Set the milliseconds of vibration you want.
vibrator.vibrate(500);
}
});
}
A: for the xml you created in drawable to make button rectangle
add this line to that xml
<item android:state_pressed="true">
A: You should try ripple for the wave effect on button pressed so as to get a button pressed feel ;)
just make a new drawable file and set this file as background to the button...
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorPrimary">
</ripple>
Hope it helps
| |
doc_3849
|
I am programming a paint editor for my final year project. One of its function is that when an user select one or more lines, these lines can be rotated according to a specific point(one of the vertex of these selected lines). Besides, when a line is chosen, it will be marked as red and both vextices will be marked. The red vertex is rotation pivot chosen by user. To implement this, i first caculate the rotation angle and then use trigonometric function to caculate the rotated lines.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class MWE extends JFrame{
MyPanel panel = new MyPanel();
public MWE(){
setTitle("MyFirstFrame");
setSize(1160,830);
setLocation(100,100);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setBackground(Color.white);
panel.requestFocus();
panel.setVisible(true);
this.getContentPane().add(panel);
}
public static void main(String[] args){
MWE myFrame = new MWE();
}
}
class MyPanel extends JPanel{
private ArrayList selectedLines = new ArrayList<MyLine2D>();
private ArrayList selectedPoints = new ArrayList<MyPoint>();
MyPoint rotationP = new MyPoint(247,309,Color.red);
int lastX = 0, lastY = 0;
public MyPanel(){
this.setBackground(Color.WHITE);
this.requestFocus();
this.setVisible(true);
addMouseListener();
Line2D myLine = new Line2D.Double(247, 309, 344, 197);
selectedLines.add(new MyLine2D(myLine, Color.red));
MyPoint p1 = new MyPoint(247,309,Color.red);
MyPoint p2 = new MyPoint(344,197,Color.black);
selectedPoints.add(p1);
selectedPoints.add(p2);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i = 0; i< selectedLines.size(); i++){
g.setColor(((MyLine2D)selectedLines.get(i)).getColor());
g.drawLine(((MyLine2D)selectedLines.get(i)).getX1(), ((MyLine2D)selectedLines.get(i)).getY1(),
((MyLine2D)selectedLines.get(i)).getX2(), ((MyLine2D)selectedLines.get(i)).getY2());
}
for(int i = 0; i < selectedPoints.size(); i++){
g.setColor(((MyPoint)selectedPoints.get(i)).getColor());
g.drawOval(((MyPoint)selectedPoints.get(i)).getX() - 3, ((MyPoint)selectedPoints.get(i)).getY() - 3, 6, 6);
}
}
private void addMouseListener(){
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
lastX = e.getX();
lastY = e.getY();
}
});
this.addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e){
double vecCross = (lastX - rotationP.getX()) * (e.getX() - rotationP.getX()) + (lastY - rotationP.getY()) * (e.getY() - rotationP.getY());
int c = (Math.abs((lastX - rotationP.getX()) * (lastX - rotationP.getX())) + Math.abs((lastY - rotationP.getY()) * (lastY - rotationP.getY())))
* (Math.abs((e.getX() - rotationP.getX()) * (e.getX() - rotationP.getX())) + Math.abs((e.getY() - rotationP.getY()) * (e.getY() - rotationP.getY())));
double sqrt = Math.sqrt(c);
double cosValue = vecCross/sqrt;
double radian = Math.acos(cosValue);
if(((e.getY() - lastY)*(lastX - rotationP.getX()) < 0) && !Double.isNaN(radian)){
//
for(int i = 0; i < selectedLines.size(); i++){
((MyLine2D)selectedLines.get(i)).rotationLine(rotationP, -radian);
}
for(int i = 0; i < selectedPoints.size(); i++){
((MyPoint)selectedPoints.get(i)).rotationPoint(rotationP, -radian);
}
}
if(((e.getY() - lastY)*(lastX - rotationP.getX()) > 0) && !Double.isNaN(radian)){
for(int i = 0; i < selectedLines.size(); i++){
((MyLine2D)selectedLines.get(i)).rotationLine(rotationP, radian);
}
for(int i = 0; i < selectedPoints.size(); i++){
((MyPoint)selectedPoints.get(i)).rotationPoint(rotationP, radian);
}
}
lastX = e.getX();
lastY = e.getY();
repaint();
}
});
}
}
class MyLine2D {
private Line2D myLine = new Line2D.Double();
private Color color = Color.BLACK;
public MyLine2D(Line2D myLine, Color c){
this.myLine = myLine;
this.color = c;
}
public int getX1(){
return (int)myLine.getX1();
}
public int getY1(){
return (int)myLine.getY1();
}
public int getX2(){
return (int)myLine.getX2();
}
public int getY2(){
return (int)myLine.getY2();
}
public Color getColor(){
return this.color;
}
public void rotationLine(MyPoint pivot, double radians){
double x1=0, y1=0, x2=0, y2=0;
x1 = pivot.getX() + (myLine.getX1() - pivot.getX()) * Math.cos(radians) - (myLine.getY1() - pivot.getY()) * Math.sin(radians);
y1 = pivot.getY() + (myLine.getY1() - pivot.getY()) * Math.cos(radians) + (myLine.getX1() - pivot.getX()) * Math.sin(radians);
x2 = pivot.getX() + (myLine.getX2() - pivot.getX()) * Math.cos(radians) - (myLine.getY2() - pivot.getY()) * Math.sin(radians);
y2 = pivot.getY() + (myLine.getY2() - pivot.getY()) * Math.cos(radians) + (myLine.getX2() - pivot.getX()) * Math.sin(radians);
Line2D rotatedLine = new Line2D.Double(x1,y1,x2,y2);
myLine = rotatedLine;
}
}
class MyPoint {
private int x;
private int y;
private Color color = Color.black;
public MyPoint(int x, int y, Color c){
this.x = x;
this.y = y;
this.color = c;
}
public int getX(){
return this.x;
}
//
//
public int getY(){
return this.y;
}
public Color getColor(){
return this.color;
}
public void rotationPoint(MyPoint pivot, double radians){
double x1 = pivot.getX() + (x - pivot.getX()) * Math.cos(radians) - (y - pivot.getY()) * Math.sin(radians);
double y1 = pivot.getY() + (y - pivot.getY()) * Math.cos(radians) + (x - pivot.getX()) * Math.sin(radians);
x = (int) x1;
y = (int) y1;
}
}
vecCross is dot product of a vector from rotation pivot to original mouse pointer location and a vector from rotation pivot to present mouse pointer location. c is product of the magnitude of these two vectors. the Arraylist, selectedLines, is the lines selected and remain to be rotated. the ArrayList, selectedPoints, is the vertices of selected lines.
in the if arguement, i think '((e.getY() - lastY)*(lastX - rotationP.getX()) < 0 )' can be represented as my mouse moves anticlockwise. because origin of Jpanel is at top left, anticlockwise movement means to reduce its degree.
My Problem:
However, when i select some lines and enter Rotation mode and move my mouse clockwise, these lines dont rotate smoothly, sometimes quick and sometime slow, and those selected points will dettach from vertices, as shown in image. it is really strange because i use the some function to rotate the selected points and lines. can anyone give me some comments?
| |
doc_3850
|
this is my code, I've tried several references but I can't find a solution for my case. please help, i need some example for sure..
**
app.post('/sendFriendRequest', function (request, result) {
var accessToken = request.fields.accessToken;
var _id = request.fields._id;
database.collection('users').findOne(
{
accessToken: accessToken,
},
function (error, user) {
if (user == null) {
result.json({
status: 'error',
message: 'Pengguna telah keluar. Silahkan masuk kembali.',
});
} else {
var me = user;
database.collection('users').findOne(
{
_id: ObjectId(),
},
function (error, user) {
if (user == null) {
result.json({
status: 'error',
message: 'Pengguna tidak ditemukan.',
});
} else {
database.collection('users').updateOne(
{
_id: ObjectId(),
},
this is part of my code
| |
doc_3851
|
When visiting an existing blog post /blog/id-that-exist, it works as expected, and now I want to handle the case /blog/id-that-does-not-exist properly.
The code in /blog/[id].jsx looks something like:
export const getStaticPaths async () => {
return {
fallback: true,
paths: (await sequelize.models.Article.findAll()).map(
article => {
return {
params: {
pid: article.slug,
}
}
}
),
}
}
export const getStaticProps async () => {
// Try to get it from the database. Returns none if does not exist.
const article = await sequelize.models.Article.findOne({
where: { slug: pid },
});
return { props: { article: article } };
}
const ArticlePage = (props) => {
// This can happen due to fallback: true while waiting for
// a page that was not rendered at build time to build.
const router = useRouter()
if (router.isFallback) {
return <div>loading</div>;
}
return (
<div>{props.article.body}</div>
);
};
export const getStaticPaths = getStaticPathsArticle;
export const getStaticProps = getStaticPropsArticle;
export default ArticlePage;
I saw this related question: How to handle not found 404 for dynamic routes in Next.js which is calling API? but I'm not sure if it's the same as I'm asking here, as this does not depend on any external API being used.
A: notFound: true from Next.js 10
Starting in Next.js 10, we can do:
export const getStaticProps async () => {
// Try to get it from the database. Returns none if does not exist.
const article = await sequelize.models.Article.findOne({
where: { slug: pid },
});
if (!article) {
return {
notFound: true
}
}
return { props: { article: article } };
}
as documented at: https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
When notFound is returned, the rendering function ArticlePage just never gets called, and the default 404 page is returned instead.
Note however that ArticlePage did get
For some reason in development mode:
*
*I don't get the expected 404 HTTP status code
*ArticlePage, so if you forgot to handle the fallback case, the it might crash due to missing properties
which was confusing me a bit. But in production mode, everything works as expected.
Workaround before Next.js 10
As shown https://github.com/vercel/next.js/discussions/10960#discussioncomment-1201 you could previously do something like:
const ArticlePage = (props) => {
if (!props.article) {
return <>
<Head>
<meta name="robots" content="noindex">
</Head>
<DefaultErrorPage statusCode={404} />
</>
}
return (
<div>{props.article.body}</div>
);
};
but this is not ideal because it does not set the HTTP return code correctly I believe, and I don't know how to do it.
Tested on Next.js 10.2.2.
A: I've read your answer regarding the solution after Next.js v.10, but I didn't get what was the problem in showing the expected http 404 code during development.
I use Next.JS v.12 and I get the expected 404 normally in development
import { GetStaticPaths, GetStaticProps } from 'next'
import { useRouter } from 'next/router'
import { ParsedUrlQuery } from 'querystring'
import Loading from '../../components/loading'
export const getStaticPaths: GetStaticPaths = async () => {
//your paths
return { paths, fallback: true }
}
export const getStaticProps: GetStaticProps = async ({ params }: { params?: ParsedUrlQuery }) => {
//get your props
if (!target){
return {notFound: true}
}
return { props: { ... }, revalidate: 86400}
}
function Index({ ... }) {
const router = useRouter()
if (router.isFallback) {
return <Loading />
}
return (
<div>
//my content
</div>
)
}
export default Index
When the target isn't found, it renders my custom 404 component in pages/404.tsx if I created one or just the default 404 page.
This should work normally during development and production.
| |
doc_3852
|
A: Activity and consumption metrics can be monitored using Cloudwatch.
var cloudwatch = new AWS.CloudWatch();
var params = {
Dimensions: [
{
Name: 'STRING_VALUE', /* required */
Value: 'STRING_VALUE'
},
/* more items */
],
MetricName: 'STRING_VALUE',
Namespace: 'STRING_VALUE',
NextToken: 'STRING_VALUE'
};
cloudwatch.getMetricWidgetImage(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
cloudwatch.listMetrics(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#listMetrics-property
https://docs.aws.amazon.com/AmazonS3/latest/dev/cloudwatch-monitoring.html#s3-request-cloudwatch-metrics
| |
doc_3853
|
requirejs.config({
paths : {
jquery : "lib/jquery",
bootstrap : "lib/bootstrap",
},
shim : {
"bootstrap" : [ "jquery" ]
}
});
I will also need require-jquery. This means that I will have two jQuery files. One standard and the require-jquery.
If I do this
paths : {
jquery : "jquery-require"
bootstrap : "lib/bootstrap",
},
I will get a jQuery issue
Uncaught TypeError: Cannot read property 'fn' of undefined
Could you help me figure out how to use this?
A: You don't need to use "jquery-require". Your first configuration (using jquery and shim) is enough.
AFAIK jquery-require is a bundle of require+jquery done for the previous versions of requirejs (before 2.0).
You don't need any special configuration for latest versions of Require or jQuery. For example jQuery will export the jQuery global using define if its detected (see https://github.com/jquery/jquery/blob/master/src/exports.js).
| |
doc_3854
|
I am working on a diffusion equation. However, when I try to plot it, I am getting an error message related to the equality of the dimensions
x and y must have same first dimension, but have shapes (401,) and (2001, 401)
The x-axis should give the position of particles, while the y-axis should give the number of particles at a given position. I am not sure how to make dimensions equal in this case.
My codes:
import numpy as np
import matplotlib.pyplot as plt
D = 0.5
M = 2000
L = 200
tmax = 2000
dx = 1
dt = 1
s = D*dt/dx**2 #diffusion number
nx = int(2*L/dx)
nt = int(tmax/dt)
nx = nx + 1
nt = nt + 1
x = np.linspace(-L,L,nx)
t = np.linspace(0,tmax,not)
def InitCond(x, M):
if x == -50:
c0 = M
elif x == 50:
c0 = M
else:
c0 = 0
return c0
def LeftEnd(t):
return 0
def RightEnd(t):
return 0
def DiffusionSolver(x,t,s,L,c0,left,right):
nt = np.size(t)
nx = np.size(x)
u = np.zeros((nt,nx))
# Use the initial condition to define values of 'u' at the
#zeroeth timestep:
for j in range(nx):
u[0,j] = c0(x[j], M)
# Use the boundary condition to fix the string on its ends:
u[:,-L] = left(t)
u[:,L] = right(t)
# Entering the double loop to calculate the solution at every space
#point at every timestep:
for k in range(0,nt-1):
for j in range(1,nx-1):
u[k+1,j] = s*(u[k,j+1] + u[k,j-1]) + (1 - 2*s)*u[k,j]
return u
u_num = DiffusionSolver(x,t,s,L,InitCond,LeftEnd,RightEnd)
plt.plot(x, u_num)
A: You just need to Transform the u_num array so that it's the right shape. Like this:
import numpy as np
import matplotlib.pyplot as plt
D = 0.5
M = 2000
L = 200
tmax = 2000
dx = 1
dt = 1
s = D*dt/dx**2 #diffusion number
nx = int(2*L/dx)
nt = int(tmax/dt)
nx = nx + 1
nt = nt + 1
x = np.linspace(-L,L,nx)
t = np.linspace(0,tmax,nt)
def InitCond(x, M):
if x == -50:
c0 = M
elif x == 50:
c0 = M
else:
c0 = 0
return c0
def LeftEnd(t):
return 0
def RightEnd(t):
return 0
def DiffusionSolver(x,t,s,L,c0,left,right):
nt = np.size(t)
nx = np.size(x)
u = np.zeros((nt,nx))
# Use the initial condition to define values of 'u' at the
#zeroeth timestep:
for j in range(nx):
u[0,j] = c0(x[j], M)
# Use the boundary condition to fix the string on its ends:
u[:,-L] = left(t)
u[:,L] = right(t)
# Entering the double loop to calculate the solution at every space
#point at every timestep:
for k in range(0,nt-1):
for j in range(1,nx-1):
u[k+1,j] = s*(u[k,j+1] + u[k,j-1]) + (1 - 2*s)*u[k,j]
return u
u_num = DiffusionSolver(x,t,s,L,InitCond,LeftEnd,RightEnd)
u_num = u_num.T #HERE!
plt.plot(x, u_num)
plt.show()
This works for me.
| |
doc_3855
|
I have a formview like this:
<asp:FormView runat="server" ID="FormViewCompany" ItemType="FormViewEncoding.Model.Company" DefaultMode="ReadOnly"
SelectMethod="Select">
<ItemTemplate>
<em>Company</em>
<br/><br/>
<asp:Label runat="server" ID="lblName" Text="Name" Width="200px"/>
<asp:TextBox runat="server" ID="tbxName" Text="<%#: Item.Name %>" Width="600px" />
<br/>
<asp:Label runat="server" ID="lblAddress" Text="Address" Width="200px"/>
<asp:TextBox runat="server" ID="tbxAddress" Text="<%#: Item.Address %>" Width="600px" />
<br/>
<asp:Label runat="server" ID="lblZipAndCity" Text="Zip/City" Width="200px"/>
<asp:TextBox runat="server" ID="tbxZip" Text="<%#: Item.ZipCode %>" Width="75px" />
<asp:TextBox runat="server" ID="tbxCity" Text="<%#: Item.City %>" Width="525px"/>
<br/>
</ItemTemplate>
</asp:FormView>
and when I load a company with German umlauts in its name and address from my SQL Server database (simplified to just return a new instance of an object here):
public class Company
{
public string Name { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
}
public Company Select()
{
return new Company
{
Name = "Müller & Söhne AG",
Address = "Haupstrasse 14",
ZipCode = "5600",
City = "Münchenstein"
};
}
I get this output which is NOT good!
WHY are the German umlauts like ü encoded into #252; ??
This makes no sense to me..... I was hoping to use the new <%#: data binding syntax to do automatic HTML encoding to prevent inadvertently rendering any malicious code - but if all German umlauts get "mangled" in the process, too, I get absolutely not use that feature which is really a pity!
A: I believe it is because the text is being encoded twice.
Take the following line as an example:
<asp:TextBox runat="server" ID="tbxCity" Text="<%#: Item.City %>" Width="525px"/>
This will effectively become:
<asp:TextBox runat="server" ID="tbxCity" Text="Münchenstein" Width="525px"/>
This is due to encoding done by using <%#: %> syntax.
The TextBox control itself also does HtmlEncoding of it's Text Value so the TextBox control will output the html encoding of "Münchenstein" which is "M&#252;nchenstein".
When M&#252;nchenstein is rendered by the browser you will see Münchenstein.
| |
doc_3856
|
{"name": "test1", "type": "string"}
{"name": "test2", "type": "string"}
but after sending and consuming a while, I need modify schema to change the second filed to long type, then it threw the following exception:
Schema being registered is incompatible with an earlier schema; error code: 409
I'm confused, if schema registry can not evolve the schema upgrade/change, then why should I use Schema registry, or say why I use Avro?
A: https://docs.confluent.io/current/avro.html
You might need to add a "default": null.
You can also delete existing one and register the updated one.
A: You can simply append a default value like this.
{"name": "test3", "type": "string","default": null}
A: Fields cannot be renamed in BACKWARD compatibility mode. As a workaround you can change the compatibility rules for the schema registry.
According to the docs:
The schema registry server can enforce certain compatibility rules
when new schemas are registered in a subject. Currently, we support
the following compatibility rules.
Backward compatibility (default): A new schema is backward compatible
if it can be used to read the data written in all previous schemas.
Backward compatibility is useful for loading data into systems like
Hadoop since one can always query data of all versions using the
latest schema.
Forward compatibility: A new schema is forward
compatible if all previous schemas can read data written in this
schema. Forward compatibility is useful for consumer applications that
can only deal with data in a particular version that may not always be
the latest version.
Full compatibility: A new schema is fully
compatible if it’s both backward and forward compatible.
No compatibility: A new schema can be any schema as long as it’s a valid
Avro.
Setting compatibility to NONE should do the trick.
# Update compatibility requirements globally
$ curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data '{"compatibility": "NONE"}' \
http://localhost:8081/config
And the response should be
{"compatibility":"NONE"}
I generally discourage setting compatibility to NONE on a subject unless absolutely necessary.
A: If you need just the new schema and you don't need the previous schemas from schema registry, you can delete the older schemas as mentioned below
:
I've tested this with confluent-kafka and it worked for me
Deletes all schema versions registered under the subject "Kafka-value"
curl -X DELETE http://localhost:8081/subjects/Kafka-value
Deletes version 1 of the schema registered under subject "Kafka-value"
curl -X DELETE http://localhost:8081/subjects/Kafka-value/versions/1
Deletes the most recently registered schema under subject "Kafka-value"
curl -X DELETE http://localhost:8081/subjects/Kafka-value/versions/latest
Ref: https://docs.confluent.io/platform/current/schema-registry/schema-deletion-guidelines.html
| |
doc_3857
|
date - when data changed
a,b,c - some data and it can be anything
date,a,b,c
04/26/2008,1,1,1
04/25/2008,1,2,1
04/24/2008,1,1,1
04/23/2008,1,1,1
04/22/2008,1,1,1
04/21/2008,2,2,2
04/20/2008,1,1,1
This is should be the result. It might have the same data on different dates, but it missing the next day when data stayed the same.
04/26/2008,1,1,1
04/25/2008,1,2,1
04/22/2008,1,1,1
04/21/2008,2,2,2
04/20/2008,1,1,1
It should work on MS SQL Server 2008 r2
A: ; with cte as
(select *,
row_number() over (partition by a,b,c order by date asc) as rn
,row_number() over (order by date asc) as rn1
from yourtablename
)
select min(date) date,a,b,c from cte group by (rn1-rn),a,b,c
order by min(date) desc
Check below link
For reference click here
A: This is like a gaps and islands problem.
create table yourtablename ([date] date,a int,b int,c int);
insert into yourtablename values
('04/26/2008',1,1,1)
,('04/25/2008',1,2,1)
,('04/24/2008',1,1,1)
,('04/23/2008',1,1,1)
,('04/22/2008',1,1,1)
,('04/21/2008',2,2,2)
,('04/20/2008',1,1,1);
; with cte as
(
select date, a,b,c,combinedstring=cast(a as varchar(max))+ cast(b as varchar(max))+ cast(c as varchar(max))
from yourtablename
)
,cte2 as
(select *,
rn1=row_number() over (partition by combinedstring order by date asc)
,rn2= row_number() over (order by date asc)
from cte
)
select y.*
from
(
select date=min(date)
from cte2
group by (rn2-rn1),combinedstring) t
join yourtablename y
on t.date=y.date
| |
doc_3858
|
id date holiday
2 2015-07-04 Independence Day
1 2016-01-01 New Years
3 2016-01-16 Pongal
The intended results will return:
id date holiday
1 2016-01-01 New Years
3 2016-01-16 Pongal
2 2015-07-04 Independence Day
| |
doc_3859
|
=COUNTIFS(MachineData!N:N,{"*Arlington*","*RenewNorfolk*"}, MachineData!$X:$X,"Y",MachineData!$E:$E,"<>*rinse*", MachineData!$C:$C,">="&$O$15-30, MachineData!C:C,"<="&$O$15+0.999988)
On the very first part of the formula I am trying to say "Count if MachineData!N:N is either like Arlington or like RenewNorfolk" but for some reason that specific part of the formula is giving me problems. Can someone help me figure out what the issue is with my syntax? Thank you
A: As explained here, using the *IF(S) type of functions with arrays will make them return an array, so you need to use SUM to get one value.
| |
doc_3860
|
Code inside .bash_profile (below)
alias pxsz='sips -g pixelWidth $1 && sips -g pixelHeight $1'
pxlsz () {
sips -g pixelWidth $1 && sips -g pixelHeight $1
}
When I tested the alias with
alias pxsz="echo '$1 1' && echo '$1 2' "
gives
$pxsz tag_struct.jpg
1
2 tag_struct.jpg
A: You can't use a variable inside an alias like this. Here you just call to the $1 that must be defined beforehand in your shell, and it is the previous first argument of previous command:
$ set TEST
$ echo $1
TEST
$ alias pxsz="echo '$1 1' && echo '$1 2' "
$ pxsz
TEST 1
TEST 2
The function, like you did, is the way to go.
| |
doc_3861
|
camera_pi.py:
import time
import io
import threading
import picamera
class Camera(object):
thread = None # background thread that reads frames from camera
frame = None # current frame is stored here by background thread
def __init__(self):
if self.thread is None:
# start background frame thread
self.thread = threading.Thread(target=self._thread)
self.thread.start()
# wait until frames start to be available
while self.frame is None:
time.sleep(0)
def get_frame(self):
return self.frame
@classmethod
def _thread(cls):
with picamera.PiCamera() as camera:
# camera setup
camera.resolution = (1280, 720)
camera.hflip = False
camera.vflip = False
# let camera warm up
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
for foo in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
# store frame
stream.seek(0)
cls.frame = stream.read()
# reset stream for next frame
stream.seek(0)
stream.truncate()
Main Flask App(This is a part of my code:
from camera_pi import Camera
@app.route('/video_feed')
def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
def gen(camera):
"""Video streaming generator function."""
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
Stream.html:
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Live Streaming</h1>
</div>
<div class="panel-body">
<img id="pic" src="{{ url_for('video_feed') }}" alt="live stream link" class="img-responsive img-rounded"></img>
</div>
</div>
My whole project works fine till i render the stream.html page and call the streaming functions. When you actually load another page it seems that the streaming thread still running right?
Is there any way to kill the thread when I leave the stream.html page? Leaving the stream.html means you are not streaming anymore, so the thread is not needed to be running. The reason is that is killing my pi memory with no reason.
A: Killing threads is not supported. Just add to your thread's loop a check for a global flag, such as:
for foo in camera.capture_continuous(stream, 'jpeg',
use_video_port=True):
if stop_the_thread: break
(and after the loop do whatever's needed to properly close the camera, if anything).
In your main code, set global stop_the_thread to False at the start, and then to True at the time you determine the thread must stop.
It's more elegant, in this specific case, to use a class attribute cls.stop_the_thread rather than an actual global variable, but that doesn't affect the key concepts.
| |
doc_3862
|
I was trying to use SQLite in-memory database for unit tests (we are using MySQL) but I stumbled upon something.
The search engine part of the project use Lucene indexing. Basically, you query it and you get an ordered list of ids, which you can use to query your database with a Where In() clause.
The problem is that there is an ORDER BY Field(id, ...) clause in the query, which order the result in the same order as the results returned by Lucene.
Is there any alternative to ORDER BY Field using SQLite ? Or is there another way to order the results the same way Lucene does ?
Thanks :)
Edit:
Simplified query might looks like this :
SELECT i.* FROM item i
WHERE i.id IN(1, 2, 3, 4, 5)
ORDER BY FIELD(i.id, 5, 1, 3, 2, 4)
A: This is quite nasty and clunky, but it should work. Create a temporary table, and insert the ordered list of IDs, as returned by Lucene. Join the table containing the items to the table containing the list of ordered IDs:
CREATE TABLE item (
id INTEGER PRIMARY KEY ASC,
thing TEXT);
INSERT INTO item (thing) VALUES ("thing 1");
INSERT INTO item (thing) VALUES ("thing 2");
INSERT INTO item (thing) VALUES ("thing 3");
CREATE TEMP TABLE ordered (
id INTEGER PRIMARY KEY ASC,
item_id INTEGER);
INSERT INTO ordered (item_id) VALUES (2);
INSERT INTO ordered (item_id) VALUES (3);
INSERT INTO ordered (item_id) VALUES (1);
SELECT item.thing
FROM item
JOIN ordered
ON ordered.item_id = item.id
ORDER BY ordered.id;
Output:
thing 2
thing 3
thing 1
Yes, it's the sort of SQL that will make people shudder, but I don't know of a SQLite equivalent for ORDER BY FIELD.
| |
doc_3863
|
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] =>
[Ask] =>
)
[1] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] => BidValue1
[Ask] =>
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] =>
)
[3] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] =>
[Ask] => AskValue1
)
[4] => Array
(
[Name] =>Name 2
[Last] =>
[Bid] =>
[Ask] => AskValue2
)
)
and i want to achieve array looks like this
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
I try this way (get it from google)
$result = array();
foreach ($newArray as $element) {
$result[$element['Name']][] = $element;
}
echo "<pre>";print_r($result);
But it is not showing the result that i want. How can i achieve it ?
thanks in advance and sorry for my english
A: You can use below snippet for the same,
$result = [];
foreach ($newArray as $element) {
foreach ($element as $key => $value) {
// checking if value for key is already added to result array
if ((!empty($result[$element['Name']]) && !array_key_exists($key, $result[$element['Name']])) || empty($result[$element['Name']])) {
if (!empty($value)) { // checking if value not empty
$result[$element['Name']] = ($result[$element['Name']] ?? []);
// merge it to group wise name result array
$result[$element['Name']] = array_merge($result[$element['Name']], [$key => $value]);
}
}
}
}
array_merge — Merge one or more arrays
array_key_exists — Checks if the given key or index exists in the array
Demo
Output:-
Array
(
[0] => Array
(
[Name] => NAME1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[1] => Array
(
[Name] => Name2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
A: Here is the shortest and simple solution by using foreach with array_filter
foreach($a as &$v){
$v = array_filter($v);
isset($r[$v['Name']]) ? ($r[$v['Name']] += $v) : ($r[$v['Name']] = $v);
}
You can use array_values to re arrange the order of array.
Working example : https://3v4l.org/XeQHa
| |
doc_3864
|
require.config({
baseUrl: '../global/js',
paths: {
use: 'libs/utilities/use',
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-optamd3-min',
text: 'libs/require/text',
relational: 'libs/backbone/backbone-relational'
},
use: {
"relational": {
deps: ["backbone","underscore"]
}
}
});
I've also gone ahead and augmented the Backbone Relational library
(function(Backbone, _) {
"use strict";
Backbone.Relational = {
showWarnings: true
};
})(this.Backbone, this._);
Finally, I am calling relational within a model
define([
'jquery',
'underscore',
'backbone',
'mediator',
'relational'
], function($, _, Backbone, Mediator){
I am getting an error of cannot set property Relational of undefined. Meaning Backbone is not available. What am I missing?
Some links that I have been using
https://github.com/tbranyen/use.js
https://github.com/tbranyen/layoutmanager-example/blob/master/app/index.js
https://raw.github.com/PaulUithol/Backbone-relational/master/backbone-relational.js
A: Backbone and underscore are not AMD compatible.
Upgrade warning: versions 1.3.0 and higher remove AMD (RequireJS) support.
A: To use (sic) the use plugin you do not need the AMD versions of underscore/backbone.
You do need to wrap them though accordingly, i.e. in your require config have:
use: {
backbone: {
deps: ["use!underscore", "jquery"],
attach: "Backbone"
},
underscore: {
attach: "_"
},
relational: {
deps: ["use!underscore", "use!backbone"]
}
....
}
| |
doc_3865
|
There are many controls ( 100 labels ) in a form. When I resize the form or when I try to update them, the labels will be update one by one. I tried some functions of double buffer to solve this problem, but the following function do not work on mono. Is there any other method to avoid the problem of label flickering?
*
*Setting the style ( UserPaint, AllPaintingInWmPaint and OptimizedDoubleBuffer )
*Setting the property of Form.DoubleBuffered to true
*Overriding the "CreateParam" function to set the WS_EX_COMPOSITED
*SuspendLayout/ ResumeLayout
The method 3 can solve the flicker problem on Windows. However, the flag is not implemented on the mono. so the method 3 do not work on mono.
.Net framework version : 4.7.2
Mono JIT compiler version : 5.12.0.226
Linux kernel version: 4.14.248
| |
doc_3866
|
<div className="md:hidden">Hello</div>
will result the div hidden after the breakpoint md - which after Tailwind doc , it is 768px;
I would like to be able to do the same, but for custom widths, so not 768px;
And I Don't want to write it in the CSS file and I dont want to modify Tailwind files.
I would like to be still inline . Is it possible?
A: Documentation
If you need to use a one-off breakpoint that doesn’t make sense to include in your theme, use the min or max modifiers to generate custom breakpoint on the fly using any arbitrary value.
<div class="min-[320px]:text-center max-[600px]:bg-sky-300">
<!-- ... -->
</div>
| |
doc_3867
|
bulk.find({_id: new mongo.ObjectID(req.session._id)}).updateOne({$pull: {
firstArray: {id: req.params.id},
'secondArray.firstArrayIds': req.params.id
'secondArray.$.firstArrayIds': req.params.id
}});
The firstArray $pull works just fine.
But the secondArray.firstArrayIds and/or secondArray.$.firstArrayIds does not. What am I doing wrong here?
This is my data structure:
clients: {
firstArray: [
{
_id: '153'.
someField1: 'someVal1',
}
...
]
secondArray: [
{
_id: '7423'.
someField1: 'someVal1',
firstArrayIds: [153, 154, 155, ...]
}
...
]
}
EDIT What if there are more than one embedded object in secondArray which firstArrayIds can contain the id i want to delete. In other words, when deleting an object in firstdArray i want to delete references in all secondArray's firstArrayIds Not just the first match.
A: Your "secondArray" has a nested element structure, so you must identify the outer element you want to match in your query when using a positional $ operator in the update. You basically need something like this:
bulk.find({
"_id": new mongo.ObjectID(req.session._id),
"secondArray._id": "7423"
}).update({
"$pull": {
"firstArray": { "_id": "153" },
"secondArray.$.firstArrayIds": 153
}
});
So there are in fact "two" id values you need to pass in with your request in addition to the general document id. Even though this is nested it is okay since you are only matching on the "outer" level and only on one array. If you tried to match the position on more than one array then this is not possible with the positional operator.
| |
doc_3868
|
For execution of command I am using the following code
Runtime rt = Runtime.getRuntime();
String command = "/data/data/app_package_name/files/libs/xyz -edir/data/data/app_package_name/files/libs/ "+ var1 +" "+ var2+" -someFlag , -fl -g, -head";
Process pr = rt.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
line=input.readLine()
I am getting line as nullbut in only Android Lollipop .Its working in Kitkat or below Android versions.
Please comment if any more information is required.
I covered this part of code in try,catch block also but no exceptions is there.
| |
doc_3869
|
I'm using the oauth-sign npm package (which as ~14.5MM weekly downloads at the time of writing this question, so I think it should be working properly) with the following code snippet:
import { hmacsign256 } from 'oauth-sign'
export const API_URL = 'https://account.api.here.com/oauth2/token'
export const nonceLength = 2**5
export interface TokenResponse {
AccessToken: string
TokenType: string
ExpiresIn: number
}
export const generateNonce = (length: number): string => {
let s = ''
do {
s += Math.random().toString(36).substr(2)
} while (s.length < length)
return s.substr(0, length)
}
export const fetchNewTokenFromAPI = async ({ key, secret }: { key: string, secret: string }): Promise<TokenResponse> => {
const url = API_URL
const method = 'POST'
const body = 'grant_type=client_credentials'
const auth = {
oauth_consumer_key: key,
oauth_nonce: generateNonce(nonceLength),
oauth_signature_method: 'HMAC-SHA256',
oauth_timestamp: String(Math.round(new Date().getTime() / 1000)),
oauth_version: '1.0',
}
const sig = encodeURIComponent(hmacsign256(method, API_URL, auth, key, secret))
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `OAuth oauth_consumer_key="${auth['oauth_consumer_key']}",oauth_nonce="${auth['oauth_nonce']}",oauth_signature="${sig}",oauth_signature_method="HMAC-SHA256",oauth_timestamp="${auth['oauth_timestamp']}",oauth_version="1.0"`
}
const options: RequestInit = {
method,
headers,
body,
mode: 'cors',
}
const response = await fetch(url, options)
if (response.ok)
throw new Error(`expected 200 status, received ${response.status}`)
return await response.json()
}
When I run that function, I recieve the following from the api:
{
"error": "invalid_client"
"errorCode": 401300
"errorId": "ERROR-32e365d0-11ce-4fff-86d7-5ca51970e017"
"error_description": "errorCode: '401300'. Signature mismatch. Authorization signature or client credential is wrong."
"httpStatus": 401
"message": "Signature mismatch. Authorization signature or client credential is wrong."
}
A: Sharing the CURL request after testing the token generation API on postman. Consumer key and Consumer secret are here.access.key.id and key.secret respectively. signature method : HMAC-SHA1, Version : 1.0
curl -X POST \
https://account.api.here.com/oauth2/token \
-H 'Authorization: OAuth' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Postman-Token: xxxxxxxxxxxx' \
-H 'cache-control: no-cache' \
-d grant_type=client_credentials
A: curl -X POST \
https://account.api.here.com/oauth2/token \
-H 'Accept: /' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Authorization: OAuth' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Length: 238' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Host: account.api.here.com' \
-H 'Postman-Token: xxxxxxxxx’ \
-H 'User-Agent: PostmanRuntime/7.20.1' \
-H 'cache-control: no-cache' \
-d 'grant_type=client_credentials&oauth_consumer_key=xxxx&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1576653105&oauth_nonce=xxx&oauth_version=1.0&oauth_signature=xxx’
| |
doc_3870
|
On Windows, I downloaded the zip file for the Git plugin for Vim from
https://github.com/WolfgangMehner/git-support
The zip file is entitled git-support-master.zip and has this tree:
git-support-master\doc
git-support-master\git-support
git-support-master\plugin
git-support-master\project
git-support-master\syntax
git-support-master\README.md
My $HOME is c:\Users\myuser
and I have c:\Users\myuser\vimfiles.
I interpreted the instructions to mean that I should be able to extract the zip files so that the doc files in the above zip go into the doc directory above. To do this, I have to extract put prune the
git-support-master from the paths.
~ vimfiles/
~ autoload/
pathogen.vim
~ bundle/
+ delimitMate/
+ nerdtree/
~ doc/
gitsupport.txt
tags
~ git-support/
~ doc/
ChangeLog
~ git-doc/
commands.txt
compile_changelog.lua
help_topics.txt
+ rc/
README.md
+ pack/typescript/start/typescript-vim/
~ plugin/
git-support.vim
~ project/
release.lua
+ syntax/
README.md
vimrc
My .vimrc is:
execute pathogen#infect()
syntax on
filetype plugin indent on
set nocompatible
let $ORACLE_HOME='C:\app\oracle\product\12.1.0\client'
set expandtab
nmap <C-n> :NERDTreeToggle<CR>
set autoindent
set sw=4
set clipboard=unnamed
set nu
set noerrorbells
set nohlsearch
set vb t_vb=
"if $OSTYPE=="cygwin"
" set SHELL=C:\programs\cygwin\bin\bash.exe
"endif
"
"let g:Git_Executable = 'LANG=en_US git'
let g:Git_Executable = 'C:\programs\cygwin\bin\git.exe'
When I run things in the git menu, I get errors like this:
E492: Not an editor command: GitStatus
However, it can find the plugin support.
The Git executable above does exist, and yes I'm using the Cygwin version of it.
I ran the scriptnames command mentioned in the comments but couldn't capture it in a scratchbuffer, but did see that it did not load anything Git plugin related. It loaded the .vimrc, pathogen vim plugins.
I tried :GitHelp and it gave me this:
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
[--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
<command> [<args>]
These are common Git commands used in various situations:
start a working area (see also: git help tutorial)
clone Clone a repository into a new directory
init Create an empty Git repository or reinitialize an existing one
work on the current change (see also: git help everyday)
add Add file contents to the index
mv Move or rename a file, a directory, or a symlink
restore Restore working tree files
rm Remove files from the working tree and from the index
sparse-checkout Initialize and modify the sparse-checkout
examine the history and state (see also: git help revisions)
bisect Use binary search to find the commit that introduced a bug
diff Show changes between commits, commit and working tree, etc
grep Print lines matching a pattern
log Show commit logs
show Show various types of objects
status Show the working tree status
grow, mark and tweak your common history
branch List, create, or delete branches
commit Record changes to the repository
merge Join two or more development histories together
rebase Reapply commits on top of another base tip
reset Reset current HEAD to the specified state
switch Switch branches
tag Create, list, delete or verify a tag object signed with GPG
collaborate (see also: git help workflows)
fetch Download objects and refs from another repository
pull Fetch from and integrate with another repository or a local branch
push Update remote refs along with associated objects
'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
to read about a specific subcommand or concept.
See 'git help git' for an overview of the system.
A: You seem to be mixing three different plugin handling methods:
~ vimfiles/
~ autoload/
pathogen.vim
~ bundle/
shows that you are using Pathogen,
+ pack/typescript/start/typescript-vim/
shows that you are using the new :help package feature,
I interpreted the instructions to mean that I should be able to extract the zip files so that the doc files in the above zip go into the doc directory above. To do this, I have to extract put prune the git-support-master from the paths.
shows that you are trying to install that plugin the "classical" way.
You should choose one method and stick to it…
*
*The classical way is universally considered messy so you should probably avoid it.
*If you only use a recent Vim, you should probably consider Pathogen as deprecated and opt for either the new "package" method—if you don't mind managing your plugins yourself— or a full-fledged plugin manager like vim-plug.
A: if it's show in after type wrong command in CMP panel, then just press esc and then type again your command, that you want to run.
| |
doc_3871
|
A: To generate an .ipa you need a Mac or at least a VM with a MAC that has a developer account (something already bought if i'm not mistaken).
| |
doc_3872
|
pip install --upgrade pip
I get this error message:
Collecting pip
Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB)
100% |████████████████████████████████| 1.2MB 371kB/s
Installing collected packages: pip
Found existing installation: pip 8.0.2
Uninstalling pip-8.0.2:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames
shutil.move(old, new)
File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move
os.unlink(src)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst'
Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac.
I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later).
Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal.
Thanks.
A: A permission issue means your user privileges don't allow you to write on the desired folder(/Library/Python/2.7/site-packages/pip/). There's basically two things you can do:
*
*run pip as sudo:
sudo pip install --upgrade pip
*Configure pip to install only for the current user, as covered here and here.
A: The best way to do it is as follows:
$ python3 -m pip install --upgrade pip
as it's generally not advised to use
$ sudo pip install
More answers can be found here: https://github.com/pypa/pip/issues/5599
A: From administrator mode command prompt, you can run the following command, that should fix the issue:
python -m ensurepip --user
Replace python3 if your version supports that.
A: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirement.txt'
WARNING: You are using pip version 19.2.3, however version 20.3.4 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
$ pip install pip
Requirement already satisfied: pip in /data/data/com.termux/files/usr/lib/python3.9/site-packages (21.0.1)
Showing like this help !!!
| |
doc_3873
|
www.kinektd.ca.
Only when viewing on a mobile device the background banner images on the site get super zoomed in and pixelated.
Is there a mobile device media query I can add that ensures these images do not get zoomed in and pixelated on mobile devices?
Here is the css code that targets the background image;
.ts-home1-data-transferred{
background-attachment: fixed;
background-image: url(../images/background/main02_2-1920x1200.jpg) ;
background-repeat: repeat;
}
Can I target mobile devices and include certain coding that will solve the zoom issue?
Thanks in advance.
| |
doc_3874
|
for example, I have a container that is view having opacity 0.5 and there is a text component inside it, I want to give opacity 0.9 to text but it does not take the opacity , it take the parent's opacity
A: Don't add the opacity value to View style, just give some transparency to the background color as following:
backgroundColor: '#00000009' // the last 2 numbers (05) refer to opacity here.
| |
doc_3875
|
My working structure is
Gruntfile.js
package.json
assets
|
|--sass
| |
| styles.scss
|
|--css
and this is my grunt file
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
sass: {
dist: {
options: {
style: 'expanded'
},
files: [{
expand: true,
cwd: 'assets/sass',
src: ['*.scss'],
dest: '../css',
ext: '.css'
}]
}
}
});
grunt.loadNpmTasks('grunt-sass');
grunt.registerTask('default', ['sass']);
};
I have already verified that I have sass installed
when I run grunt sass, it says that everything when okay. But I have yet to see a compiled css file. The only way that I got this to work is by using the "destination" : "source" syntax.
EDIT: The exact problem I'm having is not that the files are generating in the wrong place, but that they aren't generating. Also, grunt is not showing any errors
Does anyone have a clue as to what is wrong with this?
A: This configuration works for me:
files: [{
expand: true,
cwd: 'assets/sass',
src: ['**/*.scss'],
dest: 'assets/css',
ext: '.css'
}]
Perhaps the ../ is throwing it off; I don't believe the destination path is relative to the source path, it's relative to the Gruntfile.
| |
doc_3876
|
#!groovy
def slack_channel() {
try { if ('' != SLACK_CHANNEL) { return SLACK_CHANNEL } }
catch (MissingPropertyException e) { return '#nathan-webhooks' }
}
// simplify the generation of Slack notifications for start and finish of Job
def jenkinsSlack(type, channel=slack_channel()) {
echo("echo 'In jenkinsSlack()...")
echo("echo 'type specified as : ${type}'")
echo("echo 'channel specified as : ${channel}'")
if ( 'SUCCESS' == currentBuild.result ) {
slackSend channel: channel, color: 'good', message: "type: ${type}"
} else if ( 'FAILURE' == currentBuild.result ) {
slackSend channel: channel, color: 'danger', message:"type: ${type}"
} else {
slackSend channel: channel, color: 'warning', message: "type: ${type}"
}
// node - action starts here
node {
wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm', 'defaultFg': 2, 'defaultBg':1]) {
stage ("send Slack start message") {
checkout scm
jenkinsSlack('start')
}
stage("send Slack finish message") {
jenkinsSlack('finish')
}
} // AnsiColorBuildWrapper
}
Thx
A: Echo messages are missing because jenkinsSlack(type, channel=slack_channel()) just returns the value of slack_channel() without executing the method body including echo.
This is Jenkins specific problem related to CPS transform. Jenkins pipeline script is based on groovy but it has some constraints with regard to its syntax and usage. See more details here: https://github.com/jenkinsci/workflow-cps-plugin/blob/master/README.md#technical-design
Possible workarounds below.
1.Use @NonCPS annotation for slack_channel()
@NonCPS
def slack_channel() {
try { if ('' != SLACK_CHANNEL) { return SLACK_CHANNEL } }
catch (MissingPropertyException e) { return '#nathan-webhooks' }
}
2.determine SLACK_CHANNEL in advance and pass it to the default argument channel:
def slack_channel() {
try { if ('' != SLACK_CHANNEL) { return SLACK_CHANNEL } }
catch (MissingPropertyException e) { return '#nathan-webhooks' }
}
SLACK_CHANNEL = slack_channel()
def jenkinsSlack(type, channel=SLACK_CHANNEL) {
echo type
echo channel
}
| |
doc_3877
|
search_topic_hsv <- "HSV"
search_query_hsv <- EUtilsSummary(search_topic_hsv, retmax= 27000, mindate= 1970, maxdate= 2022)
summary(search_query_hsv) #returns to 26149
records_hsv <- EUtilsGet(search_query_hsv)
EutilsGet functions gives this error:
Error in readLines(collapse(EUtilsFetch, "&retmode=xml"), warn = FALSE, :
cannot read from connection
In addition: Warning message:
In readLines(collapse(EUtilsFetch, "&retmode=xml"), warn = FALSE, :
URL 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=35245365,35243667,35243023,35241838,35240194,35239848,35230726,35229412,35228129,35225980,35225036,35223260,35217873,35216177,35215908,35215799,35214758,35214644,35212944,35208817,35208572,35206263,35205731,35204477,35201702,35202955,35202734,35202567,35201013,35200997,35200729,35200645,35199176,35199165,35198914,35198826,35197947,35197285,35196784,35193038,35187895,35187000,35186664,35185822,35182142,35180012,35179120,35178081,35176987,35175220,35172828,35168095,35167501,35167411,35165387,35164537,35163675,35163086,35161988,35157734,35155582,35154980,35154946,35154584,35150885,35146210,35145504,35144835,35144523,35143960,35142052,35141364,35141210,35141072,35130299,35126336,35121324,35120255,35119473,35119328,35115776,35114961,35114414,35112018,35111489,35110532,35107381,35106980,35106191,35105326,35105322,35103749,35102178,35101046,35100650,35100323,35099587,35097177,35087520,35085968,35083659,35082770,350825 [... truncated]
is this a pubmed connection related issue or package related issue?
packageVersion("RISmed")
[1] ‘2.3.0’
Thanks in advance.
| |
doc_3878
|
Here's the process:
User views movie. Site average rating for the movie is displayed.
Layout code for the RatingBar:
<RatingBar android:id="@+id/ratingBar" android:isIndicator="true"
android:layout_margin="10dip" style="@style/RatingBar"
android:progressDrawable="@drawable/site_rating_bar" android:stepSize="0.1" />
RatingBar style:
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:numStars">10</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:minHeight">30dip</item>
<item name="android:maxHeight">30dip</item>
</style>
site_rating_bar.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/secondaryProgress"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/progress"
android:drawable="@drawable/btn_site_rating_star_on" />
</layer-list>
The user can click on the RatingBar and bring up a dialog where they can add their own custom rating of the movie. Upon close of the dialog, the code updates the rating displayed in the RatingBar above. I'd like to also change the ProgressDrawable so that the color of the stars changes to indicate the user has added a custom rating.
But when I try to set the ProgressDrawable programmatically it does update it so it's displaying the right color, but it only displays a single star, stretched across the screen.
ratingBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.user_rating_bar));
user_rating_bar.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/secondaryProgress"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/progress"
android:drawable="@drawable/btn_user_rating_star_on" />
</layer-list>
I've tried saving the original bounds and resetting them, but it didn't help:
Rect bounds = ratingBar.getProgressDrawable().getBounds();
ratingBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.user_rating_bar));
ratingBar.getProgressDrawable().setBounds(bounds);
Also tried resetting the numStars in case it had gotten lost.
Any ideas greatly appreciated. TIA. :)
A: I'm going through this same thing right now...I can't for the life of me get it to work as expected through code, so I'm going the janky-layout route. :(
<RatingBar
android:id="@+id/beer_rating"
android:numStars="5"
android:progressDrawable="@drawable/rating_bar"
android:indeterminateDrawable="@drawable/rating_bar"
android:stepSize="0.5"
android:isIndicator="true"
android:layout_gravity="center"
style="?android:attr/ratingBarStyleSmall" />
<RatingBar
android:id="@+id/beer_rating_average"
android:indeterminateDrawable="@drawable/rating_bar_average"
android:isIndicator="true"
android:layout_gravity="center"
android:numStars="5"
android:progressDrawable="@drawable/rating_bar_average"
android:stepSize="0.5"
android:visibility="gone"
style="?android:attr/ratingBarStyleSmall"/>
Then just flipping the visibility on them when needed:
findViewById(R.id.beer_rating).setVisibility(View.GONE);
findViewById(R.di.beer_rating_average).setVisibility(View.VISIBLE);
Sucks, but it works. Let me know if you come up with any other solves.
A: Try using:
Use ProgressBar.setProgressDrawableTiled(Drawable)
and set minSDK to 21
| |
doc_3879
|
I've read through the ECS portion of the API documentation (https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ECS.html) a few times but cannot find an API method to update the configuration of an ECS cluster.
You can do this on the UI if you go into ECS > clusters > your cluster > ECS Instances > Scale ECS Instances:
Is there a way to do this programatically do this with the existing methods? Does there exist an ECS.updateCluster method?
A: It appears, your cluster was created with the console first-run experience and that's why you were able to see Scale ECS Instances Option.
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/scale_cluster.html
If your cluster was created with the console first-run experience after November 24, 2015, then the Auto Scaling group associated with the AWS CloudFormation stack created for your cluster can be scaled up or down to add or remove container instances. You can perform this scaling operation from within the Amazon ECS console.
If your cluster was not created with the console first-run experience after November 24, 2015, then you cannot scale your cluster from the Amazon ECS console. However, you can still modify existing Auto Scaling groups associated with your cluster in the Auto Scaling console. If you do not have an Auto Scaling group associated with your cluster, you can create one from an existing container instance.
I would not recommend using console for cluster creation in production environment. You should ideally use CF template to create cluster which can be placed AutoScaling Group.
You can modify AutoScaling Group desired count using following API.
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/AutoScaling.html#setDesiredCapacity-property
var params = {
AutoScalingGroupName: "my-auto-scaling-group",
DesiredCapacity: 2,
HonorCooldown: true
};
autoscaling.setDesiredCapacity(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
A: There is no way to do it via SDK directly. You have to use underlying ASG to set the desired count. As in the backend, ECS Cluster setup is done by the cloudformation template which creates an Auto-Scaling group for that EC2 pool.
You will be able to find the associated autoscaling group with the cluster in the ASG section of EC2. You can use SDK to update the desired count of that auto-scaling group, That will affect this desired count in ECS.
If you want to use autoscaling feature then you may use cloudwatch alarms to scale up and scale down instances based on different metrics say CPU Reservation/Utilization or MEMORY Reservation/Utilization.
Ref: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cloudwatch_alarm_autoscaling.html
| |
doc_3880
|
Where the exception contains culture-sensitive data, the string
representation returned by ToString is required to take into account
the current system culture.
What does it means? Does it means that if the language of the system is French, then the returned message will be in French?
A: It means that the text may be displayed to the users so it should be understandable to the users. If they are all French, then it would be a good idea for the message to be in French.
More than that though, they need to understand the terms used in the message. It's not much good talking about array bounds and stack overflows and IO exceptions if the target audience is (for example) hairdressers.
| |
doc_3881
|
Example of the file is:
BBBBB
BBBBB
BBBBB
BBBBB
public class maze_2D{
static Scanner s = new Scanner(System.in);
public static void FromFile() throws Exception{//
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// Read from file.....
But when I run the program, i get an error
Enter Filename
java.io.FileNotFoundException:
Why is this happening, why this scanner doesn't allow me to enter any file name?
A: While inputting file name in command prompt give the full path including file name with extension where your file resides in the File System.
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
try {
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
A: I made a little class using most of your code ad it worked fine... try examining your path+filename to ensure it is really there.
I have heard of scanner.getInteger forcing you to add a scanner.nextLine() after it but you are using nextLine to the the fileName so this shouldn't be the case.
public class NewClass {
static Scanner s = new Scanner(System.in);
public static void main(String args[]) throws Exception {
FromFile();
}
public static void FromFile() throws Exception {
System.out.println("Enter File name");
// I enter '/Users/myMame/Downloads/testFile.txt'
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// do your 2D array manipulation
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println("line: " + line);
}
}
}
| |
doc_3882
|
I was thinking I could somehow use the GitHub URL, but that doesn't seem like it'll work. For example say my code is at https://github.com/apple/swift, then the unique organization DNS would have to be something like apple/com.github, but apple/ is not a valid part of a domain; and thus I would be left with com.github, which is belongs to another company.
I could theoretically use com.github.apple but this is a made up URL, and what's to say that it won't be a valid URL for some other organization in the future?
A: Each GitHub user or organization can have their own set of GitHub Pages, which, among other things, gives you a domain such as apple.github.io.
Follow the tutorial, and choose to create a "User or organization site." Once you are done, you can use the domain as a company identifier in reverse DNS notation: io.github.username
| |
doc_3883
|
HEAP CORRUPTION causes when i try to make n x n matrix and put numbers in :/
i dont know where to fix as i am using malloc for the first time
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
//void gauss(matrix);
int main(void)
{
int i, n;
int x, y;
int **matrix; //define matrix[x][y]
int **L;
int **U;
printf("nxn matrix type n.\n");
scanf("%d", &x);
y = x, n = x;
matrix = (int **)malloc(sizeof(int *) * x); // int* number x primary structure
for (i = 0; i<x; i++)
{
matrix[i] = (int *)malloc(sizeof(int) * y);
} //build matrix[x][y(size of x)] structure
L = (int **)malloc(sizeof(int *) * x); // int* number x primary structure
for (i = 0; i<x; i++)
{
L[i] = (int *)malloc(sizeof(int) * y);
} //build L[x][y(size of x)] structure
U = (int **)malloc(sizeof(int *) * x); // int* number x primary structure
for (i = 0; i<x; i++)
{
U[i] = (int *)malloc(sizeof(int) * y);
} //build U[x][y(size of x)] structure
printf("type the number of matrix \n");
for (x = 0; x < n; x++){
for (y = 0; y < n; y++){
printf("line %d x%d number : ", x + 1, y + 1);
scanf("%lf", &matrix[x][y]);
}
}
for (i = 0; i<x; i++)
{
free(matrix[i]);
}
free(matrix);//free matrix
for (i = 0; i<x; i++)
{
free(L[i]);
}
free(L);//free L
for (i = 0; i<x; i++)
{
free(U[i]);
}
free(U);//free U
return 0;
}
A: A warning is printed as i compiled your code by gcc main.c -o main -Wall :
main.c:51:9: attention : format ‘%lf’ expects argument of type ‘double *’, but argument 2 has type ‘int *’ [-Wformat]
I was able to reproduce the heap corruption by using a size of 6.
The correct way to ask for an integer, since matrix is of type int** is :
scanf("%d", &matrix[x][y]);
Once this is corrected, the heap corruption seems to be solved.
Here is the resulting code. Notice that the return value of malloc() is checked and x is not used as the size of the matrix anymore. Compile it by gcc main.c -o main
#include <stdio.h>
#include <stdlib.h>
//void gauss(matrix);
int main(void)
{
int i, n;
int x, y;
int **matrix; //define matrix[x][y]
int **L;
int **U;
printf("nxn matrix type n.\n");
scanf("%d", &n);
//y = x, n = x;
matrix = malloc(sizeof(int *) * n); // int* number x primary structure
if(matrix==NULL){printf("malloc failed\n");exit(1);}
for (i = 0; i<n; i++)
{
matrix[i] = malloc(sizeof(int) * n);
if(matrix[i]==NULL){printf("malloc failed\n");exit(1);}
} //build matrix[x][y(size of x)] structure
L = malloc(sizeof(int *) * n); // int* number x primary structure
if(L==NULL){printf("malloc failed\n");exit(1);}
for (i = 0; i<n; i++)
{
L[i] = malloc(sizeof(int) * n);
if(L[i]==NULL){printf("malloc failed\n");exit(1);}
} //build L[x][y(size of x)] structure
U = malloc(sizeof(int *) * n); // int* number x primary structure
if(U==NULL){printf("malloc failed\n");exit(1);}
for (i = 0; i<n; i++)
{
U[i] = malloc(sizeof(int) * n);
if(U[i]==NULL){printf("malloc failed\n");exit(1);}
} //build U[x][y(size of x)] structure
printf("type the number of matrix \n");
for (x = 0; x < n; x++){
for (y = 0; y < n; y++){
printf("line %d x%d number : ", x + 1, y + 1);
scanf("%d", &matrix[x][y]);
}
}
for (i = 0; i<n; i++)
{
free(matrix[i]);
}
free(matrix);//free matrix
for (i = 0; i<n; i++)
{
free(L[i]);
}
free(L);//free L
for (i = 0; i<n; i++)
{
free(U[i]);
}
free(U);//free U
return 0;
}
Hope it helps !
EDIT : here is a link to an interesting question about
memory allocation of 2D array. Yours is correct and allows to change the length of each line independently. The other alternative is to allocate all values at once and values are contiguous in memory. This is required by libraries such as lapack of fftw.
| |
doc_3884
|
A: Your question is not very clear to me. But with what I feel is use ActionBarSherlock and define both left fragment and right fragment in xml and use refer it in the MainActivity. I hope I helped. Is this what you want?
| |
doc_3885
|
What I do is, I take snapshots of a system every 15 minutes and I want to be able to draw some graph over a long period. Since the graphs get really confusing if too many points are shown (besides getting really slow to render) I want to reduce the number of points by aggregating multiple points into a single point by averaging over them.
For this I'd have to be able to group by buckets that can be defined by me (daily, weekly, monthly, yearly, ...) but so far all my experiments had no luck at all.
Is there some trick I can apply to do so?
A: It's easy to truncate times to the last 15 minutes (for example), by doing something like:
SELECT dateadd(minute, datediff(minute, '20000101', yourDateTimeField) / 15 * 15, '20000101') AS the15minuteBlock, COUNT(*) as Cnt
FROM yourTable
GROUP BY dateadd(minute, datediff(minute, '20000101', yourDateTimeField) / 15 * 15, '20000101');
Use similar truncation methods to group by hour, week, whatever.
You could always wrap it up in a CASE statement to handle multiple methods, using:
GROUP BY CASE @option WHEN 'week' THEN dateadd(week, .....
A: I had a similar question: collating-stats-into-time-chunks and had it answered very well. In essence, the answer was:
Perhaps you can use the DATE_FORMAT() function, and grouping. Here's an example, hopefully you can adapt to your precise needs.
SELECT
DATE_FORMAT( time, "%H:%i" ),
SUM( bytesIn ),
SUM( bytesOut )
FROM
stats
WHERE
time BETWEEN <start> AND <end>
GROUP BY
DATE_FORMAT( time, "%H:%i" )
If your time window covers more than one day and you use the example format, data from different days will be aggregated into 'hour-of-day' buckets. If the raw data doesn't fall exactly on the hour, you can smooth it out by using "%H:00."
Thanks be to martin clayton for the answer he provided me.
A: As an addition to @cmroanirgo, I didn't need "sums" of data, but avarages (to see the avarage FPS / player count of my game servers). And, I need to view in detail per 5 minutes - or view an entire week of data (data gets stored every minute).
As an example, you can use the SQL command AVG instead of SUM to get an avarage. Also, you'd have to name your selected values to something, and it shouldn't be the actual field name (that will conflict lateron in your query). Here's the query I'm using to aggregate avarages, of 1 week, by the hour:
SELECT
DATE_FORMAT( moment, "%Y-%m-%d %H:00" ) as _moment,
AVG( maxplayers ) as _maxplayers,
AVG( players ) as _players,
AVG( servers ) as _servers,
AVG( avarage_fps ) as _avarage_fps,
AVG( avarage_realfps ) as _avarage_realfps,
AVG( avarage_maxfps ) as _avarage_maxfps
FROM
playercount
WHERE
moment BETWEEN "<date minus 1 week>" AND "<now>"
GROUP BY
_moment
ORDER BY moment ASC
This is then used (together with PHP) to use in a Bootstrap graph;
<?php
//Do the query here
foreach ($result->fetch_all(MYSQLI_ASSOC) as $item) {
$labels[] = $item['_moment'];
$maxplayers[] = $item['_maxplayers'];
$players[] = $item['_players'];
$servers[] = $item['_servers'];
$fps[] = $item['_avarage_fps'];
$fpsreal[] = $item['_avarage_realfps']/10;
$fpsmax[] = $item['_avarage_maxfps'];
}
?>
var playerChartId = document.getElementById("playerChartId");
var playerChart = new Chart(playerChartId, {
type: 'line',
data: {
labels: ["<?= implode('","', $labels); ?>"],
datasets: [
{
data: [<?= implode(',', $servers); ?>],
borderColor: '#007bff',
pointRadius: 0
},
//etc...
| |
doc_3886
|
I have a UITableViewController having 4 sections and one row in each section.
In section 1, I have a hide button that should hide the row in section 1.
When I click this button again, then row should re-appear.
I am using following code:
-(void)hide:(id)sender
{
HideBtn = (UIButton *)sender;
isReadMoreButtonTouched = YES;
[[self tableView] beginUpdates];
[[self tableView] reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem: HideBtn.tag
inSection:0]]
withRowAnimation:UITableViewRowAnimationAutomatic];
[[self tableView] endUpdates];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
if (indexPath.section==0) {
if(isReadMoreButtonTouched && [indexPath row] == indexOfReadMoreButton) {
//design your read more label here
CGRect detailFrame = [Utility getlabelHeight:CGRectMake(10,0,310,20)
withFontName:appFont
andFontSize:15
andText:description];
DeatilsTxtView = [[UILabel alloc] initWithFrame:detailFrame];
DeatilsTxtView.backgroundColor = [UIColor whiteColor];
DeatilsTxtView.font = [UIFont fontWithName:appFont size:15];
DeatilsTxtView.text = description;
[DeatilsTxtView setLineBreakMode:NSLineBreakByWordWrapping];
DeatilsTxtView.numberOfLines = 0;
[DeatilsTxtView sizeToFit];
[cell.contentView addSubview:DeatilsTxtView];
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && isReadMoreButtonTouched && [indexPath row] == indexOfReadMoreButton) {
float height = 10;
description = [description stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
CGRect frame1 = [Utility getlabelHeight:CGRectMake(0,10, 250,20)
withFontName:appFont
andFontSize:15
andText:description];
height = height+frame1.size.height;
return height;
}
}
Using this code, when I run that time row invisible and when i click hide button row visible but when I again click its not invisible.
I want when I click hide button that time row should invisible and when i again click, row should become visible.
A: It's not hiding before you are not making isReadMoreButtonTouched flag FALSE and also not providing any step for FALSE in cellForRowAtIndex method. Check out below lines to be added.
-(void)hide:(id)sender
{
HideBtn = (UIButton *)sender;
If(!isReadMoreButtonTouched);
isReadMoreButtonTouched = YES;
else
isReadMoreButtonTouched = N0; /* Making isReadMoreButtonTouched FALSE for making row invisible on second tap of button */
[[self tableView] beginUpdates];
[[self tableView] reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem: HideBtn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
[[self tableView] endUpdates];
}
Also in cellForRowAtIndex method-
if(isReadMoreButtonTouched && [indexPath row]== indexOfReadMoreButton)
{
// design your read more label here
//Detail TextView
[cell.contentView addSubview:DeatilsTxtView];
}
else /* ADD THIS ELSE PART SO AS TO REMOVE SUBVIEW ADDED */
{
[cell.contentView removeFromSuperview];
}
Similarly you will provide false condition in heightForRowAtIndexPath method as per you need.
If any query let me know.
| |
doc_3887
|
First query:
Dim costAmounts = (From t In model.OrderTrades
Join o In model.Orders On t.OrdNum Equals o.OrdNum
Where o.ClientCode = clientNumber And o.BookDate = sysrec.ETicketsBookDate
Group t By t.Buy, t.OrdNum Into Amount = Sum(t.BuyAmount) _
Select OrdNum = OrdNum, Currency = Buy, SellAmount = Amount).ToList().AsQueryable()
Second Query:
Dim orders = (From a In costAmounts _
Group Join s In settlements On s.Currency Equals a.Currency _
And s.OrdNum Equals a.OrdNum Into amounts = Group _
From g In amounts.DefaultIfEmpty _
Where g Is Nothing OrElse a.SellAmount - g.Paid <> 0 _
Select OrdNum = a.OrdNum Distinct).ToList()
A: You should never need to combine the two.
AsQueryable is there to give you lazy evaluation features, which the ToList completely negates.
So, the LINQ query is forced to be evaluated by ToList, then, the in memory list is converted to an IQueryable in order to allow... querying over it. Instead of constructing the query and only getting the results as needed.
A: The .ToList() would break the delayed execution which is often very helpful (passing queryables around will defer the execution, but could end up actually doing several executions later instead, if passed to multiple classes or methods). Once you do .AsQueryable() you then return the result as Queryable which might be a requirement.
EDIT: If we can agree that calling .ToList() on a queryable, and then pass the list around is the right pattern for some uses (i can really speed up your application in cases where your queryables explode into multiple variations, each needed to be executed at some point). If you break the delayed execution at some point your queries from there will be simplified and faster - then calling .AsQueryable() later would only serve the purpose of fitting the result to a specific (perhaps needed for some api) type.
| |
doc_3888
|
CSS example:
div.something {
background:transparent url(../images/table_column.jpg) repeat scroll 0 0;
}
(The issue is described in many places but haven't seen any conclusive explanation or fix.)
A: Strangely enough, after smashing my head on the keyboard for hours, I added display:table; to the DIV's style and the background image magically appeared in FF.
A: It looks like a background-attachment issue. It needs to be set to fixed (not scroll) to work in FF.
See: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_background-position
A: Happend with me. The jpg does shows in IE but not in Firefox or Chrome. Here is the solution
Change the following css for the element where image is displayed. It can be span, div or any other element :
display:block
A: Old post but I just Had a similar problem images not showing up in Firefox turns out it was Ad-block add-on, had to change the names of my images
A: Try putting the image name in quotes, e.g.:
background-image: url('image.jpg');
A: I've had a similar issue. The reason is that firefox is sensitive for missing fields in your css. Chrome will (sometimes) auto complete missing field, thus the issue appears on your firefox browser.
You need to add a display type, because right now it is being translated to 0 height.
In my case:
.left-bg-image {
display: block; // add this line
background-image: url('../images/profile.jpeg');
background-repeat: no-repeat;
background-size: cover;
background-position: center center;
opacity: .6;
min-width: 100%;
min-height: 100vh;
}
A: Sorry this got huge, but it covers two possibilities that consistently happen to me.
Possibility 1
You may find the path to the CSS file isn't correct. For example:
Say I have the following file structure:
public/
css/
global.css
images/
background.jpg
something/
index.html
index.html
On public/index.html the following paths will include the CSS file:
#1: <link href="./css/global.css"
#2: <link href="/css/global.css"
#3: <link href="css/global.css"
However on public/something/index.html number 1 and 3 will fail. If you are using a directory structure like this (or an MVC structure e.g.: http://localhost/controller/action/params) use the second href type.
Firebug's Net monitor tab will tell you if the CSS file can't be included.
On the subject of paths remember that images are relative to the path of the CSS file. So:
url('./images/background.jpg') /* won't work */
url('../images/background.jpg') /* works: ../ == up one level */
Hover over the url() part of the background attribute in Firebug's CSS tab to check if the file's being loaded.
Possibility 2
It could be that the div has no content and thus has a 0 height. Make sure the div has at least a line of something in (e.g.: lorem ipsum delors secorum) or:
div.something {
display: block; /* for verification */
min-height: 50px;
min-width: 50px;
}
Check Firebug's layout tab (of the HTML tab) to check the div has a height/width.
A: Make sure that the image you are referring to is relative to the css file and not the html file.
A: try this.
background-color: transparent;
background-image: url("/path/to/image/file.jpg");
background-repeat: repeat;
background-position: top;
background-attachment: scroll;
A: Instead of using URLs relative to the page/stylesheet, a cross-browser solution is to give a relative URL starting with the application/domain root.
/* Relative to Stylesheet (Works in Firefox) */
background: url('../images/logo.gif');
/* Relative to Page (Works in IE, Chrome etc.) */
background: url('images/logo.gif');
/* Absolute path (Fine, unless you change domains)*/
background: url('http://www.webby.com/myproduct/images/factsheet.gif');
/* Domain Root-relative path (Works in Firefox, IE, Chrome and Opera) */
background: url('/myproduct/images/factsheet.gif');
FYI: As far as I'm concerned, there is no requirement to use quotes in CSS URLs, I've used them here 'cause it looks prettier.
A: I solved a similar problem by renaming the CSS class. MSIE allows CSS class IDs to begin with numbers; Firefox doesn't. I had created a class using the width of the image in pixels e.g. .1594px-01a
I actually knew it was non-standard syntax but since it was working fine in MSIE I had forgotten about it. After trying all the other stuff it finally dawned on me that it could be a simple as the naming, and as soon as I put a letter in front of the class, presto!
A: For me, it was a matter of the file-name being case-sensitive. I'm not sure if it was CSS or if it was my Ubuntu operating system, or if it was firefox, but the way that I finally got the background images to display was by referring to BlueGrad.jpg instead of bluegrad.jpg. The former of the two is how it was saved. I didn't think it would be case sensitive, but it was.
A: You could try this:
div.something {
background: transparent url(../images/table_column.jpg);
}
The other declarations are shorthand CSS properties, and I afaik they are not needed.
Do you have this online somewhere? I'd like to see if I can fiddle with it a bit. (locally)
A: More questions than answers I'm afraid, but they might help you get to the right answer:
Is it possible that you are collapsing the div in Firefox in some way (with some floats or similar)?
Is there any other content in the div to ensure it's large enough to display the image?
Have you installed Firebug and taken a look at the CSS definitions on the page?
A: Are you absolutely sure the image is a JPG file and not a PNG/Other file?
I'm wondering if IE is letting you get away with something other browsers are not.
Likewise, is the files case exactly as specified?
A: There's this HTML 'base' tag like in
<head>
<base href="http://example.com/some/bizarre/directory"/>
</head>
If this is present in your page, the image for the url is not relative to your current url, but to the given base url. I wouldn't know why IE displays it and Firefox doesn't, though.
The Webdeveloper Firefox extension provides the option to "Display broken images" - this may come in handy. Also, you might try "Live Http Headers" to see if/what image is requested and what the return code is.
A: I had a similar problem regarding the CSS background-image property in FF. It worked fine in IE but refused to work in FF ;) After reading a few posts I established that the issue was indeed that there was no content in the div except for a table (I was trying to make the background image adjust to the size of the broswer without collapsing or expanding and therefore used a much larger image in the background of the div in order to form a 'cropping' of sorts.) The solution for me it seems was to simply 'cheat' by placing an img tag that displayed a blank .png file that I then re-adjusted to the the correct height of the image with width set to 100%. This worked for my problem, and I hope it helps anyone else who is running into a similar problem. Probably not the best fix, but it's a fix ;)
A: The only other thing I can think of besides what has already been said is the way the picture was created. If you made/edited the image in Photoshop, make sure you save as Save For Web...
Sometimes if you use a JPG image for Photoshop without saving as a Web image, it may not appear in Firefox. I had that happen a few weeks ago where a graphic artist created a beautiful header for a mini site and it would NOT appear in FF!
Wait...
Try setting a width and height on the div to expand it. It may be a no-content issue in your div.
A: For those, who encounter the problem in FF, but not in Chrome:
You could mistakenly mix between different value types for the position.
For example,
background: transparent url("/my/image.png") right 60% no-repeat;
Will make this error. The fix could be:
background: transparent url("/my/image.png") 100% 60% no-repeat;
A: I found two things that were causing this problem:
*
*I was using a .tif file which Firefox did not seem to like - I changed to a .png file.
*I added overflow:auto; to the CSS for the div - display:block; did not work for me.
A: My mistake was to use '\' instead of '/'. Worked OK in IE, but not in other browsers.
A: It may look very weird, but this works for me >
#hwrap {
background-color: #d5b75a;
background: url("..//design/bg_header_daddy.png"), url("..//design/nasty_fabric.png");
background-position: 50% 50%, top left;
background-origin: border-box, border-box;
background-repeat: no-repeat, repeat;
}
Yes, a double dot and double slash ... ??!!?? ... I can't find anything on the internet that reports this strange behaviour.
[edit]
I've made a seperate post > https://stackoverflow.com/q/18342019/529802
A: (It doesn't seem like these are the exact circumstances as of the OP but the issue is somewhat related and I've found a workaround for that which I want to share)
I've had the same problem – background-image visible everywhere except in Firefox – and for me, the issue had to do with the fact that I'm working on a browser add-on.
I'm injecting a file style.css in the pageMod module with the contentStyleFile attribute. In it, there's the rule background-image: url(/img/editlist.png); where I'm referencing an image file external to the add-on. The problem here is that Firefox, unlike other browsers, misinterprets this external domain root as the add-on's internal root!
The css-file is a 1:1 port from the Chrome version of the extension/add-on, so I didn't want to mess around with it. That's why I've added an additional contentStyle rule in combination with a copy of that image in my resource folder. This rule simply overwrites the rule inside the css-file.
(In hindsight maybe even a more elegant method than before …)
A: Nobody mentioned background-origin so there you go :
background-image:url('dead.beef');
background-size: 100% 100%;
background-origin:border-box;
Solved the problem for me ; my background apparently was outside my div.
A: In my case it caused by "Strict" mode in FF Privacy & Security settings. After I have changed to "Standard" all background images had become visible.
A: This worked for me:
1) Click on the background image table.
2) Right click on the status bar at the bottom of the page.
3) Click Inline styles.
4) Click the Background styles tab.
5) If you see 'Transparent' in the colour title, that is the problem.
6) Click the colour box and select a colour (white is a good choice.)
7) The colour title should now read white.
8) Click OK.
9) Save the page.
10) Upload the page and overwrite the existing file.
11) Refresh the page and your background picture will display.
Note: Please ensure that you have uploaded your background picture jpeg. I forgot to upload the background jpeg once and spent ages trying to sort it before I realised my error.
Regards
Martin
| |
doc_3889
|
Task 1:
protected Void doInBackground(Void... paramArrayOfParams) {
android.os.Debug.waitForDebugger();
for(j=1; j<(size+1); j++)
{
....
try{ othertask.wait();
}catch(InterruptedException e){}
//wait for other task();
}
Task 2:
protected Void doInBackground(Void... paramArrayOfParams) {
android.os.Debug.waitForDebugger();
for(j=1; j<(size+1); j++)
{
....
notifyAll();
//notifythatroundisfinished();
}
I tried to use notify and wait, but it seems that this is not solving the issue. I do not know any additional methods which I could use to solve the issue. Is it actually possible to wait two for the other task while both are running?
A: I believe the answer to questions below can provide you about the abstract information on how to manage multiple Async tasks.
How to manage multiple Async Tasks efficiently in Android
Running multiple AsyncTasks at the same time -- not possible?
and github example:
https://github.com/vitkhudenko/test_asynctask (credits to: vitkhudenko)
A: If this is Java-7 you are looking for a Phaser. The method you need is arriveAndAwaitAdvance.
In earlier versions of Java (5.1 or later) you would probably use a Semaphore.
Alternatively - you could switch to using a thread pool such as an ExecutorService and Futures. This would be much more scalable and take better advantage of the a multi-core processor.
| |
doc_3890
|
Here is some example code:
species=c(rep("sorgho" , 1) , rep("poacee" , 1) )
condition=rep(c("normal" , "stress") ,1)
value=abs(rnorm(4 , 0 , 4))
data2=data.frame(species,condition,value)
library(ggplot2)
# Stacked Percent
ggplot(data2, aes(fill=condition, y=value, x=species)) +
geom_bar( stat="identity", position="fill")
But my data looks like:
A B
Group C 4 5
D 1 2
The plot should tell me: What percentage of A is in Group C, and what percentage of B is in Group D?
Thanks.
A: Are you looking for something like this?
library(reshape2)
library(ggplot2)
data <- matrix(c(4, 1, 5, 2), ncol = 2, dimnames = list(c("C", "D"), c("A", "B")))
data_m <- melt(data, varnames = c("Exp", "Obs"), id.vars = "Exp")
ggplot(data_m %>% group_by(Exp) %>%
mutate(perc = round(value/sum(value),2)),
aes(x = Exp, y = perc,
fill = Obs, cumulative = TRUE)) +
geom_col() +
geom_text(aes(label = paste0(perc*100,"%")),
position = position_stack(vjust = 0.5))
| |
doc_3891
|
I tried using both /dev/random and /dev/urandom but that didn't make a big difference: starting my HTTPS server takes minutes as well as generating a seed for any incoming connection.
What's the solution to a lack of entropy ?
| |
doc_3892
|
In this case im trying to Book a flight BCN MAD for 1 ADT + 1 CNN + 1 INF
EnhancedAirBookRQ
<EnhancedAirBookRQ xmlns="http://services.sabre.com/sp/eab/v3_7" version="3.7.0" HaltOnError="false">
<OTA_AirBookRQ>
<RetryRebook Option="true"/>
<HaltOnStatus Code="UC"/>
<HaltOnStatus Code="US"/>
<HaltOnStatus Code="NO"/>
<OriginDestinationInformation>
<FlightSegment DepartureDateTime="2018-06-12T11:00:00" ArrivalDateTime="2018-06-12T12:25:00" FlightNumber="1101" NumberInParty="2" ResBookDesigCode="A" Status="NN">
<DestinationLocation LocationCode="MAD" />
<MarketingAirline Code="IB" FlightNumber="1101" />
<OriginLocation LocationCode="BCN" />
</FlightSegment>
<FlightSegment DepartureDateTime="2018-06-16T09:30:00" ArrivalDateTime="2018-06-16T10:45:00" FlightNumber="930" NumberInParty="2" ResBookDesigCode="A" Status="NN">
<DestinationLocation LocationCode="BCN" />
<MarketingAirline Code="IB" FlightNumber="930" />
<OriginLocation LocationCode="MAD" />
</FlightSegment>
</OriginDestinationInformation>
<RedisplayReservation NumAttempts="5" WaitInterval="2000"/>
</OTA_AirBookRQ>
<OTA_AirPriceRQ>
<PriceRequestInformation Retain="true">
<OptionalQualifiers>
<PricingQualifiers>
<PassengerType Code="ADT" Quantity="1" /><PassengerType Code="CNN" Quantity="1" /><PassengerType Code="INF" Force="true" Quantity="1" />
</PricingQualifiers>
</OptionalQualifiers>
</PriceRequestInformation>
</OTA_AirPriceRQ>
<PostProcessing IgnoreAfter="false">
<RedisplayReservation WaitInterval="500"/>
</PostProcessing>
<PreProcessing IgnoreBefore="false"/>
</EnhancedAirBookRQ>
EnhancedAirBookRS
<EnhancedAirBookRS xmlns="http://services.sabre.com/sp/eab/v3_7">
<ApplicationResults
xmlns="http://services.sabre.com/STL_Payload/v02_01" status="Incomplete">
<Error type="BusinessLogic" timeStamp="2018-05-26T12:01:57.688-05:00">
<SystemSpecificResults>
<Message code="ERR.SP.HALT_ON_STATUS_RECEIVED">Specified HaltOnStatus Received - Processing Aborted</Message>
</SystemSpecificResults>
</Error>
</ApplicationResults>
<OTA_AirBookRS>
<OriginDestinationOption>
<FlightSegment ArrivalDateTime="06-12T12:25" DepartureDateTime="06-12T11:00" FlightNumber="1101" NumberInParty="002" ResBookDesigCode="A" Status="QF" eTicket="true">
<DestinationLocation LocationCode="MAD"/>
<MarketingAirline Code="IB" FlightNumber="1101"/>
<OriginLocation LocationCode="BCN"/>
</FlightSegment>
<FlightSegment ArrivalDateTime="06-16T10:45" DepartureDateTime="06-16T09:30" FlightNumber="0930" NumberInParty="002" ResBookDesigCode="A" Status="QF" eTicket="true">
<DestinationLocation LocationCode="BCN"/>
<MarketingAirline Code="IB" FlightNumber="0930"/>
<OriginLocation LocationCode="MAD"/>
</FlightSegment>
</OriginDestinationOption>
</OTA_AirBookRS>
<TravelItineraryReadRS>
<RetryRebook Successful="false"/>
<TravelItinerary>
<CustomerInfo/>
<ItineraryInfo>
<ReservationItems>
<Item RPH="1">
<FlightSegment AirMilesFlown="0301" ArrivalDateTime="06-12T12:25" DayOfWeekInd="2" DepartureDateTime="2018-06-12T11:00" ElapsedTime="01.25" eTicket="false" FlightNumber="1101" NumberInParty="02" ResBookDesigCode="O" SegmentNumber="0001" SmokingAllowed="false" SpecialMeal="false" Status="UC" StopQuantity="00" IsPast="false">
<DestinationLocation LocationCode="MAD" Terminal="TERMINAL 4" TerminalCode="4"/>
<Equipment AirEquipType="32A"/>
<MarketingAirline Code="IB" FlightNumber="1101"/>
<Meal Code="G"/>
<OriginLocation LocationCode="BCN" Terminal="TERMINAL 1" TerminalCode="1"/>
<SupplierRef ID="DCIB"/>
<UpdatedArrivalTime>06-12T12:25</UpdatedArrivalTime>
<UpdatedDepartureTime>06-12T11:00</UpdatedDepartureTime>
</FlightSegment>
</Item>
<Item RPH="2">
<FlightSegment AirMilesFlown="0301" ArrivalDateTime="06-16T10:45" DayOfWeekInd="6" DepartureDateTime="2018-06-16T09:30" ElapsedTime="01.15" eTicket="false" FlightNumber="0930" NumberInParty="02" ResBookDesigCode="O" SegmentNumber="0002" SmokingAllowed="false" SpecialMeal="false" Status="UC" StopQuantity="00" IsPast="false">
<DestinationLocation LocationCode="BCN" Terminal="TERMINAL 1" TerminalCode="1"/>
<Equipment AirEquipType="32A"/>
<MarketingAirline Code="IB" FlightNumber="0930"/>
<Meal Code="G"/>
<OriginLocation LocationCode="MAD" Terminal="TERMINAL 4" TerminalCode="4"/>
<SupplierRef ID="DCIB"/>
<UpdatedArrivalTime>06-16T10:45</UpdatedArrivalTime>
<UpdatedDepartureTime>06-16T09:30</UpdatedDepartureTime>
</FlightSegment>
</Item>
</ReservationItems>
</ItineraryInfo>
<ItineraryRef AirExtras="false" InhibitCode="U" PartitionID="AA" PrimeHostID="1S">
<Source PseudoCityCode="K3FJ"/>
</ItineraryRef>
</TravelItinerary>
</TravelItineraryReadRS>
</EnhancedAirBookRS>
I hope you can help, thanks for your time.
A: In your request I can see HaltOnStatus Code="UC", and you are in fact having that status in your response (Status="UC") for both segments.
In this case it seems the airline rejected both flights, maybe because of the lack of space or for any other reason. In such a case, you should discard this itinerary. However, there is an element that can help by booking the segments in QF status (that's a special status that does not take inventory from the carrier, and does not check actual availability) and then doing WPNCB, which will book real segments for the given options in the cheapest class of service. You can activate that with RetryRebook Option="true"just before HaltOnStatus.
| |
doc_3893
|
For testing purposes I create a simple new DeclarativeComponent which is a panelGroupLayout that contains 2 OutputText. After that I deploy the jar file and add it to my other Fusion web application libraries.
I want to add this DeclarativeComponent in another UIComponent at runtime by pressing a button which contains the next code in the javabean:
`public void addComponent(ActionEvent actionEvent)
{
// Add event code here...
createOutputComponent();
}
private void createOutputComponent()
{
CuadroDeTextoComponent ui = new CuadroDeTextoComponent(); //This is my Declarative Component
UIComponent parentUIComponent = getPglComponente(); This is the panelGrouopLayout in which i want to add my declarativeComponent
addComponent(parentUIComponent, ui);
}
public void addComponent(UIComponent parentUIComponent, UIXDeclarativeComponent childUIComponent)
{
parentUIComponent.getChildren().add(childUIComponent);
AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);
}`
I have tried draging the declarative component and it works, but when I do it dynamically the component doesn't display
A: For your component to display you may need to add a PPR refresh to it's parent element :
In your case :
public void addComponent(ActionEvent actionEvent)
{
// Add event code here...
createOutputComponent();
}
private void createOutputComponent()
{
CuadroDeTextoComponent ui = new CuadroDeTextoComponent(); //This is my Declarative Component
UIComponent parentUIComponent = getPglComponente(); This is the panelGrouopLayout in which i want to add my declarativeComponent
addComponent(parentUIComponent, ui);
addPPR(parentUIComponent); //Refresh the parent component
}
public void addComponent(UIComponent parentUIComponent, UIXDeclarativeComponent childUIComponent)
{
parentUIComponent.getChildren().add(childUIComponent);
AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);
}
public static void addPPR(UIComponent component) {
if (component != null) {
AdfFacesContext.getCurrentInstance().addPartialTarget(component.getParent());
}
}
| |
doc_3894
|
sql:CASE
when ${Today} < ${XXX} then ${XXX}
ELSE ${Today}
END;;
Tried ${TODAY} + 90(just to check syntax) , TRIED '01/01/2050.
A: You're writing SQL, so the syntax might be a little different for your RDBMS, but you should be okay with a string literal ISO Date value, optionally casted to a date type.
sql:CASE
when ${Today} < ${XXX} then ${XXX}
ELSE '2050-01-01'
END;;
| |
doc_3895
|
A: If you are using YAML pipeline, you can call Builds-Get rest api first:
GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=5.1
In "_links" you will find timeline:
"_links": {
"self": {
"href": "https://dev.azure.com/{org}/{proId}/_apis/build/Builds/2703"
},
"web": {
"href": "https://dev.azure.com/{org}/{proId}/_build/results?buildId=2703"
},
"sourceVersionDisplayUri": {
"href": "https://dev.azure.com/{org}/{proId}/_apis/build/builds/2703/sources"
},
"timeline": {
"href": "https://dev.azure.com/{org}/{proId}/_apis/build/builds/2703/Timeline"
},
"badge": {
"href": "https://dev.azure.com/{org}/{proId}/_apis/build/status/29"
}
},
You will get the result of stages from timeline:
{
"previousAttempts": [],
"id": "d4a9a205-d52e-57fb-7b17-15a9d984af62",
"parentId": null,
"type": "Stage",
"name": "deploy",
"startTime": "2020-03-23T08:42:37.2133333Z",
"finishTime": "2020-03-23T08:42:46.9933333Z",
"currentOperation": null,
"percentComplete": null,
"state": "completed",
"result": "succeeded",
"resultCode": null,
"changeId": 7,
"lastModified": "0001-01-01T00:00:00",
"workerName": null,
"order": 1,
"details": null,
"errorCount": 0,
"warningCount": 0,
"url": null,
"log": null,
"task": null,
"attempt": 1,
"identifier": "deploy"
},
If you want to get the stage status in a release pipeline, you need to use Get Release Environment rest api.
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/releases/{releaseId}/environments/{environmentId}?api-version=6.0-preview.7
| |
doc_3896
|
I have used C3.js to create a bar chart very similar to this, but the problem am facing is setting a threshold for every point on the bar as regards to the value on the x-axis. For instance when the GOAL is < 10% on the x-axis there should be a dotted line exactly on the 10% mark on the y-axis and the same thing should happen for the subsequent value i.e <3%, <2% and <1%.
My question is, please how do I create the threshold or set a mark on the chart like it is on the mockup? Thanks in advance.
A: You can use the same functions that c3 uses to draw the bars to figure out where to draw your target lines, like so
...
// where to draw the target lines for each data point
var scalingFactors = [0.1, 0.03, 0.02, 0.01]
// svg layer for each bar series
var barsLayers = chart.internal.main.selectAll('.' + c3.chart.internal.fn.CLASS.bars)[0]
var bars = chart.internal.main.selectAll('.' + c3.chart.internal.fn.CLASS.bar)[0];
// use the same function c3 uses to get each bars corners
var getPoints = chart.internal.generateGetBarPoints(chart.internal.getShapeIndices(chart.internal.isBarType));
// just in case there are multiple series
chart.internal.data.targets.forEach(function (series, i) {
// for each point in the series
series.values.forEach(function (d, j) {
// highlight if over threshold
if (d.value > scalingFactors[j])
d3.select(bars[j]).classed('crossed', true);
// get the position for our target lines
var value = d.value;
d.value = scalingFactors[j];
var pos = getPoints(d, j);
d.value = value;
var posTopLeft = pos[1]
var posTopRight = pos[2]
// draw target lines
d3.select(barsLayers[i]).append("line")
.attr("x1", posTopLeft[0] - 10)
.attr("y1", posTopLeft[1])
.attr("x2", posTopRight[0] + 10)
.attr("y2", posTopRight[1])
.attr("stroke-width", 1)
.style("stroke-dasharray", ("6, 4"));
})
})
CSS
.crossed {
fill: orange !important;
}
Fiddle - http://jsfiddle.net/puvhLb6x/
| |
doc_3897
|
In the thread dump, I found out that most of the threads belong to the ThreadPoolExecutors waiting for tasks. Are there any side effects in keeping these worker threads alive? Should I use setAllowCoreThreadTimeOut() in ThreadPoolExecutor so that the worker threads die after being idle for sometime?
A: Every thread has an associated stack which requires some amount of memory (configurable). If your threads are in the waiting state (and even if they aren't), they are reserving that memory. It can't be used by the rest of your application. Therefore, it might make sense to stop those threads (with setAllowCoreThreadTimeout()), release the memory they had reserved, and let the ThreadPoolExecutor recreate them as needed.
| |
doc_3898
|
Let’s say an example: Imagine I have a 250.000 token sequence, I should slide the transformer 488 times producing 488 tokens. Concatenate this output to obtain a summary array of the sequence and build a classifier on top of it.
I’m trying to find any examples that could guide me in this direction but I hardly can find any of them. Does someone think that’s a good idea? Where could I look for some near examples of sliding a transformer/LSTM over a longer sequence?
Thank you very much, I’ll appreciate everything!
| |
doc_3899
|
html form
<form name="multiform" id="multiform" action="multi-form-submit.php" method="POST" enctype="multipart/form-data">
Image1 :<input type="file" name="photo1" /><br/>
image2 :
Image3 :
javascript code
function getDoc(frame) {
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch(err) {
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch(err) {
// last attempt
doc = frame.document;
}
return doc;
}
$("#multiform").submit(function(e)
{
var formObj = $(this);
//var formURL = formObj.attr("action");
var formURL="multi-form-submit.php";
var iframeId = "unique" + (new Date().getTime());
//create an empty iframe
var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');
//hide it
iframe.hide();
//set form target to iframe
formObj.attr("target",iframeId);
//Add iframe to body
iframe.appendTo("body");
iframe.load(function(e)
{
var doc = getDoc(iframe[0]);
var docRoot = doc.body ? doc.body : doc.documentElement;
var data = docRoot.innerHTML;
alert(data);
});
multi-form-submit.php file :
<?php
move_uploaded_file($_FILES["photo"]["tmp_name"],
"upload/" . $_FILES["photo"]["name"]);
?>
when the user select photo1 and photo2 and photo3 and click on the submit i want to send only photo2 to server.how can I do that?
A: for olden browsers, iframe submit form would create gibberish when form contains Chinese, Japanese...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.